script.c revision 297352
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: stable/10/usr.bin/script/script.c 297352 2016-03-28 16:21:45Z bdrewery $");
33#ifndef lint
34static 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
39static 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
64struct 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
71static FILE *fscript;
72static int master, slave;
73static int child;
74static const char *fname;
75static char *fmfname;
76static int fflg, qflg, ttyflg;
77static int usesleep, rawout, showexit;
78
79static struct termios tt;
80
81static void done(int) __dead2;
82static void doshell(char **);
83static void finish(void);
84static void record(FILE *, char *, size_t, int);
85static void consume(FILE *, off_t, char *, int);
86static void playback(FILE *) __dead2;
87static void usage(void);
88
89int
90main(int argc, char *argv[])
91{
92	int cc;
93	struct termios rtt, stt;
94	struct winsize win;
95	struct timeval tv, *tvp;
96	time_t tvec, start;
97	char obuf[BUFSIZ];
98	char ibuf[BUFSIZ];
99	fd_set rfd;
100	int aflg, kflg, pflg, ch, k, n;
101	int flushtime, readstdin;
102	int fm_fd, fm_log;
103
104	aflg = kflg = pflg = 0;
105	usesleep = 1;
106	rawout = 0;
107	flushtime = 30;
108	fm_fd = -1;	/* Shut up stupid "may be used uninitialized" GCC
109			   warning. (not needed w/clang) */
110	showexit = 0;
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				showexit = 1;
200				fprintf(fscript, "Command: ");
201				for (k = 0 ; argv[k] ; ++k)
202					fprintf(fscript, "%s%s", k ? " " : "",
203						argv[k]);
204				fprintf(fscript, "\n");
205			}
206		}
207		fflush(fscript);
208		if (fflg) {
209			(void)printf("Filemon started, output file is %s\n",
210			    fmfname);
211		}
212	}
213	if (ttyflg) {
214		rtt = tt;
215		cfmakeraw(&rtt);
216		rtt.c_lflag &= ~ECHO;
217		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
218	}
219
220	child = fork();
221	if (child < 0) {
222		warn("fork");
223		done(1);
224	}
225	if (child == 0) {
226		if (fflg) {
227			int pid;
228
229			pid = getpid();
230			if (ioctl(fm_fd, FILEMON_SET_PID, &pid) < 0)
231				err(1, "Cannot set filemon PID");
232		}
233
234		doshell(argv);
235	}
236	close(slave);
237
238	start = tvec = time(0);
239	readstdin = 1;
240	for (;;) {
241		FD_ZERO(&rfd);
242		FD_SET(master, &rfd);
243		if (readstdin)
244			FD_SET(STDIN_FILENO, &rfd);
245		if (!readstdin && ttyflg) {
246			tv.tv_sec = 1;
247			tv.tv_usec = 0;
248			tvp = &tv;
249			readstdin = 1;
250		} else if (flushtime > 0) {
251			tv.tv_sec = flushtime - (tvec - start);
252			tv.tv_usec = 0;
253			tvp = &tv;
254		} else {
255			tvp = NULL;
256		}
257		n = select(master + 1, &rfd, 0, 0, tvp);
258		if (n < 0 && errno != EINTR)
259			break;
260		if (n > 0 && FD_ISSET(STDIN_FILENO, &rfd)) {
261			cc = read(STDIN_FILENO, ibuf, BUFSIZ);
262			if (cc < 0)
263				break;
264			if (cc == 0) {
265				if (tcgetattr(master, &stt) == 0 &&
266				    (stt.c_lflag & ICANON) != 0) {
267					(void)write(master, &stt.c_cc[VEOF], 1);
268				}
269				readstdin = 0;
270			}
271			if (cc > 0) {
272				if (rawout)
273					record(fscript, ibuf, cc, 'i');
274				(void)write(master, ibuf, cc);
275				if (kflg && tcgetattr(master, &stt) >= 0 &&
276				    ((stt.c_lflag & ECHO) == 0)) {
277					(void)fwrite(ibuf, 1, cc, fscript);
278				}
279			}
280		}
281		if (n > 0 && FD_ISSET(master, &rfd)) {
282			cc = read(master, obuf, sizeof (obuf));
283			if (cc <= 0)
284				break;
285			(void)write(STDOUT_FILENO, obuf, cc);
286			if (rawout)
287				record(fscript, obuf, cc, 'o');
288			else
289				(void)fwrite(obuf, 1, cc, fscript);
290		}
291		tvec = time(0);
292		if (tvec - start >= flushtime) {
293			fflush(fscript);
294			start = tvec;
295		}
296	}
297	finish();
298	done(0);
299}
300
301static void
302usage(void)
303{
304	(void)fprintf(stderr,
305	    "usage: script [-adfkpqr] [-t time] [file [command ...]]\n");
306	exit(1);
307}
308
309static void
310finish(void)
311{
312	int e, status;
313
314	if (waitpid(child, &status, 0) == child) {
315		if (WIFEXITED(status))
316			e = WEXITSTATUS(status);
317		else if (WIFSIGNALED(status))
318			e = WTERMSIG(status);
319		else /* can't happen */
320			e = 1;
321		done(e);
322	}
323}
324
325static void
326doshell(char **av)
327{
328	const char *shell;
329
330	shell = getenv("SHELL");
331	if (shell == NULL)
332		shell = _PATH_BSHELL;
333
334	(void)close(master);
335	(void)fclose(fscript);
336	free(fmfname);
337	login_tty(slave);
338	setenv("SCRIPT", fname, 1);
339	if (av[0]) {
340		execvp(av[0], av);
341		warn("%s", av[0]);
342	} else {
343		execl(shell, shell, "-i", (char *)NULL);
344		warn("%s", shell);
345	}
346	exit(1);
347}
348
349static void
350done(int eno)
351{
352	time_t tvec;
353
354	if (ttyflg)
355		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
356	tvec = time(NULL);
357	if (rawout)
358		record(fscript, NULL, 0, 'e');
359	if (!qflg) {
360		if (!rawout) {
361			if (showexit)
362				(void)fprintf(fscript, "\nCommand exit status:"
363				    " %d", eno);
364			(void)fprintf(fscript,"\nScript done on %s",
365			    ctime(&tvec));
366		}
367		(void)printf("\nScript done, output file is %s\n", fname);
368		if (fflg) {
369			(void)printf("Filemon done, output file is %s\n",
370			    fmfname);
371		}
372	}
373	(void)fclose(fscript);
374	(void)close(master);
375	exit(eno);
376}
377
378static void
379record(FILE *fp, char *buf, size_t cc, int direction)
380{
381	struct iovec iov[2];
382	struct stamp stamp;
383	struct timeval tv;
384
385	(void)gettimeofday(&tv, NULL);
386	stamp.scr_len = cc;
387	stamp.scr_sec = tv.tv_sec;
388	stamp.scr_usec = tv.tv_usec;
389	stamp.scr_direction = direction;
390	iov[0].iov_len = sizeof(stamp);
391	iov[0].iov_base = &stamp;
392	iov[1].iov_len = cc;
393	iov[1].iov_base = buf;
394	if (writev(fileno(fp), &iov[0], 2) == -1)
395		err(1, "writev");
396}
397
398static void
399consume(FILE *fp, off_t len, char *buf, int reg)
400{
401	size_t l;
402
403	if (reg) {
404		if (fseeko(fp, len, SEEK_CUR) == -1)
405			err(1, NULL);
406	}
407	else {
408		while (len > 0) {
409			l = MIN(DEF_BUF, len);
410			if (fread(buf, sizeof(char), l, fp) != l)
411				err(1, "cannot read buffer");
412			len -= l;
413		}
414	}
415}
416
417#define swapstamp(stamp) do { \
418	if (stamp.scr_direction > 0xff) { \
419		stamp.scr_len = bswap64(stamp.scr_len); \
420		stamp.scr_sec = bswap64(stamp.scr_sec); \
421		stamp.scr_usec = bswap32(stamp.scr_usec); \
422		stamp.scr_direction = bswap32(stamp.scr_direction); \
423	} \
424} while (0/*CONSTCOND*/)
425
426static void
427playback(FILE *fp)
428{
429	struct timespec tsi, tso;
430	struct stamp stamp;
431	struct stat pst;
432	char buf[DEF_BUF];
433	off_t nread, save_len;
434	size_t l;
435	time_t tclock;
436	int reg;
437
438	if (fstat(fileno(fp), &pst) == -1)
439		err(1, "fstat failed");
440
441	reg = S_ISREG(pst.st_mode);
442
443	for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
444		if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
445			if (reg)
446				err(1, "reading playback header");
447			else
448				break;
449		}
450		swapstamp(stamp);
451		save_len = sizeof(stamp);
452
453		if (reg && stamp.scr_len >
454		    (uint64_t)(pst.st_size - save_len) - nread)
455			errx(1, "invalid stamp");
456
457		save_len += stamp.scr_len;
458		tclock = stamp.scr_sec;
459		tso.tv_sec = stamp.scr_sec;
460		tso.tv_nsec = stamp.scr_usec * 1000;
461
462		switch (stamp.scr_direction) {
463		case 's':
464			if (!qflg)
465			    (void)printf("Script started on %s",
466				ctime(&tclock));
467			tsi = tso;
468			(void)consume(fp, stamp.scr_len, buf, reg);
469			break;
470		case 'e':
471			if (!qflg)
472				(void)printf("\nScript done on %s",
473				    ctime(&tclock));
474			(void)consume(fp, stamp.scr_len, buf, reg);
475			break;
476		case 'i':
477			/* throw input away */
478			(void)consume(fp, stamp.scr_len, buf, reg);
479			break;
480		case 'o':
481			tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
482			tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
483			if (tsi.tv_nsec < 0) {
484				tsi.tv_sec -= 1;
485				tsi.tv_nsec += 1000000000;
486			}
487			if (usesleep)
488				(void)nanosleep(&tsi, NULL);
489			tsi = tso;
490			while (stamp.scr_len > 0) {
491				l = MIN(DEF_BUF, stamp.scr_len);
492				if (fread(buf, sizeof(char), l, fp) != l)
493					err(1, "cannot read buffer");
494
495				(void)write(STDOUT_FILENO, buf, l);
496				stamp.scr_len -= l;
497			}
498			break;
499		default:
500			errx(1, "invalid direction");
501		}
502	}
503	(void)fclose(fp);
504	exit(0);
505}
506