-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathttyrec.c
2148 lines (1948 loc) · 69 KB
/
ttyrec.c
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// vim: noai:sts=4:ts=4:sw=4:et
/* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
* Copyright 2001-2019 The ovh-ttyrec Authors. All rights reserved.
*
* This work is based on the original ttyrec, whose license text
* can be found below unmodified.
*
* Copyright (c) 1980 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/* 1999-02-22 Arkadiusz Miśkiewicz <misiek@misiek.eu.org>
* - added Native Language Support
*/
/* 2000-12-27 Satoru Takabayashi <satoru@namazu.org>
* - modify `script' to create `ttyrec'.
*/
/* 2001-2010 Several OVH contributors who will recognize themselves
* - lots of forgotten things
*/
/* 2010-2019 Stéphane Lesimple <stephane.lesimple@corp.ovh.com>
* - bugfixes (SIGWINCH handling and others)
* - BSD/MacOS compatibility
* - SIGUSR1 handling for ttyrec log rotation
* - input timeout locking mechanism
* - more things (see features in the README.md file)
*/
/*
* script
*/
#include <sys/types.h> // open, waitpid
#include <sys/stat.h> // open
#include <fcntl.h> // open, access
#include <termios.h> // tcsetattr
#include <sys/ioctl.h> // ioctl
#include <sys/time.h> // gettimeofday
#ifdef __HAIKU__
# include <posix/sys/wait.h> // waitpid
#else
# include <sys/wait.h> // waitpid
#endif
#include <libgen.h> // dirname
#include <stdio.h> // printf, ...
#include <unistd.h> // read, write, usleep, ...
#include <string.h> // strlen, memset, ...
#include <stdlib.h> // exit, free, getpt, ...
#include <errno.h> // errno
#include <pthread.h> // pthread_create
#include <signal.h> // sigaction
#include <sys/utsname.h> // uname
#include <time.h> // localtime
#include <getopt.h> // getopt_long
#include "configure.h"
#include "ttyrec.h"
#include "io.h"
#include "compress.h"
#ifdef HAVE_openpty
# if defined(HAVE_openpty_pty_h)
# include <pty.h>
# elif defined(HAVE_openpty_util_h)
# include <util.h>
# elif defined(HAVE_openpty_libutil_h)
# include <libutil.h>
# endif
#endif
// for ZSTD_versionNumber()
// and zstd_set_max_flush()
#ifdef HAVE_zstd
# include <zstd.h>
# include "compress_zstd.h"
#endif
#if defined(__linux__)
# define OS_STR "Linux"
#elif defined(__FreeBSD__)
# define OS_STR "FreeBSD"
#elif defined(__NetBSD__)
# define OS_STR "NetBSD"
#elif defined(__OpenBSD__)
# define OS_STR "OpenBSD"
#elif defined(__DragonFly__)
# define OS_STR "DragonFlyBSD"
#elif defined(__bsdi__)
# define OS_STR "BSD"
#elif defined(__SVR4) || defined(__svr4__) || defined(sun) || defined(__sun)
# define SUN_OS
# define OS_STR "SUN"
#elif defined(macintosh) || defined(Macintosh) || (defined(__APPLE__) && defined(__MACH__))
# define OS_STR "Darwin"
#elif defined(__HAIKU__)
# define OS_STR "Haiku"
#else
# define OS_STR "UnknownOS"
#endif
#ifdef HAVE_isastream
# include <stropts.h>
#endif
#ifdef SUN_OS
# include <sys/termios.h>
#endif
#ifdef SUN_OS
# define PID_T_FORMAT "%ld"
#else
# define PID_T_FORMAT "%d"
#endif
#define HAVE_inet_aton
#define HAVE_scsi_h
#define HAVE_kd_h
#if !defined(CDEL)
# if defined(_POSIX_VDISABLE)
# define CDEL _POSIX_VDISABLE
# elif defined(CDISABLE)
# define CDEL CDISABLE
# else /* not _POSIX_VISIBLE && not CDISABLE */
# define CDEL 255
# endif /* not _POSIX_VISIBLE && not CDISABLE */
#endif /* !CDEL */
#define printdbg(...) if (opt_debug > 0) { fprintf(stderr, __VA_ARGS__); }
#define printdbg2(...) if (opt_debug > 1) { fprintf(stderr, __VA_ARGS__); }
// functions used in the main() before the forks
void fixtty(void);
void help(void);
void set_ttyrec_file_name(char **nameptr);
void getmaster(void);
// functions used by the parent
void doinput(void);
void sigwinch_handler_parent(int signal);
void *timeout_watcher(void *arg);
void do_lock(void);
void handle_cheatcodes(char c);
// functions used by the child
void dooutput(void);
void sigwinch_handler_child(int signal);
// functions used by the subchild
void doshell(const char *, char **);
void getslave(void);
// sighandlers (parent and child)
void swing_output_file(int signal);
void unlock_session(int signal);
void lock_session(int signal);
void finish(int signal);
void sigterm_handler(int signal);
void sighup_handler(int signal);
// other functions used by parent and child
void done(int status);
void fail(void);
void print_termios_info(int fd, const char *prefix);
// ansi control codes
static const char *ansi_clear = "\033[2J";
static const char *ansi_home = "\033[H";
static const char *ansi_hidecursor = "\033[?25l";
static const char *ansi_showcursor = "\033[?25h";
static const char *ansi_save = "\033[?47h";
static const char *ansi_restore = "\033[?47l";
static const char *ansi_savecursor = "\0337";
static const char *ansi_restorecursor = "\0338";
static time_t last_activity = 0;
static time_t locked_since = 0;
static int lock_warned = 0;
static int kill_warned = 0;
static const char version[] = "1.1.7.1";
static FILE *fscript;
static int child;
static int subchild;
static char *me = NULL;
#ifdef HAVE_openpty
static int openpty_used = 0;
static int openpty_disable = 0;
#endif
// below: only used in notty mode
int stdout_pipe[2]; // subchild will write to it, child will read from it
int stderr_pipe[2]; // subchild will write to it, child will read from it
// below: only used in tty mode
static int master;
static int slave;
static char *fname = NULL;
static char *dname = NULL;
static char *uuid = NULL;
static char *namefmt = NULL;
static long timeout_lock = 0;
static long timeout_kill = 0;
static long warn_before_lock_seconds = 0;
static long warn_before_kill_seconds = 0;
static struct termios parent_stdin_termios;
static struct winsize parent_stdin_winsize;
static int parent_stdin_isatty = 0;
#if !defined(HAVE_openpty)
static char line[] = "/dev/ptyXX";
#endif
static long opt_compress_level = 0;
static int opt_zstd = 0;
static int opt_want_tty = 1; // never=0, auto=1, force=2
static int opt_append = 0;
static int opt_debug = 0;
static int opt_count_bytes = 0;
static int opt_cheatcodes = 0;
static int opt_stealth_stdout = 0;
static int opt_stealth_stderr = 0;
static char *opt_custom_message = NULL;
static int use_tty = 1; // no=0, yes=1
static int can_exit = 0;
static int childexit = 254;
int main(int argc, char **argv)
{
char *command = NULL;
char **params = NULL;
char *shell = NULL;
int legacy = 0;
int ch;
shell = getenv("SHELL");
if (shell == NULL)
{
shell = "/bin/sh";
}
while (1)
{
static struct option long_options[] =
{
/*
* "long-opt-name", a, b, c
* a: 1 if requires an arg, 0 otherwise
* b: always 0
* c: an optional char for the corresponding short-option, 0 otherwise
*/
{ "zstd", 0, 0, 0 },
{ "level", 1, 0, 'l' },
{ "verbose", 0, 0, 'v' },
{ "append", 0, 0, 'a' },
{ "cheatcodes", 0, 0, 'c' },
{ "no-cheatcodes", 0, 0, 'C' },
{ "shell-cmd", 1, 0, 'e' },
{ "dir", 1, 0, 'd' },
{ "output", 1, 0, 'f' },
{ "uuid", 1, 0, 'z' },
{ "no-openpty", 0, 0, 'p' },
{ "lock-timeout", 1, 0, 'l' },
{ "kill-timeout", 1, 0, 'k' },
{ "msg", 1, 0, 's' },
{ "count-bytes", 0, 0, 'n' },
{ "term", 1, 0, 'T' },
{ "stealth-stdout", 0, 0, 0 },
{ "stealth-stderr", 0, 0, 0 },
{ "version", 0, 0, 'V' },
{ "help", 0, 0, 'h' },
{ "max-flush-time", 1, 0, 0 },
{ "name-format", 1, 0, 'F' },
{ "warn-before-lock", 1, 0, 0 },
{ "warn-before-kill", 1, 0, 0 },
{ "help", 0, 0, 'h' },
{ "usage", 0, 0, 'h' },
{ 0, 0, 0, 0 }
};
int option_index = 0;
ch = getopt_long(argc, argv, "ZcCupVhvanf:z:d:t:T:k:s:e:l:F:", long_options, &option_index);
if (ch == -1)
{
break;
}
switch ((char)ch)
{
// long option without short-option counterpart
case 0:
if (strcmp(long_options[option_index].name, "zstd") == 0)
{
if (set_compress_mode(COMPRESS_ZSTD) != 0)
{
fprintf(stderr, "zstd support has not been enabled at compile time.\r\n");
fail();
}
opt_zstd++;
}
else if (strcmp(long_options[option_index].name, "max-flush-time") == 0)
{
#ifdef HAVE_zstd
errno = 0;
long max_flush_seconds = strtol(optarg, NULL, 10);
if ((errno != 0) || (max_flush_seconds <= 0))
{
help();
fprintf(stderr, "Invalid value passed to --%s (%s), expected a strictly positive integer\r\n", long_options[option_index].name, optarg);
exit(EXIT_FAILURE);
}
zstd_set_max_flush(max_flush_seconds);
#endif
}
else if (strcmp(long_options[option_index].name, "warn-before-lock") == 0)
{
errno = 0;
warn_before_lock_seconds = strtol(optarg, NULL, 10);
if ((errno != 0) || (warn_before_lock_seconds <= 0))
{
help();
fprintf(stderr, "Invalid value passed to --%s (%s), expected a strictly positive integer\r\n", long_options[option_index].name, optarg);
exit(EXIT_FAILURE);
}
}
else if (strcmp(long_options[option_index].name, "warn-before-kill") == 0)
{
errno = 0;
warn_before_kill_seconds = strtol(optarg, NULL, 10);
if ((errno != 0) || (warn_before_kill_seconds <= 0))
{
help();
fprintf(stderr, "Invalid value passed to --%s (%s), expected a strictly positive integer\r\n", long_options[option_index].name, optarg);
exit(EXIT_FAILURE);
}
}
else if (strcmp(long_options[option_index].name, "stealth-stdout") == 0)
{
opt_stealth_stdout = 1;
}
else if (strcmp(long_options[option_index].name, "stealth-stderr") == 0)
{
opt_stealth_stderr = 1;
}
else
{
fprintf(stderr, "Unknown long option %s\r\n", long_options[option_index].name);
fail();
}
break;
// on-the-fly zstd compression
case 'Z':
if (set_compress_mode(COMPRESS_ZSTD) == 0)
{
opt_zstd++;
}
break;
// compression level of compression algorithm
case 'l':
errno = 0;
opt_compress_level = strtol(optarg, NULL, 10);
if ((errno != 0) || (opt_compress_level <= 0))
{
help();
fprintf(stderr, "Invalid value passed to -%c (%s), expected a strictly positive integer\r\n", (char)ch, optarg);
exit(EXIT_FAILURE);
}
printdbg("level %c=%ld\r\n", ch, opt_compress_level);
set_compress_level(opt_compress_level);
break;
// debug ttyrec
case 'v':
opt_debug++;
break;
// open ttyrec file in append mode instead of write mode
case 'a':
opt_append++;
break;
// inhibit cheatcodes (force lock, force kill)
case 'C':
opt_cheatcodes = 0;
break;
// enable cheatcodes (force lock, force kill)
case 'c':
opt_cheatcodes = 1;
break;
// ignored (for compatibility with ttyrec classic)
case 'u':
break;
// ttyrec classic way of specifying the command to launch, it uses sh -c
case 'e':
if (legacy == 1)
{
help();
fprintf(stderr, "Option -e specified more than once.\r\n");
exit(EXIT_FAILURE);
}
legacy = 1;
params = malloc(sizeof(char *) * 4);
command = shell;
params[0] = strrchr(shell, '/') + 1;
params[1] = "-c";
params[2] = strdup(optarg);
params[3] = NULL;
break;
// directory to write ttyrec files to (autogenerated)
case 'd':
dname = strdup(optarg);
break;
// fullpath of ttyrec file to write to (optional, autogenerated if missing)
case 'f':
fname = strdup(optarg);
break;
// uuid, will appear in my ttyrec output file names, to keep track even after rotation (if omitted, will default to my pid)
case 'z':
uuid = strdup(optarg);
break;
// custom format
case 'F':
namefmt = strdup(optarg);
break;
// openpty_disable, don't prefer openpty() on systems that support it
case 'p':
#ifdef HAVE_openpty
openpty_disable++;
#else
fprintf(stderr, "Ignored option 'p': openpty() not supported on this system.\r\n");
#endif
break;
// timeout before lock (t) or kill (k)
case 't':
case 'k':
errno = 0;
long timeout = strtol(optarg, NULL, 10);
if ((errno != 0) || (timeout <= 0))
{
help();
fprintf(stderr, "Invalid value passed to -%c (%s), expected a strictly positive integer\r\n", (char)ch, optarg);
exit(EXIT_FAILURE);
}
printdbg("timeout %c=%ld\r\n", ch, timeout_lock);
if ((char)ch == 't')
{
timeout_lock = timeout;
}
else if ((char)ch == 'k')
{
timeout_kill = timeout;
}
break;
case 's':
opt_custom_message = strdup(optarg);
break;
// if specified, will count number of bytes out and print it on termination (experimental)
case 'n':
opt_count_bytes++;
break;
case 'T':
if (strncmp(optarg, "never", strlen("never")) == 0)
{
opt_want_tty = 0;
}
else if (strncmp(optarg, "auto", strlen("auto")) == 0)
{
opt_want_tty = 1;
}
else if (strncmp(optarg, "always", strlen("always")) == 0)
{
opt_want_tty = 2;
}
else
{
help();
fprintf(stderr, "Invalid value passed to -T (%s), expected either 'never', 'auto' or 'always'\r\n", optarg);
exit(EXIT_FAILURE);
}
break;
// version
case 'V':
printf("ttyrec v%s (%s)\n", version, MACHINE_STR);
#ifdef DEFINES_STR
printf("%s (%s)\n", DEFINES_STR, OS_STR);
#endif
#ifdef __VERSION__
printf("compiler version %s (%s)\n", __VERSION__, COMPILER_NAME);
#endif
#ifdef HAVE_zstd
printf("libzstd version %u (%d.%d.%d)\n", ZSTD_versionNumber(), ZSTD_VERSION_MAJOR, ZSTD_VERSION_MINOR, ZSTD_VERSION_RELEASE);
#endif
exit(0);
// 'h', and any other unknown option
case 'h':
default:
help();
exit(EXIT_FAILURE);
}
}
argc -= optind;
argv += optind;
printdbg("remaining non-parsed options argc=%d\r\n", argc);
for (int i = 0; i < argc; i++)
{
printdbg("option %d: <%s>\r\n", i, argv[i]);
}
if ((namefmt != NULL) && ((dname != NULL) || (uuid != NULL)))
{
fprintf(stderr, "Option -F (--name-format) can't be used with -d (--dir) or -z (--uuid)\n");
fail();
}
if (uuid == NULL)
{
uuid = malloc(sizeof(char) * BUFSIZ);
snprintf(uuid, BUFSIZ, PID_T_FORMAT, getpid());
}
if ((timeout_lock > 0) && (timeout_kill > 0) && (timeout_kill < timeout_lock))
{
help();
fprintf(stderr, "specified timeout_lock (%ld) is higher than timeout_kill (%ld), this doesn't make sense\r\n", timeout_lock, timeout_kill);
exit(EXIT_FAILURE);
}
if ((warn_before_lock_seconds > 0) && (timeout_lock == 0))
{
help();
fprintf(stderr, "You specified --warn-before-lock without enabling --timeout-lock, this doesn't make sense\r\n");
exit(EXIT_FAILURE);
}
if (warn_before_lock_seconds > timeout_lock)
{
help();
fprintf(stderr, "The specified value for --warn-before-lock is higher than --timeout-lock, this doesn't make sense\r\n");
exit(EXIT_FAILURE);
}
if ((warn_before_kill_seconds > 0) && (timeout_kill == 0))
{
help();
fprintf(stderr, "You specified --warn-before-kill without enabling --timeout-kill, this doesn't make sense\r\n");
exit(EXIT_FAILURE);
}
if (warn_before_kill_seconds > timeout_kill)
{
help();
fprintf(stderr, "The specified value for --warn-before-kill is higher than --timeout-kill, this doesn't make sense\r\n");
exit(EXIT_FAILURE);
}
if (legacy)
{
// strdup: make it free()able
fname = (argv[0] == NULL ? strdup("ttyrecord") : strdup(argv[0]));
}
else
{
if (argv[0] == NULL)
{
command = shell;
params = malloc(sizeof(char *) * 3);
params[0] = strrchr(shell, '/') + 1;
params[1] = "-i";
params[2] = NULL;
}
else
{
command = argv[0];
params = argv;
}
}
printdbg("will execvp %s with the following params:\r\n", command);
if (params == NULL)
{
printdbg("(none)\r\n");
}
else
{
for (int index = 0; params[index] != NULL; index++)
{
printdbg("- '%s'\r\n", params[index]);
}
}
// if neither dname nor fname are given, set dname to current dir
if ((dname == NULL) && (fname == NULL))
{
dname = strdup(".");
}
// if no file name given, generate it (dname is used as directory)
if (fname == NULL)
{
set_ttyrec_file_name(&fname);
}
else
{
// otherwise, append .zst if applicable
if (opt_zstd)
{
fname = realloc(fname, strlen(fname) + 4 + 1);
if (fname == NULL)
{
perror("realloc");
exit(EXIT_FAILURE);
}
strcat(fname, ".zst");
}
}
// if dname == ".", it might be because we've set it
if (dname == NULL)
{
char *tmpfname = strdup(fname);
// strdup(dirname) because in done() we free() dname
dname = strdup(dirname(tmpfname));
free(tmpfname);
}
if (dname == NULL)
{
fprintf(stderr, "failed to find a proper dname from fname=<%s>\r\n", fname);
exit(EXIT_FAILURE);
}
printdbg("will use %s as dname\r\n", dname);
if ((fscript = fopen(fname, opt_append ? "a" : "w")) == NULL)
{
perror(fname);
exit(EXIT_FAILURE);
}
free(fname);
setbuf(fscript, NULL);
{
struct sigaction act;
memset(&act, '\0', sizeof(act));
act.sa_handler = &finish;
act.sa_flags = SA_NOCLDSTOP | SA_RESTART;
if (sigaction(SIGCHLD, &act, NULL))
{
perror("sigaction");
exit(EXIT_FAILURE);
}
memset(&act, '\0', sizeof(act));
act.sa_handler = &swing_output_file;
act.sa_flags = SA_RESTART;
if (sigaction(SIGUSR1, &act, NULL))
{
perror("sigaction");
exit(EXIT_FAILURE);
}
memset(&act, '\0', sizeof(act));
act.sa_handler = &unlock_session;
act.sa_flags = SA_RESTART;
if (sigaction(SIGUSR2, &act, NULL))
{
perror("sigaction");
exit(EXIT_FAILURE);
}
memset(&act, '\0', sizeof(act));
act.sa_handler = &lock_session;
act.sa_flags = SA_RESTART;
if (sigaction(SIGURG, &act, NULL))
{
perror("sigaction");
exit(EXIT_FAILURE);
}
memset(&act, '\0', sizeof(act));
act.sa_handler = &sigterm_handler;
act.sa_flags = SA_RESTART;
if (sigaction(SIGTERM, &act, NULL))
{
perror("sigaction");
exit(EXIT_FAILURE);
}
// we can get SIGHUP if our tty is closed, fclose() properly in that case
memset(&act, '\0', sizeof(act));
act.sa_handler = &sighup_handler;
act.sa_flags = SA_RESTART;
if (sigaction(SIGHUP, &act, NULL))
{
perror("sigaction");
exit(EXIT_FAILURE);
}
}
parent_stdin_isatty = isatty(0);
switch (opt_want_tty)
{
case 2:
use_tty = 1;
break;
case 0:
use_tty = 0;
break;
default:
use_tty = parent_stdin_isatty;
}
printdbg("parent: isatty(stdin) == %d, opt_want_tty == %d, use_tty == %d\r\n", parent_stdin_isatty, opt_want_tty, use_tty);
if (use_tty)
{
getmaster();
print_termios_info(master, "parent master");
print_termios_info(0, "parent stdin b4 fixtty");
if (parent_stdin_isatty)
{
fixtty();
}
print_termios_info(0, "parent stdin after fixtty");
}
else
{
// pipe[0] is read, pipe[1] is write
if (pipe(stdout_pipe))
{
perror("pipe");
exit(EXIT_FAILURE);
}
if (pipe(stderr_pipe))
{
perror("pipe");
exit(EXIT_FAILURE);
}
}
child = fork();
if (child < 0)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if (child == 0)
{
// we are the child
printdbg("child pid is %ld\r\n", (long int)getpid());
print_termios_info(0, "child stdin");
subchild = child = fork();
if (child < 0)
{
perror("fork");
fail();
}
else if (child)
{
// we are still the child (parent of subchild)
me = "child";
dooutput();
}
else
{
// we are the subchild
printdbg("subchild pid is %ld\r\n", (long int)getpid());
print_termios_info(0, "subchild stdin");
me = "subchild";
doshell(command, params);
}
}
else
{
// we are the parent
me = "parent";
printdbg("parent pid is %ld\r\n", (long int)getpid());
sigwinch_handler_parent(SIGWINCH);
if (timeout_lock || timeout_kill)
{
pthread_t watcher_thread;
if (pthread_create(&watcher_thread, NULL, timeout_watcher, NULL) == -1)
{
perror("pthread");
fail();
}
}
doinput();
}
return 0;
}
void handle_cheatcodes(char c)
{
static int lockseq = 0;
static int killseq = 0;
if (opt_cheatcodes != 1)
{
return;
}
// LOCK
if (c == '\x0c') // ^L
{
if (++lockseq >= 8)
{
lockseq = 0;
do_lock();
}
}
else
{
lockseq = 0;
}
// KILL
if (((c == '\x0b') && ((killseq == 0) || (killseq == 4))) || // ^K
((c == '\x09') && ((killseq == 1) || (killseq == 5))) || // ^I
((c == '\x0c') && ((killseq == 2) || (killseq == 3) || (killseq == 6) || (killseq == 7)))) // ^L
{
killseq++;
}
else
{
killseq = 0;
}
if (killseq >= 8)
{
kill(child, SIGTERM);
}
}
// called by parent
void doinput(void)
{
int cc;
char ibuf[BUFSIZ];
(void)fclose_wrapper(fscript);
#ifdef HAVE_openpty
if (openpty_used)
{
// openpty opens the master and the slave in a single call to getmaster(),
// but in that case we don't want the slave (we won't call getslave())
(void)close(slave);
}
#endif
struct sigaction act;
memset(&act, '\0', sizeof(act));
act.sa_handler = &sigwinch_handler_parent;
act.sa_flags = SA_RESTART;
if (sigaction(SIGWINCH, &act, NULL))
{
perror("sigaction");
fail();
}
last_activity = time(NULL);
lock_warned = 0;
kill_warned = 0;
if (use_tty)
{
print_termios_info(master, "parent master in doinput");
#ifdef __HAIKU__
// under Haiku, if we use BUFSIZ as read size, it reads 4 bytes per 4 bytes
// instead of returning read data as soon as possible
const size_t readsz = 1;
#else
const size_t readsz = BUFSIZ;
#endif
while ((cc = read(0, ibuf, readsz)) > 0)
{
printdbg2("[in:%d]", cc);
if (!locked_since)
{
if (write(master, ibuf, cc) == -1)
{
perror("write[parent-master]");
fail();
}
last_activity = time(NULL);
lock_warned = 0;
kill_warned = 0;
if (cc == 1)
{
handle_cheatcodes(ibuf[0]);
}
}
}
if (opt_debug && (cc == -1))
{
perror("read");
}
}
else
{
// we won't use a pseudotty, just pipes, but as we're the parent so we don't need those
// also our STDIN is passed thru the subchild, so we don't need to handle it ourselves, we'll just wait for our child exit
close(0);
close(stdout_pipe[0]);
close(stdout_pipe[1]);
close(stderr_pipe[0]);
close(stderr_pipe[1]);
}
printdbg("%s("PID_T_FORMAT "): end doinput, waiting for child\r\n", me, getpid());
waitpid(-1, &childexit, 0);
printdbg("%s("PID_T_FORMAT "): end doinput, child exited with status=%d, exiting too\r\n", me, getpid(), childexit);
done(childexit);
}
// handler of SIGCHLD
void finish(int signal)
{
int waitedpid;
int die = 0;
(void)signal;
printdbg("%s("PID_T_FORMAT "): got SIGCHLD, calling waitpid\r\n", me, getpid());
while ((waitedpid = waitpid(-1, &childexit, WNOHANG)) > 0)
{
if (waitedpid == subchild)
{
printdbg("%s("PID_T_FORMAT "): subchild exited with %d, setting can_exit to 1\r\n", me, getpid(), childexit);
can_exit = 1;
}
else if (waitedpid == child)
{
printdbg("%s("PID_T_FORMAT "): child exited with %d, exiting too\r\n", me, getpid(), childexit);
die = 1;
}
}
if (die)
{
done(childexit);
}
}
void set_ttyrec_file_name(char **nameptr)