Repository navigation
Expand file tree
/
Copy pathpb_relay.c
More file actions
2146 lines (2026 loc) · 82.8 KB
/
Copy pathpb_relay.c
File metadata and controls
2146 lines (2026 loc) · 82.8 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
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
// Userspace relay for the eBPF backend: TCP (SOCKS5 / HTTP CONNECT / DIRECT) and UDP (SOCKS5 UDP ASSOCIATE / DIRECT).
// Every conn/session is owned by exactly one epoll thread; handshake workers hand finished objects over through queues.
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <sys/resource.h>
#include <stdarg.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/socket.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
#include "pb_internal.h"
#define SCRATCH_SZ 65536
#define HDR_MAX 8192
#define WORKERS_MIN 8 // handshake workers: a few always, more while handshakes pile up, extras leave after a pause
#define WORKERS_MAX 64
#define WORKER_IDLE_S 20
#define UPSTREAM_CAP 48 // handshakes in flight per upstream, so a dead proxy cannot take every worker
#define MAX_DATA 8
#define PIPE_SZ (1 << 20)
#define JOBQ_MAX 4096 // handshake queue; excess accepts are shed with a log
#define MAX_UDP_SESS 4096
#define MAX_FLOWS 64
#define UDP_QMAX 32
#define UDP_QBYTES (256 * 1024)
#define UDP_MAXDG 65536
#define UDP_BATCH 16
#define FLOW_TTL_MS 1000
#define DC_SIZE 1024
#define UFLOWS_MAX 200
#define UDP_LIVE_MS 30000
#define SESS_BUCKETS 256
#define DIRECT_ID 0xFFFFFFFFu
static char TAG_STOP, TAG_WAKE, TAG_UDP, TAG_TIMER;
static int64_t now_ms(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
static void close_fd(int *fd)
{
if (*fd >= 0) { close(*fd); *fd = -1; }
}
static void fmt_ip(int family, const uint8_t *addr16, char *out, size_t n)
{
if (family == AF_INET) inet_ntop(AF_INET, addr16 + 12, out, (socklen_t)n);
else inet_ntop(AF_INET6, addr16, out, (socklen_t)n);
}
static void orig_str(const struct pb_orig *o, char *out, size_t n)
{
char ip[INET6_ADDRSTRLEN];
fmt_ip(o->family, o->addr, ip, sizeof ip);
snprintf(out, n, "%s:%u", ip, o->port);
}
static socklen_t orig_to_sa(const struct pb_orig *o, struct sockaddr_storage *ss)
{
memset(ss, 0, sizeof *ss);
if (o->family == AF_INET) {
struct sockaddr_in *a = (struct sockaddr_in *)ss;
a->sin_family = AF_INET;
a->sin_port = htons(o->port);
memcpy(&a->sin_addr, o->addr + 12, 4);
return sizeof *a;
}
struct sockaddr_in6 *a = (struct sockaddr_in6 *)ss;
a->sin6_family = AF_INET6;
a->sin6_port = htons(o->port);
memcpy(&a->sin6_addr, o->addr, 16);
return sizeof *a;
}
// Waits for fd readiness. 0 = ready (or error/hup: the next I/O call reports it), -1 = timeout, -2 = stop requested.
static int wait_fd(int fd, short ev, int64_t deadline, int stopfd)
{
for (;;) {
int64_t rem = deadline - now_ms();
if (rem <= 0) return -1;
struct pollfd p[2] = { { .fd = fd, .events = ev }, { .fd = stopfd, .events = POLLIN } };
int r = poll(p, stopfd >= 0 ? 2 : 1, rem > 60000 ? 60000 : (int)rem);
if (r < 0) { if (errno == EINTR) continue; return -1; }
if (r == 0) continue;
if (stopfd >= 0 && p[1].revents) return -2;
if (p[0].revents) return 0;
}
}
struct io {
int fd;
int64_t dl;
int stopfd;
char err[200];
};
static void seterr(struct io *x, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
static void seterr(struct io *x, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(x->err, sizeof x->err, fmt, ap);
va_end(ap);
}
static void io_waitfail(struct io *x, int w)
{
seterr(x, w == -1 ? "timed out" : "relay stopping");
}
static int io_send(struct io *x, const void *buf, size_t n)
{
const uint8_t *p = buf;
while (n) {
ssize_t r = send(x->fd, p, n, MSG_NOSIGNAL);
if (r > 0) { p += r; n -= (size_t)r; continue; }
if (r < 0 && errno == EINTR) continue;
if (r < 0 && errno == EAGAIN) {
int w = wait_fd(x->fd, POLLOUT, x->dl, x->stopfd);
if (w) { io_waitfail(x, w); return -1; }
continue;
}
seterr(x, "send failed: %s", strerror(errno));
return -1;
}
return 0;
}
static ssize_t io_recv(struct io *x, void *buf, size_t n)
{
for (;;) {
ssize_t r = recv(x->fd, buf, n, 0);
if (r > 0) return r;
if (r == 0) { seterr(x, "connection closed by peer during handshake"); return -1; }
if (errno == EINTR) continue;
if (errno == EAGAIN) {
int w = wait_fd(x->fd, POLLIN, x->dl, x->stopfd);
if (w) { io_waitfail(x, w); return -1; }
continue;
}
seterr(x, "recv failed: %s", strerror(errno));
return -1;
}
}
static int io_recv_exact(struct io *x, void *buf, size_t n)
{
uint8_t *p = buf;
while (n) {
ssize_t r = io_recv(x, p, n);
if (r < 0) return -1;
p += r;
n -= (size_t)r;
}
return 0;
}
static void tune_sock(int fd)
{
int one = 1, idle = 60, intvl = 15, cnt = 4;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one);
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof one);
setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof idle);
setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof intvl);
setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof cnt);
}
static int connect_addr(const struct sockaddr *sa, socklen_t len, int64_t dl, int stopfd, int *eno)
{
int fd = socket(sa->sa_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0) { *eno = errno; return -1; }
tune_sock(fd);
if (connect(fd, sa, len) < 0) {
if (errno != EINPROGRESS) { *eno = errno; close(fd); return -1; }
int w = wait_fd(fd, POLLOUT, dl, stopfd);
if (w) { *eno = w == -1 ? ETIMEDOUT : ECANCELED; close(fd); return -1; }
int e = 0;
socklen_t el = sizeof e;
getsockopt(fd, SOL_SOCKET, SO_ERROR, &e, &el);
if (e) { *eno = e; close(fd); return -1; }
}
return fd;
}
// Hostname resolution (IPv4): at most RES_MAX_THREADS short-lived detached lookups, deadline-bounded for the waiter,
// results cached (fresh for 60 s; last good answer reused for up to 10 min when re-resolution fails).
#define RES_MAX_THREADS 4
#define RES_DEADLINE_MS 5000
#define RES_TTL_MS 60000
#define RES_STALE_MS 600000
#define RES_CACHE_N 64
struct resreq {
struct resreq *next;
char name[256];
int refs;
bool done;
int gai;
struct in_addr addr;
pthread_cond_t cv;
};
struct rescache { char name[256]; struct in_addr addr; int64_t when; bool used; };
static pthread_mutex_t res_mu = PTHREAD_MUTEX_INITIALIZER;
static struct resreq *res_inflight;
static int res_threads;
static struct rescache res_cache[RES_CACHE_N];
static struct rescache *res_cache_find(const char *name) // res_mu held
{
for (int i = 0; i < RES_CACHE_N; i++) if (res_cache[i].used && !strcmp(res_cache[i].name, name)) return &res_cache[i];
return NULL;
}
static void res_unref(struct resreq *r) // res_mu held
{
if (--r->refs == 0) { pthread_cond_destroy(&r->cv); free(r); }
}
static bool block_sigpipe(void);
static void *res_thread(void *arg)
{
struct resreq *r = arg;
block_sigpipe();
struct addrinfo hints, *res = NULL;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
int gr = getaddrinfo(r->name, NULL, &hints, &res);
pthread_mutex_lock(&res_mu);
if (gr == 0 && res && res->ai_family == AF_INET) {
r->addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
struct rescache *c = res_cache_find(r->name);
if (!c) {
c = &res_cache[0];
for (int i = 0; i < RES_CACHE_N; i++) {
if (!res_cache[i].used) { c = &res_cache[i]; break; }
if (res_cache[i].when < c->when) c = &res_cache[i];
}
}
snprintf(c->name, sizeof c->name, "%s", r->name);
c->addr = r->addr; c->when = now_ms(); c->used = true;
} else {
r->gai = gr ? gr : EAI_NONAME;
}
r->done = true;
for (struct resreq **pp = &res_inflight; *pp; pp = &(*pp)->next)
if (*pp == r) { *pp = r->next; break; }
res_threads--;
pthread_cond_broadcast(&r->cv);
res_unref(r);
pthread_mutex_unlock(&res_mu);
if (res) freeaddrinfo(res);
return NULL;
}
static int resolve_v4(const char *name, int64_t dl, int stopfd, struct in_addr *out, char *err, size_t errn)
{
int64_t limit = now_ms() + RES_DEADLINE_MS;
if (dl > limit) dl = limit;
pthread_mutex_lock(&res_mu);
struct rescache *c = res_cache_find(name);
if (c && now_ms() - c->when < RES_TTL_MS) { *out = c->addr; pthread_mutex_unlock(&res_mu); return 0; }
struct resreq *r;
for (r = res_inflight; r; r = r->next) if (!strcmp(r->name, name)) break;
const char *why = NULL;
if (!r) {
if (res_threads >= RES_MAX_THREADS) {
why = "resolver busy";
} else {
r = calloc(1, sizeof *r);
pthread_condattr_t ca;
pthread_condattr_init(&ca);
pthread_condattr_setclock(&ca, CLOCK_MONOTONIC);
if (r) pthread_cond_init(&r->cv, &ca);
pthread_condattr_destroy(&ca);
pthread_t th;
pthread_attr_t at;
pthread_attr_init(&at);
pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&at, 256 * 1024);
if (r) {
snprintf(r->name, sizeof r->name, "%s", name);
r->refs = 2;
r->next = res_inflight; res_inflight = r;
res_threads++;
if (pthread_create(&th, &at, res_thread, r) != 0) {
res_inflight = r->next; res_threads--; r->refs = 1;
res_unref(r); r = NULL; why = "cannot start resolver thread";
}
} else why = "out of memory";
pthread_attr_destroy(&at);
}
} else {
r->refs++;
}
int rc = -1;
if (r) {
while (!r->done) {
int64_t rem = dl - now_ms();
if (rem <= 0) { why = "timed out"; break; }
struct pollfd sp = { .fd = stopfd, .events = POLLIN };
if (stopfd >= 0 && poll(&sp, 1, 0) > 0) { why = "relay stopping"; break; }
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
int64_t ms = rem < 50 ? rem : 50;
ts.tv_nsec += ms * 1000000;
ts.tv_sec += ts.tv_nsec / 1000000000; ts.tv_nsec %= 1000000000;
pthread_cond_timedwait(&r->cv, &res_mu, &ts);
}
if (r->done && !r->gai) { *out = r->addr; rc = 0; }
else if (r->done) { snprintf(err, errn, "cannot resolve '%s': %s", name, gai_strerror(r->gai)); why = NULL; }
res_unref(r);
}
if (rc != 0) {
c = res_cache_find(name);
if (c && now_ms() - c->when < RES_STALE_MS) { *out = c->addr; rc = 0; }
}
pthread_mutex_unlock(&res_mu);
if (rc != 0 && why) snprintf(err, errn, "cannot resolve '%s': %s", name, why);
return rc;
}
// Resolves and connects to the proxy; on failure writes a readable reason to err.
static int connect_host(const char *host, uint16_t port, int64_t dl, int stopfd, char *err, size_t errn)
{
struct sockaddr_storage ss[1];
socklen_t sl[1];
int n = 0;
struct in_addr a4;
struct in6_addr a6;
memset(ss, 0, sizeof ss);
if (inet_pton(AF_INET, host, &a4) == 1 || (inet_pton(AF_INET6, host, &a6) != 1 && resolve_v4(host, dl, stopfd, &a4, err, errn) == 0)) {
struct sockaddr_in *s = (struct sockaddr_in *)&ss[0];
s->sin_family = AF_INET; s->sin_port = htons(port); s->sin_addr = a4;
sl[0] = sizeof *s; n = 1;
} else if (inet_pton(AF_INET6, host, &a6) == 1) {
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&ss[0];
s->sin6_family = AF_INET6; s->sin6_port = htons(port); s->sin6_addr = a6;
sl[0] = sizeof *s; n = 1;
} else {
return -1;
}
int eno = ETIMEDOUT;
for (int i = 0; i < n; i++) {
int64_t rem = dl - now_ms();
int64_t d = (i + 1 < n && rem > 2) ? now_ms() + rem / 2 : dl;
int fd = connect_addr((struct sockaddr *)&ss[i], sl[i], d, stopfd, &eno);
if (fd >= 0) return fd;
if (eno == ECANCELED) break;
}
snprintf(err, errn, "connect to %s:%u failed: %s", host, port, strerror(eno));
return -1;
}
struct s5dst { uint8_t atyp; uint8_t addr[16]; char host[256]; uint16_t port; };
struct s5bnd { uint8_t atyp; uint8_t addr[16]; uint16_t port; };
static const char *socks5_rep_str(int rep)
{
switch (rep) {
case 1: return "general SOCKS server failure";
case 2: return "connection not allowed by ruleset";
case 3: return "network unreachable";
case 4: return "host unreachable";
case 5: return "connection refused by target";
case 6: return "TTL expired";
case 7: return "command not supported";
case 8: return "address type not supported";
default: return "unknown error";
}
}
static void s5dst_from_orig(struct s5dst *d, const struct pb_orig *o)
{
memset(d, 0, sizeof *d);
d->port = o->port;
if (o->family == AF_INET) { d->atyp = 1; memcpy(d->addr, o->addr + 12, 4); }
else { d->atyp = 4; memcpy(d->addr, o->addr, 16); }
}
static int socks5_request(struct io *x, const struct pb_proxy *p, uint8_t cmd, const struct s5dst *d, struct s5bnd *b)
{
bool auth = p->user[0] != 0;
uint8_t g[4] = { 5, auth ? 2 : 1, 0, 2 };
if (io_send(x, g, auth ? 4 : 3)) return -1;
uint8_t r[2];
if (io_recv_exact(x, r, 2)) return -1;
if (r[0] != 5) { seterr(x, "not a SOCKS5 server (bad greeting reply 0x%02x)", r[0]); return -1; }
if (r[1] == 0xFF) { seterr(x, "SOCKS5 proxy rejected all auth methods (credentials required or not accepted)"); return -1; }
if (r[1] == 2) {
size_t ul = strlen(p->user), pl = strlen(p->pass);
if (!auth) { seterr(x, "SOCKS5 proxy requires username/password but none configured"); return -1; }
if (ul > 255 || pl > 255) { seterr(x, "SOCKS5 credentials too long"); return -1; }
uint8_t ab[3 + 255 + 255];
size_t o = 0;
ab[o++] = 1; ab[o++] = (uint8_t)ul; memcpy(ab + o, p->user, ul); o += ul;
ab[o++] = (uint8_t)pl; memcpy(ab + o, p->pass, pl); o += pl;
int sent = io_send(x, ab, o);
explicit_bzero(ab, sizeof ab);
if (sent) return -1;
if (io_recv_exact(x, r, 2)) return -1;
if (r[1] != 0) { seterr(x, "SOCKS5 authentication failed (wrong username or password)"); return -1; }
} else if (r[1] != 0) {
seterr(x, "SOCKS5 proxy selected unsupported auth method 0x%02x", r[1]);
return -1;
}
uint8_t rq[4 + 1 + 255 + 2];
size_t o = 0;
rq[o++] = 5; rq[o++] = cmd; rq[o++] = 0; rq[o++] = d->atyp;
if (d->atyp == 1) { memcpy(rq + o, d->addr, 4); o += 4; }
else if (d->atyp == 4) { memcpy(rq + o, d->addr, 16); o += 16; }
else {
size_t hl = strlen(d->host);
if (hl == 0 || hl > 255) { seterr(x, "invalid target host name"); return -1; }
rq[o++] = (uint8_t)hl; memcpy(rq + o, d->host, hl); o += hl;
}
rq[o++] = (uint8_t)(d->port >> 8); rq[o++] = (uint8_t)d->port;
if (io_send(x, rq, o)) return -1;
uint8_t h[4];
if (io_recv_exact(x, h, 4)) return -1;
if (h[0] != 5) { seterr(x, "bad SOCKS5 reply version 0x%02x", h[0]); return -1; }
if (h[1] != 0) { seterr(x, "SOCKS5 request failed: %s (code %u)", socks5_rep_str(h[1]), h[1]); return -1; }
struct s5bnd tmp;
if (!b) b = &tmp;
memset(b, 0, sizeof *b);
b->atyp = h[3];
size_t al;
if (h[3] == 1) al = 4;
else if (h[3] == 4) al = 16;
else if (h[3] == 3) {
uint8_t l;
if (io_recv_exact(x, &l, 1)) return -1;
uint8_t skip[256];
if (io_recv_exact(x, skip, l)) return -1;
al = 0;
} else { seterr(x, "SOCKS5 reply has unknown address type %u", h[3]); return -1; }
if (al && io_recv_exact(x, b->addr, al)) return -1;
uint8_t pt[2];
if (io_recv_exact(x, pt, 2)) return -1;
b->port = (uint16_t)(pt[0] << 8 | pt[1]);
return 0;
}
static void b64(const char *in, size_t n, char *out)
{
static const char t[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t i, o = 0;
for (i = 0; i + 2 < n; i += 3) {
uint32_t v = (uint8_t)in[i] << 16 | (uint8_t)in[i + 1] << 8 | (uint8_t)in[i + 2];
out[o++] = t[v >> 18]; out[o++] = t[(v >> 12) & 63]; out[o++] = t[(v >> 6) & 63]; out[o++] = t[v & 63];
}
if (i < n) {
uint32_t v = (uint8_t)in[i] << 16 | (i + 1 < n ? (uint8_t)in[i + 1] << 8 : 0);
out[o++] = t[v >> 18]; out[o++] = t[(v >> 12) & 63];
out[o++] = i + 1 < n ? t[(v >> 6) & 63] : '=';
out[o++] = '=';
}
out[o] = 0;
}
static int http_connect(struct io *x, const struct pb_proxy *p, const char *host, uint16_t port, uint8_t *left, size_t *leftn)
{
char hp[300];
snprintf(hp, sizeof hp, strchr(host, ':') ? "[%s]:%u" : "%s:%u", host, port);
char req[1024 + 700];
int n = snprintf(req, sizeof req, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n", hp, hp);
if (p->user[0]) {
char cred[520], enc[720];
int cl = snprintf(cred, sizeof cred, "%s:%s", p->user, p->pass);
if (cl < 0 || cl >= (int)sizeof cred) { seterr(x, "HTTP proxy credentials too long"); return -1; }
b64(cred, (size_t)cl, enc);
n += snprintf(req + n, sizeof req - (size_t)n, "Proxy-Authorization: Basic %s\r\n", enc);
explicit_bzero(cred, sizeof cred);
explicit_bzero(enc, sizeof enc);
}
n += snprintf(req + n, sizeof req - (size_t)n, "\r\n");
int sent = io_send(x, req, (size_t)n);
explicit_bzero(req, sizeof req);
if (sent) return -1;
uint8_t buf[HDR_MAX];
size_t tot = 0, hend = 0;
while (!hend) {
if (tot >= sizeof buf) { seterr(x, "HTTP proxy response headers too large"); return -1; }
ssize_t r = io_recv(x, buf + tot, sizeof buf - tot);
if (r < 0) return -1;
size_t from = tot >= 3 ? tot - 3 : 0;
tot += (size_t)r;
for (size_t i = from; i + 4 <= tot; i++)
if (!memcmp(buf + i, "\r\n\r\n", 4)) { hend = i + 4; break; }
}
int code = 0;
if (hend >= 12 && !memcmp(buf, "HTTP/", 5)) {
const uint8_t *sp = memchr(buf, ' ', hend);
if (sp && sp + 4 <= buf + hend) code = (sp[1] - '0') * 100 + (sp[2] - '0') * 10 + (sp[3] - '0');
}
if (code < 200 || code > 299) {
if (code == 0) seterr(x, "invalid HTTP proxy response");
else if (code == 407) seterr(x, "HTTP proxy authentication required (407): check username/password");
else if (code == 403) seterr(x, "HTTP proxy forbids this connection (403)");
else if (code >= 500) seterr(x, "HTTP proxy or upstream error (%d)", code);
else seterr(x, "HTTP proxy refused CONNECT (%d)", code);
return -1;
}
*leftn = tot - hend;
if (*leftn) memcpy(left, buf + hend, *leftn);
return 0;
}
struct conn {
struct conn *prev, *next;
int fd[2];
size_t off[2], len[2]; // pend[d]: unsent tail of bytes read from fd[d] (heap, freed once drained)
uint8_t *pend[2];
bool dns; // original destination port 53: upstream->client is parsed as TCP-DNS
bool doff; // stopped observing (malformed stream)
uint8_t *dbuf;
size_t dhave, dcap;
uint32_t mask[2];
bool eof[2], shut[2], dead;
int64_t last;
// what GetFlows reports
uint64_t id, bytes[2];
int64_t t0;
uint32_t pid;
uint16_t port, proxy_id;
uint8_t family, addr[16];
};
static void conn_bufs_free(struct conn *c)
{
free(c->pend[0]); free(c->pend[1]); free(c->dbuf);
c->pend[0] = c->pend[1] = c->dbuf = NULL;
}
struct dthread {
pthread_t th;
bool started;
int ep, wake;
pthread_mutex_t mu;
struct conn *inq_head, *inq_tail;
struct conn *conns;
struct conn *grave;
uint8_t *scratch;
int pfd[2]; // reusable splice pipe; always empty between connections
bool nosplice;
atomic_int load;
};
enum { J_TCP = 1, J_UDP };
struct sess;
struct job {
struct job *next;
int kind;
unsigned key; // upstream the handshake talks to (0 = not known before the decision)
int fd;
struct pb_orig o;
struct sess *s;
};
struct flowent { uint8_t addr[16]; uint16_t port; uint32_t ip_be; int64_t last; };
struct pkt { size_t len; uint8_t d[]; };
enum { SK_DIRECT = 1, SK_SOCKS5, SK_DROP };
enum { ST_SETUP = 1, ST_READY, ST_FAILED };
struct ref { struct sess *s; int which; };
struct sess {
struct sess *hnext, *prev, *next, *dnext;
struct sockaddr_in cli;
uint32_t id, flow_be; // id = proxy id or DIRECT_ID; flow_be only for DIRECT sessions
uint64_t sid;
int kind, state;
int up_fd, ctl_fd;
bool connected; // DIRECT: v6 sockets are connected; v4 are not (replies from any port of the host are accepted)
struct sockaddr_storage dst;
socklen_t dstlen;
uint16_t dport;
bool dead, ok, warned;
uint32_t pid; // process the session belongs to
int64_t last, fail_until;
struct pb_proxy proxy;
char err[700];
struct ref ref[2];
int nflows;
struct flowent flows[MAX_FLOWS];
struct pkt *q[UDP_QMAX];
int nq;
size_t qbytes;
};
struct dce {
bool used;
struct sockaddr_in cli;
uint32_t flow_be, pid;
struct pb_orig o;
int action, fidx;
int64_t looked, last, t0;
uint64_t sid, id, sent, recv;
};
static struct {
pthread_mutex_t life;
bool running;
struct pb_relay_cfg cfg;
int lfd, ufd, stopfd, tmfd, uep, uwake;
atomic_bool stopping;
atomic_int nconn;
atomic_uint rr;
atomic_ullong flow_id;
uint16_t tcp_port, udp_port;
pthread_t acceptor; bool acc_started;
int nworkers, nidle;
int busy[256]; // handshakes in flight per upstream key
pthread_cond_t wdone;
struct dthread data[MAX_DATA];
int ndata;
pthread_t udpth; bool udp_started;
pthread_mutex_t jmu;
pthread_cond_t jcv;
struct job *jhead, *jtail;
int jcount;
pthread_mutex_t dmu;
struct sess *done;
struct sess *sess_head;
struct sess *buckets[SESS_BUCKETS];
int nsess;
struct sess *sgrave;
struct dce *dc;
pthread_mutex_t fmu; // guards uflows, the UDP side of GetFlows (published by the UDP thread once a second)
struct pb_flow_info uflows[UFLOWS_MAX]; int nuflows;
uint8_t *rxbuf;
int64_t drop_count, drop_logged;
uint64_t next_sid;
struct mmsghdr *mm;
struct iovec *mmiov;
struct sockaddr_in *mmname;
char (*mmctl)[CMSG_SPACE(sizeof(struct in_pktinfo))];
} R = { .life = PTHREAD_MUTEX_INITIALIZER, .jmu = PTHREAD_MUTEX_INITIALIZER, .jcv = PTHREAD_COND_INITIALIZER, .wdone = PTHREAD_COND_INITIALIZER,
.dmu = PTHREAD_MUTEX_INITIALIZER, .fmu = PTHREAD_MUTEX_INITIALIZER, .lfd = -1, .ufd = -1, .stopfd = -1, .tmfd = -1, .uep = -1, .uwake = -1 };
static void proxy_desc(const struct pb_proxy *p, char *out, size_t n)
{
snprintf(out, n, "%s %s:%u", p->type == PROXY_TYPE_SOCKS5 ? "SOCKS5" : "HTTP", p->host, p->port);
}
static void *worker_main(void *arg);
// splice() has no MSG_NOSIGNAL: writing into a connection the peer already reset raises SIGPIPE, whose default action ends
// the whole process (the CLI or GUI that hosts this library). Every relay thread blocks the signal for its lifetime, so the
// write fails with EPIPE and the connection is closed by the ordinary error path. The embedding application's own signal
// handling is not touched. Returns false when the mask could not be set.
static bool block_sigpipe(void)
{
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGPIPE);
return pthread_sigmask(SIG_BLOCK, &set, NULL) == 0;
}
// Caller holds R.jmu.
static void worker_spawn_locked(void)
{
pthread_attr_t at;
pthread_t th;
pthread_attr_init(&at);
pthread_attr_setstacksize(&at, 512 * 1024);
pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
R.nworkers++;
if (pthread_create(&th, &at, worker_main, NULL) != 0) R.nworkers--;
pthread_attr_destroy(&at);
}
static int job_push(int kind, int fd, const struct pb_orig *o, struct sess *s)
{
struct job *j = calloc(1, sizeof *j);
if (!j) return -1;
j->kind = kind; j->fd = fd; j->s = s;
if (o) j->o = *o;
if (kind == J_TCP && o && o->action == PB_ACT_PROXY) j->key = 1 + o->proxy_id % 255u;
else if (kind != J_TCP && s) j->key = 1 + s->proxy.id % 255u;
pthread_mutex_lock(&R.jmu);
if (R.jcount >= JOBQ_MAX || atomic_load(&R.stopping)) {
pthread_mutex_unlock(&R.jmu);
free(j);
return -1;
}
if (R.jtail) R.jtail->next = j; else R.jhead = j;
R.jtail = j;
R.jcount++;
if (R.jcount > R.nidle && R.nworkers < WORKERS_MAX && R.busy[j->key] < UPSTREAM_CAP) worker_spawn_locked();
pthread_cond_signal(&R.jcv);
pthread_mutex_unlock(&R.jmu);
return 0;
}
static void conn_handoff(int cfd, int ufd, const uint8_t *left, size_t leftn, bool dns, const struct pb_orig *o, uint32_t proxy_id)
{
struct conn *c = calloc(1, sizeof *c);
if (!c) { close(cfd); close(ufd); atomic_fetch_sub(&R.nconn, 1); return; }
c->fd[0] = cfd; c->fd[1] = ufd;
c->dns = dns;
c->id = atomic_fetch_add(&R.flow_id, 1) + 1;
c->t0 = now_ms();
c->pid = o->pid; c->port = o->port; c->proxy_id = (uint16_t)proxy_id; c->family = o->family;
memcpy(c->addr, o->addr, 16);
if (leftn) {
uint8_t *m = malloc(leftn);
if (!m) { close(cfd); close(ufd); free(c); atomic_fetch_sub(&R.nconn, 1); return; }
memcpy(m, left, leftn);
if (dns) { c->dbuf = m; c->dhave = c->dcap = leftn; } // must pass through the DNS parser
else { c->pend[1] = m; c->len[1] = leftn; }
}
unsigned start = atomic_fetch_add(&R.rr, 1);
struct dthread *t = &R.data[start % R.ndata];
for (int i = 1; i < R.ndata; i++) {
struct dthread *u = &R.data[(start + i) % R.ndata];
if (atomic_load(&u->load) < atomic_load(&t->load)) t = u;
}
atomic_fetch_add(&t->load, 1);
pthread_mutex_lock(&t->mu);
if (atomic_load(&R.stopping)) {
pthread_mutex_unlock(&t->mu);
atomic_fetch_sub(&t->load, 1);
close(cfd); close(ufd); conn_bufs_free(c); free(c);
atomic_fetch_sub(&R.nconn, 1);
return;
}
if (t->inq_tail) t->inq_tail->next = c; else t->inq_head = c;
t->inq_tail = c;
pthread_mutex_unlock(&t->mu);
eventfd_write(t->wake, 1);
}
static void tcp_job_run(struct job *j)
{
struct pb_orig *o = &j->o;
int cfd = j->fd, up = -1, action = o->action;
uint32_t pid = o->proxy_id;
int64_t dl = now_ms() + (int64_t)R.cfg.handshake_timeout_s * 1000;
char dst[80], err[1024] = "", desc[300];
uint8_t left[HDR_MAX];
size_t leftn = 0;
orig_str(o, dst, sizeof dst);
if (action == PB_ACT_DECIDE) {
struct pb_decision d;
pb_core_decide(o, &d);
action = d.action; pid = d.proxy_id;
}
if (action == PB_ACT_PROXY && pb_core_is_proxy_process(o->pid, pid)) action = PB_ACT_DIRECT; // a local proxy must not loop through itself
if (action == PB_ACT_DIRECT) {
pb_core_flow_event(o, PB_ACT_DIRECT);
struct sockaddr_storage ss;
socklen_t sl = orig_to_sa(o, &ss);
int eno = 0;
up = connect_addr((struct sockaddr *)&ss, sl, dl, R.stopfd, &eno);
if (up < 0) snprintf(err, sizeof err, "direct connect to %s failed: %s", dst, strerror(eno));
} else if (action == PB_ACT_PROXY) {
struct pb_proxy px;
if (pb_core_get_proxy(pid, &px) != 0) {
pb_core_flow_event(o, PB_ACT_PROXY);
snprintf(err, sizeof err, "no proxy configured (id %u) for %s", pid, dst);
} else {
proxy_desc(&px, desc, sizeof desc);
pb_core_flow_event(o, PB_ACT_PROXY);
char cerr[200];
up = connect_host(px.host, px.port, dl, R.stopfd, cerr, sizeof cerr);
if (up < 0) {
snprintf(err, sizeof err, "proxy %s: %s", desc, cerr);
} else {
struct io x = { .fd = up, .dl = dl, .stopfd = R.stopfd };
int rc;
char hn[256];
bool named = px.send_domain && pb_core_name_for(o, hn, sizeof hn) == 0;
if (px.type == PROXY_TYPE_SOCKS5) {
struct s5dst d;
s5dst_from_orig(&d, o);
if (named) { d.atyp = 3; snprintf(d.host, sizeof d.host, "%s", hn); }
rc = socks5_request(&x, &px, 1, &d, NULL);
} else {
char ip[INET6_ADDRSTRLEN];
fmt_ip(o->family, o->addr, ip, sizeof ip);
rc = http_connect(&x, &px, named ? hn : ip, o->port, left, &leftn);
}
if (rc) {
snprintf(err, sizeof err, "proxy %s -> %s: %s", desc, dst, x.err);
close(up); up = -1;
}
}
}
} else {
pb_core_flow_event(o, PB_ACT_BLOCK);
setsockopt(cfd, SOL_SOCKET, SO_LINGER, &(struct linger){ 1, 0 }, sizeof(struct linger));
close(cfd);
atomic_fetch_sub(&R.nconn, 1);
return;
}
if (up < 0) {
pb_core_log("relay: %s", err);
close(cfd);
atomic_fetch_sub(&R.nconn, 1);
return;
}
conn_handoff(cfd, up, left, leftn, o->port == 53, o, action == PB_ACT_PROXY ? pid : 0);
}
static void udp_job_run(struct sess *s)
{
int64_t dl = now_ms() + (int64_t)R.cfg.handshake_timeout_s * 1000;
char cerr[200], desc[300];
int ctl = -1, up = -1;
proxy_desc(&s->proxy, desc, sizeof desc);
s->ok = false;
ctl = connect_host(s->proxy.host, s->proxy.port, dl, R.stopfd, cerr, sizeof cerr);
if (ctl < 0) { snprintf(s->err, sizeof s->err, "%s: %s", desc, cerr); goto out; }
struct io x = { .fd = ctl, .dl = dl, .stopfd = R.stopfd };
struct s5dst d;
struct s5bnd b;
memset(&d, 0, sizeof d);
d.atyp = 1;
if (socks5_request(&x, &s->proxy, 3, &d, &b)) { snprintf(s->err, sizeof s->err, "%s UDP ASSOCIATE: %s", desc, x.err); goto out; }
if (b.atyp == 3) { snprintf(s->err, sizeof s->err, "%s: UDP relay address is a domain name (unsupported)", desc); goto out; }
struct sockaddr_storage ra;
socklen_t rl;
memset(&ra, 0, sizeof ra);
static const uint8_t zero[16];
bool unspec = !memcmp(b.addr, zero, b.atyp == 1 ? 4 : 16);
if (unspec) { // use the address we reached the proxy at
rl = sizeof ra;
if (getpeername(ctl, (struct sockaddr *)&ra, &rl) < 0) { snprintf(s->err, sizeof s->err, "%s: getpeername: %s", desc, strerror(errno)); goto out; }
if (ra.ss_family == AF_INET) ((struct sockaddr_in *)&ra)->sin_port = htons(b.port);
else ((struct sockaddr_in6 *)&ra)->sin6_port = htons(b.port);
} else {
// A relay address inside this host is only plausible when the proxy itself is here; a remote proxy that names
// 127.x or ::1 would turn the relay into a blind sender towards local services.
struct sockaddr_storage pa;
socklen_t pl = sizeof pa;
bool peer_local = getpeername(ctl, (struct sockaddr *)&pa, &pl) == 0 &&
((pa.ss_family == AF_INET && (ntohl(((struct sockaddr_in *)&pa)->sin_addr.s_addr) >> 24) == 127) ||
(pa.ss_family == AF_INET6 && IN6_IS_ADDR_LOOPBACK(&((struct sockaddr_in6 *)&pa)->sin6_addr)));
bool bnd_local = b.atyp == 1 ? b.addr[0] == 127 : IN6_IS_ADDR_LOOPBACK((const struct in6_addr *)b.addr);
if (bnd_local && !peer_local) { snprintf(s->err, sizeof s->err, "%s: UDP relay address points at this host", desc); goto out; }
if (b.atyp == 1) {
struct sockaddr_in *a = (struct sockaddr_in *)&ra;
a->sin_family = AF_INET; a->sin_port = htons(b.port); memcpy(&a->sin_addr, b.addr, 4);
rl = sizeof *a;
} else {
struct sockaddr_in6 *a = (struct sockaddr_in6 *)&ra;
a->sin6_family = AF_INET6; a->sin6_port = htons(b.port); memcpy(&a->sin6_addr, b.addr, 16);
rl = sizeof *a;
}
}
up = socket(ra.ss_family, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (up < 0 || connect(up, (struct sockaddr *)&ra, rl) < 0) {
snprintf(s->err, sizeof s->err, "%s: UDP relay socket: %s", desc, strerror(errno));
goto out;
}
s->ctl_fd = ctl; s->up_fd = up; s->ok = true;
ctl = up = -1;
out:
close_fd(&ctl);
close_fd(&up);
pthread_mutex_lock(&R.dmu);
s->dnext = R.done;
R.done = s;
pthread_mutex_unlock(&R.dmu);
eventfd_write(R.uwake, 1);
}
static void *worker_main(void *arg)
{
(void)arg;
block_sigpipe();
pthread_mutex_lock(&R.jmu);
while (!atomic_load(&R.stopping)) {
struct job *prev = NULL, *j;
for (j = R.jhead; j; prev = j, j = j->next)
if (R.busy[j->key] < UPSTREAM_CAP) break;
if (j) {
if (prev) prev->next = j->next; else R.jhead = j->next;
if (R.jtail == j) R.jtail = prev;
R.jcount--;
unsigned key = j->key;
R.busy[key]++;
pthread_mutex_unlock(&R.jmu);
if (j->kind == J_TCP) tcp_job_run(j); else udp_job_run(j->s);
free(j);
pthread_mutex_lock(&R.jmu);
R.busy[key]--;
pthread_cond_signal(&R.jcv); // a job held back by this upstream's cap may be able to run now
continue;
}
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += WORKER_IDLE_S;
R.nidle++;
int rc = pthread_cond_timedwait(&R.jcv, &R.jmu, &ts);
R.nidle--;
if (rc == ETIMEDOUT && !R.jhead && R.nworkers > WORKERS_MIN) break;
}
R.nworkers--;
pthread_cond_broadcast(&R.wdone);
pthread_mutex_unlock(&R.jmu);
return NULL;
}
static void *acceptor_main(void *arg)
{
(void)arg;
block_sigpipe();
int64_t last_cap_log = 0;
while (!atomic_load(&R.stopping)) {
struct pollfd p[2] = { { .fd = R.lfd, .events = POLLIN }, { .fd = R.stopfd, .events = POLLIN } };
if (poll(p, 2, -1) < 0) { if (errno == EINTR) continue; break; }
if (p[1].revents) break;
for (int i = 0; i < 256; i++) {
struct sockaddr_in pa;
socklen_t pl = sizeof pa;
int fd = accept4(R.lfd, (struct sockaddr *)&pa, &pl, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (fd < 0) {
if (errno == EMFILE || errno == ENFILE || errno == ENOBUFS || errno == ENOMEM) {
pb_core_log("relay: accept: %s, backing off", strerror(errno));
struct pollfd s = { .fd = R.stopfd, .events = POLLIN };
poll(&s, 1, 200);
}
break;
}
struct pb_orig o;
if (pb_core_take_tcp_orig(pa.sin_addr.s_addr, ntohs(pa.sin_port), &o) != 0) {
static int64_t last_log; static unsigned long unknown; // anyone can connect to the port: one line per 5 s
unknown++;
int64_t t = now_ms();
if (t - last_log > 5000) {
pb_core_log("relay: no original destination for client %s:%u, closing (%lu such connections)", inet_ntoa(pa.sin_addr), ntohs(pa.sin_port), unknown);
last_log = t;
}
close(fd);
continue;
}
if (atomic_fetch_add(&R.nconn, 1) >= R.cfg.max_tcp_conns) {
atomic_fetch_sub(&R.nconn, 1);
int64_t t = now_ms();
if (t - last_cap_log > 5000) { last_cap_log = t; pb_core_log("relay: connection limit (%d) reached, dropping new connections", R.cfg.max_tcp_conns); }
close(fd);
continue;
}
if (job_push(J_TCP, fd, &o, NULL) != 0) {
atomic_fetch_sub(&R.nconn, 1);
close(fd);
int64_t t = now_ms();
if (t - last_cap_log > 5000) { last_cap_log = t; pb_core_log("relay: handshake queue full (%d), shedding new connections", JOBQ_MAX); }
}
}
}
return NULL;
}
static void pipe_discard(int fd)
{
char b[4096];
while (read(fd, b, sizeof b) > 0) {}
}
static int spill_from_pipe(struct conn *c, int d, int pipe_rd, size_t n)
{
c->pend[d] = malloc(n);
if (!c->pend[d]) { pipe_discard(pipe_rd); return -1; }
size_t got = 0;
while (got < n) {
ssize_t r = read(pipe_rd, c->pend[d] + got, n - got);
if (r <= 0) { if (r < 0 && errno == EINTR) continue; break; }
got += (size_t)r;