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