]> git.ipfire.org Git - thirdparty/util-linux.git/blobdiff - term-utils/scriptreplay.c
script: default to new format when new features expected
[thirdparty/util-linux.git] / term-utils / scriptreplay.c
index ecea592e009d29a0be2dfe3a19efb7dfcdf02744..3bc60d2562ba5a36d831b1f4e27a6ba0f2af3ab0 100644 (file)
 #include <unistd.h>
 #include <getopt.h>
 
+
+#include "c.h"
+#include "debug.h"
+#include "xalloc.h"
 #include "closestream.h"
 #include "nls.h"
-#include "c.h"
+#include "strutils.h"
+#include "optutils.h"
+
+static UL_DEBUG_DEFINE_MASK(scriptreplay);
+UL_DEBUG_DEFINE_MASKNAMES(scriptreplay) = UL_DEBUG_EMPTY_MASKNAMES;
+
+#define SCRIPTREPLAY_DEBUG_INIT        (1 << 1)
+#define SCRIPTREPLAY_DEBUG_TIMING (1 << 2)
+#define SCRIPTREPLAY_DEBUG_LOG (1 << 3)
+#define SCRIPTREPLAY_DEBUG_MISC        (1 << 4)
+#define SCRIPTREPLAY_DEBUG_ALL 0xFFFF
+
+#define DBG(m, x)       __UL_DBG(scriptreplay, SCRIPTREPLAY_DEBUG_, m, x)
+#define ON_DBG(m, x)    __UL_DBG_CALL(scriptreplay, SCRIPTREPLAY_DEBUG_, m, x)
 
 #define SCRIPT_MIN_DELAY 0.0001                /* from original sripreplay.pl */
 
+/*
+ * The script replay is driven by timing file where each entry describes one
+ * step in the replay. The timing step may refer input or output (or
+ * signal, extra informations, etc.)
+ *
+ * The step data are stored in log files, the right log file for the step is
+ * selected from replay_setup.
+ *
+ * TODO: move struct replay_{log,step,setup} to script-playutils.c to make it
+ * usable for scriptlive(1) code.
+ */
+
+enum {
+       REPLAY_TIMING_SIMPLE,           /* timing info in classic "<delta> <offset>" format */
+       REPLAY_TIMING_MULTI             /* multiple streams in format "<type> <delta> <offset|etc> */
+};
+
+struct replay_log {
+       const char      *streams;               /* 'I'nput, 'O'utput or both */
+       const char      *filename;
+       FILE            *fp;
+};
+
+struct replay_step {
+       char    type;           /* 'I'nput, 'O'utput, ... */
+       double  delay;
+       size_t  size;
+
+       struct replay_log *data;
+};
+
+struct replay_setup {
+       struct replay_log       *logs;
+       size_t                  nlogs;
+
+       struct replay_step      step;   /* current step */
+
+       FILE                    *timing_fp;
+       const char              *timing_filename;
+       int                     timing_format;
+       int                     timing_line;
+};
+
+static void scriptreplay_init_debug(void)
+{
+       __UL_INIT_DEBUG_FROM_ENV(scriptreplay, SCRIPTREPLAY_DEBUG_, 0, SCRIPTREPLAY_DEBUG);
+}
+
+static int ignore_line(FILE *f)
+{
+       int c;
+
+       while((c = fgetc(f)) != EOF && c != '\n');
+       if (ferror(f))
+               return -errno;
+
+       DBG(LOG, ul_debug("  ignore line"));
+       return 0;
+}
+
+static int replay_set_timing_file(struct replay_setup *stp, const char *filename)
+{
+       int c, rc = 0;
+
+       assert(stp);
+       assert(filename);
+
+       stp->timing_filename = filename;
+       stp->timing_line = 0;
+
+       stp->timing_fp = fopen(filename, "r");
+       if (!stp->timing_fp)
+               rc = -errno;
+       else {
+               /* detect timing file format */
+               c = fgetc(stp->timing_fp);
+               if (c != EOF) {
+                       if (isdigit((unsigned int) c))
+                               stp->timing_format = REPLAY_TIMING_SIMPLE;
+                       else
+                               stp->timing_format = REPLAY_TIMING_MULTI;
+                       ungetc(c, stp->timing_fp);
+               } else if (ferror(stp->timing_fp))
+                       rc = -errno;
+       }
+
+       if (rc) {
+               fclose(stp->timing_fp);
+               stp->timing_fp = NULL;
+       }
+
+       DBG(TIMING, ul_debug("timing file set to %s [rc=%d]", filename, rc));
+       return rc;
+}
+
+static int replay_associate_log(struct replay_setup *stp,
+                               const char *streams, const char *filename)
+{
+       struct replay_log *log;
+       int rc;
+
+       assert(stp);
+       assert(streams);
+       assert(filename);
+
+       stp->logs = xrealloc(stp->logs, (stp->nlogs + 1) *  sizeof(*log));
+       log = &stp->logs[stp->nlogs];
+       stp->nlogs++;
+
+       log->filename = filename;
+       log->streams = streams;
+
+       /* open the file and skip the first line */
+       log->fp = fopen(filename, "r");
+       rc = log->fp == NULL ? -errno : ignore_line(log->fp);
+
+       DBG(LOG, ul_debug("accociate log file %s with '%s' [rc=%d]", filename, streams, rc));
+       return rc;
+}
+
+static int is_wanted_stream(char type, const char *streams)
+{
+       if (streams == NULL)
+               return 1;
+       if (strchr(streams, type))
+               return 1;
+       return 0;
+}
+
+static int read_multistream_step(struct replay_step *step, FILE *f, char type)
+{
+       int rc = 0;
+       char nl;
+
+       switch (type) {
+       case 'O': /* output */
+       case 'I': /* input */
+               rc = fscanf(f, "%lf %zu%c\n", &step->delay, &step->size, &nl);
+               if (rc != 3 || nl != '\n')
+                       rc = -EINVAL;
+               else
+                       rc = 0;
+               break;
+
+       case 'S': /* signal */
+               rc = ignore_line(f);    /* not implemnted yet */
+               break;
+
+       case 'H': /* header */
+               rc = ignore_line(f);    /* not implemnted yet */
+               break;
+       default:
+               break;
+       }
+
+       DBG(TIMING, ul_debug(" read step delay & size [rc=%d]", rc));
+       return rc;
+}
+
+static struct replay_log *replay_get_stream_log(struct replay_setup *stp, char stream)
+{
+       size_t i;
+
+       for (i = 0; i < stp->nlogs; i++) {
+               struct replay_log *log = &stp->logs[i];
+
+               if (is_wanted_stream(stream, log->streams))
+                       return log;
+       }
+       return NULL;
+}
+
+static int replay_seek_log(struct replay_log *log, size_t move)
+{
+       DBG(LOG, ul_debug(" %s: seek ++ %zu", log->filename, move));
+       return fseek(log->fp, move, SEEK_CUR) == (off_t) -1 ? -errno : 0;
+}
+
+/* returns next step with pointer to the right log file for specified streams (e.g.
+ * "IOS" for in/out/signals) or all streams if stream is NULL.
+ *
+ * returns: 0 = success, <0 = error, 1 = done (EOF)
+ */
+static int replay_get_next_step(struct replay_setup *stp, char *streams, struct replay_step **xstep)
+{
+       struct replay_step *step;
+       int rc;
+       double ignored_delay = 0;
+
+       assert(stp);
+       assert(stp->timing_fp);
+       assert(xstep && *xstep);
+
+       /* old format supports only 'O'utput */
+       if (stp->timing_format == REPLAY_TIMING_SIMPLE &&
+           !is_wanted_stream('O', streams))
+               return 1;
+
+
+       step = &stp->step;
+       *xstep = NULL;
+
+       do {
+               struct replay_log *log = NULL;
+
+               rc = 1; /* done */
+               if (feof(stp->timing_fp))
+                       break;
+
+               DBG(TIMING, ul_debug("reading next step"));
+
+               memset(step, 0, sizeof(*step));
+               stp->timing_line++;
+
+               switch (stp->timing_format) {
+               case REPLAY_TIMING_SIMPLE:
+                       /* old format supports only output entries and format is the same
+                        * as new format, but without <type> prefix */
+                       rc = read_multistream_step(step, stp->timing_fp, 'O');
+                       if (rc == 0)
+                               step->type = 'O';       /* 'O'utput */
+                       break;
+               case REPLAY_TIMING_MULTI:
+                       rc = fscanf(stp->timing_fp, "%c ", &step->type);
+                       if (rc != 1)
+                               rc = -EINVAL;
+                       else
+                               rc = read_multistream_step(step,
+                                               stp->timing_fp,
+                                               step->type);
+                       break;
+               }
+
+               if (rc)
+                       break;;         /* error */
+
+               DBG(TIMING, ul_debug(" step entry is '%c'", step->type));
+
+               log = replay_get_stream_log(stp, step->type);
+               if (log) {
+                       if (is_wanted_stream(step->type, streams)) {
+                               step->data = log;
+                               *xstep = step;
+                               DBG(LOG, ul_debug(" use %s as data source", log->filename));
+                               goto done;
+                       }
+                       /* The step entry is unwanted, but we keep the right
+                        * position in the log file although the data are ignored.
+                        */
+                       replay_seek_log(log, step->size);
+               } else
+                       DBG(TIMING, ul_debug(" not found log for '%c' stream", step->type));
+
+               DBG(TIMING, ul_debug(" ignore step '%c' [delay=%f]",
+                                       step->type, step->delay));
+               ignored_delay += step->delay;
+       } while (rc == 0);
+
+done:
+       if (ignored_delay)
+               step->delay += ignored_delay;
+
+       DBG(TIMING, ul_debug("reading next step done [rc=%d delay=%f (ignored=%f) size=%zu]",
+                               rc, step->delay, ignored_delay, step->size));
+       return rc;
+}
+
+/* return: 0 = success, <0 = error, 1 = done (EOF) */
+static int replay_emit_step_data(struct replay_step *step, int fd)
+{
+       size_t ct;
+       int rc = 0;
+       char buf[BUFSIZ];
+
+       assert(step);
+       assert(step->size);
+       assert(step->data);
+       assert(step->data->fp);
+
+       for (ct = step->size; ct > 0; ) {
+               size_t len, cc;
+
+               cc = ct > sizeof(buf) ? sizeof(buf): ct;
+               len = fread(buf, 1, cc, step->data->fp);
+
+               if (!len) {
+                       DBG(LOG, ul_debug("log data emit: failed to read log %m"));
+                       break;
+               }
+
+               ct -= len;
+               cc = write(fd, buf, len);
+               if (cc != len) {
+                       rc = -errno;
+                       DBG(LOG, ul_debug("log data emit: failed write data %m"));
+                       break;
+               }
+       }
+
+       if (ct && ferror(step->data->fp))
+               rc = -errno;
+       if (ct && feof(step->data->fp))
+               rc = 1;
+
+       DBG(LOG, ul_debug("log data emited [rc=%d size=%zu]", rc, step->size));
+       return rc;
+}
+
 static void __attribute__((__noreturn__))
-usage(FILE *out)
+usage(void)
 {
-       fputs(_("\nUsage:\n"), out);
+       FILE *out = stdout;
+       fputs(USAGE_HEADER, out);
+       fprintf(out,
+             _(" %s [options]\n"),
+             program_invocation_short_name);
        fprintf(out,
              _(" %s [-t] timingfile [typescript] [divisor]\n"),
              program_invocation_short_name);
 
-       fputs(_("\nOptions:\n"), out);
-       fputs(_(" -t, --timing <file>     script timing output file\n"
-               " -s, --typescript <file> script terminal session output file\n"
-               " -d, --divisor <num>     speed up or slow down execution with time divisor\n"
-               " -m, --maxdelay <num>    wait at most this many seconds between updates\n"
-               " -V, --version           output version information and exit\n"
-               " -h, --help              display this help and exit\n\n"), out);
+       fputs(USAGE_SEPARATOR, out);
+       fputs(_("Play back terminal typescripts, using timing information.\n"), out);
 
-       exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
+       fputs(USAGE_OPTIONS, out);
+       fputs(_(" -t, --timing <file>     script timing log file\n"), out);
+       fputs(_(" -I, --log-in <file>     script stdin log file\n"), out);
+       fputs(_(" -O, --log-out <file>    script stdout log file (default)\n"), out);
+       fputs(_(" -B, --log-io <file>     script stdin and stdout log file\n"), out);
+       fputs(_(" -s, --typescript <file> deprecated alist to -O\n"), out);
+
+       fputs(USAGE_SEPARATOR, out);
+       fputs(_(" -d, --divisor <num>     speed up or slow down execution with time divisor\n"), out);
+       fputs(_(" -m, --maxdelay <num>    wait at most this many seconds between updates\n"), out);
+       printf(USAGE_HELP_OPTIONS(25));
+
+       printf(USAGE_MAN_TAIL("scriptreplay(1)"));
+       exit(EXIT_SUCCESS);
 }
 
 static double
 getnum(const char *s)
 {
-       double d;
-       char *end;
-
-       errno = 0;
-       d = strtod(s, &end);
+       const double d = strtod_or_err(s, _("failed to parse number"));
 
-       if (end && *end != '\0')
-               errx(EXIT_FAILURE, _("expected a number, but got '%s'"), s);
-
-       if ((d == HUGE_VAL || d == -HUGE_VAL) && ERANGE == errno)
-               err(EXIT_FAILURE, _("divisor '%s'"), s);
-
-       if (!(d==d)) { /* did they specify "nan"? */
+       if (isnan(d)) {
                errno = EINVAL;
-               err(EXIT_FAILURE, _("divisor '%s'"), s);
+               err(EXIT_FAILURE, "%s: %s", _("failed to parse number"), s);
        }
        return d;
 }
@@ -83,6 +410,8 @@ delay_for(double delay)
        ts.tv_sec = (time_t) delay;
        ts.tv_nsec = (delay - ts.tv_sec) * 1.0e9;
 
+       DBG(TIMING, ul_debug("going to sleep for %fs", delay));
+
        while (-1 == nanosleep(&ts, &remainder)) {
                if (EINTR == errno)
                        ts = remainder;
@@ -97,47 +426,24 @@ delay_for(double delay)
 #endif
 }
 
-static void
-emit(FILE *fd, const char *filename, size_t ct)
-{
-       char buf[BUFSIZ];
-
-       while(ct) {
-               size_t len, cc;
-
-               cc = ct > sizeof(buf) ? sizeof(buf) : ct;
-               len = fread(buf, 1, cc, fd);
-
-               if (!len)
-                      break;
-
-               ct -= len;
-               cc = write(STDOUT_FILENO, buf, len);
-               if (cc != len)
-                       err(EXIT_FAILURE, _("write to stdout failed"));
-       }
-
-       if (!ct)
-               return;
-       if (feof(fd))
-               errx(EXIT_FAILURE, _("unexpected end of file on %s"), filename);
-
-       err(EXIT_FAILURE, _("failed to read typescript file %s"), filename);
-}
-
-
 int
 main(int argc, char *argv[])
 {
-       FILE *tfile, *sfile;
-       const char *sname = NULL, *tname = NULL;
+       struct replay_setup setup = { .nlogs = 0 };
+       struct replay_step *step;
+       const char *log_out = NULL,
+                  *log_in = NULL,
+                  *log_io = NULL,
+                  *log_tm = NULL;
        double divi = 1, maxdelay = 0;
-       int c, diviopt = FALSE, maxdelayopt = FALSE, idx;
-       unsigned long line;
-       char ch;
+       int diviopt = FALSE, maxdelayopt = FALSE, idx;
+       int ch, rc;
 
        static const struct option longopts[] = {
                { "timing",     required_argument,      0, 't' },
+               { "log-in",     required_argument,      0, 'I'},
+               { "log-out",    required_argument,      0, 'O'},
+               { "log-io",     required_argument,      0, 'B'},
                { "typescript", required_argument,      0, 's' },
                { "divisor",    required_argument,      0, 'd' },
                { "maxdelay",   required_argument,      0, 'm' },
@@ -145,7 +451,11 @@ main(int argc, char *argv[])
                { "help",       no_argument,            0, 'h' },
                { NULL,         0, 0, 0 }
        };
-
+       static const ul_excl_t excl[] = {       /* rows and cols in ASCII order */
+               { 'O', 's' },
+               { 0 }
+       };
+       int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
        /* Because we use space as a separator, we can't afford to use any
         * locale which tolerates a space in a number.  In any case, script.c
         * sets the LC_NUMERIC locale to C, anyway.
@@ -155,15 +465,27 @@ main(int argc, char *argv[])
 
        bindtextdomain(PACKAGE, LOCALEDIR);
        textdomain(PACKAGE);
-       atexit(close_stdout);
+       close_stdout_atexit();
+
+       scriptreplay_init_debug();
+
+       while ((ch = getopt_long(argc, argv, "B:I:O:t:s:d:m:Vh", longopts, NULL)) != -1) {
+
+               err_exclusive_options(ch, longopts, excl, excl_st);
 
-       while ((ch = getopt_long(argc, argv, "t:s:d:m:Vh", longopts, NULL)) != -1)
                switch(ch) {
                case 't':
-                       tname = optarg;
+                       log_tm = optarg;
                        break;
+               case 'O':
                case 's':
-                       sname = optarg;
+                       log_out = optarg;
+                       break;
+               case 'I':
+                       log_in = optarg;
+                       break;
+               case 'B':
+                       log_io = optarg;
                        break;
                case 'd':
                        diviopt = TRUE;
@@ -173,69 +495,65 @@ main(int argc, char *argv[])
                        maxdelayopt = TRUE;
                        maxdelay = getnum(optarg);
                        break;
+
                case 'V':
-                       printf(_("%s from %s\n"), program_invocation_short_name,
-                                                 PACKAGE_STRING);
-                       exit(EXIT_SUCCESS);
+                       print_version(EXIT_SUCCESS);
                case 'h':
-                       usage(stdout);
+                       usage();
                default:
-                       usage(stderr);
-                       }
+                       errtryhelp(EXIT_FAILURE);
+               }
+       }
        argc -= optind;
        argv += optind;
        idx = 0;
 
-       if ((argc < 1 && !tname) || argc > 3) {
+       if ((argc < 1 && !(log_out || log_in || log_io)) || argc > 3) {
                warnx(_("wrong number of arguments"));
-               usage(stderr);
+               errtryhelp(EXIT_FAILURE);
        }
-       if (!tname)
-               tname = argv[idx++];
-       if (!sname)
-               sname = idx < argc ? argv[idx++] : "typescript";
+       if (!log_tm)
+               log_tm = argv[idx++];
+       if (!log_out && !log_in && !log_io)
+               log_out = idx < argc ? argv[idx++] : "typescript";
+
        if (!diviopt)
                divi = idx < argc ? getnum(argv[idx]) : 1;
        if (maxdelay < 0)
                maxdelay = 0;
-       tfile = fopen(tname, "r");
-       if (!tfile)
-               err(EXIT_FAILURE, _("cannot open %s"), tname);
-       sfile = fopen(sname, "r");
-       if (!sfile)
-               err(EXIT_FAILURE, _("cannot open %s"), sname);
-
-       /* ignore the first typescript line */
-       while((c = fgetc(sfile)) != EOF && c != '\n');
-
-       for(line = 0; ; line++) {
-               double delay;
-               size_t blk;
-               char nl;
-               if (fscanf(tfile, "%lf %zu%c\n", &delay, &blk, &nl) != 3 ||
-                                                                nl != '\n') {
-                       if (feof(tfile))
-                               break;
-                       if (ferror(tfile))
-                               err(EXIT_FAILURE,
-                                       _("failed to read timing file %s"), tname);
-                       errx(EXIT_FAILURE,
-                               _("timings file %s: %lu: unexpected format"),
-                               tname, line);
-               }
-               delay /= divi;
 
-               if (maxdelayopt && delay > maxdelay)
-                       delay = maxdelay;
+       if (replay_set_timing_file(&setup, log_tm) != 0)
+               err(EXIT_FAILURE, _("cannot open %s"), log_tm);
 
-               if (delay > SCRIPT_MIN_DELAY)
-                       delay_for(delay);
+       if (log_out && replay_associate_log(&setup, "O", log_out) != 0)
+               err(EXIT_FAILURE, _("cannot open %s"), log_out);
 
-               emit(sfile, sname, blk);
-       }
+       if (log_in && replay_associate_log(&setup, "I", log_in) != 0)
+               err(EXIT_FAILURE, _("cannot open %s"), log_in);
+
+       if (log_io && replay_associate_log(&setup, "IO", log_io) != 0)
+               err(EXIT_FAILURE, _("cannot open %s"), log_io);
+
+       do {
+               rc = replay_get_next_step(&setup, "O", &step);
+               if (rc)
+                       break;
 
-       fclose(sfile);
-       fclose(tfile);
+               step->delay /= divi;
+               if (maxdelayopt && step->delay > maxdelay)
+                       step->delay = maxdelay;
+               if (step->delay > SCRIPT_MIN_DELAY)
+                       delay_for(step->delay);
+
+               rc = replay_emit_step_data(step, STDOUT_FILENO);
+       } while (rc == 0);
+
+       if (step && rc < 0)
+               err(EXIT_FAILURE, _("%s: log file error"), step->data->filename);
+       else if (rc < 0)
+               err(EXIT_FAILURE, _("%s: line %d: timing file error"),
+                               setup.timing_filename,
+                               setup.timing_line);
        printf("\n");
        exit(EXIT_SUCCESS);
 }