]> git.ipfire.org Git - thirdparty/util-linux.git/blob - term-utils/scriptreplay.c
scriptreplay: fix error path
[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 struct replay_log {
72 const char *streams; /* 'I'nput, 'O'utput or both */
73 const char *filename;
74 FILE *fp;
75 };
76
77 struct replay_step {
78 char type; /* 'I'nput, 'O'utput, ... */
79 double delay;
80 size_t size;
81
82 struct replay_log *data;
83 };
84
85 struct replay_setup {
86 struct replay_log *logs;
87 size_t nlogs;
88
89 struct replay_step step; /* current step */
90
91 FILE *timing_fp;
92 const char *timing_filename;
93 int timing_format;
94 int timing_line;
95
96 char default_type; /* type for REPLAY_TIMING_SIMPLE */
97 };
98
99 static void scriptreplay_init_debug(void)
100 {
101 __UL_INIT_DEBUG_FROM_ENV(scriptreplay, SCRIPTREPLAY_DEBUG_, 0, SCRIPTREPLAY_DEBUG);
102 }
103
104 static int ignore_line(FILE *f)
105 {
106 int c;
107
108 while((c = fgetc(f)) != EOF && c != '\n');
109 if (ferror(f))
110 return -errno;
111
112 DBG(LOG, ul_debug(" ignore line"));
113 return 0;
114 }
115
116 /* if timing file does not contains types of entries (old format) than use this
117 * type as the default */
118 static int replay_set_default_type(struct replay_setup *stp, char type)
119 {
120 assert(stp);
121 stp->default_type = type;
122
123 return 0;
124 }
125
126 static int replay_set_timing_file(struct replay_setup *stp, const char *filename)
127 {
128 int c, rc = 0;
129
130 assert(stp);
131 assert(filename);
132
133 stp->timing_filename = filename;
134 stp->timing_line = 0;
135
136 stp->timing_fp = fopen(filename, "r");
137 if (!stp->timing_fp)
138 rc = -errno;
139 else {
140 /* detect timing file format */
141 c = fgetc(stp->timing_fp);
142 if (c != EOF) {
143 if (isdigit((unsigned int) c))
144 stp->timing_format = REPLAY_TIMING_SIMPLE;
145 else
146 stp->timing_format = REPLAY_TIMING_MULTI;
147 ungetc(c, stp->timing_fp);
148 } else if (ferror(stp->timing_fp))
149 rc = -errno;
150 }
151
152 if (rc && stp->timing_fp) {
153 fclose(stp->timing_fp);
154 stp->timing_fp = NULL;
155 }
156
157 DBG(TIMING, ul_debug("timing file set to '%s' [rc=%d]", filename, rc));
158 return rc;
159 }
160
161 static int replay_associate_log(struct replay_setup *stp,
162 const char *streams, const char *filename)
163 {
164 struct replay_log *log;
165 int rc;
166
167 assert(stp);
168 assert(streams);
169 assert(filename);
170
171 stp->logs = xrealloc(stp->logs, (stp->nlogs + 1) * sizeof(*log));
172 log = &stp->logs[stp->nlogs];
173 stp->nlogs++;
174
175 log->filename = filename;
176 log->streams = streams;
177
178 /* open the file and skip the first line */
179 log->fp = fopen(filename, "r");
180 rc = log->fp == NULL ? -errno : ignore_line(log->fp);
181
182 DBG(LOG, ul_debug("accociate log file '%s' with '%s' [rc=%d]", filename, streams, rc));
183 return rc;
184 }
185
186 static int is_wanted_stream(char type, const char *streams)
187 {
188 if (streams == NULL)
189 return 1;
190 if (strchr(streams, type))
191 return 1;
192 return 0;
193 }
194
195 static int read_multistream_step(struct replay_step *step, FILE *f, char type)
196 {
197 int rc = 0;
198 char nl;
199
200 switch (type) {
201 case 'O': /* output */
202 case 'I': /* input */
203 rc = fscanf(f, "%lf %zu%c\n", &step->delay, &step->size, &nl);
204 if (rc != 3 || nl != '\n')
205 rc = -EINVAL;
206 else
207 rc = 0;
208 break;
209
210 case 'S': /* signal */
211 rc = ignore_line(f); /* not implemnted yet */
212 break;
213
214 case 'H': /* header */
215 rc = ignore_line(f); /* not implemnted yet */
216 break;
217 default:
218 break;
219 }
220
221 DBG(TIMING, ul_debug(" read step delay & size [rc=%d]", rc));
222 return rc;
223 }
224
225 static struct replay_log *replay_get_stream_log(struct replay_setup *stp, char stream)
226 {
227 size_t i;
228
229 for (i = 0; i < stp->nlogs; i++) {
230 struct replay_log *log = &stp->logs[i];
231
232 if (is_wanted_stream(stream, log->streams))
233 return log;
234 }
235 return NULL;
236 }
237
238 static int replay_seek_log(struct replay_log *log, size_t move)
239 {
240 DBG(LOG, ul_debug(" %s: seek ++ %zu", log->filename, move));
241 return fseek(log->fp, move, SEEK_CUR) == (off_t) -1 ? -errno : 0;
242 }
243
244 /* returns next step with pointer to the right log file for specified streams (e.g.
245 * "IOS" for in/out/signals) or all streams if stream is NULL.
246 *
247 * returns: 0 = success, <0 = error, 1 = done (EOF)
248 */
249 static int replay_get_next_step(struct replay_setup *stp, char *streams, struct replay_step **xstep)
250 {
251 struct replay_step *step;
252 int rc;
253 double ignored_delay = 0;
254
255 assert(stp);
256 assert(stp->timing_fp);
257 assert(xstep && *xstep);
258
259 step = &stp->step;
260 *xstep = NULL;
261
262 do {
263 struct replay_log *log = NULL;
264
265 rc = 1; /* done */
266 if (feof(stp->timing_fp))
267 break;
268
269 DBG(TIMING, ul_debug("reading next step"));
270
271 memset(step, 0, sizeof(*step));
272 stp->timing_line++;
273
274 switch (stp->timing_format) {
275 case REPLAY_TIMING_SIMPLE:
276 /* old format is the same as new format, but without <type> prefix */
277 rc = read_multistream_step(step, stp->timing_fp, stp->default_type);
278 if (rc == 0)
279 step->type = stp->default_type;
280 break;
281 case REPLAY_TIMING_MULTI:
282 rc = fscanf(stp->timing_fp, "%c ", &step->type);
283 if (rc != 1)
284 rc = -EINVAL;
285 else
286 rc = read_multistream_step(step,
287 stp->timing_fp,
288 step->type);
289 break;
290 }
291
292 if (rc)
293 break;; /* error */
294
295 DBG(TIMING, ul_debug(" step entry is '%c'", step->type));
296
297 log = replay_get_stream_log(stp, step->type);
298 if (log) {
299 if (is_wanted_stream(step->type, streams)) {
300 step->data = log;
301 *xstep = step;
302 DBG(LOG, ul_debug(" use %s as data source", log->filename));
303 goto done;
304 }
305 /* The step entry is unwanted, but we keep the right
306 * position in the log file although the data are ignored.
307 */
308 replay_seek_log(log, step->size);
309 } else
310 DBG(TIMING, ul_debug(" not found log for '%c' stream", step->type));
311
312 DBG(TIMING, ul_debug(" ignore step '%c' [delay=%f]",
313 step->type, step->delay));
314 ignored_delay += step->delay;
315 } while (rc == 0);
316
317 done:
318 if (ignored_delay)
319 step->delay += ignored_delay;
320
321 DBG(TIMING, ul_debug("reading next step done [rc=%d delay=%f (ignored=%f) size=%zu]",
322 rc, step->delay, ignored_delay, step->size));
323 return rc;
324 }
325
326 /* return: 0 = success, <0 = error, 1 = done (EOF) */
327 static int replay_emit_step_data(struct replay_step *step, int fd)
328 {
329 size_t ct;
330 int rc = 0;
331 char buf[BUFSIZ];
332
333 assert(step);
334 assert(step->size);
335 assert(step->data);
336 assert(step->data->fp);
337
338 for (ct = step->size; ct > 0; ) {
339 size_t len, cc;
340
341 cc = ct > sizeof(buf) ? sizeof(buf): ct;
342 len = fread(buf, 1, cc, step->data->fp);
343
344 if (!len) {
345 DBG(LOG, ul_debug("log data emit: failed to read log %m"));
346 break;
347 }
348
349 ct -= len;
350 cc = write(fd, buf, len);
351 if (cc != len) {
352 rc = -errno;
353 DBG(LOG, ul_debug("log data emit: failed write data %m"));
354 break;
355 }
356 }
357
358 if (ct && ferror(step->data->fp))
359 rc = -errno;
360 if (ct && feof(step->data->fp))
361 rc = 1;
362
363 DBG(LOG, ul_debug("log data emited [rc=%d size=%zu]", rc, step->size));
364 return rc;
365 }
366
367 static void __attribute__((__noreturn__))
368 usage(void)
369 {
370 FILE *out = stdout;
371 fputs(USAGE_HEADER, out);
372 fprintf(out,
373 _(" %s [options]\n"),
374 program_invocation_short_name);
375 fprintf(out,
376 _(" %s [-t] timingfile [typescript] [divisor]\n"),
377 program_invocation_short_name);
378
379 fputs(USAGE_SEPARATOR, out);
380 fputs(_("Play back terminal typescripts, using timing information.\n"), out);
381
382 fputs(USAGE_OPTIONS, out);
383 fputs(_(" -t, --timing <file> script timing log file\n"), out);
384 fputs(_(" -I, --log-in <file> script stdin log file\n"), out);
385 fputs(_(" -O, --log-out <file> script stdout log file (default)\n"), out);
386 fputs(_(" -B, --log-io <file> script stdin and stdout log file\n"), out);
387 fputs(_(" -s, --typescript <file> deprecated alist to -O\n"), out);
388
389 fputs(USAGE_SEPARATOR, out);
390 fputs(_(" -d, --divisor <num> speed up or slow down execution with time divisor\n"), out);
391 fputs(_(" -m, --maxdelay <num> wait at most this many seconds between updates\n"), out);
392 fputs(_(" -x, --stream <name> stream type (out, in or signal)\n"), out);
393 printf(USAGE_HELP_OPTIONS(25));
394
395 printf(USAGE_MAN_TAIL("scriptreplay(1)"));
396 exit(EXIT_SUCCESS);
397 }
398
399 static double
400 getnum(const char *s)
401 {
402 const double d = strtod_or_err(s, _("failed to parse number"));
403
404 if (isnan(d)) {
405 errno = EINVAL;
406 err(EXIT_FAILURE, "%s: %s", _("failed to parse number"), s);
407 }
408 return d;
409 }
410
411 static void
412 delay_for(double delay)
413 {
414 #ifdef HAVE_NANOSLEEP
415 struct timespec ts, remainder;
416 ts.tv_sec = (time_t) delay;
417 ts.tv_nsec = (delay - ts.tv_sec) * 1.0e9;
418
419 DBG(TIMING, ul_debug("going to sleep for %fs", delay));
420
421 while (-1 == nanosleep(&ts, &remainder)) {
422 if (EINTR == errno)
423 ts = remainder;
424 else
425 break;
426 }
427 #else
428 struct timeval tv;
429 tv.tv_sec = (long) delay;
430 tv.tv_usec = (delay - tv.tv_sec) * 1.0e6;
431 select(0, NULL, NULL, NULL, &tv);
432 #endif
433 }
434
435 static void appendchr(char *buf, size_t bufsz, int c)
436 {
437 size_t sz;
438
439 if (strchr(buf, c))
440 return; /* already in */
441
442 sz = strlen(buf);
443 if (sz + 1 < bufsz)
444 buf[sz] = c;
445 }
446
447 int
448 main(int argc, char *argv[])
449 {
450 struct replay_setup setup = { .nlogs = 0 };
451 struct replay_step *step;
452 char streams[6] = {0}; /* IOSI - in, out, signal,info */
453 const char *log_out = NULL,
454 *log_in = NULL,
455 *log_io = NULL,
456 *log_tm = NULL;
457 double divi = 1, maxdelay = 0;
458 int diviopt = FALSE, maxdelayopt = FALSE, idx;
459 int ch, rc;
460
461 static const struct option longopts[] = {
462 { "timing", required_argument, 0, 't' },
463 { "log-in", required_argument, 0, 'I'},
464 { "log-out", required_argument, 0, 'O'},
465 { "log-io", required_argument, 0, 'B'},
466 { "typescript", required_argument, 0, 's' },
467 { "divisor", required_argument, 0, 'd' },
468 { "maxdelay", required_argument, 0, 'm' },
469 { "stream", required_argument, 0, 'x' },
470 { "version", no_argument, 0, 'V' },
471 { "help", no_argument, 0, 'h' },
472 { NULL, 0, 0, 0 }
473 };
474 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
475 { 'O', 's' },
476 { 0 }
477 };
478 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
479 /* Because we use space as a separator, we can't afford to use any
480 * locale which tolerates a space in a number. In any case, script.c
481 * sets the LC_NUMERIC locale to C, anyway.
482 */
483 setlocale(LC_ALL, "");
484 setlocale(LC_NUMERIC, "C");
485
486 bindtextdomain(PACKAGE, LOCALEDIR);
487 textdomain(PACKAGE);
488 close_stdout_atexit();
489
490 scriptreplay_init_debug();
491
492 while ((ch = getopt_long(argc, argv, "B:I:O:t:s:d:m:x:Vh", longopts, NULL)) != -1) {
493
494 err_exclusive_options(ch, longopts, excl, excl_st);
495
496 switch(ch) {
497 case 't':
498 log_tm = optarg;
499 break;
500 case 'O':
501 case 's':
502 log_out = optarg;
503 break;
504 case 'I':
505 log_in = optarg;
506 break;
507 case 'B':
508 log_io = optarg;
509 break;
510 case 'd':
511 diviopt = TRUE;
512 divi = getnum(optarg);
513 break;
514 case 'm':
515 maxdelayopt = TRUE;
516 maxdelay = getnum(optarg);
517 break;
518 case 'x':
519 if (strcmp("in", optarg) == 0)
520 appendchr(streams, sizeof(streams), 'I');
521 else if (strcmp("out", optarg) == 0)
522 appendchr(streams, sizeof(streams), 'O');
523 else if (strcmp("signal", optarg) == 0)
524 appendchr(streams, sizeof(streams), 'S');
525 else
526 errx(EXIT_FAILURE, _("unsupported stream name: '%s'"), optarg);
527 break;
528 case 'V':
529 print_version(EXIT_SUCCESS);
530 case 'h':
531 usage();
532 default:
533 errtryhelp(EXIT_FAILURE);
534 }
535 }
536 argc -= optind;
537 argv += optind;
538 idx = 0;
539
540 if ((argc < 1 && !(log_out || log_in || log_io)) || argc > 3) {
541 warnx(_("wrong number of arguments"));
542 errtryhelp(EXIT_FAILURE);
543 }
544 if (!log_tm)
545 log_tm = argv[idx++];
546 if (!log_out && !log_in && !log_io)
547 log_out = idx < argc ? argv[idx++] : "typescript";
548
549 if (!diviopt)
550 divi = idx < argc ? getnum(argv[idx]) : 1;
551 if (maxdelay < 0)
552 maxdelay = 0;
553
554 if (replay_set_timing_file(&setup, log_tm) != 0)
555 err(EXIT_FAILURE, _("cannot open %s"), log_tm);
556
557 if (log_out && replay_associate_log(&setup, "O", log_out) != 0)
558 err(EXIT_FAILURE, _("cannot open %s"), log_out);
559
560 if (log_in && replay_associate_log(&setup, "I", log_in) != 0)
561 err(EXIT_FAILURE, _("cannot open %s"), log_in);
562
563 if (log_io && replay_associate_log(&setup, "IO", log_io) != 0)
564 err(EXIT_FAILURE, _("cannot open %s"), log_io);
565
566 if (!*streams) {
567 /* output is prefered default */
568 if (log_out || log_io)
569 appendchr(streams, sizeof(streams), 'O');
570 else if (log_in)
571 appendchr(streams, sizeof(streams), 'I');
572 }
573
574 replay_set_default_type(&setup,
575 *streams && streams[1] == '\0' ? *streams : 'O');
576
577 do {
578 rc = replay_get_next_step(&setup, streams, &step);
579 if (rc)
580 break;
581
582 step->delay /= divi;
583 if (maxdelayopt && step->delay > maxdelay)
584 step->delay = maxdelay;
585 if (step->delay > SCRIPT_MIN_DELAY)
586 delay_for(step->delay);
587
588 rc = replay_emit_step_data(step, STDOUT_FILENO);
589 } while (rc == 0);
590
591 if (step && rc < 0)
592 err(EXIT_FAILURE, _("%s: log file error"), step->data->filename);
593 else if (rc < 0)
594 err(EXIT_FAILURE, _("%s: line %d: timing file error"),
595 setup.timing_filename,
596 setup.timing_line);
597 printf("\n");
598 exit(EXIT_SUCCESS);
599 }