forked from yiselieren/con
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcon.cpp
More file actions
955 lines (881 loc) · 36.1 KB
/
Copy pathcon.cpp
File metadata and controls
955 lines (881 loc) · 36.1 KB
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
/*********************
* Console utility
*********************
*
*/
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <memory.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include <poll.h>
#include "tty.h"
#ifndef CON_VERSION
#define CON_VERSION "unknown"
#endif
#ifndef CON_GIT_HASH
#define CON_GIT_HASH "unknown"
#endif
#ifndef CON_BUILD_DATE
#define CON_BUILD_DATE "unreleased"
#endif
#define PERR(...) do { fprintf(stderr, __VA_ARGS__); finish(1); } while(0)
#define RERR(...) do { fprintf(stderr, __VA_ARGS__); return; } while(0)
// SUN_LEN(&a) equals the former strlen(sun_path) + sizeof(sun_family) only when
// sun_path begins exactly at the end of sun_family with no padding (issue #6).
static_assert(offsetof(struct sockaddr_un, sun_path) == sizeof(((struct sockaddr_un *)0)->sun_family),
"SUN_LEN identity (#6): sun_path offset must equal sun_family size");
Tty *tty = 0;
int tty1 = -1;
char *tty1_name = 0;
const char *tty2_name = "/dev/tty";
unsigned char exitChr = '\001';
bool echo_flag = false;
bool readonly_flag = false;
unsigned char diagChr = '\024';
bool hexa_flag = false;
bool hexa_ascii_flag = false;
int hexa_inline = 16;
int hexa_ascii_inline = 8;
FILE *log_file = NULL;
void usage(const char *s)
{
fprintf(stderr, "Usage:\n\t%s [SWITCHES] {tty_device | path_to_local_socket | [host]:port}\n", s);
fputs(
"\n"
"The tool can be used in a few different modes:\n"
"\n"
"1. Communication program to serial line (like minicom):\n"
" con [-t] [-b BAUDRATE] TERM_DEVICE\n"
" Example:\n"
" con -b 115200 /dev/ttyUSB0\n"
" con -x ctrl/b /dev/ttyS0\n"
"\n"
"2. Communication program to TCP socket in a client mode:\n"
" con -c ADDR:PORT\n"
" Example:\n"
" con -c www.something.org:80\n"
" con -c 192.168.2.100:8080\n"
"\n"
"3. Communication program to TCP socket in a server mode:\n"
" con -s :PORT\n"
" Example:\n"
" con -s :8080\n"
"\n"
"4. Communication program to UNIX socket in a client mode:\n"
" con [-u] -c SOCKET_PATH\n"
" Example:\n"
" con -c /tmp/my_named_socket\n"
" con -u -c cache:6379\n"
"\n"
"5. Communication program to UNIX socket in a server mode:\n"
" con [-u] -s SOCKET_PATH\n"
" Warning:\n"
" Server mode removes an existing target path before binding.\n"
" Example:\n"
" con -s /tmp/my_named_socket\n"
" con --unix -s listen:6380\n"
"\n"
"6. Read-only monitoring (observe without sending input):\n"
" con -r -c SOCKET_PATH\n"
" Example:\n"
" con -r -c /tmp/my_named_socket\n"
"\n"
"SWITCHES may be:\n"
"\t-h[elp] - Print help message.\n"
"\t-e[cho] - Echo keyboard input locally.\n"
"\t-r[eadonly] - Read-only mode, keyboard input is not sent\n"
"\t-l[og] FILENAME - Log everything to specified file, file be overwritten\n"
"\t-a[ppend] FILENAME - Appends all logs to specified file\n"
"\t-n[ocolor] - Filter out colors and CRNL sequences in a log file\n"
"\t-X - Output as hexa bytes\n"
"\t-Y - Output as hexa and ascii\n"
"\t-x[exit] KEY - Exit connection key. May be in integer as 0x01 or 001\n"
"\t or in a \"control-a\", \"cntrl/a\" or \"ctrl/a\" form\n"
"\t Default is \"cntrl/a\".\n"
"\t-q - Be quiet\n"
"\tCtrl-T - Diagnostic: show receive buffer queue depth\n"
"\t-V - Print version information and exit.\n"
"\n"
"Switches specific for tty_device:\n"
"\t-t[erm] - Work as serial communication program. This is a default\n"
"\t mode. Note that \"-b\" switch assumes \"-t\"\n"
"\t-b[aud] <baud_rate> - Set the baud rate for target connection.\n"
"\n"
"Switches specific for socket connection:\n"
"\t-s[erver] - Accept connection to socket as server.\n"
"\t-c[lient] - Connection to socket as client.\n"
"\t-u, --unix - Force UNIX socket transport; client/server selection is unchanged.\n"
, stderr);
exit(1);
}
void finish(int stat = 0)
{
fprintf(stderr, "\r\n");
if (tty)
{
delete tty;
tty = 0;
}
if (tty1 >= 0)
{
close(tty1);
tty1 = -1;
}
if (tty1_name)
{
free(tty1_name);
tty1_name = 0;
}
if (log_file)
{
fclose(log_file);
log_file = NULL;
}
exit (stat);
}
extern "C" void finish_int(int)
{
finish(1);
}
int readn(int fd, void *ptr, int nbytes)
{
int nread;
do
nread = read(fd, ptr, nbytes);
while (nread < 0 && (errno == EINTR || errno == EAGAIN));
return nread;
}
int writen(int fd, const void *ptr, int nbytes)
{
int nwritten;
do
nwritten = write(fd, ptr, nbytes);
while (nwritten < 0 && (errno == EINTR || errno == EAGAIN));
return nwritten;
}
enum Pstate { REGULAR, COLOR, CRNL };
static Pstate log_pstate = REGULAR;
static int cr_count = 0;
/*
* Write data to the log file efficiently.
* If color filtering is enabled, it buffers the filtered characters
* into a single chunk to minimize fwrite() lock/unlock overhead.
*/
void write_log(const unsigned char *buf, const int buf_cnt, bool filter_colors)
{
if (!log_file)
return;
if (filter_colors)
{
unsigned char out_buf[buf_cnt];
int out_cnt = 0;
for (int i = 0; i < buf_cnt; i++)
{
switch(log_pstate)
{
case REGULAR:
if (buf[i] == '\033')
log_pstate = COLOR;
else if (buf[i] == '\r')
{
log_pstate = CRNL;
cr_count++;
}
else
out_buf[out_cnt++] = buf[i];
break;
case COLOR:
if (buf[i] == 'm')
log_pstate = REGULAR;
break;
case CRNL:
if (buf[i] == '\r')
cr_count++;
else if (buf[i] == '\n')
{
out_buf[out_cnt++] = buf[i];
cr_count = 0;
}
else
{
for (int j = 0; j < cr_count; j++)
out_buf[out_cnt++] = '\r';
out_buf[out_cnt++] = buf[i];
cr_count = 0;
}
log_pstate = REGULAR;
break;
}
}
if (out_cnt > 0)
fwrite(out_buf, 1, out_cnt, log_file);
}
else
{
fwrite(buf, buf_cnt, 1, log_file);
}
}
void con_core(int cli_fd, const char *cli_name, int term_fd, const char *term_name, bool filter_colors)
{
const int MAXBUF = 8192;
static unsigned char buf[MAXBUF];
static int term_cnt = 0;
static char hex_buf[MAXBUF * 16];
struct pollfd pfds[2];
pfds[0].fd = cli_fd;
pfds[0].events = POLLIN | POLLRDHUP;
pfds[1].fd = term_fd;
pfds[1].events = POLLIN | POLLRDHUP;
for (;;)
{
if (poll(pfds, 2, -1) < 0)
{
if (errno == EINTR)
continue;
RERR("poll failure: %s\n", strerror(errno));
}
if (pfds[0].revents & (POLLERR | POLLNVAL))
RERR("\r\n\"%s\" error\n", cli_name);
if (pfds[1].revents & (POLLERR | POLLNVAL))
RERR("\r\n\"%s\" error\n", term_name);
if (pfds[0].revents & (POLLIN | POLLHUP | POLLRDHUP))
{
// From client to terminal
int buf_cnt = readn(cli_fd, buf, MAXBUF);
if (buf_cnt < 0)
RERR("\r\n\"%s\" read error: %s\n", cli_name, strerror(errno));
if (buf_cnt == 0)
RERR("\r\n\"%s\" EOF\n", cli_name);
if (hexa_ascii_flag)
{
int hex_cnt = 0;
for (int i = 0; i < buf_cnt; i++)
{
hex_cnt += sprintf(hex_buf + hex_cnt, "0x%02x [%c] ",
buf[i] & 0xff,
buf[i] >= ' ' && buf[i] <= '~' ? buf[i] : '.');
term_cnt++;
if (term_cnt == hexa_ascii_inline)
{
hex_buf[hex_cnt++] = '\r';
hex_buf[hex_cnt++] = '\n';
term_cnt = 0;
}
}
if (writen(term_fd, hex_buf, hex_cnt) != hex_cnt)
RERR("\r\n\"%s\" write error: %s\n", term_name, strerror(errno));
}
else if (hexa_flag)
{
int hex_cnt = 0;
for (int i = 0; i < buf_cnt; i++)
{
hex_cnt += sprintf(hex_buf + hex_cnt, "0x%02x ",
buf[i] & 0xff);
term_cnt++;
if (term_cnt == hexa_inline)
{
hex_buf[hex_cnt++] = '\r';
hex_buf[hex_cnt++] = '\n';
term_cnt = 0;
}
}
if (writen(term_fd, hex_buf, hex_cnt) != hex_cnt)
RERR("\r\n\"%s\" write error: %s\n", term_name, strerror(errno));
}
else
{
if (writen(term_fd, buf, buf_cnt) != buf_cnt)
RERR("\r\n\"%s\" write error: %s\n", term_name, strerror(errno));
}
if (log_file)
write_log(buf, buf_cnt, filter_colors);
}
if (pfds[1].revents & (POLLIN | POLLHUP | POLLRDHUP))
{
// From terminal to client
int buf_cnt = readn(term_fd, buf, MAXBUF);
if (buf_cnt < 0)
RERR("\r\n\"%s\" read error: %s\n", term_name, strerror(errno));
if (buf_cnt == 0)
RERR("\r\n\"%s\" EOF\n", term_name);
if (buf_cnt == 1 && *buf == exitChr)
break;
if (buf_cnt == 1 && *buf == diagChr)
{
// The "[diag] con recv buffer:" prefix in the messages below is
// asserted by tests/test-uds-diag.bash (grep -aF); keep it stable
// when editing the diagnostic output (#24, #26).
int pending = 0;
int rcvbuf = 0;
socklen_t optlen = sizeof(rcvbuf);
char diag_buf[512];
int diag_len;
if (ioctl(cli_fd, FIONREAD, &pending) == 0)
{
if (getsockopt(cli_fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &optlen) < 0)
rcvbuf = 0;
if (rcvbuf > 0)
{
int pct = (int)((long)pending * 100 / rcvbuf);
const char *level;
const char *action;
if (pct > 80)
{
level = "CRITICAL";
action = "\r\n[diag] action: remote output may block, disconnect or reduce output rate"
"\r\n[diag] action: if EPICS IOC, restart IOC or check procServ crash-loop";
}
else if (pct > 50)
{
level = "HIGH";
action = "\r\n[diag] action: check remote for output flood, consider read-only mode (con -r)"
"\r\n[diag] action: if EPICS IOC, check for device driver errors or crash-loop";
}
else
{
level = "NORMAL";
action = "";
}
diag_len = snprintf(diag_buf, sizeof(diag_buf),
"\r\n\r\n[diag] con recv buffer: %d / %d bytes (%d%%) - %s%s"
"\r\n[diag] paused -- press any key to resume\r\n",
pending, rcvbuf, pct, level, action);
}
else
diag_len = snprintf(diag_buf, sizeof(diag_buf),
"\r\n\r\n[diag] con recv buffer: %d bytes pending"
"\r\n[diag] paused -- press any key to resume\r\n",
pending);
}
else
diag_len = snprintf(diag_buf, sizeof(diag_buf),
"\r\n\r\n[diag] ioctl(FIONREAD): %s"
"\r\n[diag] paused -- press any key to resume\r\n",
strerror(errno));
writen(term_fd, diag_buf, diag_len);
if (log_file)
fwrite(diag_buf, 1, diag_len, log_file);
pfds[0].fd = -1;
readn(term_fd, buf, 1);
pfds[0].fd = cli_fd;
continue;
}
if (!readonly_flag)
{
if (echo_flag && writen(term_fd, buf, buf_cnt) != buf_cnt)
RERR("\r\n\"%s\" write error: %s\n", term_name, strerror(errno));
if (writen(cli_fd, buf, buf_cnt) != buf_cnt)
RERR("\r\n\"%s\" write error: %s\n", cli_name, strerror(errno));
if (log_file)
write_log(buf, buf_cnt, filter_colors);
}
}
}
}
// Classify a connection target as TCP host:port or a UNIX socket path.
// Returns a pointer to the host/port separator colon for a TCP target, or
// NULL for a UNIX socket path. A target containing '/' is a UNIX path
// regardless of any ':' (issue #4: a socket path may contain a colon);
// otherwise the first ':' separates host:port only when the text after it is
// a number under the same strtol(..., 0) the TCP branch uses, so no currently
// valid host:port target is reclassified.
static char *tcp_separator(char *target)
{
if (!target || !*target)
return NULL;
if (strchr(target, '/'))
return NULL;
char *p = strchr(target, ':');
if (!p || !*(p + 1))
return NULL;
char *end;
(void) strtol(p + 1, &end, 0);
if (*end)
return NULL;
return p;
}
int main(int ac, char *av[])
{
int TargetBaud = 0, nparams=0;
bool tty_flag=false, socket_flag=false, cli_flag=false, srv_flag=false, quiet_flag=false;
bool unix_flag=false;
bool filter_colors = false;
char *TargetCon = 0;
/* Command line parsing. */
if (ac < 2)
usage(av[0]);
for (int i=1; i<ac; i++)
{
switch (*av[i])
{
case '-':
++av[i];
if (!strcmp(av[i], "e") || !strcmp(av[i], "echo"))
{
echo_flag = true;
}
else if (!strcmp(av[i], "b") || !strcmp(av[i], "baud"))
{
if (++i >= ac)
PERR("After switch \"%s\" baud rate is expected.\n",av[--i]);
char *end;
TargetBaud = (int)strtol(av[i], &end, 0);
if (*end)
PERR("Invalid baud rate: \"%s\" -- ?\n", end);
tty_flag = true;
}
else if (!strcmp(av[i], "l") || !strcmp(av[i], "log"))
{
if (++i >= ac)
PERR("After switch \"%s\" baud rate is expected.\n",av[--i]);
if (log_file)
PERR("Log file have to be specified only once\n");
log_file = fopen(av[i], "w");
if (!log_file)
PERR("File \"%s\" open error: %s\n", av[i], strerror(errno));
}
else if (!strcmp(av[i], "a") || !strcmp(av[i], "append"))
{
time_t t;
struct tm *tmp;
char outstr[200];
if (++i >= ac)
PERR("After switch \"%s\" baud rate is expected.\n",av[--i]);
if (log_file)
PERR("Log file have to be specified only once\n");
log_file = fopen(av[i], "a");
if (!log_file)
PERR("File \"%s\" open error: %s\n", av[i], strerror(errno));
fprintf(log_file, "\n\n\n***** New CON session");
t = time(NULL);
tmp = localtime(&t);
if (tmp && strftime(outstr, sizeof(outstr)-1, "%a, %d %b %y %T %z", tmp))
fprintf(log_file, ", started at %s *****\n\n\n", outstr);
else
fprintf(log_file, " *****\n\n\n");
}
else if (!strcmp(av[i], "n") || !strcmp(av[i], "nocolor"))
{
filter_colors = true;
}
else if (!strcmp(av[i], "t") || !strcmp(av[i], "term"))
{
tty_flag = true;
}
else if (!strcmp(av[i], "q") || !strcmp(av[i], "quiet"))
{
quiet_flag = true;
}
else if (!strcmp(av[i], "r") || !strcmp(av[i], "readonly"))
{
readonly_flag = true;
}
else if (!strcmp(av[i], "u") || !strcmp(av[i], "unix")
|| !strcmp(av[i], "-unix"))
{
unix_flag = true;
socket_flag = true;
}
else if (!strcmp(av[i], "X") || !strcmp(av[i], "hexa"))
{
hexa_flag = true;
}
else if (!strcmp(av[i], "Y") || !strcmp(av[i], "hexa_ascii"))
{
hexa_ascii_flag = true;
}
else if (!strcmp(av[i], "x") || !strcmp(av[i], "exit"))
{
if (++i >= ac)
PERR("After switch \"%s\" quit character is expected.\n",av[--i]);
char *end;
exitChr = (unsigned char)strtol(av[i], &end, 0);
if (*end)
{
char *p = strchr(av[i], '/');
if (!p)
p = strchr(av[i], '-');
if (!p)
PERR("No delimiter ('-' or '/') found in \"KEY\" specification.\n");
*p++ = 0;
if (!strcasecmp(av[i], "control")
|| !strcasecmp(av[i], "cntrl")
|| !strcasecmp(av[i], "ctrl"))
{
}
else
{
fprintf(stderr, "No modificator found in \"KEY\" specification.\n");
fprintf(stderr, "Can be \"control\", \"cntrl\" or \"ctrl\"\n");
finish(1);
}
if (strlen(p) != 1)
{
fprintf(stderr, "Should be one character after modificator in \"KEY\" specification.\n");
fprintf(stderr, "Can be \"control\", \"cntrl\" or \"ctrl\"\n");
finish(1);
}
if (*p >= 0x40 && *p <= 0x60)
exitChr = *p - 0x40;
else if (*p > 0x60)
exitChr = *p - 0x60;
else
{
fprintf(stderr, "Invalid character after modificator in \"KEY\" specification.\n");
fprintf(stderr, "Can be \"control\", \"cntrl\" or \"ctrl\"\n");
finish(1);
}
}
// Issue #7: a configurable exit key must not shadow the fixed
// diagnostic key (diagChr, 0x14 Ctrl-T). The poll loop tests
// exitChr before diagChr, so an equal exit key silently disables
// the diagnostic. diagChr is a compile-time constant parsed
// before this point; if it ever becomes configurable, move this
// check to after all options are parsed. Comparing the finalized
// byte (not the input text) also catches numeric truncation,
// e.g. -x 0x114 wrapping to 0x14.
if (exitChr == diagChr)
{
fprintf(stderr, "Exit character 0x%02X conflicts with the "
"built-in diagnostic key (Ctrl-T, 0x14); choose a "
"different exit character.\n", exitChr);
finish(1);
}
}
else if (!strcmp(av[i], "s") || !strcmp(av[i], "server"))
{
srv_flag = true;
socket_flag = true;
}
else if (!strcmp(av[i], "c") || !strcmp(av[i], "client"))
{
cli_flag = true;
socket_flag = true;
}
else if (!strcmp(av[i], "V") || !strcmp(av[i], "version")
|| !strcmp(av[i], "-version"))
{
fprintf(stdout, "con version %s (%s)\n",
CON_VERSION, CON_GIT_HASH);
fprintf(stdout, "build date: %s\n", CON_BUILD_DATE);
exit(0);
}
else if (!strcmp(av[i], "h") || !strcmp(av[i], "help"))
{
usage(av[0]);
}
else
PERR("Invalid switch \"%s\".\n", av[i]);
break;
case '?':
usage(av[0]);
break;
default:
TargetCon = av[i];
nparams++;
}
}
if (nparams != 1)
PERR("Invalid number of parameters.\n");
if ((socket_flag && tty_flag) || (srv_flag && cli_flag))
PERR("Mutually exclusive flags are specified.\n");
// tty or socket ?
if (!socket_flag && !tty_flag)
{
if (strchr(TargetCon, ':'))
// Contains ':' - most probably socket
socket_flag = true;
else
// Otherwise - most probably tty
tty_flag = true;
}
// server or client ?
if (socket_flag && (!srv_flag && !cli_flag))
{
if (*TargetCon == ':')
// Starts with ':' - most probably server
srv_flag = true;
else if (strchr(TargetCon, ':'))
// Contains ':' - currently selected as server (not client); see issue #21
srv_flag = true;
else
PERR("\'%s\" is ambiguous - server or client flag must be specified\n", TargetCon);
}
//fprintf(stderr, "socket_flag:%d, tty_flag:%d, srv_flag:%d, cli_flag:%d\n", socket_flag, tty_flag, srv_flag, cli_flag);
signal(SIGINT, finish_int);
signal(SIGQUIT, finish_int);
signal(SIGTERM, finish_int);
signal(SIGPIPE, finish_int);
tty = new Tty();
// Open second connection, always to /dev/tty
int tty2 = tty->open(tty2_name);
if (tty2 == -1)
PERR("Can't open /dev/tty: %s\n", strerror(errno));
// Open first connection
if (socket_flag)
{
if (srv_flag)
{
int one=1;
const int name_l = sizeof(((struct hostent*)0)->h_name) + 1;
char name[name_l];
memset(name, 0, name_l);
char *p = unix_flag ? NULL : tcp_separator(TargetCon);
if (!p)
{
/*
* UNIX socket server
*/
struct sockaddr_un serv_addr;
int servlen;
const int addr_l = sizeof(((struct sockaddr_un*)0)->sun_path) + 1;
char addr[addr_l];
memset(addr, 0, addr_l);
// Open a TCP socket (an Internet stream socket).
if ((tty1 = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
PERR("socket (AF_UNIX): %s", strerror(errno));
// Reuse address
if (setsockopt(tty1, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one)) < 0)
PERR("setsockopt (SO_REUSEADDR): %s", strerror(errno));
// Bind our local address so that the client can send to us.
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sun_family = AF_UNIX;
// Keep this UNIX server guard/copy/SUN_LEN sequence aligned with
// the matching UNIX client sequence when the sun_path bound changes
// (issue #6).
if (strlen(TargetCon) >= sizeof(serv_addr.sun_path))
PERR("UNIX socket path exceeds %d bytes: \"%s\"\n", (int)(sizeof(serv_addr.sun_path) - 1), TargetCon);
strncpy(serv_addr.sun_path, TargetCon, sizeof(serv_addr.sun_path)-1);
servlen = SUN_LEN(&serv_addr);
unlink(serv_addr.sun_path);
if (bind(tty1, (struct sockaddr *)&serv_addr, servlen) < 0)
PERR("bind: %s", strerror(errno));
// Get ready to accept connection
if (listen(tty1, 1) < 0)
PERR("listen: %s", strerror(errno));
size_t name_len = strlen(TargetCon) + 32;
tty1_name = (char *)malloc(name_len);
snprintf(tty1_name, name_len, "Unix domain server %s", TargetCon);
if (!quiet_flag)
fprintf(stderr, "\r\n%s wating for connection, use Cntrl/%c to exit\r\n", tty1_name, exitChr+0x40);
for (;;)
{
struct pollfd apfds[2];
apfds[0].fd = tty1;
apfds[0].events = POLLIN;
apfds[1].fd = tty2;
apfds[1].events = POLLIN;
if (poll(apfds, 2, -1) < 0)
{
if (errno == EINTR)
continue;
PERR("poll failure: %s\n", strerror(errno));
}
if (apfds[0].revents & POLLIN)
{
struct sockaddr_un cli_unix_addr;
int clilen = sizeof(cli_unix_addr);
cli_unix_addr.sun_path[0] = 0;
int new_sock = accept(tty1, (struct sockaddr *)&cli_unix_addr, (socklen_t *)&clilen);
if (new_sock < 0)
PERR("accept: %s", strerror(errno));
if (strlen(cli_unix_addr.sun_path))
strncpy(addr, cli_unix_addr.sun_path, addr_l-1);
else
strcpy(addr, "unkonown client");
if (!quiet_flag)
fprintf(stderr, "Connection accepted from %s, use Cntrl/%c to exit\r\n", addr, exitChr+0x40);
con_core(new_sock, tty1_name, tty2, tty2_name, filter_colors);
close(new_sock);
if (!quiet_flag)
fprintf(stderr, "\r\n\r\n%s wating for connection, use Cntrl/%c to exit\r\n", tty1_name, exitChr+0x40);
}
if (apfds[1].revents & POLLIN)
{
unsigned char ch;
int buf_cnt = read(tty2, &ch, 1);
if (buf_cnt < 0)
PERR("\r\n\"%s\" read error: %s\n", tty2_name, strerror(errno));
if (buf_cnt == 0)
PERR("\r\n\"%s\" EOF\n", tty2_name);
if (ch == exitChr)
finish(0);
}
}
}
else
{
/*
* TCP socket server
*/
char *end;
TargetCon = p + 1;
int port = (int)strtol(TargetCon, &end, 0);
if (*end)
PERR("Invalid port value: \"%s\" -- ?\n", end);
struct sockaddr_in serv_addr;
struct hostent *hent;
// Open a TCP socket (an Internet stream socket).
if ((tty1 = socket(AF_INET, SOCK_STREAM, 0)) < 0)
PERR("socket (AF_INET): %s", strerror(errno));
// Reuse address
if (setsockopt(tty1, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one)) < 0)
PERR("setsockopt (SO_REUSEADDR): %s", strerror(errno));
// Bind our local address so that the client can send to us.
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
if (bind(tty1, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
PERR("bind: %s", strerror(errno));
// Get ready to accept connection
if (listen(tty1, 1) < 0)
PERR("listen: %s", strerror(errno));
tty1_name = (char*)malloc(32);
snprintf(tty1_name, 32, "TCP server :%d", port);
if (!quiet_flag)
fprintf(stderr, "\r\n%s wating for connection, use Cntrl/%c to exit\r\n", tty1_name, exitChr+0x40);
for (;;)
{
struct pollfd apfds[2];
apfds[0].fd = tty1;
apfds[0].events = POLLIN;
apfds[1].fd = tty2;
apfds[1].events = POLLIN;
if (poll(apfds, 2, -1) < 0)
{
if (errno == EINTR)
continue;
PERR("poll failure: %s\n", strerror(errno));
}
if (apfds[0].revents & POLLIN)
{
struct sockaddr_in cli_inet_addr;
int clilen = sizeof(cli_inet_addr);
const int addr_l = 16; // Max inet_ntoa()
char addr[addr_l];
memset(addr, 0, addr_l);
int new_sock = accept(tty1, (struct sockaddr *)&cli_inet_addr, (socklen_t *)&clilen);
if (new_sock < 0)
PERR("accept: %s", strerror(errno));
// Determine the client host name
hent = gethostbyaddr((char *)&cli_inet_addr.sin_addr,
sizeof(cli_inet_addr.sin_addr), AF_INET);
if (hent)
strncpy(name, hent->h_name, name_l-1);
else
strncpy(name, "???", name_l-1);
strncpy(addr, inet_ntoa(cli_inet_addr.sin_addr), addr_l-1);
if (!quiet_flag)
fprintf(stderr,"Connection accepted from %s (%s), use Cntrl/%c to exit\r\n", name, addr, exitChr+0x40);
con_core(new_sock, tty1_name, tty2, tty2_name, filter_colors);
close(new_sock);
if (!quiet_flag)
fprintf(stderr, "\r\n\r\n%s wating for connection, use Cntrl/%c to exit\r\n", tty1_name, exitChr+0x40);
}
if (apfds[1].revents & POLLIN)
{
unsigned char ch;
int buf_cnt = read(tty2, &ch, 1);
if (buf_cnt < 0)
PERR("\r\n\"%s\" read error: %s\n", tty2_name, strerror(errno));
if (buf_cnt == 0)
PERR("\r\n\"%s\" EOF\n", tty2_name);
if (ch == exitChr)
finish(0);
}
}
}
}
else if (cli_flag)
{
char *p = unix_flag ? NULL : tcp_separator(TargetCon);
if (!p)
{
/*
* UNIX local socket client
*/
struct sockaddr_un serv_addr;
int servlen;
// Fill the "serv_addr" structure
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sun_family = AF_UNIX;
// Keep this UNIX client guard/copy/SUN_LEN sequence aligned with
// the matching UNIX server sequence when the sun_path bound changes
// (issue #6).
if (strlen(TargetCon) >= sizeof(serv_addr.sun_path))
PERR("UNIX socket path exceeds %d bytes: \"%s\"\n", (int)(sizeof(serv_addr.sun_path) - 1), TargetCon);
strncpy(serv_addr.sun_path, TargetCon, sizeof(serv_addr.sun_path)-1);
servlen = SUN_LEN(&serv_addr);
// Open a UNIX socket
if ( (tty1 = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
PERR("socket (AF_UNIX): %s", strerror(errno));
tty1_name = strdup(TargetCon);
// Connect to the server.
if (connect(tty1, (struct sockaddr *) &serv_addr, servlen) < 0)
PERR("connect: %s", strerror(errno));
}
else
{
/*
* TCP socket client
*/
*p = '\0';
char *end;
int port = (int)strtol(p+1, &end, 0);
if (*end)
PERR("Invalid port value: \"%s\" -- ?\n", end);
struct sockaddr_in serv_addr;
struct hostent *hent;
// Try to determinate server IP address
if ((hent = gethostbyname(TargetCon)) == NULL)
PERR("gethostbyname(%s): %s\n", TargetCon, hstrerror(h_errno));
// Fill the "serv_addr" structure
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
memcpy(&serv_addr.sin_addr, (*(hent->h_addr_list)), sizeof(struct in_addr));
serv_addr.sin_port = htons(port);
// Open a TCP socket (an Internet stream socket).
if ( (tty1 = socket(AF_INET, SOCK_STREAM, 0)) < 0)
PERR("socket (AF_INET): %s", strerror(errno));
// Connect to the server.
if (connect(tty1, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
PERR("connect: %s", strerror(errno));
tty1_name = (char*)malloc(strlen(TargetCon) + 32);
snprintf(tty1_name, strlen(TargetCon) + 32, "%s:%d", TargetCon, port);
}
}
else
PERR("Internal error #1\n");
}
else if (tty_flag)
{
tty1_name = strdup(TargetCon);
tty1 = tty->open(TargetCon, TargetBaud);
if (tty1 < 0)
PERR("Can't open tty device %s: %s\n", TargetCon, strerror(errno));
if (!quiet_flag)
fprintf(stderr, "Connected to %s, use Cntrl/%c to exit\r\n", tty1_name, exitChr+0x40);
}
else
PERR("Internal error #2\n");
con_core(tty1, tty1_name, tty2, tty2_name, filter_colors);
finish();
}