-
Notifications
You must be signed in to change notification settings - Fork 5
/
connector.cpp
1739 lines (1494 loc) · 42.6 KB
/
connector.cpp
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
/*
from https://github.com/Alexpux/MSYS2-packages/issues/265
Copyright (c) 2015-present Maximus5
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. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*/
#define _GNU_SOURCE
#ifdef __CYGWIN__
#include <cygwin/version.h>
#endif
#undef _USE_DEBUG_LOG_INPUT
//#define SHOW_CHILD_ERR_MSG
#undef SHOW_CHILD_ERR_MSG
#if (__GNUC_MINOR__ >= 9) || (CYGWIN_VERSION_API_MINOR>=93)
#define HAS_FORKPTY
#pragma message "Has forkpty"
#else
#undef HAS_FORKPTY
#pragma message "Does NOT have forkpty"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <process.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/termios.h>
#include <sys/cygwin.h>
#include <w32api/wtypes.h>
#include <w32api/wincon.h>
#include <w32api/winuser.h>
#include <unistd.h>
#include <utmp.h>
// exists in cygwin+msys2
#if defined(HAS_FORKPTY)
#include <pty.h>
#endif
#define _max(a,b) (((a) > (b)) ? (a) : (b))
bool verbose = false;
bool debugger = false;
static int gnLogFileIn = -1;
static int gnLogFileOut = -1;
void safe_close(int& f);
char* get_cygwin_root();
static void write_verbose(const char *buf, ...);
static void print_version();
#include "version.h"
#include "ConnectorAPI.h"
// enum RequestTermConnectorMode
// enum WriteProcessedStream
// struct tag_RequestTermConnectorParm
static HMODULE hConEmuHk = NULL;
static RequestTermConnectorParm Connector = {};
typedef int (WINAPI* RequestTermConnector_t)(/*[IN/OUT]*/RequestTermConnectorParm* Parm);
static RequestTermConnector_t fnRequestTermConnector = NULL;
static int RequestTermConnector()
{
int iRc;
char sModule[] =
#if defined(__x86_64__)
"ConEmuHk64.dll"
#else
"ConEmuHk.dll"
#endif
;
const char* basedir;
basedir = getenv("ConEmuBaseDir");
if (basedir && *basedir)
{
char* path;
path = (char*)malloc(strlen(basedir)+2+strlen(sModule));
if (path)
{
strcpy(path, basedir);
strcat(path, "\\");
strcat(path, sModule);
hConEmuHk = LoadLibraryA(path);
free(path);
}
}
if (hConEmuHk == NULL)
{
hConEmuHk = LoadLibraryA(sModule);
}
if (hConEmuHk == NULL)
{
write_verbose("\r\n{PID:%u} %s is not found, exiting\r\n", getpid(), sModule);
return -1;
}
fnRequestTermConnector = (RequestTermConnector_t)GetProcAddress(hConEmuHk, "RequestTermConnector");
if (fnRequestTermConnector == NULL)
{
write_verbose("\r\n{PID:%u} RequestTermConnector function is not found, exiting\r\n", getpid());
iRc = -1;
}
else
{
// Prepare arguments
memset(&Connector, 0, sizeof(Connector));
Connector.cbSize = sizeof(Connector);
Connector.Mode = rtc_Start;
Connector.pszTtyName = ttyname(STDOUT_FILENO);
Connector.pszTerm = getenv("TERM");
Connector.pszMntPrefix = get_cygwin_root();
iRc = fnRequestTermConnector(&Connector);
if (iRc != 0)
{
write_verbose("\r\n{PID:%u} RequestTermConnector failed (%i). %s\r\n", getpid(), iRc, Connector.pszError ? Connector.pszError : "");
iRc = -1;
}
else if (!Connector.ReadInput || !Connector.WriteText)
{
write_verbose("\r\n{PID:%u} RequestTermConnector returned NULL. %s\r\n", getpid(), Connector.pszError ? Connector.pszError : "");
iRc = -1;
}
}
if (iRc != 0)
{
FreeLibrary(hConEmuHk);
hConEmuHk = NULL;
}
return iRc;
}
static void StopTermConnector()
{
if (fnRequestTermConnector)
{
Connector.cbSize = sizeof(Connector);
Connector.Mode = rtc_Stop;
fnRequestTermConnector(&Connector);
}
memset(&Connector, 0, sizeof(Connector));
safe_close(gnLogFileIn);
safe_close(gnLogFileOut);
if (hConEmuHk)
{
FreeLibrary(hConEmuHk);
}
}
#if defined(_USE_DEBUG_LOG)
#define DEBUG_LOG_MAX_BUFFER 1024
static void debug_log(const char* text)
{
OutputDebugStringA(text);
}
static void debug_log_format(const char* format,...)
{
va_list ap;
char buf[DEBUG_LOG_MAX_BUFFER];
va_start(ap, format);
vsnprintf(buf, sizeof buf, format, ap);
va_end(ap);
debug_log(buf);
}
#else
#define debug_log(text)
#define debug_log_format(format...)
#endif
static int pty_fd = -1, pty_err = -1;
static int slave_std_err = -1, slave_std_out = -1;
static pid_t pid = -1;
static void stop_threads();
static bool termination = false;
static int check_child(bool force_print = false);
static BOOL WINAPI CtrlHandlerRoutine(DWORD dwCtrlType)
{
// We do not expect to receive CTRL_C_EVENT/CTRL_BREAK_EVENT because of ProtectCtrlBreakTrap
if (verbose)
{
write_verbose("\r\n\033[31;40m{PID:%u} CtrlHandlerRoutine(%u) triggered\033[m\r\n", getpid(), dwCtrlType);
}
switch (dwCtrlType)
{
case CTRL_C_EVENT:
break;
case CTRL_BREAK_EVENT:
return TRUE; // bypass
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
if (pid > 0)
kill(-pid, SIGHUP);
break;
default:
/*sprintf(szType, "ID=%u", dwCtrlType)*/;
}
return FALSE;
}
static void stop_waiting_debugger(int sig)
{
debugger = false;
}
static void sigexit(int sig)
{
if (verbose)
{
write_verbose("\r\n\033[31;40m{PID:%u} signal %i received\033[m\r\n", getpid(), sig);
}
else
{
debug_log_format("signal %i received, pid=%i\n", sig, pid);
}
switch (sig)
{
case SIGINT:
// We do not expect to receive SIGINT because of ProtectCtrlBreakTrap
if (verbose)
write_verbose("\r\n\033[31;40m{PID:%u} Passing ^C to client\033[m\r\n", getpid());
write(pty_fd, "\3", 1);
//if (pid > 0)
// kill(pid, sig); // or kill(-group, sig)
return;
}
if (pid > 0)
kill(-pid, SIGHUP);
stop_threads();
signal(sig, SIG_DFL);
kill(getpid(), sig);
}
static bool gb_sigusr1 = false;
static void sigusr1(int sig)
{
if (sig == SIGUSR1)
{
if (verbose)
write_verbose("\033[%u;40m{PID:%u} SIGUSR1 received\033[m\r\n", pid?31:33, getpid());
gb_sigusr1 = true;
signal(SIGUSR1, SIG_DFL);
}
}
void sigusr1_throw(pid_t a_pid)
{
if (verbose)
write_verbose("\033[%u;40m{PID:%u} raising SIGUSR1 in pid=%i\033[m\r\n", pid?31:33, getpid(), a_pid);
kill(a_pid, SIGUSR1);
}
char * const * child_argv = NULL;
const char * work_dir = NULL;
static void print_shell_args()
{
char* cwd = work_dir ? NULL : getcwd(NULL, 0);
write_verbose("\033[33;40m{PID:%u} shell: `%s`", getpid(), child_argv[0]);
for (int c = 1; child_argv[c]; c++)
write_verbose(" `%s`", child_argv[c]);
write_verbose("\033[m\r\n");
write_verbose("\033[33;40m{PID:%u} dir: `%s`\033[m\r\n", getpid(), work_dir ? work_dir : cwd ? cwd : "<%cd%>");
free(cwd);
}
static void sigfault(int sig)
{
if (sig == SIGSEGV)
{
write_verbose("\033[%u;40m{PID:%u} Failed to run shell (SIGSEGV)\033[m\r\n", pid?31:33, getpid());
print_shell_args();
// if we exit immediately, some versions of cygwin/msys will not be able to print our message
sleep(1);
exit(EFAULT);
}
}
static void log_system_time(bool force)
{
if (gnLogFileOut < 0)
return;
struct timespec ts = {};
#if defined(HAS_FORKPTY)
clock_gettime(CLOCK_REALTIME, &ts);
#else
ts.tv_sec = time(0); // msys1 does not have clock_gettime
#endif
if (ts.tv_sec)
{
const long long min_diff = 500;
static long long last_ms = 0;
long long cur_ms = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
long long diff_ms = (cur_ms > last_ms) ? (cur_ms - last_ms) : (last_ms - cur_ms);
if (force || (min_diff >= min_diff))
{
char log_time[80];
const struct tm* ltm;
ltm = localtime(&ts.tv_sec);
sprintf(log_time, "\x1B]9;11;\"%02i:%02i:%02i.%03i\"\x07", ltm->tm_hour, ltm->tm_min, ltm->tm_sec, ts.tv_nsec / 1000000);
write(gnLogFileOut, log_time, strlen(log_time));
if (!force)
last_ms = cur_ms;
}
}
}
static bool write_console(const char *buf, int len, WriteProcessedStream strm = wps_Output)
{
if (len == -1)
len = strlen(buf);
debug_log_format("%u:PID=%u:TID=%u: writing ANSI: %s\n", GetTickCount(), getpid(), GetCurrentThreadId(), (len > (DEBUG_LOG_MAX_BUFFER-80)) ? "<Too long text to use debug_log_format>" : buf);
while (len > 0)
{
DWORD written = 0; BOOL bRc;
if (Connector.WriteText)
{
// Server side, initialized
// First, log the string if required
if (gnLogFileOut >= 0)
{
log_system_time(false);
write(gnLogFileOut, buf, len);
}
// Dump to console
bRc = Connector.WriteText(buf, len, &written, wps_Output);
}
else if (pid != 0) // Not-a-child or before-fork
{
// Server side, before initialization
// We need to call API directly, because fwrite/printf/...
// may break colors, if they were written in wrong moment
bRc = WriteConsoleA(GetStdHandle((strm == wps_Output) ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE), buf, len, &written, NULL);
}
else
{
// Child (client) side
ssize_t term_written;
int h_out = (strm == wps_Output) ? slave_std_out : slave_std_err;
//if (h_out < 0) h_out = STDOUT_FILENO;
term_written = write(h_out, buf, len);
bRc = (term_written > 0);
written = term_written;
}
if (!bRc)
return false;
len -= written;
buf += written;
}
return true;
}
// Don't check for `verbose` flag here, the function may be used in other places
static void write_verbose(const char *buf, ...)
{
//OutputDebugStringA(buf); -- no need, Debug versions of ConEmuHk dump ANSI output automatically
char szBuf[1024]; // don't use static here!
va_list args;
int ilen = -1;
if (strchr(buf, '%'))
{
va_start(args, buf);
ilen = vsnprintf(szBuf, sizeof(szBuf) - 1, buf, args);
va_end(args);
}
write_console((ilen > 0) ? szBuf : buf, -1, wps_Error);
}
void safe_close(int& f)
{
if (f >= 0)
{
if (verbose)
write_verbose("\r\n\033[31;40m{PID:%u} closing log file (%i)\033[m\r\n", getpid(), f);
close(f);
f = -1;
}
}
#if defined(SHOW_CHILD_ERR_MSG)
void child_msg_box(const char* text, const char* title)
{
MessageBox(NULL, text, title, MB_SYSTEMMODAL);
}
#else
#define child_msg_box(text,title)
#endif
void child_err_msg(const char* reason)
{
int e = errno;
const char* pszErDescr = strerror(errno);
#if defined(SHOW_CHILD_ERR_MSG)
char* pchMsg = (char*)malloc(255+pszErDescr?strlen(pszErDescr):0);
if (pchMsg)
{
sprintf(pchMsg, "{PID:%u} %s (%i): %s", getpid(), reason ? reason : "<unknown fail>", e, pszErDescr);
child_msg_box(pchMsg, "connector");
free(pchMsg);
}
#endif
write_verbose("\033[30;41m\033[K{PID:%u} %s (%i): %s\033[m\r\n", getpid(), reason ? reason : "<unknown fail>", e, pszErDescr);
print_shell_args();
}
static int resize_pty(int pty, struct winsize *winp)
{
int iRc = -99;
if (pty >= 0)
{
// SIGWINCH signal is sent to the foreground process group
iRc = ioctl(pty, TIOCSWINSZ, winp);
debug_log_format("resize_pty: TIOCSWINSZ(pty=%i,cell={%i,%i},pix={%i,%i})=%i\n", pty, winp->ws_col, winp->ws_row, winp->ws_xpixel, winp->ws_ypixel, iRc);
if (verbose)
{
if (iRc == -1)
write_verbose("\033[31;40m{PID:%u} ioctl(%i,TIOCSWINSZ,(%i,%i)) failed (%i): %s\033[m\r\n", getpid(), pty, winp->ws_col, winp->ws_row, errno, strerror(errno));
else
write_verbose("\033[31;40m{PID:%u} ioctl(%i,TIOCSWINSZ,(%i,%i)) succeeded (%i)\033[m\r\n", getpid(), pty, winp->ws_col, winp->ws_row, iRc);
}
if (gnLogFileOut >= 0)
{
char szLogSize[80];
log_system_time(true);
sprintf(szLogSize, "\x1B]9;11;\"TIOCSWINSZ(%i,%i) %s\"\x07\n", winp->ws_col, winp->ws_row, (iRc == -1) ? "failed" : "succeeded");
write(gnLogFileOut, szLogSize, strlen(szLogSize));
}
}
else
{
debug_log_format("resize_pty: invalid pty\n");
}
return iRc;
}
static bool query_console_size(struct winsize* winp)
{
bool bRc = false;
memset(winp, 0, sizeof(winp));
CONSOLE_SCREEN_BUFFER_INFO csbi = {};
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
{
winp->ws_row = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
winp->ws_col = csbi.dwSize.X;
bRc = true;
}
else
{
winp->ws_row = 25;
winp->ws_col = 80;
}
winp->ws_xpixel = winp->ws_col * 3;
winp->ws_ypixel = winp->ws_row * 5;
return bRc;
}
void write_input_buffered(char* data, int len)
{
const int buffer_max = 16;
static char buffer[buffer_max] = "";
static int buffer_used = 0;
char log_input[80];
if (data == NULL || len <= 0)
{
if (buffer_used > 0)
{
ssize_t written = write(pty_fd, buffer, buffer_used);
if (gnLogFileIn >= 0)
{
sprintf(log_input, " written %i of %i bytes\n", written, buffer_used);
write(gnLogFileIn, log_input, strlen(log_input));
}
}
buffer_used = 0;
return;
}
for (int i = 0; i < len; ++i)
{
if (data[i] == 27 || buffer_used == buffer_max)
{
write_input_buffered(NULL, 0);
}
buffer[buffer_used++] = data[i];
}
sprintf(log_input, " buffered, total %i bytes\n", buffer_used);
write(gnLogFileIn, log_input, strlen(log_input));
}
// returns true on more events in queue
bool read_input()
{
char log_input[200];
bool has_more_data = false;
if (!termination)
{
log_input[0] = 0;
DWORD nReady = 0;
const DWORD buffer_max = 32;
INPUT_RECORD rr[buffer_max] = {};
ReadInputResult read_rc = Connector.ReadInput(rr, buffer_max, &nReady);
if (!read_rc || !nReady)
return false;
has_more_data = (read_rc == rir_Ready_More);
for (DWORD n = 0; n < nReady; ++n)
{
const INPUT_RECORD& r = rr[n];
switch (r.EventType)
{
case WINDOW_BUFFER_SIZE_EVENT:
{
winsize winp;
if (gnLogFileIn >= 0)
{
sprintf(log_input, "input: WindowBufferSize (%i,%i)\n", r.Event.WindowBufferSizeEvent.dwSize.X, r.Event.WindowBufferSizeEvent.dwSize.Y);
write(gnLogFileIn, log_input, strlen(log_input));
}
if (query_console_size(&winp))
{
write_input_buffered(NULL, 0);
if (pty_fd >= 0)
resize_pty(pty_fd, &winp);
else if (gnLogFileIn >= 0)
{
const char* invalid_pty = "input: invalid pty_fd\n";
write(gnLogFileIn, invalid_pty, strlen(invalid_pty));
}
if (pty_err >= 0)
resize_pty(pty_err, &winp);
}
else
{
const char* query_console_size_failed = "input: query_console_size failed!!!\n";
write(gnLogFileIn, query_console_size_failed, strlen(query_console_size_failed));
}
break;
} // WINDOW_BUFFER_SIZE_EVENT
case KEY_EVENT:
{
if (!r.Event.KeyEvent.bKeyDown)
{
if (gnLogFileIn >= 0)
{
sprintf(log_input, "input: KeyUp=%u skipped\n", r.Event.KeyEvent.wVirtualKeyCode);
write(gnLogFileIn, log_input, strlen(log_input));
}
break;
}
// special for 'Ctrl+Space'
if (r.Event.KeyEvent.wVirtualKeyCode == VK_SPACE || r.Event.KeyEvent.wVirtualKeyCode == '2' || r.Event.KeyEvent.wVirtualKeyCode == '`')
{
if (r.Event.KeyEvent.dwControlKeyState & (RIGHT_CTRL_PRESSED|LEFT_CTRL_PRESSED))
{
char zero = 0;
int len = 1; // 'Ctrl+Space' --> '\x00'
if (gnLogFileIn >= 0)
{
sprintf(log_input, "input: `\\x00` ");
write(gnLogFileIn, log_input, strlen(log_input));
}
// #TODO: Alt/Shift combo?
write_input_buffered(&zero, len);
break;
}
}
if (r.Event.KeyEvent.uChar.UnicodeChar)
{
char s[5];
int len = WideCharToMultiByte(CP_UTF8, 0, &r.Event.KeyEvent.uChar.UnicodeChar, 1, s, sizeof(s)-1, 0, 0);
if (len > 0)
{
s[len] = 0;
if (gnLogFileIn >= 0)
{
sprintf(log_input, "input: `%s` ", s);
write(gnLogFileIn, log_input, strlen(log_input));
}
write_input_buffered(s, len);
}
}
break;
} // KEY_EVENT
default:
if (gnLogFileIn >= 0)
{
sprintf(log_input, "input: event %u received\n", r.EventType);
write(gnLogFileIn, log_input, strlen(log_input));
}
} // switch (r.EventType)
} // if (Connector.ReadInput
if (!has_more_data)
{
write_input_buffered(NULL, 0);
}
} // if (!termination)
return has_more_data;
}
static void stop_threads()
{
termination = true;
if (verbose)
{
write_verbose("\r\n\033[31;40m{PID:%u} Stopping our threads\033[m\r\n", getpid());
}
StopTermConnector();
}
static int process_pty(int& pty, char* buf, const int bufCount, const int preferredCount)
{
debug_log_format("%u:PID=%u:TID=%u: calling read(%i)\n", GetTickCount(), getpid(), GetCurrentThreadId(), pty);
int len = read(pty, buf, bufCount);
if (len > 0)
{
while ((len+4) < preferredCount)
{
int addLen = read(pty, buf+len, bufCount-len);
if (addLen <= 0)
break;
len += addLen;
}
buf[len] = 0;
write_console(buf, len, (pty == pty_err) ? wps_Error : wps_Output);
}
else
{
if (verbose)
{
write_verbose("\r\n\033[31;40m{PID:%u} read(pty=%i) failed (len=%i,errno=%i): %s\033[m\r\n", getpid(), pty, len, errno, strerror(errno));
check_child();
}
pty = -1;
}
return len;
}
static int check_child(bool force_print /*= false*/)
{
if (pid <= 0)
return -1;
int status = 0, wait_rc;
debug_log_format("%u:PID=%u:TID=%u: calling waitpid(%i)\n", GetTickCount(), getpid(), GetCurrentThreadId(), pid);
wait_rc = waitpid(pid, &status, WNOHANG);
debug_log_format("%u:PID=%u:TID=%u: waitpid(%i) done rc=%u status=0x%X\n", GetTickCount(), getpid(), GetCurrentThreadId(), pid, wait_rc, status);
if (wait_rc == pid)
{
if (verbose || force_print)
{
if (WIFEXITED(status))
write_verbose("\r\n\033[31;40m{PID:%u} pid=%i was terminated, exitcode=%u", getpid(), pid, WEXITSTATUS(status), strerror(WEXITSTATUS(status)));
else if (WIFSIGNALED(status))
write_verbose("\r\n\033[31;40m{PID:%u} pid=%i was terminated by signal (%u): %s", getpid(), pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
else
write_verbose("\r\n\033[31;40m{PID:%u} pid=%i was terminated, status=%i\033[m\r\n", getpid(), pid, status);
}
pid = -2;
}
else if (wait_rc == 0)
{
// One or more child(ren) exist
if (force_print)
{
write_verbose("\r\n\033[31;40m{PID:%u} one or more children with pid=%i are alive\033[m\r\n", getpid(), pid);
}
}
else if (verbose || force_print)
{
write_verbose("\r\n\033[31;40m{PID:%u} waitpid(%i) failed (%i): %s", getpid(), pid, errno, strerror(errno));
}
return (pid <= 0) ? -1 : 0;
}
static int run()
{
fd_set fds;
const int preferredCount = 280;
const int bufCount = 4096;
char buf[bufCount+1];
for (;;)
{
struct timeval timeout = {0, 100000};
FD_ZERO(&fds);
if (pty_fd >= 0)
{
FD_SET(pty_fd, &fds);
if (pty_err >= 0)
FD_SET(pty_err, &fds);
}
else if (pid > 0)
{
if (check_child() == -1)
{
if (pty_fd < 0)
break;
}
else
{
// Pty gone, but process still there: keep checking?
}
}
const int fdsmax = _max(pty_fd,pty_err) + 1;
debug_log_format("%u:PID=%u:TID=%u: calling select on (%i,%i)\n", GetTickCount(), getpid(), GetCurrentThreadId(), pty_fd, pty_err);
timeout.tv_usec = 10000;
if (select(fdsmax, &fds, 0, 0, &timeout) > 0)
{
if (pty_fd >= 0 && FD_ISSET(pty_fd, &fds))
{
process_pty(pty_fd, buf, bufCount, preferredCount);
if (verbose && (pty_fd < 0))
write_verbose("\r\n\033[31;40m{PID:%u} pty_fd set to -1\033[m\r\n", getpid(), pid);
}
if (pty_err >= 0 && FD_ISSET(pty_err, &fds))
{
process_pty(pty_err, buf, bufCount, preferredCount);
if (verbose && (pty_err < 0))
write_verbose("\r\n\033[31;40m{PID:%u} pty_err set to -1\033[m\r\n", getpid(), pid);
}
}
else
{
debug_log_format("%u:PID=%u:TID=%u: select failed\n", GetTickCount(), getpid(), GetCurrentThreadId());
}
DWORD start_tick = GetTickCount(), end_tick;
while (read_input())
{
end_tick = GetTickCount();
if ((end_tick - start_tick) >= 10)
break;
}
}
check_child(true);
stop_threads();
return 0;
}
// switch `--keys` useful to check keyboard translations
static int test_read_keys()
{
struct termios old = {0}, raw = {};
print_version();
printf("Starting raw conin reader, press Ctrl+C to stop\n");
if (tcgetattr(0, &old) < 0)
perror("tcgetattr()");
raw = old;
raw.c_lflag &= ~(ICANON|ECHO);
raw.c_cc[VMIN] = 1;
raw.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &raw) < 0)
perror("tcsetattr()");
for (;;)
{
int c = fgetc(stdin);
if (c > 32 && c != 0x7F)
printf("<x%02X:%c>", c, c);
else if (c == 0xA)
printf("<ENTER>\n");
else
printf("<x%02X>", c);
}
if (tcsetattr(0, TCSADRAIN, &old) < 0)
perror ("reverting tcsetattr()");
return 0;
}
static void print_version()
{
printf("ConEmu cygwin/msys connector version %s\n", VERSION_S);
}
static void print_environ(bool bChild)
{
char** pp = environ;
if (!pp)
{
write_verbose("\033[31;40m{PID:%u} `environ` variable is NULL!\033[m\r\n", getpid());
return;
}
write_verbose("\033[31;40m{PID:%u} printing `environ` lines\033[m\r\n", getpid());
while (*pp)
{
write_console(*(pp++), -1);
write_console("\r\n", 2);
}
write_verbose("\033[31;40m{PID:%u} end of `environ`, total=%i\033[m\r\n", getpid(), (pp - environ));
}
static int print_isatty(bool bChild)
{
bool isTty = true;
int iTty, errNoTty, errNoPgrp;
pid_t ttyPgrp = -1;
char* ttyName;
for (int f = STDIN_FILENO; f <= STDERR_FILENO; f++)
{
ttyName = ttyname(f);
errno = 0;
iTty = isatty(f);
errNoTty = errno;
errno = 0;
ttyPgrp = tcgetpgrp(f);
errNoPgrp = errno;
if (iTty == 1)
{
write_verbose("\033[%u;40m{PID:%u} %i: isatty()=%i; pgrp=%i; ttyname()=`%s`\033[m\r\n", pid?31:33, getpid(), f, iTty, ttyPgrp, ttyName?ttyName:"<NULL>");
}
else
{
write_verbose("\033[%u;40m{PID:%u} %i: isatty()=%i; pgrp=%i; ttyname()=`%s`\033[m\r\n", pid?31:33, getpid(), f, iTty, ttyPgrp, ttyName?ttyName:"<NULL>");
isTty = false;
}
if (errNoTty)
write_verbose("\033[%u;40m{PID:%u} isatty error (%i): %s\033[m\r\n", pid?31:33, getpid(), errNoTty, strerror(errNoTty));
if (errNoPgrp)
write_verbose("\033[%u;40m{PID:%u} tcgetpgrp error (%i): %s\033[m\r\n", pid?31:33, getpid(), errNoPgrp, strerror(errNoPgrp));
}
return isTty ? 0 : 1;
}
#if !defined(HAS_FORKPTY)
static int ce_createpty(const char* adescr, int *pmaster, int *pslave, struct winsize *winp)
{
char* ptsName;
if (verbose)
{
write_verbose("\033[31;40m{PID:%u} creating %s `/dev/ptmx`\033[m\r\n", getpid(), adescr);
}
if ((*pmaster = open ("/dev/ptmx", O_RDWR | O_NOCTTY)) == -1)
{
write_verbose("\033[30;41m\033[K{PID:%u} open(`/dev/ptmx`) failed (%i): %s\033[m\r\n", getpid(), errno, strerror(errno));
return -1;
}
if (verbose)
{
write_verbose("\033[31;40m{PID:%u} %s handle is (%i)\033[m\r\n", getpid(), adescr, *pmaster);
}
if (grantpt(*pmaster) == -1)
{
write_verbose("\033[30;41m\033[K{PID:%u} grantpt(%i) failed (%i): %s\033[m\r\n", getpid(), *pmaster, errno, strerror(errno));
return -1;
}
if (unlockpt(*pmaster) == -1)
{
write_verbose("\033[30;41m\033[K{PID:%u} unlockpt(%i) failed (%i): %s\033[m\r\n", getpid(), *pmaster, errno, strerror(errno));
return -1;
}
ptsName = ptsname(*pmaster);
if (ptsName == NULL)
{
write_verbose("\033[30;41m\033[K{PID:%u} ptsname(%i) failed (%i): %s\033[m\r\n", getpid(), *pmaster, errno, strerror(errno));
return -1;
}
if (verbose)
{
write_verbose("\033[31;40m{PID:%u} opening slave `%s`\033[m\r\n", getpid(), ptsName);
}
if ((*pslave = open (ptsName, O_RDWR | O_NOCTTY)) == -1)
{
write_verbose("\033[30;41m\033[K{PID:%u} open(`%s`) failed (%i): %s\033[m\r\n", getpid(), ptsName, errno, strerror(errno));
close(*pmaster);
return -1;
}
if (verbose)
{
write_verbose("\033[31;40m{PID:%u} slave handle is (%i)\033[m\r\n", getpid(), *pslave);
}
if (winp)
{