File: replay.c

package info (click to toggle)
termdebug 2.2+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 456 kB
  • ctags: 685
  • sloc: ansic: 5,008; sh: 560; makefile: 48; lex: 46
file content (964 lines) | stat: -rw-r--r-- 27,217 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
/* Copyright (C) 2010,2013 G.P. Halkes
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3, as
   published by the Free Software Foundation.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/wait.h>
#include <float.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <stdarg.h>

#include "optionMacros.h"
#include "common.h"
#include "replay.h"
#include "input.h"
#ifdef HAVE_CURSES
#include "curses_handling.h"
#ifdef HAVE_UNISTRING
#include "write_stringlist.h"
#if defined(HAVE_CAIRO) && defined(HAVE_PTHREAD)
#include "picture_queue.h"
#endif
#endif
#endif

/*
TODO:

- add the posibility to require keypress for next send event (except 0 delay events)
- it may be a good idea to have a simultaneous replay mode such that one can
  verify wether the visual results are still the same. This would require some
  form of synchronisation between multiple instances of the replay program.
- restore the terminal size after completing the replay. This should be done
  the same for the view program.
- the information requests to the terminal may cause more problems: different
  version of the same terminal may respond differently. That would mean that
  the output may look slightly off. That is not so much of a problem. What is a
  problem though is that we should clear the input buffer before switching to
  interact mode. Furthermore, if we wish to rerecord for the new version of the
  terminal, we need the proper response and not the recorded one. This may
  require some new construct to make replay aware of this.
- allow user to specify different client to start from the command line
- should we allow some way to return to the original script after an interact command?

*/

#define BUFFER_SIZE 1024

typedef enum {
	ON_ERROR_ABORT,
	ON_ERROR_INTERACT,
	ON_ERROR_CONTINUE
} OnError;

static FILE *log_file;
static char *input;
static char *alert;
static double key_delay_scale = 1.0;
static double key_delay;
static td_bool display;
static OnError on_error = ON_ERROR_ABORT;
static td_bool no_resize;
static const char *log_name;
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
static td_bool visual_compare;
static td_bool describe;
#ifdef HAVE_CAIRO
static const char *picture_name;
#ifdef HAVE_PTHREAD
static const char *picture_series;
#endif
#endif
#endif

static td_bool resize_capable;
static td_bool exited;
static int status;
static struct timeval timestamp;
static int master;
static pid_t pid;
static int already_waited;

static port_pollfd fdset[2];

#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
static window_t *expectWin, *realWin;
#endif

static void printUsage(void) {
	printf("Usage: tdreplay [OPTIONS] <recording>\n");
	printf("  -a<cmd>, --alert=<cmd>              Run <cmd> on error\n");
	printf("  -d, --display                       Show the output of the running program\n");
	printf("  -e<action>, --on-error=<action>     On error perform <action> (one of\n"
	       "                                        interact, continue, abort)\n");
	printf("  -k<delay>, --key-delay=<delay>      Set key delay\n");
	printf("  -l<log>, --log=<log>                Save a log file to <log>\n");
	printf("  -R, --no-resize                     Do not try to resize the terminal\n");
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
	printf("  -v, --visual-compare                Check for visual equality\n");
	printf("  -D, --describe                      Print a description of the first visual difference found\n");
#ifdef HAVE_CAIRO
	printf("  -p<name>, --picture=<name>          Write a picture of the differences to <name>\n"
	       "                                        (only valid with -v)\n");
	printf("  -f<font>, --font=<font>             Use <font> to show text in picture.\n");
	printf("  -W<width>, --cell-width=<width>     Use <width> as cell width in picture.\n");
	printf("  -H<height>, --cell-height=<height>  Use <height> as cell width in picture.\n");
#ifdef HAVE_PTHREAD
	printf("  -P<name>, --picture-series=<name>   Create a series of picutes use <name> as template\n");
#endif
#endif
#endif
	printf("  -V, --version                       Print version and copyright information\n");
	exit(EXIT_SUCCESS);
}

static PARSE_FUNCTION(parse_options)
	OPTIONS
		OPTION('a', "alert", REQUIRED_ARG)
			alert = optArg;
		END_OPTION
		OPTION('d', "display", NO_ARG)
			display = td_true;
		END_OPTION
		OPTION('e', "on-error", REQUIRED_ARG)
			if (strcmp(optArg, "interact") == 0) {
				on_error = ON_ERROR_INTERACT;
			} else if (strcmp(optArg, "continue") == 0) {
				on_error = ON_ERROR_CONTINUE;
			} else if (strcmp(optArg, "abort") == 0) {
				on_error = ON_ERROR_ABORT;
			} else {
				fatal("Invalid argument for on-error option: %s\n", optArg);
			}
		END_OPTION
		OPTION('k', "key-delay", REQUIRED_ARG)
			while (*optArg && isspace(*optArg))
				optArg++;
			if (optArg[0] == '/') {
				optArg++;
				PARSE_DOUBLE(key_delay_scale, DBL_MIN, DBL_MAX);
				key_delay = 0;
			} else if (isdigit(*optArg)) {
				PARSE_INT(key_delay, 1, INT_MAX);
				key_delay_scale = 1.0;
			} else {
				fatal("Invalid argument for key-delay option: %s\n", optArg);
			}
		END_OPTION
		OPTION('l', "log", REQUIRED_ARG)
			log_name = optArg;
		END_OPTION
		OPTION('R', "no-resize", NO_ARG)
			no_resize = td_true;
		END_OPTION
		OPTION('v', "visual-compare", NO_ARG)
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
			visual_compare = td_true;
#else
			fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('p', "picture", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			if (picture_name != NULL)
				fatal("Option " OPTFMT " specified twice\n", OPTPRARG);
			picture_name = optArg;
#else
			fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('f', "font", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			option_font = optArg;
#else
			fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('W', "cell-width", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			PARSE_INT(cell_width, 6, 16);
#else
			fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('H', "cell-heigth", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			PARSE_INT(cell_width, 6, 24);
#else
			fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('P', "picture-series", REQUIRED_ARG)
#ifndef HAVE_CAIRO
			fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#else
#ifndef HAVE_PTHREAD
			fatal("termdebug was built without pthreads, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#else
			if (!check_fmt(optArg))
				fatal(OPTFMT " argument must have exactly one d-type printf conversion\n", OPTPRARG);
			picture_series = optArg;
#endif
#endif
		END_OPTION
		OPTION('D', "describe", NO_ARG)
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
			describe = td_true;
#else
			fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('h', "help", NO_ARG)
			printUsage();
		END_OPTION
		OPTION('V', "version", NO_ARG)
			fputs("tdreplay " VERSION_STRING "\nCopyright (C) 2010,2013 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */
			exit(0);
		END_OPTION

		DOUBLE_DASH
			NO_MORE_OPTIONS;
		END_OPTION

		fatal("Unknown option " OPTFMT "\n", OPTPRARG);
	NO_OPTION
		if (input != NULL)
			fatal("More than one recording specified\n");
		input = optcurrent;
	END_OPTIONS
	if (input == NULL)
		fatal("No recording specified\n");
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) && defined(HAVE_CAIRO) && defined(HAVE_PTHREAD)
	if (picture_series != NULL && !visual_compare)
		fatal("Picture series can only be generated in visual compare mode\n");
#endif
END_FUNCTION

static void interact(void);

static void end_client(void) {
	kill(pid, SIGTERM);

	/* Give client time to respond to SIGTERM */
	while (port_poll(fdset + 1, 1, 2000) < 0) {}
	HANDLE_SIG_BYTES()
		case SIGNAL_CHILD:
			if (waitpid(pid, &status, WNOHANG) == pid)
				return;
			break;
	END_HANDLE

	kill(pid, SIGKILL);
	waitpid(pid, &status, WNOHANG);
}

static void unexpected(const char *reason, const char *received, size_t recv_length, int line, ...) {
	(void) reason;

	if (alert != NULL) {
		/* Add reason to the environment to allow the user to be notified of the problem. */
		setenv("REASON", reason, 1);
		ignore_result(system(alert));
		/* Only alert user once. */
		alert = NULL;
	}

	if (log_file != NULL) {
		va_list args;

		fprintf(log_file, "!! ");
		va_start(args, line);
		vfprintf(log_file, reason, args);
		va_end(args);
		if (received) {
			fprintf(log_file, ": \n");
			write_escaped_string(log_file, received, recv_length);
		} else {
			fprintf(log_file, "\n");
		}
	}

	switch (on_error) {
		case ON_ERROR_ABORT: {
			va_list args;

			end_client();
			/* Reset tty to show message. */
			if (display) {
#ifdef HAVE_CURSES
				sanitize_term();
#endif
				reset_tty();
				putc('\n', stderr);
			}
			fprintf(stderr, "Different behaviour from client at line %d: ", line);

			va_start(args, line);
			vfprintf(stderr, reason, args);
			va_end(args);
			exit(EXIT_FAILURE);
		}
		case ON_ERROR_INTERACT:
			interact();
			/* We should not even get here, but just to make sure */
			exit(EXIT_SUCCESS);
		case ON_ERROR_CONTINUE:
			break;
		default:
			fatal("Internal error\n");
	}
}

static void unexpected_death(void) {
	if (alert != NULL)
		ignore_result(system(alert));

	if (log_file != NULL)
		fprintf(log_file, "!! Client stopped unexpectedly with status: %d\n", WEXITSTATUS(status));
	/* Reset tty to show message. */
	if (display)
		reset_tty();
	fprintf(stderr, "Client stopped unexpectedly with status: %d\n", WEXITSTATUS(status));
	exit(EXIT_FAILURE);
}

static void handle_signals(ExpNode *exp, const char *activity) {
	if (fdset[1].revents & PORT_POLLIN) {
		HANDLE_SIG_BYTES()
			case SIGNAL_CHILD:
				if (waitpid(pid, &status, WNOHANG | WUNTRACED) == pid) {
					unexpected("Process stopped unexpectedly while waiting %s", NULL, 0, exp->line, activity);
					if (WIFSTOPPED(status)) {
						if (display) {
							printf("Process has stopped. Will send continue signal in 3 seconds\n");
							sleep(3);
						}
						kill(pid, SIGCONT);
					} else {
						unexpected_death();
					}
				}
				break;
		END_HANDLE
	}
}

static void handle_client_output(ExpNode *exp, const char *activity) {
	if (fdset[0].revents & PORT_POLLIN) {
		char buffer[BUFFER_SIZE];
		ssize_t result;

		result = safe_read(master, buffer, sizeof(buffer));
		if (result <= 0)
			return;
		if (display)
			safe_write(STDOUT_FILENO, buffer, result);
		unexpected("Received unexpected output while waiting %s", buffer, result, exp->line, activity);
	}
}

static void set_window_size_internal(ExpNode *size) {
	struct winsize wsz;
	memset(&wsz, 0, sizeof(wsz));

	if (log_file != NULL)
		fprintf(log_file, "Changing window size to: %d %d\n", size->un.size.columns, size->un.size.rows);

	if (display && resize_capable && !no_resize) {
		char buffer[64];
		size_t result;
		result = sprintf(buffer, "\x1b[8;%d;%dt", size->un.size.rows, size->un.size.columns);
		safe_write(STDOUT_FILENO, buffer, result);
	}

	wsz.ws_col = size->un.size.columns;
	wsz.ws_row = size->un.size.rows;
	if (ioctl(master, TIOCSWINSZ, &wsz))
		fatal("Error setting window size: %s\n", strerror(errno));
}

static void set_window_size(ExpNode *size) {
	ssize_t result;
	int delay;
	struct timeval start, now;

	if (size->un.size.min_delay > 0)
		delay = size->un.size.min_delay;
	else if (key_delay)
		delay = key_delay;
	else
		delay = size->un.size.delay / key_delay_scale;

	if (delay < 0 || delay < already_waited)  {
		set_window_size_internal(size);
		already_waited = 0;
		return;
	}

	gettimeofday(&start, NULL);
	while (1) {
		result = port_poll(fdset, 2, delay - already_waited);

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
		}

		handle_signals(size, "to resize window");

		if (display)
			copy_attrs_to_terminal(master);

		gettimeofday(&now, NULL);
		already_waited += timevaldiff(start, now);

		if (result == 0 || delay <= already_waited) {
			set_window_size_internal(size);
			already_waited = 0;
			return;
		} else {
			handle_client_output(size, "to resize window");
		}
	}
}

static int get_next_delay(ExpNode *exp, int *min_delay) {
	*min_delay = 0;
	for (; exp != NULL; exp = exp->next) {
		if (exp->type == EXP_WINDOW_SIZE) {
			return exp->un.size.delay;
		} else if (exp->type == EXP_SEND) {
			if (exp->un.args->min_delay > 0)
				*min_delay = exp->un.args->min_delay;
			return exp->un.args->delay;
		}
	}
	return -1;
}

static void expect(ExpNode *exp) {
	static td_bool first_expect = td_true;
	StringListNode *current = exp->un.args;
	int todo = current->length;
	char buffer[BUFFER_SIZE];
	ssize_t result;
	struct timeval start, now;
	int remaining_timeout, timeout, min_delay;

	if (log_file != NULL) {
		fprintf(log_file, "Expecting client output: \n");
		write_escaped_string(log_file, current->string, current->length);
		fprintf(log_file, "\n");
	}

	if (key_delay) {
		timeout = get_next_delay(exp, &min_delay);

		if (key_delay < timeout || timeout < 0)
			timeout = key_delay;

		if (timeout < 10)
			timeout = 10;
	} else {
		timeout = get_next_delay(exp, &min_delay);
		timeout /= key_delay_scale;
		if (timeout < 10)
			timeout = 10;
	}

	if (min_delay > timeout)
		timeout = min_delay;

	remaining_timeout = timeout;

	/* The first time we try to read from the socket, we are faced with a
	   problem: the program start up time must be taken into account. Sometimes
	   the program may be slow to start, which would normally cause the timeout
	   to pass before the program is even started. Thus we cheat, and set the
	   initial timeout to a full second, and then reset the start time to the
	   first return from poll. */
	if (first_expect)
		remaining_timeout = 1000;

	gettimeofday(&start, NULL);
	while (current != NULL && remaining_timeout > 0) {
		result = port_poll(fdset, 2, remaining_timeout);

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
			continue;
		}

		/* See comment above. */
		if (first_expect) {
			first_expect = td_false;
			gettimeofday(&start, NULL);
		}

		handle_signals(exp, "for output");

		if (display)
			copy_attrs_to_terminal(master);

		if (result == 0) {
			unexpected("No output received within timeout\n", NULL, 0, exp->line);
			return;
		} else if (fdset[0].revents & PORT_POLLIN) {
			/* Read data from the client */
			result = safe_read(master, buffer, MIN((int) sizeof(buffer), todo));
			if (result <= 0)
				continue;

			if (display)
				safe_write(STDOUT_FILENO, buffer, result);

			/* Check that the data read from the client matches what we expect */
			if (memcmp(buffer, current->string + current->length - todo, result) == 0) {
				todo -= result;
				/* Prepare next string to wait for. The while loop takes care of
				   empty strings. */
				while (todo == 0 && current != NULL) {
					current = current->next;
					if (current == NULL && exp->next != NULL && exp->next->type == EXP_EXPECT) {
						exp = exp->next;
						current = exp->un.args;
					}

					if (current != NULL) {
						todo = current->length;
						if (log_file != NULL) {
							fprintf(log_file, "Expecting client output:\n");
							write_escaped_string(log_file, current->string, current->length);
							fprintf(log_file, "\n");
						}
					}
				}
			} else {
				unexpected("Different output received then expected", buffer, result, exp->line);
			}
		}
		gettimeofday(&now, NULL);
		remaining_timeout = timeout - timevaldiff(start, now);
	}

	if (current != NULL) {
		if (log_file != NULL) {
			fprintf(log_file, "Remaining expected client output:\n");
			write_escaped_string(log_file, current->string + current->length - todo, todo);
			fprintf(log_file, "\n");
		}
		unexpected("Differences after timeout", NULL, 0, exp->line);
	}
	already_waited = timevaldiff(start, now);
}

#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
static void visual_expect(ExpNode *exp) {
	static td_bool first_expect = td_true;
	char buffer[BUFFER_SIZE];
	ssize_t result;
	struct timeval start, now;
	int remaining_timeout, timeout, min_delay;
	td_bool do_handle_signals = td_true;

	win_write_stringlist(expectWin, exp->un.args);

	if (log_file != NULL) {
		StringListNode *string;
		fprintf(log_file, "Expecting client output:\n");
		string = exp->un.args;
		while (string != NULL) {
			for (; string != NULL; string = string->next) {
				write_escaped_string(log_file, string->string, string->length);
				fprintf(log_file, "\n");
			}
			if (exp->next != NULL && exp->next->type == EXP_EXPECT) {
				exp = exp->next;
				string = exp->un.args;
			}
		}
	}

	if (log_file != NULL)
		fprintf(log_file, "Received client output:\n");

	if (key_delay) {
		timeout = get_next_delay(exp, &min_delay);

		if (timeout == -1)
			do_handle_signals = td_false;

		if (key_delay < timeout || timeout < 0)
			timeout = key_delay;

		if (timeout < 10)
			timeout = 10;
	} else {
		timeout = get_next_delay(exp, &min_delay);
		if (timeout == -1)
			do_handle_signals = td_false;
		timeout /= key_delay_scale;
		if (timeout < 10)
			timeout = 10;
	}

	if (min_delay > timeout)
		timeout = min_delay;

	remaining_timeout = timeout;

	/* The first time we try to read from the socket, we are faced with a
	   problem: the program start up time must be taken into account. Sometimes
	   the program may be slow to start, which would normally cause the timeout
	   to pass before the program is even started. Thus we cheat, and set the
	   initial timeout to a full second, and then reset the start time to the
	   first return from poll. */
	if (first_expect)
		remaining_timeout = 1000;


	gettimeofday(&start, NULL);
	while (remaining_timeout > 0) {
		result = port_poll(fdset, 2, remaining_timeout);

		/* See comment above. */
		if (first_expect) {
			first_expect = td_false;
			gettimeofday(&start, NULL);
		}

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
			continue;
		}

		if (display)
			copy_attrs_to_terminal(master);


		if (fdset[0].revents & PORT_POLLIN) {
			/* Read data from the client */
			result = safe_read(master, buffer, sizeof(buffer));
			if (result <= 0)
				continue;

			if (display)
				safe_write(STDOUT_FILENO, buffer, result);

			win_write_data(realWin, buffer, result);
			if (log_file != NULL) {
				write_escaped_string(log_file, buffer, result);
				fprintf(log_file, "\n");
			}
		}

		if (fdset[1].revents & PORT_POLLIN) {
			if (do_handle_signals)
				handle_signals(exp, "for output");
			else
				break;
		}

		gettimeofday(&now, NULL);
		remaining_timeout = timeout - timevaldiff(start, now);
	}

#if defined(HAVE_CAIRO) && defined(HAVE_PTHREAD)
	if (picture_series != NULL) {
		static int step_count = 1;
		char output_name_buffer[1024];
		snprintf(output_name_buffer, sizeof(output_name_buffer), picture_series, step_count++);
		enqueue_pictures(expectWin, realWin, output_name_buffer);
	}
#endif

	if (!win_compare(expectWin, realWin, describe ? stderr : NULL)) {
#ifdef HAVE_CAIRO
		if (picture_name != NULL)
#ifdef HAVE_PTHREAD
			enqueue_pictures(expectWin, realWin, picture_name);
#else
			win_write_image(expectWin, realWin, picture_name);
#endif
#endif
		unexpected("Visual differences after timeout", NULL, 0, exp->line);
		describe = td_false;
	}
	already_waited = timevaldiff(start, now);
}
#endif

static void send_keys(ExpNode *keys) {
	StringListNode *current = keys->un.args;
	ssize_t result;

	while (current != NULL) {
		int delay;

		/* Calculate the delay that has to be taken into account before sending
		   the key(s) to the application. */
		if (current->delay - already_waited < 5) {
			/* The delay is so small, just send now before the terminal decides to continue.
			   This should solve issues like the one with vi, which sends information requests
			   to the terminal and then doesn't wait for the response. */
			if (display)
				copy_attrs_to_terminal(master);
			if (log_file != NULL) {
				fprintf(log_file, "Sending key(s): ");
				write_escaped_string(log_file, current->string, current->length);
				fprintf(log_file, "\n");
			}
			safe_write(master, current->string, current->length);
			current = current->next;
			already_waited = 0;
			continue;
		} else if (key_delay) {
			delay = key_delay;
		} else {
			delay = current->delay / key_delay_scale;
		}

		if (delay < current->min_delay - already_waited)
			delay = current->min_delay - already_waited;
		already_waited = 0;

		result = port_poll(fdset, 2, delay);

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
		}

		handle_signals(keys, "to send key(s)");

		if (display)
			copy_attrs_to_terminal(master);

		if (result == 0) {
			if (log_file != NULL) {
				fprintf(log_file, "Sending key(s): ");
				write_escaped_string(log_file, current->string, current->length);
				fprintf(log_file, "\n");
			}
			safe_write(master, current->string, current->length);
			current = current->next;
		} else {
			handle_client_output(keys, "to send key(s)");
		}
	}
}

static void handle_exit(ExpNode *exit_data) {
	if (WEXITSTATUS(status) != exit_data->un.number) {
		if (alert != NULL)
			ignore_result(system(alert));

		if (log_file != NULL)
			fprintf(log_file, "!! Program ended with different status: %d iso %d\n", WEXITSTATUS(status), exit_data->un.number);
		exit(EXIT_FAILURE);
	}
	if (log_file != NULL)
		fprintf(log_file, "Program ended with expected status: %d\n", exit_data->un.number);
	exit(EXIT_SUCCESS);
}

static void expect_signal(ExpNode *signal_data) {
	ssize_t result;

	if (log_file != NULL)
		fprintf(log_file, "Waiting for exit\n");

	while (1) {
		result = port_poll(fdset, 2, -1);

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
		}

		if (fdset[1].revents & PORT_POLLIN) {
			HANDLE_SIG_BYTES()
				case SIGNAL_CHILD:
					if (waitpid(pid, &status, WNOHANG | WUNTRACED) == pid) {
						if (WIFSTOPPED(status)) {
							if (signal_data->type == EXP_EXPECT_EXIT)
								unexpected("Process stopped unexpectedly while waiting for exit", NULL, 0, signal_data->line);
							if (display) {
								printf("Process has stopped. Will send continue signal in 3 seconds\n");
								sleep(3);
							}
							kill(pid, SIGCONT);
							if (signal_data->type == EXP_EXPECT_SUSPEND)
								return;
						} else {
							if (signal_data->type == EXP_EXPECT_EXIT)
								handle_exit(signal_data);
							else
								unexpected_death();
						}
					}
					break;
			END_HANDLE
		}

		if (display)
			copy_attrs_to_terminal(master);

		handle_client_output(signal_data, signal_data->type == EXP_EXPECT_EXIT ? "for exit" : "for suspend");
	}
}

static void interact(void) {
	copy_attrs_to_terminal(master);
	interact_loop(master, pid, NULL, -1);
	exit(EXIT_SUCCESS);
}

int tdreplay_main(int argc, char *argv[]) {
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
	struct winsize wsz;
#endif
	int slave;

	parse_options(argc, argv);

	if (display && !isatty(STDIN_FILENO))
		fatal("Can only replay to a terminal devices\n");

	if (log_name != NULL) {
		if ((log_file = fopen(log_name, "w")) == NULL)
			fatal("Can't open log: %s\n", strerror(errno));
		/* FIXME: do we want this??
		setvbuf(log_file, NULL, _IONBF, 0);
		*/
	}

	reset_lexer(input);
	parse();

	gettimeofday(&timestamp, NULL);

	if (display) {
		resize_capable = detect_resize_capable();
		install_signal_handler(SIGWINCH, sigwinch_handler, "SIGWINCH");
		/* Get terminal attributes. */
		save_tty();
	}
	install_signal_handler(SIGCHLD, sigchld_handler, "SIGCHLD");

	unsetenv("TERM");
	unsetenv("LINES");
	unsetenv("COLUMS");
	unsetenv("LANG");
	unsetenv("LC_CTYPE");

	if (port_openpty(&master, &slave, NULL) < 0)
		fatal("Error opening pty: %s\n", strerror(errno));

	set_non_block(STDIN_FILENO, "terminal", td_true);
	set_non_block(master, "pty", td_true);
	set_non_block(signal_pipe[PIPE_READ], "pipe", td_true);

	fdset[0].fd = master;
	fdset[0].events = PORT_POLLIN;
	fdset[1].fd = signal_pipe[PIPE_READ];
	fdset[1].events = PORT_POLLIN;

#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
	if (visual_compare) {
		const char *term;

		init_attr_map();

		if ((term = get_script_env(script, "TERM")) == NULL)
			fatal("Recording does not contain a TERM environment variable\n");
		setup_ti_strings(term, get_script_env(script, "LANG"));

		/* Get terminal size. */
		if (ioctl(STDIN_FILENO, TIOCGWINSZ, &wsz) < 0 || wsz.ws_col == 0 || wsz.ws_row == 0) {
			fprintf(stderr, "Warning: could not obtain window size: %s\n", strerror(errno));
			wsz.ws_col = 80;
			wsz.ws_row = 24;
		}

		if ((realWin = win_new(wsz.ws_row, wsz.ws_col)) == NULL)
			fatal("Out of memory\n");
		if ((expectWin = win_new(wsz.ws_row, wsz.ws_col)) == NULL)
			fatal("Out of memory\n");

#if defined(HAVE_CAIRO) && defined(HAVE_PTHREAD)
		if (picture_series != NULL || picture_name != NULL)
			start_picture_writer_thread();
#endif
	}
#endif


	while (script != NULL) {
		if (exited) {
			if (script->type != EXP_EXPECT_EXIT)
				unexpected_death();
			else
				handle_exit(script);
		}
		switch (script->type) {
			case EXP_START:
				pid = start_client(script, slave, log_file);
				break;
			case EXP_EXPECT:
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
				if (visual_compare)
					visual_expect(script);
				else
#endif
				expect(script);
				while (script->next != NULL && script->next->type == EXP_EXPECT)
					script = script->next;
				break;
			case EXP_SEND:
				send_keys(script);
				break;
			case EXP_EXPECT_EXIT:
			case EXP_EXPECT_SUSPEND:
				expect_signal(script);
				break;
			case EXP_INTERACT:
				if (display)
					interact();
				break;
			case EXP_WINDOW_SIZE:
				set_window_size(script);
				break;
			case EXP_ENV:
				if (log_file != NULL)
					fprintf(log_file, "Setting environment variable %s to %s\n", script->un.args->string, script->un.args->next->string);
				setenv(script->un.args->string, script->un.args->next->string, 0);
				break;
			case EXP_REQUIRE_VERSION:
				break;
			default:
				fatal("Internal error\n");
		}
		script = script->next;
	}
	end_client();
	return EXIT_SUCCESS;
}