1 /*
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 2010, 2012 David E. O'Brien
5 * Copyright (c) 1980, 1992, 1993
6 * The Regents of the University of California. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33 #include <sys/param.h>
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 #ifndef lint
40 static const char sccsid[] = "@(#)script.c 8.1 (Berkeley) 6/6/93";
41 #endif
42
43 #include <sys/wait.h>
44 #include <sys/stat.h>
45 #include <sys/ioctl.h>
46 #include <sys/time.h>
47 #include <sys/queue.h>
48 #include <sys/uio.h>
49 #include <sys/endian.h>
50 #include <dev/filemon/filemon.h>
51
52 #include <assert.h>
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 struct buf_elm {
75 TAILQ_ENTRY(buf_elm) link;
76 size_t rpos;
77 size_t len;
78 char ibuf[];
79 };
80
81 static FILE *fscript;
82 static int master, slave;
83 static int child;
84 static const char *fname;
85 static char *fmfname;
86 static int fflg, qflg, ttyflg;
87 static int usesleep, rawout, showexit;
88 static TAILQ_HEAD(, buf_elm) obuf_list = TAILQ_HEAD_INITIALIZER(obuf_list);
89 static volatile sig_atomic_t doresize;
90
91 static struct termios tt;
92
93 #ifndef TSTAMP_FMT
94 /* useful for tool and human reading */
95 # define TSTAMP_FMT "%n@ %s [%Y-%m-%d %T]%n"
96 #endif
97 static const char *tstamp_fmt = TSTAMP_FMT;
98 static int tflg;
99
100 static void done(int) __dead2;
101 static void doshell(char **);
102 static void finish(void);
103 static void record(FILE *, char *, size_t, int);
104 static void consume(FILE *, off_t, char *, int);
105 static void playback(FILE *) __dead2;
106 static void usage(void) __dead2;
107 static void resizeit(int);
108
109 int
main(int argc,char * argv[])110 main(int argc, char *argv[])
111 {
112 struct termios rtt, stt;
113 struct winsize win;
114 struct timespec tv, *tvp;
115 time_t tvec, start;
116 char obuf[BUFSIZ];
117 char ibuf[BUFSIZ];
118 sigset_t *pselmask, selmask;
119 fd_set rfd, wfd;
120 struct buf_elm *be;
121 ssize_t cc;
122 int aflg, Fflg, kflg, pflg, wflg, ch, k, n, fcm;
123 int flushtime, readstdin;
124 int fm_fd, fm_log;
125
126 aflg = Fflg = kflg = pflg = wflg = 0;
127 doresize = 0;
128 usesleep = 1;
129 rawout = 0;
130 flushtime = 30;
131 fm_fd = -1;
132 showexit = 0;
133
134 /*
135 * For normal operation, we'll leave pselmask == NULL so that pselect(2)
136 * leaves the signal mask alone. If -w is specified, we'll restore the
137 * process signal mask upon entry with SIGWINCH unblocked so that we can
138 * forward resize events properly.
139 */
140 sigemptyset(&selmask);
141 pselmask = NULL;
142
143 while ((ch = getopt(argc, argv, "adeFfkpqrT:t:w")) != -1)
144 switch (ch) {
145 case 'a':
146 aflg = 1;
147 break;
148 case 'd':
149 usesleep = 0;
150 break;
151 case 'e':
152 /* Default behavior, accepted for linux compat. */
153 break;
154 case 'F':
155 Fflg = 1;
156 break;
157 case 'f':
158 fflg = 1;
159 break;
160 case 'k':
161 kflg = 1;
162 break;
163 case 'p':
164 pflg = 1;
165 break;
166 case 'q':
167 qflg = 1;
168 break;
169 case 'r':
170 rawout = 1;
171 break;
172 case 't':
173 flushtime = atoi(optarg);
174 if (flushtime < 0)
175 err(1, "invalid flush time %d", flushtime);
176 break;
177 case 'T':
178 tflg = pflg = 1;
179 if (strchr(optarg, '%'))
180 tstamp_fmt = optarg;
181 break;
182 case 'w':
183 wflg = 1;
184 break;
185 case '?':
186 default:
187 usage();
188 }
189 argc -= optind;
190 argv += optind;
191
192 if (argc > 0) {
193 fname = argv[0];
194 argv++;
195 argc--;
196 } else
197 fname = "typescript";
198
199 if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
200 err(1, "%s", fname);
201
202 if (fflg) {
203 asprintf(&fmfname, "%s.filemon", fname);
204 if (!fmfname)
205 err(1, "%s.filemon", fname);
206 if ((fm_fd = open("/dev/filemon", O_RDWR | O_CLOEXEC)) == -1)
207 err(1, "open(\"/dev/filemon\", O_RDWR)");
208 if ((fm_log = open(fmfname,
209 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
210 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
211 err(1, "open(%s)", fmfname);
212 if (ioctl(fm_fd, FILEMON_SET_FD, &fm_log) < 0)
213 err(1, "Cannot set filemon log file descriptor");
214 }
215
216 if (pflg)
217 playback(fscript);
218
219 if (tcgetattr(STDIN_FILENO, &tt) == -1 ||
220 ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1) {
221 if (errno != ENOTTY) /* For debugger. */
222 err(1, "tcgetattr/ioctl");
223 if (openpty(&master, &slave, NULL, NULL, NULL) == -1)
224 err(1, "openpty");
225 } else {
226 if (openpty(&master, &slave, NULL, &tt, &win) == -1)
227 err(1, "openpty");
228 ttyflg = 1;
229 }
230 fcm = fcntl(master, F_GETFL);
231 if (fcm == -1)
232 err(1, "master F_GETFL");
233 fcm |= O_NONBLOCK;
234 if (fcntl(master, F_SETFL, fcm) == -1)
235 err(1, "master F_SETFL");
236
237 if (rawout)
238 record(fscript, NULL, 0, 's');
239
240 if (!qflg) {
241 tvec = time(NULL);
242 (void)printf("Script started, output file is %s\n", fname);
243 if (!rawout) {
244 (void)fprintf(fscript, "Script started on %s",
245 ctime(&tvec));
246 if (argv[0]) {
247 showexit = 1;
248 fprintf(fscript, "Command: ");
249 for (k = 0 ; argv[k] ; ++k)
250 fprintf(fscript, "%s%s", k ? " " : "",
251 argv[k]);
252 fprintf(fscript, "\n");
253 }
254 }
255 fflush(fscript);
256 if (fflg) {
257 (void)printf("Filemon started, output file is %s\n",
258 fmfname);
259 }
260 }
261 if (ttyflg) {
262 rtt = tt;
263 cfmakeraw(&rtt);
264 rtt.c_lflag &= ~ECHO;
265 (void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
266 }
267
268 assert(fflg ? fm_fd >= 0 : fm_fd < 0);
269
270 child = fork();
271 if (child < 0) {
272 warn("fork");
273 done(1);
274 }
275 if (child == 0) {
276 if (fflg) {
277 int pid;
278
279 pid = getpid();
280 if (ioctl(fm_fd, FILEMON_SET_PID, &pid) < 0)
281 err(1, "Cannot set filemon PID");
282 }
283
284 doshell(argv);
285 }
286 close(slave);
287
288 if (wflg) {
289 struct sigaction sa = { .sa_handler = resizeit };
290 sigset_t smask;
291
292 sigaction(SIGWINCH, &sa, NULL);
293
294 sigemptyset(&smask);
295 sigaddset(&smask, SIGWINCH);
296
297 if (sigprocmask(SIG_BLOCK, &smask, &selmask) != 0)
298 err(1, "Failed to block SIGWINCH");
299
300 /* Just in case SIGWINCH was blocked before we came in. */
301 sigdelset(&selmask, SIGWINCH);
302 pselmask = &selmask;
303 }
304
305 start = tvec = time(0);
306 readstdin = 1;
307 for (;;) {
308 FD_ZERO(&rfd);
309 FD_ZERO(&wfd);
310 FD_SET(master, &rfd);
311 if (readstdin)
312 FD_SET(STDIN_FILENO, &rfd);
313 if (!TAILQ_EMPTY(&obuf_list))
314 FD_SET(master, &wfd);
315 if (!readstdin && ttyflg) {
316 tv.tv_sec = 1;
317 tv.tv_nsec = 0;
318 tvp = &tv;
319 readstdin = 1;
320 } else if (flushtime > 0) {
321 tv.tv_sec = flushtime - (tvec - start);
322 tv.tv_nsec = 0;
323 tvp = &tv;
324 } else {
325 tvp = NULL;
326 }
327 n = pselect(master + 1, &rfd, &wfd, NULL, tvp, pselmask);
328 if (n < 0 && errno != EINTR)
329 break;
330
331 if (doresize) {
332 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &win) != -1)
333 ioctl(master, TIOCSWINSZ, &win);
334 doresize = 0;
335 }
336
337 if (n > 0 && FD_ISSET(STDIN_FILENO, &rfd)) {
338 cc = read(STDIN_FILENO, ibuf, BUFSIZ);
339 if (cc < 0)
340 break;
341 if (cc == 0) {
342 if (tcgetattr(master, &stt) == 0 &&
343 (stt.c_lflag & ICANON) != 0) {
344 (void)write(master, &stt.c_cc[VEOF], 1);
345 }
346 readstdin = 0;
347 }
348 if (cc > 0) {
349 if (rawout)
350 record(fscript, ibuf, cc, 'i');
351 be = malloc(sizeof(*be) + cc);
352 be->rpos = 0;
353 be->len = cc;
354 memcpy(be->ibuf, ibuf, cc);
355 TAILQ_INSERT_TAIL(&obuf_list, be, link);
356 }
357 }
358 if (n > 0 && FD_ISSET(master, &wfd)) {
359 while ((be = TAILQ_FIRST(&obuf_list)) != NULL) {
360 cc = write(master, be->ibuf + be->rpos,
361 be->len);
362 if (cc == -1) {
363 if (errno == EWOULDBLOCK ||
364 errno == EINTR)
365 break;
366 warn("write master");
367 done(1);
368 }
369 if (cc == 0)
370 break; /* retry later ? */
371 if (kflg && tcgetattr(master, &stt) >= 0 &&
372 ((stt.c_lflag & ECHO) == 0)) {
373 (void)fwrite(be->ibuf + be->rpos,
374 1, cc, fscript);
375 }
376 be->len -= cc;
377 if (be->len == 0) {
378 TAILQ_REMOVE(&obuf_list, be, link);
379 free(be);
380 } else {
381 be->rpos += cc;
382 }
383 }
384 }
385 if (n > 0 && FD_ISSET(master, &rfd)) {
386 cc = read(master, obuf, sizeof(obuf));
387 if (cc <= 0)
388 break;
389 (void)write(STDOUT_FILENO, obuf, cc);
390 if (rawout)
391 record(fscript, obuf, cc, 'o');
392 else
393 (void)fwrite(obuf, 1, cc, fscript);
394 }
395 tvec = time(0);
396 if (tvec - start >= flushtime) {
397 fflush(fscript);
398 start = tvec;
399 }
400 if (Fflg)
401 fflush(fscript);
402 }
403 finish();
404 done(0);
405 }
406
407 static void
usage(void)408 usage(void)
409 {
410 (void)fprintf(stderr,
411 "usage: script [-aeFfkpqrw] [-t time] [file [command ...]]\n");
412 (void)fprintf(stderr,
413 " script -p [-deq] [-T fmt] [file]\n");
414 exit(1);
415 }
416
417 static void
finish(void)418 finish(void)
419 {
420 int e, status;
421
422 if (waitpid(child, &status, 0) == child) {
423 if (WIFEXITED(status))
424 e = WEXITSTATUS(status);
425 else if (WIFSIGNALED(status))
426 e = WTERMSIG(status);
427 else /* can't happen */
428 e = 1;
429 done(e);
430 }
431 }
432
433 static void
doshell(char ** av)434 doshell(char **av)
435 {
436 const char *shell;
437
438 shell = getenv("SHELL");
439 if (shell == NULL)
440 shell = _PATH_BSHELL;
441
442 (void)close(master);
443 (void)fclose(fscript);
444 free(fmfname);
445 login_tty(slave);
446 setenv("SCRIPT", fname, 1);
447 if (av[0]) {
448 execvp(av[0], av);
449 warn("%s", av[0]);
450 } else {
451 execl(shell, shell, "-i", (char *)NULL);
452 warn("%s", shell);
453 }
454 exit(1);
455 }
456
457 static void
done(int eno)458 done(int eno)
459 {
460 time_t tvec;
461
462 if (ttyflg)
463 (void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
464 tvec = time(NULL);
465 if (rawout)
466 record(fscript, NULL, 0, 'e');
467 if (!qflg) {
468 if (!rawout) {
469 if (showexit)
470 (void)fprintf(fscript, "\nCommand exit status:"
471 " %d", eno);
472 (void)fprintf(fscript, "\nScript done on %s",
473 ctime(&tvec));
474 }
475 (void)printf("\nScript done, output file is %s\n", fname);
476 if (fflg) {
477 (void)printf("Filemon done, output file is %s\n",
478 fmfname);
479 }
480 }
481 (void)fclose(fscript);
482 (void)close(master);
483 exit(eno);
484 }
485
486 static void
record(FILE * fp,char * buf,size_t cc,int direction)487 record(FILE *fp, char *buf, size_t cc, int direction)
488 {
489 struct iovec iov[2];
490 struct stamp stamp;
491 struct timeval tv;
492
493 (void)gettimeofday(&tv, NULL);
494 stamp.scr_len = cc;
495 stamp.scr_sec = tv.tv_sec;
496 stamp.scr_usec = tv.tv_usec;
497 stamp.scr_direction = direction;
498 iov[0].iov_len = sizeof(stamp);
499 iov[0].iov_base = &stamp;
500 iov[1].iov_len = cc;
501 iov[1].iov_base = buf;
502 if (writev(fileno(fp), &iov[0], 2) == -1)
503 err(1, "writev");
504 }
505
506 static void
consume(FILE * fp,off_t len,char * buf,int reg)507 consume(FILE *fp, off_t len, char *buf, int reg)
508 {
509 size_t l;
510
511 if (reg) {
512 if (fseeko(fp, len, SEEK_CUR) == -1)
513 err(1, NULL);
514 } else {
515 while (len > 0) {
516 l = MIN(DEF_BUF, len);
517 if (fread(buf, sizeof(char), l, fp) != l)
518 err(1, "cannot read buffer");
519 len -= l;
520 }
521 }
522 }
523
524 #define swapstamp(stamp) do { \
525 if (stamp.scr_direction > 0xff) { \
526 stamp.scr_len = bswap64(stamp.scr_len); \
527 stamp.scr_sec = bswap64(stamp.scr_sec); \
528 stamp.scr_usec = bswap32(stamp.scr_usec); \
529 stamp.scr_direction = bswap32(stamp.scr_direction); \
530 } \
531 } while (0/*CONSTCOND*/)
532
533 static void
termset(void)534 termset(void)
535 {
536 struct termios traw;
537
538 if (tcgetattr(STDOUT_FILENO, &tt) == -1) {
539 if (errno != ENOTTY) /* For debugger. */
540 err(1, "tcgetattr");
541 return;
542 }
543 ttyflg = 1;
544 traw = tt;
545 cfmakeraw(&traw);
546 traw.c_lflag |= ISIG;
547 (void)tcsetattr(STDOUT_FILENO, TCSANOW, &traw);
548 }
549
550 static void
termreset(void)551 termreset(void)
552 {
553 if (ttyflg) {
554 tcsetattr(STDOUT_FILENO, TCSADRAIN, &tt);
555 ttyflg = 0;
556 }
557 }
558
559 static void
playback(FILE * fp)560 playback(FILE *fp)
561 {
562 struct timespec tsi, tso;
563 struct stamp stamp;
564 struct stat pst;
565 char buf[DEF_BUF];
566 off_t nread, save_len;
567 size_t l;
568 time_t tclock;
569 time_t lclock;
570 int reg;
571
572 if (fstat(fileno(fp), &pst) == -1)
573 err(1, "fstat failed");
574
575 reg = S_ISREG(pst.st_mode);
576 lclock = 0;
577
578 for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
579 if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
580 if (reg)
581 err(1, "reading playback header");
582 else
583 break;
584 }
585 swapstamp(stamp);
586 save_len = sizeof(stamp);
587
588 if (reg && stamp.scr_len >
589 (uint64_t)(pst.st_size - save_len) - nread)
590 errx(1, "invalid stamp");
591
592 save_len += stamp.scr_len;
593 tclock = stamp.scr_sec;
594 tso.tv_sec = stamp.scr_sec;
595 tso.tv_nsec = stamp.scr_usec * 1000;
596 if (nread == 0)
597 tsi = tso;
598
599 switch (stamp.scr_direction) {
600 case 's':
601 if (!qflg)
602 (void)printf("Script started on %s",
603 ctime(&tclock));
604 tsi = tso;
605 (void)consume(fp, stamp.scr_len, buf, reg);
606 termset();
607 atexit(termreset);
608 break;
609 case 'e':
610 termreset();
611 if (!qflg)
612 (void)printf("\nScript done on %s",
613 ctime(&tclock));
614 (void)consume(fp, stamp.scr_len, buf, reg);
615 break;
616 case 'i':
617 /* throw input away */
618 (void)consume(fp, stamp.scr_len, buf, reg);
619 break;
620 case 'o':
621 if (tflg) {
622 if (stamp.scr_len == 0)
623 continue;
624 if (tclock - lclock > 0) {
625 l = strftime(buf, sizeof buf, tstamp_fmt,
626 localtime(&tclock));
627 (void)write(STDOUT_FILENO, buf, l);
628 }
629 lclock = tclock;
630 } else {
631 tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
632 tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
633 if (tsi.tv_nsec < 0) {
634 tsi.tv_sec -= 1;
635 tsi.tv_nsec += 1000000000;
636 }
637 if (usesleep)
638 (void)nanosleep(&tsi, NULL);
639 tsi = tso;
640 }
641 while (stamp.scr_len > 0) {
642 l = MIN(DEF_BUF, stamp.scr_len);
643 if (fread(buf, sizeof(char), l, fp) != l)
644 err(1, "cannot read buffer");
645
646 (void)write(STDOUT_FILENO, buf, l);
647 stamp.scr_len -= l;
648 }
649 break;
650 default:
651 errx(1, "invalid direction");
652 }
653 }
654 (void)fclose(fp);
655 exit(0);
656 }
657
658 static void
resizeit(int signo __unused)659 resizeit(int signo __unused)
660 {
661 doresize = 1;
662 }
663