xref: /freebsd/usr.bin/script/script.c (revision ee24d3b8401985c99a4a1755765fe9332daee568)
1 /*
2  * Copyright (c) 1980, 1992, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 
32 __FBSDID("$FreeBSD$");
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1980, 1992, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif
39 
40 #ifndef lint
41 static const char sccsid[] = "@(#)script.c	8.1 (Berkeley) 6/6/93";
42 #endif
43 
44 #include <sys/types.h>
45 #include <sys/wait.h>
46 #include <sys/stat.h>
47 #include <sys/ioctl.h>
48 #include <sys/time.h>
49 #include <sys/uio.h>
50 #include <sys/endian.h>
51 #include <sys/param.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 static FILE *fscript;
75 static int master, slave;
76 static int child;
77 static const char *fname;
78 static int qflg, ttyflg;
79 static int usesleep, rawout;
80 
81 static struct termios tt;
82 
83 static void done(int) __dead2;
84 static void doshell(char **);
85 static void fail(void);
86 static void finish(void);
87 static void record(FILE *, char *, size_t, int);
88 static void consume(FILE *, off_t, char *, int);
89 static void playback(FILE *) __dead2;
90 static void usage(void);
91 
92 int
93 main(int argc, char *argv[])
94 {
95 	int cc;
96 	struct termios rtt, stt;
97 	struct winsize win;
98 	int aflg, kflg, pflg, ch, n;
99 	struct timeval tv, *tvp;
100 	time_t tvec, start;
101 	char obuf[BUFSIZ];
102 	char ibuf[BUFSIZ];
103 	fd_set rfd;
104 	int flushtime = 30;
105 	int readstdin;
106 	int k;
107 
108 	aflg = kflg = pflg = 0;
109 	usesleep = 1;
110 	rawout = 0;
111 
112 	while ((ch = getopt(argc, argv, "adkpqrt:")) != -1)
113 		switch(ch) {
114 		case 'a':
115 			aflg = 1;
116 			break;
117 		case 'd':
118 			usesleep = 0;
119 			break;
120 		case 'k':
121 			kflg = 1;
122 			break;
123 		case 'p':
124 			pflg = 1;
125 			break;
126 		case 'q':
127 			qflg = 1;
128 			break;
129 		case 'r':
130 			rawout = 1;
131 			break;
132 		case 't':
133 			flushtime = atoi(optarg);
134 			if (flushtime < 0)
135 				err(1, "invalid flush time %d", flushtime);
136 			break;
137 		case '?':
138 		default:
139 			usage();
140 		}
141 	argc -= optind;
142 	argv += optind;
143 
144 	if (argc > 0) {
145 		fname = argv[0];
146 		argv++;
147 		argc--;
148 	} else
149 		fname = "typescript";
150 
151 	if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
152 		err(1, "%s", fname);
153 
154 	if (pflg)
155 		playback(fscript);
156 
157 	if ((ttyflg = isatty(STDIN_FILENO)) != 0) {
158 		if (tcgetattr(STDIN_FILENO, &tt) == -1)
159 			err(1, "tcgetattr");
160 		if (ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1)
161 			err(1, "ioctl");
162 		if (openpty(&master, &slave, NULL, &tt, &win) == -1)
163 			err(1, "openpty");
164 	} else {
165 		if (openpty(&master, &slave, NULL, NULL, NULL) == -1)
166 			err(1, "openpty");
167 	}
168 
169 	if (rawout)
170 		record(fscript, NULL, 0, 's');
171 
172 	if (!qflg) {
173 		tvec = time(NULL);
174 		(void)printf("Script started, output file is %s\n", fname);
175 		if (!rawout) {
176 			(void)fprintf(fscript, "Script started on %s",
177 				      ctime(&tvec));
178 			if (argv[0]) {
179 				fprintf(fscript, "command: ");
180 				for (k = 0 ; argv[k] ; ++k)
181 					fprintf(fscript, "%s%s", k ? " " : "",
182 						argv[k]);
183 				fprintf(fscript, "\n");
184 			}
185 		}
186 		fflush(fscript);
187 	}
188 	if (ttyflg) {
189 		rtt = tt;
190 		cfmakeraw(&rtt);
191 		rtt.c_lflag &= ~ECHO;
192 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
193 	}
194 
195 	child = fork();
196 	if (child < 0) {
197 		warn("fork");
198 		done(1);
199 	}
200 	if (child == 0)
201 		doshell(argv);
202 	close(slave);
203 
204 	start = tvec = time(0);
205 	readstdin = 1;
206 	for (;;) {
207 		FD_ZERO(&rfd);
208 		FD_SET(master, &rfd);
209 		if (readstdin)
210 			FD_SET(STDIN_FILENO, &rfd);
211 		if ((!readstdin && ttyflg) || flushtime > 0) {
212 			tv.tv_sec = !readstdin && ttyflg ? 1 :
213 			    flushtime - (tvec - start);
214 			tv.tv_usec = 0;
215 			tvp = &tv;
216 			readstdin = 1;
217 		} else {
218 			tvp = NULL;
219 		}
220 		n = select(master + 1, &rfd, 0, 0, tvp);
221 		if (n < 0 && errno != EINTR)
222 			break;
223 		if (n > 0 && FD_ISSET(STDIN_FILENO, &rfd)) {
224 			cc = read(STDIN_FILENO, ibuf, BUFSIZ);
225 			if (cc < 0)
226 				break;
227 			if (cc == 0) {
228 				if (tcgetattr(master, &stt) == 0 &&
229 				    (stt.c_lflag & ICANON) != 0) {
230 					(void)write(master, &stt.c_cc[VEOF], 1);
231 				}
232 				readstdin = 0;
233 			}
234 			if (cc > 0) {
235 				if (rawout)
236 					record(fscript, ibuf, cc, 'i');
237 				(void)write(master, ibuf, cc);
238 				if (kflg && tcgetattr(master, &stt) >= 0 &&
239 				    ((stt.c_lflag & ECHO) == 0)) {
240 					(void)fwrite(ibuf, 1, cc, fscript);
241 				}
242 			}
243 		}
244 		if (n > 0 && FD_ISSET(master, &rfd)) {
245 			cc = read(master, obuf, sizeof (obuf));
246 			if (cc <= 0)
247 				break;
248 			(void)write(STDOUT_FILENO, obuf, cc);
249 			if (rawout)
250 				record(fscript, obuf, cc, 'o');
251 			else
252 				(void)fwrite(obuf, 1, cc, fscript);
253 		}
254 		tvec = time(0);
255 		if (tvec - start >= flushtime) {
256 			fflush(fscript);
257 			start = tvec;
258 		}
259 	}
260 	finish();
261 	done(0);
262 }
263 
264 static void
265 usage(void)
266 {
267 	(void)fprintf(stderr,
268 	    "usage: script [-adkpqr] [-t time] [file [command ...]]\n");
269 	exit(1);
270 }
271 
272 static void
273 finish(void)
274 {
275 	int e, status;
276 
277 	if (waitpid(child, &status, 0) == child) {
278 		if (WIFEXITED(status))
279 			e = WEXITSTATUS(status);
280 		else if (WIFSIGNALED(status))
281 			e = WTERMSIG(status);
282 		else /* can't happen */
283 			e = 1;
284 		done(e);
285 	}
286 }
287 
288 static void
289 doshell(char **av)
290 {
291 	const char *shell;
292 
293 	shell = getenv("SHELL");
294 	if (shell == NULL)
295 		shell = _PATH_BSHELL;
296 
297 	(void)close(master);
298 	(void)fclose(fscript);
299 	login_tty(slave);
300 	setenv("SCRIPT", fname, 1);
301 	if (av[0]) {
302 		execvp(av[0], av);
303 		warn("%s", av[0]);
304 	} else {
305 		execl(shell, shell, "-i", (char *)NULL);
306 		warn("%s", shell);
307 	}
308 	fail();
309 }
310 
311 static void
312 fail(void)
313 {
314 	(void)kill(0, SIGTERM);
315 	done(1);
316 }
317 
318 static void
319 done(int eno)
320 {
321 	time_t tvec;
322 
323 	if (ttyflg)
324 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
325 	tvec = time(NULL);
326 	if (rawout)
327 		record(fscript, NULL, 0, 'e');
328 	if (!qflg) {
329 		if (!rawout)
330 			(void)fprintf(fscript,"\nScript done on %s",
331 				      ctime(&tvec));
332 		(void)printf("\nScript done, output file is %s\n", fname);
333 	}
334 	(void)fclose(fscript);
335 	(void)close(master);
336 	exit(eno);
337 }
338 
339 static void
340 record(FILE *fp, char *buf, size_t cc, int direction)
341 {
342 	struct iovec iov[2];
343 	struct stamp stamp;
344 	struct timeval tv;
345 
346 	(void)gettimeofday(&tv, NULL);
347 	stamp.scr_len = cc;
348 	stamp.scr_sec = tv.tv_sec;
349 	stamp.scr_usec = tv.tv_usec;
350 	stamp.scr_direction = direction;
351 	iov[0].iov_len = sizeof(stamp);
352 	iov[0].iov_base = &stamp;
353 	iov[1].iov_len = cc;
354 	iov[1].iov_base = buf;
355 	if (writev(fileno(fp), &iov[0], 2) == -1)
356 		err(1, "writev");
357 }
358 
359 static void
360 consume(FILE *fp, off_t len, char *buf, int reg)
361 {
362 	size_t l;
363 
364 	if (reg) {
365 		if (fseeko(fp, len, SEEK_CUR) == -1)
366 			err(1, NULL);
367 	}
368 	else {
369 		while (len > 0) {
370 			l = MIN(DEF_BUF, len);
371 			if (fread(buf, sizeof(char), l, fp) != l)
372 				err(1, "cannot read buffer");
373 			len -= l;
374 		}
375 	}
376 }
377 
378 #define swapstamp(stamp) do { \
379 	if (stamp.scr_direction > 0xff) { \
380 		stamp.scr_len = bswap64(stamp.scr_len); \
381 		stamp.scr_sec = bswap64(stamp.scr_sec); \
382 		stamp.scr_usec = bswap32(stamp.scr_usec); \
383 		stamp.scr_direction = bswap32(stamp.scr_direction); \
384 	} \
385 } while (0/*CONSTCOND*/)
386 
387 static void
388 playback(FILE *fp)
389 {
390 	struct timespec tsi, tso;
391 	struct stamp stamp;
392 	struct stat pst;
393 	char buf[DEF_BUF];
394 	off_t nread, save_len;
395 	size_t l;
396 	time_t tclock;
397 	int reg;
398 
399 	if (fstat(fileno(fp), &pst) == -1)
400 		err(1, "fstat failed");
401 
402 	reg = S_ISREG(pst.st_mode);
403 
404 	for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
405 		if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
406 			if (reg)
407 				err(1, "reading playback header");
408 			else
409 				break;
410 		}
411 		swapstamp(stamp);
412 		save_len = sizeof(stamp);
413 
414 		if (reg && stamp.scr_len >
415 		    (uint64_t)(pst.st_size - save_len) - nread)
416 			errx(1, "invalid stamp");
417 
418 		save_len += stamp.scr_len;
419 		tclock = stamp.scr_sec;
420 		tso.tv_sec = stamp.scr_sec;
421 		tso.tv_nsec = stamp.scr_usec * 1000;
422 
423 		switch (stamp.scr_direction) {
424 		case 's':
425 			if (!qflg)
426 			    (void)printf("Script started on %s",
427 				ctime(&tclock));
428 			tsi = tso;
429 			(void)consume(fp, stamp.scr_len, buf, reg);
430 			break;
431 		case 'e':
432 			if (!qflg)
433 				(void)printf("\nScript done on %s",
434 				    ctime(&tclock));
435 			(void)consume(fp, stamp.scr_len, buf, reg);
436 			break;
437 		case 'i':
438 			/* throw input away */
439 			(void)consume(fp, stamp.scr_len, buf, reg);
440 			break;
441 		case 'o':
442 			tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
443 			tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
444 			if (tsi.tv_nsec < 0) {
445 				tsi.tv_sec -= 1;
446 				tsi.tv_nsec += 1000000000;
447 			}
448 			if (usesleep)
449 				(void)nanosleep(&tsi, NULL);
450 			tsi = tso;
451 			while (stamp.scr_len > 0) {
452 				l = MIN(DEF_BUF, stamp.scr_len);
453 				if (fread(buf, sizeof(char), l, fp) != l)
454 					err(1, "cannot read buffer");
455 
456 				(void)write(STDOUT_FILENO, buf, l);
457 				stamp.scr_len -= l;
458 			}
459 			break;
460 		default:
461 			errx(1, "invalid direction");
462 		}
463 	}
464 	(void)fclose(fp);
465 	exit(0);
466 }
467