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