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