xref: /freebsd/usr.bin/script/script.c (revision 7be9a3b45356747f9fcb6d69a722c1c95f8060bf)
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/queue.h>
49 #include <sys/uio.h>
50 #include <sys/endian.h>
51 #include <dev/filemon/filemon.h>
52 
53 #include <err.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <libutil.h>
57 #include <paths.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <termios.h>
63 #include <unistd.h>
64 
65 #define DEF_BUF 65536
66 
67 struct stamp {
68 	uint64_t scr_len;	/* amount of data */
69 	uint64_t scr_sec;	/* time it arrived in seconds... */
70 	uint32_t scr_usec;	/* ...and microseconds */
71 	uint32_t scr_direction; /* 'i', 'o', etc (also indicates endianness) */
72 };
73 
74 struct buf_elm {
75 	TAILQ_ENTRY(buf_elm) link;
76 	int rpos;
77 	int len;
78 	char ibuf[];
79 };
80 
81 static FILE *fscript;
82 static int master, slave;
83 static int child;
84 static const char *fname;
85 static char *fmfname;
86 static int fflg, qflg, ttyflg;
87 static int usesleep, rawout, showexit;
88 static TAILQ_HEAD(, buf_elm) obuf_list = TAILQ_HEAD_INITIALIZER(obuf_list);
89 
90 static struct termios tt;
91 
92 static void done(int) __dead2;
93 static void doshell(char **);
94 static void finish(void);
95 static void record(FILE *, char *, size_t, int);
96 static void consume(FILE *, off_t, char *, int);
97 static void playback(FILE *) __dead2;
98 static void usage(void);
99 
100 int
101 main(int argc, char *argv[])
102 {
103 	int cc;
104 	struct termios rtt, stt;
105 	struct winsize win;
106 	struct timeval tv, *tvp;
107 	time_t tvec, start;
108 	char obuf[BUFSIZ];
109 	char ibuf[BUFSIZ];
110 	fd_set rfd, wfd;
111 	struct buf_elm *be;
112 	int aflg, Fflg, kflg, pflg, ch, k, n, fcm;
113 	int flushtime, readstdin;
114 	int fm_fd, fm_log;
115 
116 	aflg = Fflg = kflg = pflg = 0;
117 	usesleep = 1;
118 	rawout = 0;
119 	flushtime = 30;
120 	fm_fd = -1;	/* Shut up stupid "may be used uninitialized" GCC
121 			   warning. (not needed w/clang) */
122 	showexit = 0;
123 
124 	while ((ch = getopt(argc, argv, "adeFfkpqrt:")) != -1)
125 		switch(ch) {
126 		case 'a':
127 			aflg = 1;
128 			break;
129 		case 'd':
130 			usesleep = 0;
131 			break;
132 		case 'e':	/* Default behavior, accepted for linux compat */
133 			break;
134 		case 'F':
135 			Fflg = 1;
136 			break;
137 		case 'f':
138 			fflg = 1;
139 			break;
140 		case 'k':
141 			kflg = 1;
142 			break;
143 		case 'p':
144 			pflg = 1;
145 			break;
146 		case 'q':
147 			qflg = 1;
148 			break;
149 		case 'r':
150 			rawout = 1;
151 			break;
152 		case 't':
153 			flushtime = atoi(optarg);
154 			if (flushtime < 0)
155 				err(1, "invalid flush time %d", flushtime);
156 			break;
157 		case '?':
158 		default:
159 			usage();
160 		}
161 	argc -= optind;
162 	argv += optind;
163 
164 	if (argc > 0) {
165 		fname = argv[0];
166 		argv++;
167 		argc--;
168 	} else
169 		fname = "typescript";
170 
171 	if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
172 		err(1, "%s", fname);
173 
174 	if (fflg) {
175 		asprintf(&fmfname, "%s.filemon", fname);
176 		if (!fmfname)
177 			err(1, "%s.filemon", fname);
178 		if ((fm_fd = open("/dev/filemon", O_RDWR | O_CLOEXEC)) == -1)
179 			err(1, "open(\"/dev/filemon\", O_RDWR)");
180 		if ((fm_log = open(fmfname,
181 		    O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
182 		    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
183 			err(1, "open(%s)", fmfname);
184 		if (ioctl(fm_fd, FILEMON_SET_FD, &fm_log) < 0)
185 			err(1, "Cannot set filemon log file descriptor");
186 	}
187 
188 	if (pflg)
189 		playback(fscript);
190 
191 	if (tcgetattr(STDIN_FILENO, &tt) == -1 ||
192 	    ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1) {
193 		if (errno != ENOTTY) /* For debugger. */
194 			err(1, "tcgetattr/ioctl");
195 		if (openpty(&master, &slave, NULL, NULL, NULL) == -1)
196 			err(1, "openpty");
197 	} else {
198 		if (openpty(&master, &slave, NULL, &tt, &win) == -1)
199 			err(1, "openpty");
200 		ttyflg = 1;
201 	}
202 	fcm = fcntl(master, F_GETFL);
203 	if (fcm == -1)
204 		err(1, "master F_GETFL");
205 	fcm |= O_NONBLOCK;
206 	if (fcntl(master, F_SETFL, fcm) == -1)
207 		err(1, "master F_SETFL");
208 
209 	if (rawout)
210 		record(fscript, NULL, 0, 's');
211 
212 	if (!qflg) {
213 		tvec = time(NULL);
214 		(void)printf("Script started, output file is %s\n", fname);
215 		if (!rawout) {
216 			(void)fprintf(fscript, "Script started on %s",
217 			    ctime(&tvec));
218 			if (argv[0]) {
219 				showexit = 1;
220 				fprintf(fscript, "Command: ");
221 				for (k = 0 ; argv[k] ; ++k)
222 					fprintf(fscript, "%s%s", k ? " " : "",
223 						argv[k]);
224 				fprintf(fscript, "\n");
225 			}
226 		}
227 		fflush(fscript);
228 		if (fflg) {
229 			(void)printf("Filemon started, output file is %s\n",
230 			    fmfname);
231 		}
232 	}
233 	if (ttyflg) {
234 		rtt = tt;
235 		cfmakeraw(&rtt);
236 		rtt.c_lflag &= ~ECHO;
237 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
238 	}
239 
240 	child = fork();
241 	if (child < 0) {
242 		warn("fork");
243 		done(1);
244 	}
245 	if (child == 0) {
246 		if (fflg) {
247 			int pid;
248 
249 			pid = getpid();
250 			if (ioctl(fm_fd, FILEMON_SET_PID, &pid) < 0)
251 				err(1, "Cannot set filemon PID");
252 		}
253 
254 		doshell(argv);
255 	}
256 	close(slave);
257 
258 	start = tvec = time(0);
259 	readstdin = 1;
260 	for (;;) {
261 		FD_ZERO(&rfd);
262 		FD_ZERO(&wfd);
263 		FD_SET(master, &rfd);
264 		if (readstdin)
265 			FD_SET(STDIN_FILENO, &rfd);
266 		if (!TAILQ_EMPTY(&obuf_list))
267 			FD_SET(master, &wfd);
268 		if (!readstdin && ttyflg) {
269 			tv.tv_sec = 1;
270 			tv.tv_usec = 0;
271 			tvp = &tv;
272 			readstdin = 1;
273 		} else if (flushtime > 0) {
274 			tv.tv_sec = flushtime - (tvec - start);
275 			tv.tv_usec = 0;
276 			tvp = &tv;
277 		} else {
278 			tvp = NULL;
279 		}
280 		n = select(master + 1, &rfd, &wfd, NULL, tvp);
281 		if (n < 0 && errno != EINTR)
282 			break;
283 		if (n > 0 && FD_ISSET(STDIN_FILENO, &rfd)) {
284 			cc = read(STDIN_FILENO, ibuf, BUFSIZ);
285 			if (cc < 0)
286 				break;
287 			if (cc == 0) {
288 				if (tcgetattr(master, &stt) == 0 &&
289 				    (stt.c_lflag & ICANON) != 0) {
290 					(void)write(master, &stt.c_cc[VEOF], 1);
291 				}
292 				readstdin = 0;
293 			}
294 			if (cc > 0) {
295 				if (rawout)
296 					record(fscript, ibuf, cc, 'i');
297 				be = malloc(sizeof(*be) + cc);
298 				be->rpos = 0;
299 				be->len = cc;
300 				memcpy(be->ibuf, ibuf, cc);
301 				TAILQ_INSERT_TAIL(&obuf_list, be, link);
302 			}
303 		}
304 		if (n > 0 && FD_ISSET(master, &wfd)) {
305 			while ((be = TAILQ_FIRST(&obuf_list)) != NULL) {
306 				cc = write(master, be->ibuf + be->rpos,
307 				    be->len);
308 				if (cc == -1) {
309 					if (errno == EWOULDBLOCK ||
310 					    errno == EINTR)
311 						break;
312 					warn("write master");
313 					done(1);
314 				}
315 				if (cc == 0)
316 					break;		/* retry later ? */
317 				if (kflg && tcgetattr(master, &stt) >= 0 &&
318 				    ((stt.c_lflag & ECHO) == 0)) {
319 					(void)fwrite(be->ibuf + be->rpos,
320 					    1, cc, fscript);
321 				}
322 				be->len -= cc;
323 				if (be->len == 0) {
324 					TAILQ_REMOVE(&obuf_list, be, link);
325 					free(be);
326 				} else {
327 					be->rpos += cc;
328 				}
329 			}
330 		}
331 		if (n > 0 && FD_ISSET(master, &rfd)) {
332 			cc = read(master, obuf, sizeof (obuf));
333 			if (cc <= 0)
334 				break;
335 			(void)write(STDOUT_FILENO, obuf, cc);
336 			if (rawout)
337 				record(fscript, obuf, cc, 'o');
338 			else
339 				(void)fwrite(obuf, 1, cc, fscript);
340 		}
341 		tvec = time(0);
342 		if (tvec - start >= flushtime) {
343 			fflush(fscript);
344 			start = tvec;
345 		}
346 		if (Fflg)
347 			fflush(fscript);
348 	}
349 	finish();
350 	done(0);
351 }
352 
353 static void
354 usage(void)
355 {
356 	(void)fprintf(stderr,
357 	    "usage: script [-adfkpqr] [-t time] [file [command ...]]\n");
358 	exit(1);
359 }
360 
361 static void
362 finish(void)
363 {
364 	int e, status;
365 
366 	if (waitpid(child, &status, 0) == child) {
367 		if (WIFEXITED(status))
368 			e = WEXITSTATUS(status);
369 		else if (WIFSIGNALED(status))
370 			e = WTERMSIG(status);
371 		else /* can't happen */
372 			e = 1;
373 		done(e);
374 	}
375 }
376 
377 static void
378 doshell(char **av)
379 {
380 	const char *shell;
381 
382 	shell = getenv("SHELL");
383 	if (shell == NULL)
384 		shell = _PATH_BSHELL;
385 
386 	(void)close(master);
387 	(void)fclose(fscript);
388 	free(fmfname);
389 	login_tty(slave);
390 	setenv("SCRIPT", fname, 1);
391 	if (av[0]) {
392 		execvp(av[0], av);
393 		warn("%s", av[0]);
394 	} else {
395 		execl(shell, shell, "-i", (char *)NULL);
396 		warn("%s", shell);
397 	}
398 	exit(1);
399 }
400 
401 static void
402 done(int eno)
403 {
404 	time_t tvec;
405 
406 	if (ttyflg)
407 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
408 	tvec = time(NULL);
409 	if (rawout)
410 		record(fscript, NULL, 0, 'e');
411 	if (!qflg) {
412 		if (!rawout) {
413 			if (showexit)
414 				(void)fprintf(fscript, "\nCommand exit status:"
415 				    " %d", eno);
416 			(void)fprintf(fscript,"\nScript done on %s",
417 			    ctime(&tvec));
418 		}
419 		(void)printf("\nScript done, output file is %s\n", fname);
420 		if (fflg) {
421 			(void)printf("Filemon done, output file is %s\n",
422 			    fmfname);
423 		}
424 	}
425 	(void)fclose(fscript);
426 	(void)close(master);
427 	exit(eno);
428 }
429 
430 static void
431 record(FILE *fp, char *buf, size_t cc, int direction)
432 {
433 	struct iovec iov[2];
434 	struct stamp stamp;
435 	struct timeval tv;
436 
437 	(void)gettimeofday(&tv, NULL);
438 	stamp.scr_len = cc;
439 	stamp.scr_sec = tv.tv_sec;
440 	stamp.scr_usec = tv.tv_usec;
441 	stamp.scr_direction = direction;
442 	iov[0].iov_len = sizeof(stamp);
443 	iov[0].iov_base = &stamp;
444 	iov[1].iov_len = cc;
445 	iov[1].iov_base = buf;
446 	if (writev(fileno(fp), &iov[0], 2) == -1)
447 		err(1, "writev");
448 }
449 
450 static void
451 consume(FILE *fp, off_t len, char *buf, int reg)
452 {
453 	size_t l;
454 
455 	if (reg) {
456 		if (fseeko(fp, len, SEEK_CUR) == -1)
457 			err(1, NULL);
458 	}
459 	else {
460 		while (len > 0) {
461 			l = MIN(DEF_BUF, len);
462 			if (fread(buf, sizeof(char), l, fp) != l)
463 				err(1, "cannot read buffer");
464 			len -= l;
465 		}
466 	}
467 }
468 
469 #define swapstamp(stamp) do { \
470 	if (stamp.scr_direction > 0xff) { \
471 		stamp.scr_len = bswap64(stamp.scr_len); \
472 		stamp.scr_sec = bswap64(stamp.scr_sec); \
473 		stamp.scr_usec = bswap32(stamp.scr_usec); \
474 		stamp.scr_direction = bswap32(stamp.scr_direction); \
475 	} \
476 } while (0/*CONSTCOND*/)
477 
478 static void
479 termset(void)
480 {
481 	struct termios traw;
482 
483 	if (tcgetattr(STDOUT_FILENO, &tt) == -1) {
484 		if (errno != ENOTTY) /* For debugger. */
485 			err(1, "tcgetattr");
486 		return;
487 	}
488 	ttyflg = 1;
489 	traw = tt;
490 	cfmakeraw(&traw);
491 	traw.c_lflag |= ISIG;
492 	(void)tcsetattr(STDOUT_FILENO, TCSANOW, &traw);
493 }
494 
495 static void
496 termreset(void)
497 {
498 	if (ttyflg) {
499 		tcsetattr(STDOUT_FILENO, TCSADRAIN, &tt);
500 		ttyflg = 0;
501 	}
502 }
503 
504 static void
505 playback(FILE *fp)
506 {
507 	struct timespec tsi, tso;
508 	struct stamp stamp;
509 	struct stat pst;
510 	char buf[DEF_BUF];
511 	off_t nread, save_len;
512 	size_t l;
513 	time_t tclock;
514 	int reg;
515 
516 	if (fstat(fileno(fp), &pst) == -1)
517 		err(1, "fstat failed");
518 
519 	reg = S_ISREG(pst.st_mode);
520 
521 	for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
522 		if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
523 			if (reg)
524 				err(1, "reading playback header");
525 			else
526 				break;
527 		}
528 		swapstamp(stamp);
529 		save_len = sizeof(stamp);
530 
531 		if (reg && stamp.scr_len >
532 		    (uint64_t)(pst.st_size - save_len) - nread)
533 			errx(1, "invalid stamp");
534 
535 		save_len += stamp.scr_len;
536 		tclock = stamp.scr_sec;
537 		tso.tv_sec = stamp.scr_sec;
538 		tso.tv_nsec = stamp.scr_usec * 1000;
539 
540 		switch (stamp.scr_direction) {
541 		case 's':
542 			if (!qflg)
543 			    (void)printf("Script started on %s",
544 				ctime(&tclock));
545 			tsi = tso;
546 			(void)consume(fp, stamp.scr_len, buf, reg);
547 			termset();
548 			atexit(termreset);
549 			break;
550 		case 'e':
551 			termreset();
552 			if (!qflg)
553 				(void)printf("\nScript done on %s",
554 				    ctime(&tclock));
555 			(void)consume(fp, stamp.scr_len, buf, reg);
556 			break;
557 		case 'i':
558 			/* throw input away */
559 			(void)consume(fp, stamp.scr_len, buf, reg);
560 			break;
561 		case 'o':
562 			tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
563 			tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
564 			if (tsi.tv_nsec < 0) {
565 				tsi.tv_sec -= 1;
566 				tsi.tv_nsec += 1000000000;
567 			}
568 			if (usesleep)
569 				(void)nanosleep(&tsi, NULL);
570 			tsi = tso;
571 			while (stamp.scr_len > 0) {
572 				l = MIN(DEF_BUF, stamp.scr_len);
573 				if (fread(buf, sizeof(char), l, fp) != l)
574 					err(1, "cannot read buffer");
575 
576 				(void)write(STDOUT_FILENO, buf, l);
577 				stamp.scr_len -= l;
578 			}
579 			break;
580 		default:
581 			errx(1, "invalid direction");
582 		}
583 	}
584 	(void)fclose(fp);
585 	exit(0);
586 }
587