-
Notifications
You must be signed in to change notification settings - Fork 2
/
pylon.cpp
1301 lines (1148 loc) · 48 KB
/
pylon.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
// (c) 2020-2023 ZeroTier, Inc. -- currently proprietary pending actual release and licensing. See LICENSE.md.
// HACK! Will eventually use epoll() or something in Phy<> instead of select().
// Also be sure to change ulimit -n and fs.file-max in /etc/sysctl.conf on relays.
#if defined(__linux__) || defined(__LINUX__) || defined(__LINUX) || defined(LINUX)
#include <bits/types.h>
#include <linux/posix_types.h>
#undef __FD_SETSIZE
#define __FD_SETSIZE 1048576
#undef FD_SETSIZE
#define FD_SETSIZE 1048576
#endif
#include "Phy.hpp"
#define ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS 300
#define ZT_TCP_PROXY_TCP_PORT 443
#define INVALID_SOCKET_FD -1
#include "ZeroTierSockets.h"
#include "ext/libzt/ext/ZeroTierOne/node/Mutex.hpp"
#include <algorithm>
#include <arpa/inet.h>
#include <cstdio>
#include <errno.h>
#include <fcntl.h>
#include <map>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <set>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/poll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <vector>
#define SOCKS_OPEN 0x00
#define SOCKS_CONNECT_INIT 0x01
#define SOCKS_CONNECT_IPV4 0x02
#define SOCKS_UDP 0x03
#define SOCKS_COMPLETE 0x04
#define CONNECTION_TIMEOUT 0x05
#define SOCKS_IDX_VERSION 0x00
#define IDX_COMMAND 0x01
#define IDX_METHOD 0x01
#define IDX_FRAG 0x01
#define IDX_ERROR_CODE 0x01
#define IDX_NMETHODS 0x01
#define IDX_METHODS 0x02 // Supported methods
#define IDX_ATYP 0x03
#define IDX_DST_ADDR 0x04
#define THIS_PROXY_VERSION 0x5
#define REPLY_LEN 10
#define CONNECT_TIMEOUT_S 10
#define MAX_ADDR_LEN 32
#define PORT_LEN 2
#define LISTEN_BACKLOG 32
#define MAX_PROXY_CONNECTIONS 256
#define BUF_SIZE (16 * 1024)
#define SLEEP_INTERVAL 5000
#define POLL_TIMEOUT_MS (500)
#define ZT_FILENAME (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#define ZT_RED "\x1B[31m"
#define ZT_GRN "\x1B[32m"
#define ZT_YEL "\x1B[33m"
#define ZT_BLU "\x1B[34m"
#define ZT_MAG "\x1B[35m"
#define ZT_CYN "\x1B[36m"
#define ZT_WHT "\x1B[37m"
#define ZT_RESET "\x1B[0m"
#define LOG_INFO(fmt, args...) fprintf(stderr, ZT_WHT "%17s:%06d:%25s: " fmt "\n" ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args)
#define LOG_WARN(fmt, args...) fprintf(stderr, ZT_YEL "%17s:%06d:%25s: " fmt "\n" ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args)
#define LOG_ERROR(fmt, args...) fprintf(stderr, ZT_RED "%17s:%06d:%25s: " fmt "\n" ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args)
#ifdef PYLON_DEBUG
#define LOG_DEBUG(fmt, args...) fprintf(stderr, ZT_WHT "%17s:%06d:%25s: " fmt "\n" ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args)
#else
#if defined(_WIN32)
#define LOG_DEBUG(...)
#else
#define LOG_DEBUG(fmt, args...)
#endif
#endif
ZeroTier::Mutex conn_m;
void* handle_proxy_conn(void* conn_ptr);
enum ConnectDirection { ToZeroTierNetwork, ToLocalAreaNetwork };
struct proxy_connection {
int state;
pthread_t handler;
ConnectDirection direction;
int fused_closed; // Whether this fused socket has been closed
bool shouldStop;
bool rxStopped;
bool txStopped;
int fd_lan;
int fd_zan; // end of socketpair that OS can read and write to (data on this socket is forwarded to and from the ZAN)
int fd_zts; // libzt non-OS socket
int fd_int; // end of socketpair that helper will read and write to
};
struct proxy_connection connections[MAX_PROXY_CONNECTIONS];
pthread_t threads[MAX_PROXY_CONNECTIONS];
// Retrieve data from libzt
void* fused_socket_tx_helper(void* ptr)
{
struct proxy_connection* conn = (struct proxy_connection*)ptr;
while (! conn->shouldStop && ! conn->fused_closed) {
LOG_DEBUG("0x%p A <--- Z: (%2d, %2d, %2d): polling", conn, conn->fd_zan, conn->fd_int, conn->fd_zts);
struct zts_pollfd fds[1];
int nfds = 1;
memset(fds, 0, sizeof(fds));
fds[0].fd = conn->fd_zts;
fds[0].events = ZTS_POLLIN;
int rc = zts_bsd_poll(fds, nfds, POLL_TIMEOUT_MS);
if (rc < 0) {
LOG_ERROR("0x%p A <--- Z: poll() failed", conn);
// perror("");
usleep(SLEEP_INTERVAL);
continue;
}
if (rc == 0) {
LOG_DEBUG("0x%p A <--- Z: rc==0", conn);
usleep(SLEEP_INTERVAL);
continue;
}
for (int i = 0; i < nfds; i++) {
if (fds[i].revents == 0) {
LOG_DEBUG("0x%p A <--- Z: revents==0", conn);
usleep(SLEEP_INTERVAL);
continue;
}
if (fds[i].revents != ZTS_POLLIN) {
LOG_DEBUG("0x%p A <--- Z: != ZTS_POLLIN", conn);
usleep(SLEEP_INTERVAL);
break;
}
if (fds[i].fd == conn->fd_zts) {
usleep(SLEEP_INTERVAL);
LOG_DEBUG("0x%p A <--- Z: reading from fused zt socket", conn);
char rx_from_zt_buf[BUF_SIZE];
int r = zts_read(conn->fd_zts, rx_from_zt_buf, sizeof(rx_from_zt_buf));
if (r < 0) {
LOG_DEBUG("0x%p A <--- Z: from fused zt socket (%d)", conn, r);
// perror("");
close(conn->fd_int);
conn->fused_closed = 1;
}
if (r > 0) {
int w = write(conn->fd_int, rx_from_zt_buf, r);
if (w < 0) {
LOG_ERROR("0x%p A <--- Z: to zt socket", conn);
// perror("");
}
if (w > 0) {
LOG_DEBUG("0x%p A <--- Z: wrote %d", conn, w);
}
}
}
}
}
conn->txStopped = true;
LOG_DEBUG("0x%p A <--- Z: (%2d, %2d, %2d): stopping thread", conn, conn->fd_zan, conn->fd_int, conn->fd_zts);
return NULL;
}
// Feed data into libzt
void* fused_socket_rx_helper(void* ptr)
{
struct proxy_connection* conn = (struct proxy_connection*)ptr;
while (! conn->shouldStop && ! conn->fused_closed) {
LOG_DEBUG("0x%p A ---> Z: (%2d, %2d, %2d): polling", conn, conn->fd_zan, conn->fd_int, conn->fd_zts);
struct pollfd fds[1];
int nfds = 1;
memset(fds, 0, sizeof(fds));
fds[0].fd = conn->fd_int;
fds[0].events = POLLIN;
int rc = poll(fds, nfds, POLL_TIMEOUT_MS);
if (rc < 0) {
LOG_ERROR("0x%p A ---> Z: poll failed", conn);
// perror("");
usleep(SLEEP_INTERVAL);
continue;
}
if (rc == 0) {
continue;
}
for (int i = 0; i < nfds; i++) {
if (fds[i].revents == 0) {
continue;
}
if (fds[i].revents != POLLIN) {
usleep(SLEEP_INTERVAL);
}
if (fds[i].fd == conn->fd_int) {
usleep(SLEEP_INTERVAL);
LOG_DEBUG("0x%p A ---> Z: reading from fused client socket", conn);
char rx_from_client_buf[BUF_SIZE];
int r = read(conn->fd_int, rx_from_client_buf, sizeof(rx_from_client_buf));
if (r < 0) {
LOG_DEBUG("0x%p A ---> Z: from fused client socket (%d)", conn, r);
// perror("");
}
if (r > 0) {
int w = zts_write(conn->fd_zts, rx_from_client_buf, r);
if (w < 0) {
LOG_ERROR("0x%p A ---> Z: to zt socket", conn);
// perror("");
close(conn->fd_int);
conn->fused_closed = 1;
}
if (w > 0) {
LOG_DEBUG("0x%p A ---> Z: wrote %d", conn, w);
}
}
}
}
}
conn->rxStopped = true;
LOG_DEBUG("0x%p A ---> Z: (%2d, %2d, %2d): stopping thread", conn, conn->fd_zan, conn->fd_int, conn->fd_zts);
return NULL;
}
int zts_fused_socket(int fd_pre_existing, struct proxy_connection* conn)
{
if (! conn) {
LOG_ERROR("invalid connection object provided");
return -1;
}
int fd_zts = INVALID_SOCKET_FD;
if (fd_pre_existing > 0) {
fd_zts = fd_pre_existing;
}
else {
fd_zts = zts_socket(AF_INET, SOCK_STREAM, 0);
}
// Create zt socket
if (fd_zts < 0) {
LOG_ERROR("Failed to create zt socket");
return fd_zts;
}
conn->fd_zts = fd_zts;
// Create socket pair
int sockets[2];
int err = socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
if (err < 0) {
LOG_ERROR("Failed to create socket pair");
return err;
}
conn->fd_zan = sockets[0];
conn->fd_int = sockets[1];
conn->fused_closed = 0;
LOG_DEBUG("fused socket (%d) : [%d:%d <---> %d]", conn->fd_zan, conn->fd_zan, conn->fd_int, conn->fd_zts);
pthread_t tx_thread;
pthread_create(&tx_thread, NULL, fused_socket_tx_helper, (void*)conn);
pthread_t rx_thread;
pthread_create(&rx_thread, NULL, fused_socket_rx_helper, (void*)conn);
return 0;
}
void* get_in_addr(struct sockaddr* sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int add_proxy_client_conn(int fd_socks_client, ConnectDirection dir)
{
conn_m.lock();
// Find empty connection slot for new proxied connection
int empty_slot = MAX_PROXY_CONNECTIONS;
for (int i = 0; i < MAX_PROXY_CONNECTIONS; i++) {
if (connections[i].state == SOCKS_OPEN) {
empty_slot = i;
break;
}
}
if (empty_slot == MAX_PROXY_CONNECTIONS) {
LOG_ERROR("Max number of proxied connections reached.");
conn_m.unlock();
return -1; //
}
LOG_INFO("0x%p New connection added to slot %d", (void*)&connections[empty_slot], empty_slot);
if (dir == ConnectDirection::ToZeroTierNetwork) {
connections[empty_slot].fd_lan = fd_socks_client;
}
if (dir == ConnectDirection::ToLocalAreaNetwork) {
connections[empty_slot].fd_zan = fd_socks_client;
}
connections[empty_slot].state = SOCKS_OPEN;
connections[empty_slot].direction = dir;
connections[empty_slot].shouldStop = false;
connections[empty_slot].rxStopped = false;
connections[empty_slot].txStopped = false;
pthread_create(&connections[empty_slot].handler, NULL, handle_proxy_conn, (void*)&connections[empty_slot]);
conn_m.unlock();
return 0;
}
int proxy_server(char* listen_addr, unsigned short listen_port)
{
int fd_lan_listen, fd_lan_accept;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage client_addr;
socklen_t sin_size;
struct sigaction sa;
char s[INET6_ADDRSTRLEN];
int yes = 1;
int err;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
char port_str[5] = { 0 };
snprintf(port_str, sizeof(port_str), "%d", listen_port);
if ((err = getaddrinfo(listen_addr, port_str, &hints, &servinfo)) != 0) {
LOG_DEBUG("getaddrinfo: %s", gai_strerror(err));
return 1;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((fd_lan_listen = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("socket");
continue;
}
if (setsockopt(fd_lan_listen, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (bind(fd_lan_listen, p->ai_addr, p->ai_addrlen) == -1) {
close(fd_lan_listen);
perror("bind");
continue;
}
break;
}
freeaddrinfo(servinfo);
if (p == NULL) {
LOG_DEBUG("failed to bind");
exit(1);
}
if (listen(fd_lan_listen, LISTEN_BACKLOG) < 0) {
perror("listen");
exit(1);
}
char* zt_listen_addr = (char*)"0.0.0.0";
LOG_INFO("Listening for connections via LAN on %s:%d", listen_addr, listen_port);
LOG_INFO("Listening for connections via ZeroTier network on %s:%d", zt_listen_addr, listen_port);
// Start listening on ZeroTier network using libzt
int fd_zt_listen, fd_zt_accept;
LOG_DEBUG("Creating socket...\n");
if ((fd_zt_listen = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) {
LOG_ERROR("Error (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd_zt_listen, err, zts_errno);
exit(1);
}
LOG_DEBUG("Binding...\n");
if ((err = zts_bind(fd_zt_listen, zt_listen_addr, listen_port) < 0)) {
LOG_ERROR("Error (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd_zt_listen, err, zts_errno);
exit(1);
}
LOG_DEBUG("Listening...\n");
if ((err = zts_listen(fd_zt_listen, LISTEN_BACKLOG)) < 0) {
LOG_ERROR("Error (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd_zt_listen, err, zts_errno);
exit(1);
}
// Set listen sockets to non blocking
zts_set_blocking(fd_zt_listen, false);
err = fcntl(fd_lan_listen, F_SETFL, fcntl(fd_lan_listen, F_GETFL, 0) | O_NONBLOCK);
if (err == -1) {
perror("calling fcntl");
exit(0);
}
// Accept connections
while (1) {
sleep(1);
LOG_DEBUG("Listening poll...");
// Try to accept ZeroTier virtual network connections
char remote_ipstr[ZTS_INET6_ADDRSTRLEN] = { 0 };
unsigned short port = 0;
if ((fd_zt_accept = zts_accept(fd_zt_listen, remote_ipstr, ZTS_INET6_ADDRSTRLEN, &port)) < 0) {
// Nothing
}
else {
LOG_INFO("Accepted connection from %s:%d\n", remote_ipstr, port);
if (add_proxy_client_conn(fd_zt_accept, ConnectDirection::ToLocalAreaNetwork) < 0) {
zts_close(fd_zt_accept);
}
}
// Try to accept LAN connections
sin_size = sizeof(client_addr);
fd_lan_accept = accept(fd_lan_listen, (struct sockaddr*)&client_addr, &sin_size);
if (fd_lan_accept == -1) {
// Nothing
}
else {
inet_ntop(client_addr.ss_family, get_in_addr((struct sockaddr*)&client_addr), s, sizeof(s));
LOG_INFO("Accepted connection from %s", s);
// TODO: Add port
if (add_proxy_client_conn(fd_lan_accept, ConnectDirection::ToZeroTierNetwork) < 0) {
close(fd_lan_accept);
}
}
}
return 0;
}
void* handle_proxy_conn(void* conn_ptr)
{
struct proxy_connection* conn = (struct proxy_connection*)conn_ptr;
if (! conn_ptr) {
LOG_DEBUG("invalid connection object");
return NULL;
}
if (conn->direction == ConnectDirection::ToZeroTierNetwork) {
LOG_INFO("0x%p Connection request from LAN to ZeroTier network", (void*)conn);
}
if (conn->direction == ConnectDirection::ToLocalAreaNetwork) {
LOG_INFO("0x%p Connection request from ZeroTier network to LAN", (void*)conn);
zts_fused_socket(conn->fd_zan, conn);
}
bool _run = true;
while (_run) {
if (conn->fused_closed && conn->state == SOCKS_COMPLETE) {
LOG_WARN("0x%p shutting down", conn);
break;
}
usleep(SLEEP_INTERVAL);
int rx_len_client = 0;
int rx_len_resource = 0;
char rx_from_client_buf[BUF_SIZE];
char rx_from_zt_to_client_buf[BUF_SIZE];
int nfds = 1;
struct pollfd fds[2];
memset(fds, 0, sizeof(fds));
// Poll OS client socket, and OS socketpair end
if (conn->direction == ConnectDirection::ToZeroTierNetwork) {
fds[0].fd = conn->fd_lan;
fds[0].events = POLLIN;
LOG_DEBUG("0x%p poll (fd_lan:%2d)", conn, fds[0].fd);
if (conn->state == SOCKS_COMPLETE) {
fds[1].fd = conn->fd_zan;
fds[1].events = POLLIN;
nfds = 2;
LOG_DEBUG("0x%p poll (fd_zan:%2d)", conn, fds[1].fd);
}
LOG_DEBUG("0x%p polling (%d) sockets", conn, nfds);
int rc = poll(fds, nfds, POLL_TIMEOUT_MS);
if (rc < 0) {
LOG_ERROR("0x%p poll failed", conn);
break;
}
if (rc == 0) {
break;
}
}
// Poll on OS socketpair end and LAN socket
if (conn->direction == ConnectDirection::ToLocalAreaNetwork) {
fds[0].fd = conn->fd_zan;
fds[0].events = POLLIN;
LOG_DEBUG("0x%p poll (fd_zan:%2d)", conn, fds[0].fd);
if (conn->state == SOCKS_COMPLETE) {
fds[1].fd = conn->fd_lan;
fds[1].events = POLLIN;
nfds = 2;
LOG_DEBUG("0x%p poll (fd_lan:%2d)", conn, fds[1].fd);
}
int rc = poll(fds, nfds, POLL_TIMEOUT_MS);
if (rc < 0) {
LOG_ERROR("0x%p poll failed", conn);
break;
}
if (rc == 0) {
break;
}
}
// Read data in preparation for forwarding
for (int i = 0; i < nfds; i++) {
if (fds[i].revents == 0) {
continue;
}
if (fds[i].revents != POLLIN) {
LOG_ERROR("0x%p != POLLIN (fd=%d)", conn, fds[i].fd);
_run = false;
break;
}
// Read data from client
if ((fds[i].fd == conn->fd_lan && conn->direction == ConnectDirection::ToZeroTierNetwork) || (fds[i].fd == conn->fd_zan && conn->direction == ConnectDirection::ToLocalAreaNetwork)) {
if (fds[i].fd == conn->fd_lan && conn->direction == ConnectDirection::ToZeroTierNetwork) {
LOG_DEBUG("0x%p RX reading from client socket (OS:%d)", conn, conn->fd_lan);
rx_len_client = read(conn->fd_lan, rx_from_client_buf, sizeof(rx_from_client_buf));
}
if (fds[i].fd == conn->fd_zan && conn->direction == ConnectDirection::ToLocalAreaNetwork) {
LOG_DEBUG("0x%p RX reading from client socket (OS:%d)", conn, conn->fd_zan);
rx_len_client = read(conn->fd_zan, rx_from_client_buf, sizeof(rx_from_client_buf));
}
if (rx_len_client < 0) {
LOG_ERROR("0x%p RX read (%d) from client", conn, rx_len_client);
}
if (rx_len_client == 0) {
// Closed connection
LOG_DEBUG("0x%p RX read (%d) from client", conn, rx_len_client);
_run = false;
break;
}
if (rx_len_client > 0) {
LOG_INFO("0x%p RX read (%d) from client", conn, rx_len_client);
}
}
// Read data from resource
if (conn->state == SOCKS_COMPLETE) {
if ((fds[i].fd == conn->fd_zan && conn->direction == ConnectDirection::ToZeroTierNetwork) || (fds[i].fd == conn->fd_lan && conn->direction == ConnectDirection::ToLocalAreaNetwork)) {
if (fds[i].fd == conn->fd_zan && conn->direction == ConnectDirection::ToZeroTierNetwork) {
LOG_DEBUG("0x%p RX reading from resource socket (OS:%d)", conn, conn->fd_zan);
rx_len_resource = read(conn->fd_zan, rx_from_zt_to_client_buf, sizeof(rx_from_zt_to_client_buf));
}
if (fds[i].fd == conn->fd_lan && conn->direction == ConnectDirection::ToLocalAreaNetwork) {
LOG_DEBUG("0x%p RX reading from resource socket (OS:%d)", conn, conn->fd_lan);
rx_len_resource = read(conn->fd_lan, rx_from_zt_to_client_buf, sizeof(rx_from_zt_to_client_buf));
}
if (rx_len_resource < 0) {
LOG_ERROR("0x%p RX read (%d) from resource", conn, rx_len_resource);
_run = false;
break;
}
if (rx_len_resource > 0) {
LOG_DEBUG("0x%p RX read (%d) from resource", conn, rx_len_resource);
}
}
}
}
// General data forwarding
if (conn->state == SOCKS_COMPLETE) {
// Forward traffic from client to resource
if (rx_len_client > 0) {
int tx_len_to_resource = -1;
if (conn->direction == ConnectDirection::ToZeroTierNetwork) {
LOG_DEBUG("0x%p TX writing (%d) from client to resource (OS:%d)", conn, rx_len_client, conn->fd_zan);
tx_len_to_resource = write(conn->fd_zan, rx_from_client_buf, rx_len_client);
}
if (conn->direction == ConnectDirection::ToLocalAreaNetwork) {
LOG_DEBUG("0x%p TX writing (%d) from client to resource (OS:%d)", conn, rx_len_client, conn->fd_lan);
tx_len_to_resource = write(conn->fd_lan, rx_from_client_buf, rx_len_client);
}
if (tx_len_to_resource < 0) {
LOG_ERROR("0x%p TX wrote (%d) to resource", conn, tx_len_to_resource);
}
if (tx_len_to_resource > 0) {
LOG_DEBUG("0x%p TX wrote (%d) to resource", conn, tx_len_to_resource);
}
}
// Forward traffic from resource to client
if (rx_len_resource > 0) {
int tx_len_to_client = -1;
if (conn->direction == ConnectDirection::ToZeroTierNetwork) {
LOG_DEBUG("0x%p TX writing (%d) from resource to client (OS:%d)", conn, rx_len_resource, conn->fd_lan);
tx_len_to_client = write(conn->fd_lan, rx_from_zt_to_client_buf, rx_len_resource);
}
if (conn->direction == ConnectDirection::ToLocalAreaNetwork) {
LOG_DEBUG("0x%p TX writing (%d) from resource to client (ZT:%d)", conn, rx_len_resource, conn->fd_zan);
tx_len_to_client = write(conn->fd_zan, rx_from_zt_to_client_buf, rx_len_resource);
}
if (tx_len_to_client < 0) {
LOG_ERROR("0x%p TX wrote (%d) to client", conn, tx_len_to_client);
}
if (tx_len_to_client > 0) {
LOG_DEBUG("0x%p TX wrote (%d) to client", conn, tx_len_to_client);
}
}
}
if (conn->state == SOCKS_OPEN) {
// SOCKS_OPEN
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+
LOG_DEBUG("0x%p SOCKS_OPEN", conn);
if (rx_len_client >= 3) {
int version = rx_from_client_buf[SOCKS_IDX_VERSION];
int methodsLength = rx_from_client_buf[IDX_NMETHODS];
int firstSupportedMethod = rx_from_client_buf[IDX_METHODS];
int supportedMethod = 0;
if (firstSupportedMethod == 2) {
supportedMethod = firstSupportedMethod;
}
LOG_DEBUG("0x%p <ver=%d, meth_len=%d, supp_meth=%d>", conn, version, methodsLength, supportedMethod);
// Send METHOD selection msg
// +----+--------+
// |VER | METHOD |
// +----+--------+
// | 1 | 1 |
// +----+--------+
char reply[2];
reply[SOCKS_IDX_VERSION] = THIS_PROXY_VERSION;
reply[IDX_METHOD] = supportedMethod;
if (conn->direction == ConnectDirection::ToZeroTierNetwork) {
send(conn->fd_lan, reply, sizeof(reply), 0);
}
if (conn->direction == ConnectDirection::ToLocalAreaNetwork) {
send(conn->fd_zan, reply, sizeof(reply), 0);
}
conn->state = SOCKS_CONNECT_INIT;
continue;
}
}
if (conn->state == SOCKS_CONNECT_INIT) {
// SOCKS_CONNECT_INIT
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
LOG_DEBUG("0x%p SOCKS_CONNECT_INIT", conn);
// Ex. 4(meta) + 4(ipv4) + 2(port) = 10
if (rx_len_client >= 10) {
int version = rx_from_client_buf[SOCKS_IDX_VERSION];
int cmd = rx_from_client_buf[IDX_COMMAND];
int addr_type = rx_from_client_buf[IDX_ATYP];
LOG_DEBUG("0x%p <ver=%d, cmd=%d, typ=%d>", conn, version, cmd, addr_type);
// CONNECT request
if (cmd == 1) {
LOG_DEBUG("0x%p cmd=%d", conn, cmd);
// Ipv4
if (addr_type == 1) {
int raw_addr;
memcpy(&raw_addr, &rx_from_client_buf[4], 4);
char ipstr[16];
inet_ntop(AF_INET, &raw_addr, (char*)ipstr, INET_ADDRSTRLEN);
unsigned short port = 0;
memcpy(&port, &rx_from_client_buf[8], 2);
int err = -1;
// Connect to resource on ZeroTier network
if (conn->direction == ConnectDirection::ToZeroTierNetwork) {
zts_fused_socket(INVALID_SOCKET_FD, conn);
port = ntohs(port);
LOG_DEBUG("0x%p connecting via zt to: %s:%d", conn, ipstr, port);
err = zts_connect(conn->fd_zts, ipstr, port, CONNECT_TIMEOUT_S);
LOG_DEBUG("0x%p conn->fd_zts=(ZT:%d)", conn, conn->fd_zts);
}
// Connect to resource on LAN
if (conn->direction == ConnectDirection::ToLocalAreaNetwork) {
LOG_DEBUG("0x%p connecting via lan to: %s:%d", conn, ipstr, ntohs(port));
struct sockaddr_in in4;
in4.sin_family = AF_INET;
in4.sin_addr.s_addr = raw_addr;
in4.sin_port = port;
conn->fd_lan = socket(AF_INET, SOCK_STREAM, 0);
err = connect(conn->fd_lan, (struct sockaddr*)&in4, sizeof(struct sockaddr));
LOG_DEBUG("0x%p conn->fd_lan=(OS:%d)", conn, conn->fd_lan);
}
if (err < 0) {
LOG_ERROR("0x%p error establishing connection to resource", conn);
perror("");
continue;
}
else {
/*
+----+-----+-------+------+----------+----------+
|VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
Where:
o VER protocol version: X'05'
o REP Reply field:
o X'00' succeeded
o X'01' general SOCKS server failure
o X'02' connection not allowed by ruleset
o X'03' Network unreachable
o X'04' Host unreachable
o X'05' Connection refused
o X'06' TTL expired
o X'07' Command not supported
o X'08' Address type not supported
o X'09' to X'FF' unassigned
o RSV RESERVED
o ATYP address type of following address
*/
// REPLY
conn->state = SOCKS_COMPLETE;
char replybuf[REPLY_LEN] = { 0 };
replybuf[0] = 5; // ver
replybuf[1] = 0; // rep
replybuf[2] = 0; // rsv
replybuf[3] = 1; // address type
memcpy(&replybuf[4], &raw_addr, 4);
short bind_port = htonl(port);
memcpy(&replybuf[8], &bind_port, 2);
int reply_len = -1;
if (conn->direction == ConnectDirection::ToZeroTierNetwork) {
reply_len = send(conn->fd_lan, replybuf, REPLY_LEN, 0);
}
if (conn->direction == ConnectDirection::ToLocalAreaNetwork) {
reply_len = send(conn->fd_zan, replybuf, REPLY_LEN, 0);
}
LOG_DEBUG("0x%p SOCKS Replying to client with (%d) bytes", conn, reply_len);
}
}
}
}
}
}
LOG_INFO("0x%p Closing connection", conn);
conn_m.lock();
conn->shouldStop = true;
conn->state = SOCKS_OPEN;
LOG_WARN("0x%p waiting for IO threads to stop", conn);
while (1) {
usleep(SLEEP_INTERVAL);
if (conn->txStopped && conn->rxStopped) {
break;
}
}
if (conn->direction == ConnectDirection::ToZeroTierNetwork) {
close(conn->fd_lan);
}
if (conn->direction == ConnectDirection::ToLocalAreaNetwork) {
close(conn->fd_zan);
}
conn_m.unlock();
return NULL;
}
void on_zts_event(void* msgPtr)
{
zts_event_msg_t* msg = (zts_event_msg_t*)msgPtr;
if (msg->event_code == ZTS_EVENT_NODE_ONLINE) {
LOG_DEBUG("ZTS_EVENT_NODE_ONLINE: %lx", msg->node->node_id);
}
if (msg->event_code == ZTS_EVENT_NODE_OFFLINE) {
LOG_DEBUG("ZTS_EVENT_NODE_OFFLINE");
}
if (msg->event_code == ZTS_EVENT_NETWORK_NOT_FOUND) {
LOG_DEBUG("ZTS_EVENT_NETWORK_NOT_FOUND: %lx", msg->network->net_id);
}
if (msg->event_code == ZTS_EVENT_NETWORK_ACCESS_DENIED) {
LOG_DEBUG("ZTS_EVENT_NETWORK_ACCESS_DENIED: %lx", msg->network->net_id);
}
if (msg->event_code == ZTS_EVENT_ADDR_ADDED_IP4) {
char ipstr[ZTS_INET6_ADDRSTRLEN] = { 0 };
struct zts_sockaddr_in* in = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in->sin_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
LOG_DEBUG("ZTS_EVENT_ADDR_NEW_IP: %s", ipstr);
}
}
using namespace ZeroTier;
/*
* ZeroTier TCP Proxy Server
*
* This implements a simple packet encapsulation that is designed to look like
* a TLS connection. It's not a TLS connection, but it sends TLS format record
* headers. It could be extended in the future to implement a fake TLS
* handshake.
*
* At the moment, each packet is just made to look like TLS application data:
* <[1] TLS content type> - currently 0x17 for "application data"
* <[1] TLS major version> - currently 0x03 for TLS 1.2
* <[1] TLS minor version> - currently 0x03 for TLS 1.2
* <[2] payload length> - 16-bit length of payload in bytes
* <[...] payload> - Message payload
*
* TCP is inherently inefficient for encapsulating Ethernet, since TCP and TCP
* like protocols over TCP lead to double-ACKs. So this transport is only used
* to enable access when UDP or other datagram protocols are not available.
*
* Clients send a greeting, which is a four-byte message that contains:
* <[1] ZeroTier major version>
* <[1] minor version>
* <[2] revision>
*
* If a client has sent a greeting, it uses the new version of this protocol
* in which every encapsulated ZT packet is prepended by an IP address where
* it should be forwarded (or where it came from for replies). This causes
* this proxy to act as a remote UDP socket similar to a socks proxy, which
* will allow us to move this function off the rootservers and onto dedicated
* proxy nodes.
*
* Older ZT clients that do not send this message get their packets relayed
* to/from 127.0.0.1:9993, which will allow them to talk to and relay via
* the ZT node on the same machine as the proxy. We'll only support this for
* as long as such nodes appear to be in the wild.
*/
struct TcpProxyService;
struct TcpProxyService {
Phy<TcpProxyService*>* phy;
int udpPortCounter;
struct Client {
char tcpReadBuf[131072];
char tcpWriteBuf[131072];
unsigned long tcpWritePtr;
unsigned long tcpReadPtr;
PhySocket* tcp;
PhySocket* udp;
time_t lastActivity;
bool newVersion;
};
std::map<PhySocket*, Client> clients;
PhySocket* getUnusedUdp(void* uptr)
{
for (int i = 0; i < 65535; ++i) {
++udpPortCounter;
if (udpPortCounter > 0xfffe) {
udpPortCounter = 1024;
}
struct sockaddr_in laddr;
memset(&laddr, 0, sizeof(struct sockaddr_in));
laddr.sin_family = AF_INET;
laddr.sin_port = htons((uint16_t)udpPortCounter);
PhySocket* udp = phy->udpBind(reinterpret_cast<struct sockaddr*>(&laddr), uptr);
if (udp) {
return udp;
}
}
return (PhySocket*)0;
}
void phyOnDatagram(PhySocket* sock, void** uptr, const struct sockaddr* localAddr, const struct sockaddr* from, void* data, unsigned long len)
{
if (! *uptr) {
return;
}
if ((from->sa_family == AF_INET) && (len >= 16) && (len < 2048)) {
Client& c = *((Client*)*uptr);
c.lastActivity = time((time_t*)0);
unsigned long mlen = len;
if (c.newVersion) {
mlen += 7; // new clients get IP info
}
if ((c.tcpWritePtr + 5 + mlen) <= sizeof(c.tcpWriteBuf)) {
if (! c.tcpWritePtr) {
phy->setNotifyWritable(c.tcp, true);
}
c.tcpWriteBuf[c.tcpWritePtr++] = 0x17; // look like TLS data
c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
c.tcpWriteBuf[c.tcpWritePtr++] = (char)((mlen >> 8) & 0xff);
c.tcpWriteBuf[c.tcpWritePtr++] = (char)(mlen & 0xff);
if (c.newVersion) {
c.tcpWriteBuf[c.tcpWritePtr++] = (char)4; // IPv4
*((uint32_t*)(c.tcpWriteBuf + c.tcpWritePtr)) = ((const struct sockaddr_in*)from)->sin_addr.s_addr;
c.tcpWritePtr += 4;
*((uint16_t*)(c.tcpWriteBuf + c.tcpWritePtr)) = ((const struct sockaddr_in*)from)->sin_port;
c.tcpWritePtr += 2;
}
for (unsigned long i = 0; i < len; ++i) {
c.tcpWriteBuf[c.tcpWritePtr++] = ((const char*)data)[i];
}
}
printf("<< UDP %s:%d -> %.16llx\n", inet_ntoa(reinterpret_cast<const struct sockaddr_in*>(from)->sin_addr), (int)ntohs(reinterpret_cast<const struct sockaddr_in*>(from)->sin_port), (unsigned long long)&c);
}
}
void phyOnTcpConnect(PhySocket* sock, void** uptr, bool success)
{
// unused, we don't initiate outbound connections
}
void phyOnTcpAccept(PhySocket* sockL, PhySocket* sockN, void** uptrL, void** uptrN, const struct sockaddr* from)
{
Client& c = clients[sockN];
PhySocket* udp = getUnusedUdp((void*)&c);
if (! udp) {
phy->close(sockN);
clients.erase(sockN);
printf("** TCP rejected, no more UDP ports to assign\n");
return;
}
c.tcpWritePtr = 0;
c.tcpReadPtr = 0;
c.tcp = sockN;
c.udp = udp;
c.lastActivity = time((time_t*)0);
c.newVersion = false;
*uptrN = (void*)&c;
printf("<< TCP from %s -> %.16llx\n", inet_ntoa(reinterpret_cast<const struct sockaddr_in*>(from)->sin_addr), (unsigned long long)&c);
}
void phyOnTcpClose(PhySocket* sock, void** uptr)
{
if (! *uptr) {
return;
}
Client& c = *((Client*)*uptr);
phy->close(c.udp);
clients.erase(sock);
printf("** TCP %.16llx closed\n", (unsigned long long)*uptr);
}
void phyOnTcpData(PhySocket* sock, void** uptr, void* data, unsigned long len)
{
Client& c = *((Client*)*uptr);
c.lastActivity = time((time_t*)0);
for (unsigned long i = 0; i < len; ++i) {
if (c.tcpReadPtr >= sizeof(c.tcpReadBuf)) {
phy->close(sock);
return;