]> git.ipfire.org Git - thirdparty/util-linux.git/blob - term-utils/scriptreplay.c
78e2daa4d88ce2b537d4d93559ed238493374ef3
[thirdparty/util-linux.git] / term-utils / scriptreplay.c
1 /*
2 * Copyright (C) 2008, Karel Zak <kzak@redhat.com>
3 * Copyright (C) 2008, James Youngman <jay@gnu.org>
4 *
5 * This file is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This file is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 *
16 * Based on scriptreplay.pl by Joey Hess <joey@kitenet.net>
17 */
18
19 #include <stdio.h>
20 #include <stdarg.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <time.h>
25 #include <limits.h>
26 #include <math.h>
27 #include <sys/select.h>
28 #include <unistd.h>
29 #include <getopt.h>
30
31
32 #include "c.h"
33 #include "debug.h"
34 #include "xalloc.h"
35 #include "closestream.h"
36 #include "nls.h"
37 #include "strutils.h"
38 #include "optutils.h"
39
40 static UL_DEBUG_DEFINE_MASK(scriptreplay);
41 UL_DEBUG_DEFINE_MASKNAMES(scriptreplay) = UL_DEBUG_EMPTY_MASKNAMES;
42
43 #define SCRIPTREPLAY_DEBUG_INIT (1 << 1)
44 #define SCRIPTREPLAY_DEBUG_TIMING (1 << 2)
45 #define SCRIPTREPLAY_DEBUG_LOG (1 << 3)
46 #define SCRIPTREPLAY_DEBUG_MISC (1 << 4)
47 #define SCRIPTREPLAY_DEBUG_ALL 0xFFFF
48
49 #define DBG(m, x) __UL_DBG(scriptreplay, SCRIPTREPLAY_DEBUG_, m, x)
50 #define ON_DBG(m, x) __UL_DBG_CALL(scriptreplay, SCRIPTREPLAY_DEBUG_, m, x)
51
52 #define SCRIPT_MIN_DELAY 0.0001 /* from original sripreplay.pl */
53
54 /*
55 * The script replay is driven by timing file where each entry describes one
56 * step in the replay. The timing step may refer input or output (or
57 * signal, extra informations, etc.)
58 *
59 * The step data are stored in log files, the right log file for the step is
60 * selected from replay_setup.
61 *
62 * TODO: move struct replay_{log,step,setup} to script-playutils.c to make it
63 * usable for scriptlive(1) code.
64 */
65
66 enum {
67 REPLAY_TIMING_SIMPLE, /* timing info in classic "<delta> <offset>" format */
68 REPLAY_TIMING_MULTI /* multiple streams in format "<type> <delta> <offset|etc> */
69 };
70
71 /* CR to '\n' mode */
72 enum {
73 REPLAY_CRMODE_AUTO = 0,
74 REPLAY_CRMODE_NEVER,
75 REPLAY_CRMODE_ALWAYS
76 };
77
78 struct replay_log {
79 const char *streams; /* 'I'nput, 'O'utput or both */
80 const char *filename;
81 FILE *fp;
82
83 unsigned int noseek; /* do not seek in this log */
84 };
85
86 struct replay_step {
87 char type; /* 'I'nput, 'O'utput, ... */
88 double delay;
89 size_t size;
90
91 char *name; /* signals / heders */
92 char *value;
93
94 struct replay_log *data;
95 };
96
97 struct replay_setup {
98 struct replay_log *logs;
99 size_t nlogs;
100
101 struct replay_step step; /* current step */
102
103 FILE *timing_fp;
104 const char *timing_filename;
105 int timing_format;
106 int timing_line;
107
108 char default_type; /* type for REPLAY_TIMING_SIMPLE */
109 int crmode;
110 };
111
112 static void scriptreplay_init_debug(void)
113 {
114 __UL_INIT_DEBUG_FROM_ENV(scriptreplay, SCRIPTREPLAY_DEBUG_, 0, SCRIPTREPLAY_DEBUG);
115 }
116
117 static int ignore_line(FILE *f)
118 {
119 int c;
120
121 while((c = fgetc(f)) != EOF && c != '\n');
122 if (ferror(f))
123 return -errno;
124
125 DBG(LOG, ul_debug(" ignore line"));
126 return 0;
127 }
128
129 /* if timing file does not contains types of entries (old format) than use this
130 * type as the default */
131 static int replay_set_default_type(struct replay_setup *stp, char type)
132 {
133 assert(stp);
134 stp->default_type = type;
135
136 return 0;
137 }
138
139 static int replay_set_crmode(struct replay_setup *stp, int mode)
140 {
141 assert(stp);
142 stp->crmode = mode;
143
144 return 0;
145 }
146
147 static struct replay_log *replay_new_log(struct replay_setup *stp,
148 const char *streams,
149 const char *filename,
150 FILE *f)
151 {
152 struct replay_log *log;
153
154 assert(stp);
155 assert(streams);
156 assert(filename);
157
158 stp->logs = xrealloc(stp->logs, (stp->nlogs + 1) * sizeof(*log));
159 log = &stp->logs[stp->nlogs];
160 stp->nlogs++;
161
162 log->filename = filename;
163 log->streams = streams;
164 log->fp = f;
165
166 return log;
167 }
168
169 static int replay_set_timing_file(struct replay_setup *stp, const char *filename)
170 {
171 int c, rc = 0;
172
173 assert(stp);
174 assert(filename);
175
176 stp->timing_filename = filename;
177 stp->timing_line = 0;
178
179 stp->timing_fp = fopen(filename, "r");
180 if (!stp->timing_fp)
181 rc = -errno;
182 else {
183 /* detect timing file format */
184 c = fgetc(stp->timing_fp);
185 if (c != EOF) {
186 if (isdigit((unsigned int) c))
187 stp->timing_format = REPLAY_TIMING_SIMPLE;
188 else
189 stp->timing_format = REPLAY_TIMING_MULTI;
190 ungetc(c, stp->timing_fp);
191 } else if (ferror(stp->timing_fp))
192 rc = -errno;
193 }
194
195 if (rc && stp->timing_fp) {
196 fclose(stp->timing_fp);
197 stp->timing_fp = NULL;
198 }
199
200 /* create quasi-log for signals, headers, etc. */
201 if (rc == 0 && stp->timing_format == REPLAY_TIMING_MULTI) {
202 struct replay_log *log = replay_new_log(stp, "SH",
203 filename, stp->timing_fp);
204 if (!log)
205 rc = -ENOMEM;
206 else {
207 log->noseek = 1;
208 DBG(LOG, ul_debug("accociate log file '%s' with 'SH'", filename));
209 }
210 }
211
212 DBG(TIMING, ul_debug("timing file set to '%s' [rc=%d]", filename, rc));
213 return rc;
214 }
215
216
217 static int replay_associate_log(struct replay_setup *stp,
218 const char *streams, const char *filename)
219 {
220 FILE *f;
221 int rc;
222
223 assert(stp);
224 assert(streams);
225 assert(filename);
226
227 /* open the file and skip the first line */
228 f = fopen(filename, "r");
229 rc = f == NULL ? -errno : ignore_line(f);
230
231 if (rc == 0)
232 replay_new_log(stp, streams, filename, f);
233
234 DBG(LOG, ul_debug("accociate log file '%s' with '%s' [rc=%d]", filename, streams, rc));
235 return rc;
236 }
237
238 static int is_wanted_stream(char type, const char *streams)
239 {
240 if (streams == NULL)
241 return 1;
242 if (strchr(streams, type))
243 return 1;
244 return 0;
245 }
246
247 static void replay_reset_step(struct replay_step *step)
248 {
249 assert(step);
250
251 step->size = 0;
252 step->delay = 0;
253 step->data = NULL;
254 step->type = 0;
255 }
256
257 static int read_multistream_step(struct replay_step *step, FILE *f, char type)
258 {
259 int rc = 0;
260 char nl;
261
262
263 switch (type) {
264 case 'O': /* output */
265 case 'I': /* input */
266 rc = fscanf(f, "%lf %zu%c\n", &step->delay, &step->size, &nl);
267 if (rc != 3 || nl != '\n')
268 rc = -EINVAL;
269 else
270 rc = 0;
271 break;
272
273 case 'S': /* signal */
274 case 'H': /* header */
275 {
276 char buf[BUFSIZ];
277
278 rc = fscanf(f, "%lf ", &step->delay); /* delay */
279 if (rc != 1)
280 break;
281
282 rc = fscanf(f, "%s", buf); /* name */
283 if (rc != 1)
284 break;
285 step->name = strrealloc(step->name, buf);
286 if (!step->name)
287 err_oom();
288
289 if (!fgets(buf, sizeof(buf), f)) { /* value */
290 rc = -errno;
291 break;
292 }
293 if (*buf) {
294 strrem(buf, '\n');
295 step->value = strrealloc(step->value, buf);
296 if (!step->value)
297 err_oom();
298 }
299 rc = 0;
300 break;
301 }
302 default:
303 break;
304 }
305
306 DBG(TIMING, ul_debug(" read step delay & size [rc=%d]", rc));
307 return rc;
308 }
309
310 static struct replay_log *replay_get_stream_log(struct replay_setup *stp, char stream)
311 {
312 size_t i;
313
314 for (i = 0; i < stp->nlogs; i++) {
315 struct replay_log *log = &stp->logs[i];
316
317 if (is_wanted_stream(stream, log->streams))
318 return log;
319 }
320 return NULL;
321 }
322
323 static int replay_seek_log(struct replay_log *log, size_t move)
324 {
325 if (log->noseek)
326 return 0;
327
328 DBG(LOG, ul_debug(" %s: seek ++ %zu", log->filename, move));
329 return fseek(log->fp, move, SEEK_CUR) == (off_t) -1 ? -errno : 0;
330 }
331
332 /* returns next step with pointer to the right log file for specified streams (e.g.
333 * "IOS" for in/out/signals) or all streams if stream is NULL.
334 *
335 * returns: 0 = success, <0 = error, 1 = done (EOF)
336 */
337 static int replay_get_next_step(struct replay_setup *stp, char *streams, struct replay_step **xstep)
338 {
339 struct replay_step *step;
340 int rc;
341 double ignored_delay = 0;
342
343 assert(stp);
344 assert(stp->timing_fp);
345 assert(xstep && *xstep);
346
347 step = &stp->step;
348 *xstep = NULL;
349
350 do {
351 struct replay_log *log = NULL;
352
353 rc = 1; /* done */
354 if (feof(stp->timing_fp))
355 break;
356
357 DBG(TIMING, ul_debug("reading next step"));
358
359 replay_reset_step(step);
360 stp->timing_line++;
361
362 switch (stp->timing_format) {
363 case REPLAY_TIMING_SIMPLE:
364 /* old format is the same as new format, but without <type> prefix */
365 rc = read_multistream_step(step, stp->timing_fp, stp->default_type);
366 if (rc == 0)
367 step->type = stp->default_type;
368 break;
369 case REPLAY_TIMING_MULTI:
370 rc = fscanf(stp->timing_fp, "%c ", &step->type);
371 if (rc != 1)
372 rc = -EINVAL;
373 else
374 rc = read_multistream_step(step,
375 stp->timing_fp,
376 step->type);
377 break;
378 }
379
380 if (rc)
381 break;; /* error */
382
383 DBG(TIMING, ul_debug(" step entry is '%c'", step->type));
384
385 log = replay_get_stream_log(stp, step->type);
386 if (log) {
387 if (is_wanted_stream(step->type, streams)) {
388 step->data = log;
389 *xstep = step;
390 DBG(LOG, ul_debug(" use %s as data source", log->filename));
391 goto done;
392 }
393 /* The step entry is unwanted, but we keep the right
394 * position in the log file although the data are ignored.
395 */
396 replay_seek_log(log, step->size);
397 } else
398 DBG(TIMING, ul_debug(" not found log for '%c' stream", step->type));
399
400 DBG(TIMING, ul_debug(" ignore step '%c' [delay=%f]",
401 step->type, step->delay));
402 ignored_delay += step->delay;
403 } while (rc == 0);
404
405 done:
406 if (ignored_delay)
407 step->delay += ignored_delay;
408
409 DBG(TIMING, ul_debug("reading next step done [rc=%d delay=%f (ignored=%f) size=%zu]",
410 rc, step->delay, ignored_delay, step->size));
411 return rc;
412 }
413
414 /* return: 0 = success, <0 = error, 1 = done (EOF) */
415 static int replay_emit_step_data(struct replay_setup *stp, struct replay_step *step, int fd)
416 {
417 size_t ct;
418 int rc = 0, cr2nl = 0;
419 char buf[BUFSIZ];
420
421 assert(stp);
422 assert(step);
423 switch (step->type) {
424 case 'S':
425 assert(step->name);
426 assert(step->value);
427 dprintf(fd, "%s %s\n", step->name, step->value);
428 DBG(LOG, ul_debug("log signal emited"));
429 return 0;
430 case 'H':
431 assert(step->name);
432 assert(step->value);
433 dprintf(fd, "%10s: %s\n", step->name, step->value);
434 DBG(LOG, ul_debug("log signal emited"));
435 return 0;
436 default:
437 break; /* continue with real data */
438 }
439
440 assert(step->size);
441 assert(step->data);
442 assert(step->data->fp);
443
444 switch (stp->crmode) {
445 case REPLAY_CRMODE_AUTO:
446 if (step->type == 'I')
447 cr2nl = 1;
448 break;
449 case REPLAY_CRMODE_NEVER:
450 cr2nl = 0;
451 break;
452 case REPLAY_CRMODE_ALWAYS:
453 cr2nl = 1;
454 break;
455 }
456
457 for (ct = step->size; ct > 0; ) {
458 size_t len, cc;
459
460 cc = ct > sizeof(buf) ? sizeof(buf): ct;
461 len = fread(buf, 1, cc, step->data->fp);
462
463 if (!len) {
464 DBG(LOG, ul_debug("log data emit: failed to read log %m"));
465 break;
466 }
467
468 if (cr2nl) {
469 size_t i;
470
471 for (i = 0; i < len; i++) {
472 if (buf[i] == 0x0D)
473 buf[i] = '\n';
474 }
475 }
476
477 ct -= len;
478 cc = write(fd, buf, len);
479 if (cc != len) {
480 rc = -errno;
481 DBG(LOG, ul_debug("log data emit: failed write data %m"));
482 break;
483 }
484 }
485
486 if (ct && ferror(step->data->fp))
487 rc = -errno;
488 if (ct && feof(step->data->fp))
489 rc = 1;
490
491 DBG(LOG, ul_debug("log data emited [rc=%d size=%zu]", rc, step->size));
492 return rc;
493 }
494
495 static void __attribute__((__noreturn__))
496 usage(void)
497 {
498 FILE *out = stdout;
499 fputs(USAGE_HEADER, out);
500 fprintf(out,
501 _(" %s [options]\n"),
502 program_invocation_short_name);
503 fprintf(out,
504 _(" %s [-t] timingfile [typescript] [divisor]\n"),
505 program_invocation_short_name);
506
507 fputs(USAGE_SEPARATOR, out);
508 fputs(_("Play back terminal typescripts, using timing information.\n"), out);
509
510 fputs(USAGE_OPTIONS, out);
511 fputs(_(" -t, --timing <file> script timing log file\n"), out);
512 fputs(_(" -I, --log-in <file> script stdin log file\n"), out);
513 fputs(_(" -O, --log-out <file> script stdout log file (default)\n"), out);
514 fputs(_(" -B, --log-io <file> script stdin and stdout log file\n"), out);
515 fputs(_(" -s, --typescript <file> deprecated alist to -O\n"), out);
516
517 fputs(USAGE_SEPARATOR, out);
518 fputs(_(" -d, --divisor <num> speed up or slow down execution with time divisor\n"), out);
519 fputs(_(" -m, --maxdelay <num> wait at most this many seconds between updates\n"), out);
520 fputs(_(" -x, --stream <name> stream type (out, in, signal or info)\n"), out);
521 fputs(_(" -c, --cr-mode <type> CR char mode (auto, never, always)\n"), out);
522 printf(USAGE_HELP_OPTIONS(25));
523
524 printf(USAGE_MAN_TAIL("scriptreplay(1)"));
525 exit(EXIT_SUCCESS);
526 }
527
528 static double
529 getnum(const char *s)
530 {
531 const double d = strtod_or_err(s, _("failed to parse number"));
532
533 if (isnan(d)) {
534 errno = EINVAL;
535 err(EXIT_FAILURE, "%s: %s", _("failed to parse number"), s);
536 }
537 return d;
538 }
539
540 static void
541 delay_for(double delay)
542 {
543 #ifdef HAVE_NANOSLEEP
544 struct timespec ts, remainder;
545 ts.tv_sec = (time_t) delay;
546 ts.tv_nsec = (delay - ts.tv_sec) * 1.0e9;
547
548 DBG(TIMING, ul_debug("going to sleep for %fs", delay));
549
550 while (-1 == nanosleep(&ts, &remainder)) {
551 if (EINTR == errno)
552 ts = remainder;
553 else
554 break;
555 }
556 #else
557 struct timeval tv;
558 tv.tv_sec = (long) delay;
559 tv.tv_usec = (delay - tv.tv_sec) * 1.0e6;
560 select(0, NULL, NULL, NULL, &tv);
561 #endif
562 }
563
564 static void appendchr(char *buf, size_t bufsz, int c)
565 {
566 size_t sz;
567
568 if (strchr(buf, c))
569 return; /* already in */
570
571 sz = strlen(buf);
572 if (sz + 1 < bufsz)
573 buf[sz] = c;
574 }
575
576 int
577 main(int argc, char *argv[])
578 {
579 struct replay_setup setup = { .nlogs = 0 };
580 struct replay_step *step;
581 char streams[6] = {0}; /* IOSI - in, out, signal,info */
582 const char *log_out = NULL,
583 *log_in = NULL,
584 *log_io = NULL,
585 *log_tm = NULL;
586 double divi = 1, maxdelay = 0;
587 int diviopt = FALSE, maxdelayopt = FALSE, idx;
588 int ch, rc, crmode = REPLAY_CRMODE_AUTO;
589
590 static const struct option longopts[] = {
591 { "cr-mode", required_argument, 0, 'c' },
592 { "timing", required_argument, 0, 't' },
593 { "log-in", required_argument, 0, 'I'},
594 { "log-out", required_argument, 0, 'O'},
595 { "log-io", required_argument, 0, 'B'},
596 { "typescript", required_argument, 0, 's' },
597 { "divisor", required_argument, 0, 'd' },
598 { "maxdelay", required_argument, 0, 'm' },
599 { "stream", required_argument, 0, 'x' },
600 { "version", no_argument, 0, 'V' },
601 { "help", no_argument, 0, 'h' },
602 { NULL, 0, 0, 0 }
603 };
604 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
605 { 'O', 's' },
606 { 0 }
607 };
608 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
609 /* Because we use space as a separator, we can't afford to use any
610 * locale which tolerates a space in a number. In any case, script.c
611 * sets the LC_NUMERIC locale to C, anyway.
612 */
613 setlocale(LC_ALL, "");
614 setlocale(LC_NUMERIC, "C");
615
616 bindtextdomain(PACKAGE, LOCALEDIR);
617 textdomain(PACKAGE);
618 close_stdout_atexit();
619
620 scriptreplay_init_debug();
621
622 while ((ch = getopt_long(argc, argv, "B:c:I:O:t:s:d:m:x:Vh", longopts, NULL)) != -1) {
623
624 err_exclusive_options(ch, longopts, excl, excl_st);
625
626 switch(ch) {
627 case 'c':
628 if (strcmp("auto", optarg) == 0)
629 crmode = REPLAY_CRMODE_AUTO;
630 else if (strcmp("never", optarg) == 0)
631 crmode = REPLAY_CRMODE_NEVER;
632 else if (strcmp("always", optarg) == 0)
633 crmode = REPLAY_CRMODE_ALWAYS;
634 else
635 errx(EXIT_FAILURE, _("unsupported mode name: '%s'"), optarg);
636 break;
637 case 't':
638 log_tm = optarg;
639 break;
640 case 'O':
641 case 's':
642 log_out = optarg;
643 break;
644 case 'I':
645 log_in = optarg;
646 break;
647 case 'B':
648 log_io = optarg;
649 break;
650 case 'd':
651 diviopt = TRUE;
652 divi = getnum(optarg);
653 break;
654 case 'm':
655 maxdelayopt = TRUE;
656 maxdelay = getnum(optarg);
657 break;
658 case 'x':
659 if (strcmp("in", optarg) == 0)
660 appendchr(streams, sizeof(streams), 'I');
661 else if (strcmp("out", optarg) == 0)
662 appendchr(streams, sizeof(streams), 'O');
663 else if (strcmp("signal", optarg) == 0)
664 appendchr(streams, sizeof(streams), 'S');
665 else if (strcmp("info", optarg) == 0)
666 appendchr(streams, sizeof(streams), 'H');
667 else
668 errx(EXIT_FAILURE, _("unsupported stream name: '%s'"), optarg);
669 break;
670 case 'V':
671 print_version(EXIT_SUCCESS);
672 case 'h':
673 usage();
674 default:
675 errtryhelp(EXIT_FAILURE);
676 }
677 }
678 argc -= optind;
679 argv += optind;
680 idx = 0;
681
682 if (!log_tm && idx < argc)
683 log_tm = argv[idx++];
684 if (!log_out && !log_in && !log_io)
685 log_out = idx < argc ? argv[idx++] : "typescript";
686
687 if (!diviopt)
688 divi = idx < argc ? getnum(argv[idx]) : 1;
689 if (maxdelay < 0)
690 maxdelay = 0;
691
692 if (!log_tm)
693 errx(EXIT_FAILURE, _("timing file not specified"));
694 if (!(log_out || log_in || log_io))
695 errx(EXIT_FAILURE, _("data log file not specified"));
696
697 if (replay_set_timing_file(&setup, log_tm) != 0)
698 err(EXIT_FAILURE, _("cannot open %s"), log_tm);
699
700 if (log_out && replay_associate_log(&setup, "O", log_out) != 0)
701 err(EXIT_FAILURE, _("cannot open %s"), log_out);
702
703 if (log_in && replay_associate_log(&setup, "I", log_in) != 0)
704 err(EXIT_FAILURE, _("cannot open %s"), log_in);
705
706 if (log_io && replay_associate_log(&setup, "IO", log_io) != 0)
707 err(EXIT_FAILURE, _("cannot open %s"), log_io);
708
709 if (!*streams) {
710 /* output is prefered default */
711 if (log_out || log_io)
712 appendchr(streams, sizeof(streams), 'O');
713 else if (log_in)
714 appendchr(streams, sizeof(streams), 'I');
715 }
716
717 replay_set_default_type(&setup,
718 *streams && streams[1] == '\0' ? *streams : 'O');
719 replay_set_crmode(&setup, crmode);
720
721 do {
722 rc = replay_get_next_step(&setup, streams, &step);
723 if (rc)
724 break;
725
726 step->delay /= divi;
727 if (maxdelayopt && step->delay > maxdelay)
728 step->delay = maxdelay;
729 if (step->delay > SCRIPT_MIN_DELAY)
730 delay_for(step->delay);
731
732 rc = replay_emit_step_data(&setup, step, STDOUT_FILENO);
733 } while (rc == 0);
734
735 if (step && rc < 0)
736 err(EXIT_FAILURE, _("%s: log file error"), step->data->filename);
737 else if (rc < 0)
738 err(EXIT_FAILURE, _("%s: line %d: timing file error"),
739 setup.timing_filename,
740 setup.timing_line);
741 printf("\n");
742 exit(EXIT_SUCCESS);
743 }