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