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