]> git.ipfire.org Git - thirdparty/util-linux.git/blobdiff - term-utils/scriptreplay.c
Make the ways of using output stream consistent in usage()
[thirdparty/util-linux.git] / term-utils / scriptreplay.c
index 778cd59d0a3a6d1efa2283256bbb582aa7877159..98501a83c9fbe8743742ded25f578c6af439f222 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, Karel Zak <kzak@redhat.com>
+ * Copyright (C) 2008-2019, Karel Zak <kzak@redhat.com>
  * Copyright (C) 2008, James Youngman <jay@gnu.org>
  *
  * This file is free software; you can redistribute it and/or modify
 #include <sys/select.h>
 #include <unistd.h>
 #include <getopt.h>
-
+#include <sys/time.h>
+#include <termios.h>
 
 #include "c.h"
-#include "debug.h"
 #include "xalloc.h"
 #include "closestream.h"
 #include "nls.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;
-
-       char                    default_type;   /* type for REPLAY_TIMING_SIMPLE */
-};
-
-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;
-}
-
-/* if timing file does not contains types of entries (old format) than use this
- * type as the default */
-static int replay_set_default_type(struct replay_setup *stp, char type)
-{
-       assert(stp);
-       stp->default_type = type;
-
-       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 && stp->timing_fp) {
-               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);
-
-       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 is the same as new format, but without <type> prefix */
-                       rc = read_multistream_step(step, stp->timing_fp, stp->default_type);
-                       if (rc == 0)
-                               step->type = stp->default_type;
-                       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;
-}
+#include "script-playutils.h"
 
 static void __attribute__((__noreturn__))
 usage(void)
@@ -381,18 +55,22 @@ usage(void)
 
        fputs(USAGE_OPTIONS, out);
        fputs(_(" -t, --timing <file>     script timing log file\n"), out);
+       fputs(_(" -T, --log-timing <file> alias to -t\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(_(" -s, --typescript <file> deprecated alias to -O\n"), out);
 
        fputs(USAGE_SEPARATOR, out);
+       fputs(_("     --summary           display overview about recorded session and exit\n"), 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);
-       fputs(_(" -x, --stream <name>     stream type (out, in or signal)\n"), out);
-       printf(USAGE_HELP_OPTIONS(25));
+       fputs(_(" -x, --stream <name>     stream type (out, in, signal or info)\n"), out);
+       fputs(_(" -c, --cr-mode <type>    CR char mode (auto, never, always)\n"), out);
+       fprintf(out, USAGE_HELP_OPTIONS(25));
 
-       printf(USAGE_MAN_TAIL("scriptreplay(1)"));
+       fprintf(out, USAGE_MAN_TAIL("scriptreplay(1)"));
        exit(EXIT_SUCCESS);
 }
 
@@ -409,14 +87,15 @@ getnum(const char *s)
 }
 
 static void
-delay_for(double delay)
+delay_for(struct timeval *delay)
 {
 #ifdef HAVE_NANOSLEEP
        struct timespec ts, remainder;
-       ts.tv_sec = (time_t) delay;
-       ts.tv_nsec = (delay - ts.tv_sec) * 1.0e9;
+       ts.tv_sec = (time_t) delay->tv_sec;
+       ts.tv_nsec = delay->tv_usec * 1000;
 
-       DBG(TIMING, ul_debug("going to sleep for %fs", delay));
+       DBG(TIMING, ul_debug("going to sleep for %"PRId64".%06"PRId64,
+                       (int64_t) delay->tv_sec, (int64_t) delay->tv_usec));
 
        while (-1 == nanosleep(&ts, &remainder)) {
                if (EINTR == errno)
@@ -425,14 +104,12 @@ delay_for(double delay)
                        break;
        }
 #else
-       struct timeval tv;
-       tv.tv_sec = (long) delay;
-       tv.tv_usec = (delay - tv.tv_sec) * 1.0e6;
-       select(0, NULL, NULL, NULL, &tv);
+       select(0, NULL, NULL, NULL, delay);
 #endif
 }
 
-static void appendchr(char *buf, size_t bufsz, int c)
+static void
+appendchr(char *buf, size_t bufsz, int c)
 {
        size_t sz;
 
@@ -444,29 +121,59 @@ static void appendchr(char *buf, size_t bufsz, int c)
                buf[sz] = c;
 }
 
+static int
+setterm(struct termios *backup)
+{
+       struct termios tattr;
+
+       if (tcgetattr(STDOUT_FILENO, backup) != 0) {
+               if (errno != ENOTTY) /* For debugger. */
+                       err(EXIT_FAILURE, _("unexpected tcgetattr failure"));
+               return 0;
+       }
+       tattr = *backup;
+       cfmakeraw(&tattr);
+       tattr.c_lflag |= ISIG;
+       tattr.c_iflag |= IXON;
+       tcsetattr(STDOUT_FILENO, TCSANOW, &tattr);
+       return 1;
+}
+
 int
 main(int argc, char *argv[])
 {
-       struct replay_setup setup = { .nlogs = 0 };
-       struct replay_step *step;
+       static const struct timeval mindelay = { .tv_sec = 0, .tv_usec = 100 };
+       struct timeval maxdelay;
+
+       int isterm;
+       struct termios saved;
+
+       struct replay_setup *setup = NULL;
+       struct replay_step *step = NULL;
        char streams[6] = {0};          /* IOSI - in, out, signal,info */
        const char *log_out = NULL,
                   *log_in = NULL,
                   *log_io = NULL,
                   *log_tm = NULL;
-       double divi = 1, maxdelay = 0;
-       int diviopt = FALSE, maxdelayopt = FALSE, idx;
-       int ch, rc;
+       double divi = 1;
+       int diviopt = FALSE, idx;
+       int ch, rc, crmode = REPLAY_CRMODE_AUTO, summary = 0;
+       enum {
+               OPT_SUMMARY = CHAR_MAX + 1
+       };
 
        static const struct option longopts[] = {
+               { "cr-mode",    required_argument,      0, 'c' },
                { "timing",     required_argument,      0, 't' },
-               { "log-in",     required_argument,      0, 'I'},
-               { "log-out",    required_argument,      0, 'O'},
-               { "log-io",     required_argument,      0, 'B'},
+               { "log-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' },
                { "stream",     required_argument,      0, 'x' },
+               { "summary",    no_argument,            0, OPT_SUMMARY },
                { "version",    no_argument,            0, 'V' },
                { "help",       no_argument,            0, 'h' },
                { NULL,         0, 0, 0 }
@@ -487,14 +194,26 @@ main(int argc, char *argv[])
        textdomain(PACKAGE);
        close_stdout_atexit();
 
-       scriptreplay_init_debug();
+       replay_init_debug();
+       timerclear(&maxdelay);
 
-       while ((ch = getopt_long(argc, argv, "B:I:O:t:s:d:m:x:Vh", longopts, NULL)) != -1) {
+       while ((ch = getopt_long(argc, argv, "B:c:I:O:T:t:s:d:m:x:Vh", longopts, NULL)) != -1) {
 
                err_exclusive_options(ch, longopts, excl, excl_st);
 
                switch(ch) {
+               case 'c':
+                       if (strcmp("auto", optarg) == 0)
+                               crmode = REPLAY_CRMODE_AUTO;
+                       else if (strcmp("never", optarg) == 0)
+                               crmode = REPLAY_CRMODE_NEVER;
+                       else if (strcmp("always", optarg) == 0)
+                               crmode = REPLAY_CRMODE_ALWAYS;
+                       else
+                               errx(EXIT_FAILURE, _("unsupported mode name: '%s'"), optarg);
+                       break;
                case 't':
+               case 'T':
                        log_tm = optarg;
                        break;
                case 'O':
@@ -512,8 +231,7 @@ main(int argc, char *argv[])
                        divi = getnum(optarg);
                        break;
                case 'm':
-                       maxdelayopt = TRUE;
-                       maxdelay = getnum(optarg);
+                       strtotimeval_or_err(optarg, &maxdelay, _("failed to parse maximal delay argument"));
                        break;
                case 'x':
                        if (strcmp("in", optarg) == 0)
@@ -522,9 +240,14 @@ main(int argc, char *argv[])
                                appendchr(streams, sizeof(streams), 'O');
                        else if (strcmp("signal", optarg) == 0)
                                appendchr(streams, sizeof(streams), 'S');
+                       else if (strcmp("info", optarg) == 0)
+                               appendchr(streams, sizeof(streams), 'H');
                        else
                                errx(EXIT_FAILURE, _("unsupported stream name: '%s'"), optarg);
                        break;
+               case OPT_SUMMARY:
+                       summary = 1;
+                       break;
                case 'V':
                        print_version(EXIT_SUCCESS);
                case 'h':
@@ -537,63 +260,81 @@ main(int argc, char *argv[])
        argv += optind;
        idx = 0;
 
-       if ((argc < 1 && !(log_out || log_in || log_io)) || argc > 3) {
-               warnx(_("wrong number of arguments"));
-               errtryhelp(EXIT_FAILURE);
-       }
-       if (!log_tm)
+       if (summary)
+               streams[0] = 'H', streams[1] = '\0';
+
+       if (!log_tm && idx < argc)
                log_tm = argv[idx++];
-       if (!log_out && !log_in && !log_io)
+       if (!log_out && !summary && !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;
 
-       if (replay_set_timing_file(&setup, log_tm) != 0)
+       if (!log_tm)
+               errx(EXIT_FAILURE, _("timing file not specified"));
+       if (!(log_out || log_in || log_io) && !summary)
+               errx(EXIT_FAILURE, _("data log file not specified"));
+
+       setup = replay_new_setup();
+
+       if (replay_set_timing_file(setup, log_tm) != 0)
                err(EXIT_FAILURE, _("cannot open %s"), log_tm);
 
-       if (log_out && replay_associate_log(&setup, "O", log_out) != 0)
+       if (log_out && replay_associate_log(setup, "O", log_out) != 0)
                err(EXIT_FAILURE, _("cannot open %s"), log_out);
 
-       if (log_in && replay_associate_log(&setup, "I", log_in) != 0)
+       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)
+       if (log_io && replay_associate_log(setup, "IO", log_io) != 0)
                err(EXIT_FAILURE, _("cannot open %s"), log_io);
 
        if (!*streams) {
-               /* output is prefered default */
+               /* output is preferred default */
                if (log_out || log_io)
                        appendchr(streams, sizeof(streams), 'O');
                else if (log_in)
                        appendchr(streams, sizeof(streams), 'I');
        }
 
-       replay_set_default_type(&setup,
+       replay_set_default_type(setup,
                        *streams && streams[1] == '\0' ? *streams : 'O');
+       replay_set_crmode(setup, crmode);
+
+       if (divi != 1)
+               replay_set_delay_div(setup, divi);
+       if (timerisset(&maxdelay))
+               replay_set_delay_max(setup, &maxdelay);
+       replay_set_delay_min(setup, &mindelay);
+
+       isterm = setterm(&saved);
 
        do {
-               rc = replay_get_next_step(&setup, streams, &step);
+               rc = replay_get_next_step(setup, streams, &step);
                if (rc)
                        break;
 
-               step->delay /= divi;
-               if (maxdelayopt && step->delay > maxdelay)
-                       step->delay = maxdelay;
-               if (step->delay > SCRIPT_MIN_DELAY)
-                       delay_for(step->delay);
+               if (!summary) {
+                       struct timeval *delay = replay_step_get_delay(step);
 
-               rc = replay_emit_step_data(step, STDOUT_FILENO);
+                       if (delay && timerisset(delay))
+                               delay_for(delay);
+               }
+               rc = replay_emit_step_data(setup, step, STDOUT_FILENO);
        } while (rc == 0);
 
+       if (isterm)
+               tcsetattr(STDOUT_FILENO, TCSADRAIN, &saved);
+
        if (step && rc < 0)
-               err(EXIT_FAILURE, _("%s: log file error"), step->data->filename);
+               err(EXIT_FAILURE, _("%s: log file error"), replay_step_get_filename(step));
        else if (rc < 0)
                err(EXIT_FAILURE, _("%s: line %d: timing file error"),
-                               setup.timing_filename,
-                               setup.timing_line);
+                               replay_get_timing_file(setup),
+                               replay_get_timing_line(setup));
        printf("\n");
+       replay_free_setup(setup);
+
        exit(EXIT_SUCCESS);
 }