xref: /netbsd-src/usr.bin/script/script.c (revision 4511d3297e9ee26fc8486a62a7caa4a42cebb6d3)
1 /*	$NetBSD: script.c,v 1.12 2006/06/14 16:05:38 liamjfoy Exp $	*/
2 
3 /*
4  * Copyright (c) 1980, 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1980, 1992, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)script.c	8.1 (Berkeley) 6/6/93";
41 #endif
42 __RCSID("$NetBSD: script.c,v 1.12 2006/06/14 16:05:38 liamjfoy Exp $");
43 #endif /* not lint */
44 
45 #include <sys/types.h>
46 #include <sys/wait.h>
47 #include <sys/stat.h>
48 #include <sys/ioctl.h>
49 #include <sys/time.h>
50 #include <sys/param.h>
51 #include <sys/uio.h>
52 
53 #include <err.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <paths.h>
57 #include <signal.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <termios.h>
62 #include <time.h>
63 #include <tzfile.h>
64 #include <unistd.h>
65 #include <util.h>
66 
67 #define	DEF_BUF	65536
68 
69 struct stamp {
70 	uint64_t scr_len;	/* amount of data */
71 	uint64_t scr_sec;	/* time it arrived in seconds... */
72 	uint32_t scr_usec;	/* ...and microseconds */
73 	uint32_t scr_direction;	/* 'i', 'o', etc (also indicates endianness) */
74 };
75 
76 FILE	*fscript;
77 int	master, slave;
78 int	child, subchild;
79 int	outcc;
80 int	usesleep, rawout;
81 char	*fname;
82 
83 struct	termios tt;
84 
85 void	done(void);
86 void	dooutput(void);
87 void	doshell(void);
88 void	fail(void);
89 void	finish(int);
90 int	main(int, char **);
91 void	scriptflush(int);
92 void	record(FILE *, char *, size_t, int);
93 void	playback(FILE *);
94 
95 int
96 main(int argc, char *argv[])
97 {
98 	int cc;
99 	struct termios rtt;
100 	struct winsize win;
101 	int aflg, pflg, ch;
102 	char ibuf[BUFSIZ];
103 
104 	aflg = 0;
105 	pflg = 0;
106 	usesleep = 1;
107 	rawout = 0;
108 	while ((ch = getopt(argc, argv, "adpr")) != -1)
109 		switch(ch) {
110 		case 'a':
111 			aflg = 1;
112 			break;
113 		case 'd':
114 			usesleep = 0;
115 			break;
116 		case 'p':
117 			pflg = 1;
118 			break;
119 		case 'r':
120 			rawout = 1;
121 			break;
122 		case '?':
123 		default:
124 			(void)fprintf(stderr, "usage: %s [-adpr] [file]\n",
125 			    getprogname());
126 			exit(1);
127 		}
128 	argc -= optind;
129 	argv += optind;
130 
131 	if (argc > 0)
132 		fname = argv[0];
133 	else
134 		fname = "typescript";
135 
136 	if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
137 		err(1, "fopen %s", fname);
138 
139 	if (pflg)
140 		playback(fscript);
141 
142 	(void)tcgetattr(STDIN_FILENO, &tt);
143 	(void)ioctl(STDIN_FILENO, TIOCGWINSZ, &win);
144 	if (openpty(&master, &slave, NULL, &tt, &win) == -1)
145 		err(1, "openpty");
146 
147 	(void)printf("Script started, output file is %s\n", fname);
148 	rtt = tt;
149 	cfmakeraw(&rtt);
150 	rtt.c_lflag &= ~ECHO;
151 	(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
152 
153 	(void)signal(SIGCHLD, finish);
154 	child = fork();
155 	if (child < 0) {
156 		warn("fork");
157 		fail();
158 	}
159 	if (child == 0) {
160 		subchild = child = fork();
161 		if (child < 0) {
162 			warn("fork");
163 			fail();
164 		}
165 		if (child)
166 			dooutput();
167 		else
168 			doshell();
169 	}
170 
171 	if (!rawout)
172 		(void)fclose(fscript);
173 	while ((cc = read(STDIN_FILENO, ibuf, BUFSIZ)) > 0) {
174 		if (rawout)
175 			record(fscript, ibuf, cc, 'i');
176 		(void)write(master, ibuf, cc);
177 	}
178 	done();
179 	/* NOTREACHED */
180 	return (0);
181 }
182 
183 void
184 finish(int signo)
185 {
186 	int die, pid, status;
187 
188 	die = 0;
189 	while ((pid = wait3(&status, WNOHANG, 0)) > 0)
190 		if (pid == child)
191 			die = 1;
192 
193 	if (die)
194 		done();
195 }
196 
197 void
198 dooutput()
199 {
200 	struct itimerval value;
201 	int cc;
202 	time_t tvec;
203 	char obuf[BUFSIZ];
204 
205 	(void)close(STDIN_FILENO);
206 	tvec = time(NULL);
207 	if (rawout)
208 		record(fscript, NULL, 0, 's');
209 	else
210 		(void)fprintf(fscript, "Script started on %s", ctime(&tvec));
211 
212 	(void)signal(SIGALRM, scriptflush);
213 	value.it_interval.tv_sec = SECSPERMIN / 2;
214 	value.it_interval.tv_usec = 0;
215 	value.it_value = value.it_interval;
216 	(void)setitimer(ITIMER_REAL, &value, NULL);
217 	for (;;) {
218 		cc = read(master, obuf, sizeof (obuf));
219 		if (cc <= 0)
220 			break;
221 		(void)write(1, obuf, cc);
222 		if (rawout)
223 			record(fscript, obuf, cc, 'o');
224 		else
225 			(void)fwrite(obuf, 1, cc, fscript);
226 		outcc += cc;
227 	}
228 	done();
229 }
230 
231 void
232 scriptflush(int signo)
233 {
234 	if (outcc) {
235 		(void)fflush(fscript);
236 		outcc = 0;
237 	}
238 }
239 
240 void
241 doshell()
242 {
243 	char *shell;
244 
245 	shell = getenv("SHELL");
246 	if (shell == NULL)
247 		shell = _PATH_BSHELL;
248 
249 	(void)close(master);
250 	(void)fclose(fscript);
251 	login_tty(slave);
252 	execl(shell, shell, "-i", NULL);
253 	warn("execl %s", shell);
254 	fail();
255 }
256 
257 void
258 fail()
259 {
260 
261 	(void)kill(0, SIGTERM);
262 	done();
263 }
264 
265 void
266 done()
267 {
268 	time_t tvec;
269 
270 	if (subchild) {
271 		tvec = time(NULL);
272 		if (rawout)
273 			record(fscript, NULL, 0, 'e');
274 		else
275 			(void)fprintf(fscript,"\nScript done on %s",
276 			    ctime(&tvec));
277 		(void)fclose(fscript);
278 		(void)close(master);
279 	} else {
280 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
281 		(void)printf("Script done, output file is %s\n", fname);
282 	}
283 	exit(0);
284 }
285 
286 void
287 record(FILE *fscript, char *buf, size_t cc, int direction)
288 {
289 	struct iovec iov[2];
290 	struct stamp stamp;
291 	struct timeval tv;
292 
293 	(void)gettimeofday(&tv, NULL);
294 	stamp.scr_len = cc;
295 	stamp.scr_sec = tv.tv_sec;
296 	stamp.scr_usec = tv.tv_usec;
297 	stamp.scr_direction = direction;
298 	iov[0].iov_len = sizeof(stamp);
299 	iov[0].iov_base = &stamp;
300 	iov[1].iov_len = cc;
301 	iov[1].iov_base = buf;
302 	if (writev(fileno(fscript), &iov[0], 2) == -1)
303 		err(1, "writev");
304 }
305 
306 #define swapstamp(stamp) do { \
307 	if (stamp.scr_direction > 0xff) { \
308 		stamp.scr_len = bswap64(stamp.scr_len); \
309 		stamp.scr_sec = bswap64(stamp.scr_sec); \
310 		stamp.scr_usec = bswap32(stamp.scr_usec); \
311 		stamp.scr_direction = bswap32(stamp.scr_direction); \
312 	} \
313 } while (0/*CONSTCOND*/)
314 
315 void
316 playback(FILE *fscript)
317 {
318 	struct timespec tsi, tso;
319 	struct stamp stamp;
320 	struct stat playback_stat;
321 	char buf[DEF_BUF];
322 	off_t nread, save_len;
323 	size_t l;
324 	time_t clock;
325 
326 	if (fstat(fileno(fscript), &playback_stat) == -1)
327 		err(1, "fstat failed");
328 
329 	for (nread = 0; nread < playback_stat.st_size; nread += save_len) {
330 		if (fread(&stamp, sizeof(stamp), 1, fscript) != 1)
331 			err(1, "reading playback header");
332 		swapstamp(stamp);
333 		save_len = sizeof(stamp);
334 
335 		if (stamp.scr_len >
336 		    (uint64_t)(playback_stat.st_size - save_len) - nread)
337 			err(1, "invalid stamp");
338 
339 		save_len += stamp.scr_len;
340 		clock = stamp.scr_sec;
341 		tso.tv_sec = stamp.scr_sec;
342 		tso.tv_nsec = stamp.scr_usec * 1000;
343 
344 		switch (stamp.scr_direction) {
345 		case 's':
346 			(void)printf("Script started on %s", ctime(&clock));
347 			tsi = tso;
348 			fseek(fscript, stamp.scr_len, SEEK_CUR);
349 			break;
350 		case 'e':
351 			(void)printf("\nScript done on %s", ctime(&clock));
352 			fseek(fscript, stamp.scr_len, SEEK_CUR);
353 			break;
354 		case 'i':
355 			/* throw input away */
356 			fseek(fscript, stamp.scr_len, SEEK_CUR);
357 			break;
358 		case 'o':
359 			tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
360 			tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
361 			if (tsi.tv_nsec < 0) {
362 				tsi.tv_sec -= 1;
363 				tsi.tv_nsec += 1000000000;
364 			}
365 			if (usesleep)
366 				(void)nanosleep(&tsi, NULL);
367 			tsi = tso;
368 			while (stamp.scr_len > 0) {
369 				l = MIN(DEF_BUF, stamp.scr_len);
370 				if (fread(buf, sizeof(char), l, fscript) != l)
371 					err(1, "cannot read buffer");
372 
373 				(void)write(STDOUT_FILENO, buf, l);
374 				stamp.scr_len -= l;
375 			}
376 			break;
377 		default:
378 			err(1, "invalid direction");
379 		}
380 	}
381 	(void)fclose(fscript);
382 	exit(0);
383 }
384