forked from darkk/redsocks
-
Notifications
You must be signed in to change notification settings - Fork 92
/
redsocks.c
1532 lines (1320 loc) · 44.1 KB
/
redsocks.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* redsocks - transparent TCP-to-proxy redirector
* Copyright (C) 2007-2011 Leonid Evdokimov <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
#include <fcntl.h>
#include <event.h>
#include "list.h"
#include "parser.h"
#include "log.h"
#include "main.h"
#include "base.h"
#include "redsocks.h"
#include "utils.h"
#include "libevent-compat.h"
#define REDSOCKS_RELAY_HALFBUFF 4096
enum pump_state_t {
pump_active = -1,
pump_MAX = 0,
};
static const char *redsocks_event_str(unsigned short what);
static int redsocks_start_bufferpump(redsocks_client *client);
static int redsocks_start_splicepump(redsocks_client *client);
static void redsocks_conn_list_del(redsocks_client *client);
extern relay_subsys http_connect_subsys;
extern relay_subsys http_relay_subsys;
extern relay_subsys socks4_subsys;
extern relay_subsys socks5_subsys;
static relay_subsys *relay_subsystems[] =
{
&http_connect_subsys,
&http_relay_subsys,
&socks4_subsys,
&socks5_subsys,
};
static list_head instances = LIST_HEAD_INIT(instances);
// Managing connection pressure.
static uint32_t redsocks_conn;
static uint32_t accept_backoff_ms;
static struct event accept_backoff_ev;
static parser_entry redsocks_entries[] =
{
{ .key = "local_ip", .type = pt_in_addr },
{ .key = "local_port", .type = pt_uint16 },
{ .key = "ip", .type = pt_in_addr },
{ .key = "port", .type = pt_uint16 },
{ .key = "type", .type = pt_pchar },
{ .key = "login", .type = pt_pchar },
{ .key = "password", .type = pt_pchar },
{ .key = "listenq", .type = pt_uint16 },
{ .key = "splice", .type = pt_bool },
{ .key = "disclose_src", .type = pt_disclose_src },
{ .key = "on_proxy_fail", .type = pt_on_proxy_fail },
{ }
};
static bool is_splice_good()
{
struct utsname u;
if (uname(&u) != 0) {
return false;
}
unsigned long int v[4] = { 0, 0, 0, 0 };
char *rel = u.release;
for (int i = 0; i < SIZEOF_ARRAY(v); ++i) {
v[i] = strtoul(rel, &rel, 0);
while (*rel && !isdigit(*rel))
++rel;
}
// haproxy assumes that splice "works" for 2.6.27.13+
return (v[0] > 2) ||
(v[0] == 2 && v[1] > 6) ||
(v[0] == 2 && v[1] == 6 && v[2] > 27) ||
(v[0] == 2 && v[1] == 6 && v[2] == 27 && v[3] >= 13);
}
static int redsocks_onenter(parser_section *section)
{
// FIXME: find proper way to calulate instance_payload_len
int instance_payload_len = 0;
relay_subsys **ss;
FOREACH(ss, relay_subsystems)
if (instance_payload_len < (*ss)->instance_payload_len)
instance_payload_len = (*ss)->instance_payload_len;
redsocks_instance *instance = calloc(1, sizeof(*instance) + instance_payload_len);
if (!instance) {
parser_error(section->context, "Not enough memory");
return -1;
}
INIT_LIST_HEAD(&instance->list);
INIT_LIST_HEAD(&instance->clients);
instance->config.bindaddr.sin_family = AF_INET;
instance->config.bindaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
instance->config.relayaddr.sin_family = AF_INET;
instance->config.relayaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
/* Default value can be checked in run-time, but I doubt anyone needs that.
* Linux: sysctl net.core.somaxconn
* FreeBSD: sysctl kern.ipc.somaxconn */
instance->config.listenq = SOMAXCONN;
instance->config.use_splice = is_splice_good();
instance->config.disclose_src = DISCLOSE_NONE;
instance->config.on_proxy_fail = ONFAIL_CLOSE;
for (parser_entry *entry = §ion->entries[0]; entry->key; entry++)
entry->addr =
(strcmp(entry->key, "local_ip") == 0) ? (void*)&instance->config.bindaddr.sin_addr :
(strcmp(entry->key, "local_port") == 0) ? (void*)&instance->config.bindaddr.sin_port :
(strcmp(entry->key, "ip") == 0) ? (void*)&instance->config.relayaddr.sin_addr :
(strcmp(entry->key, "port") == 0) ? (void*)&instance->config.relayaddr.sin_port :
(strcmp(entry->key, "type") == 0) ? (void*)&instance->config.type :
(strcmp(entry->key, "login") == 0) ? (void*)&instance->config.login :
(strcmp(entry->key, "password") == 0) ? (void*)&instance->config.password :
(strcmp(entry->key, "listenq") == 0) ? (void*)&instance->config.listenq :
(strcmp(entry->key, "splice") == 0) ? (void*)&instance->config.use_splice :
(strcmp(entry->key, "disclose_src") == 0) ? (void*)&instance->config.disclose_src :
(strcmp(entry->key, "on_proxy_fail") == 0) ? (void*)&instance->config.on_proxy_fail :
NULL;
section->data = instance;
return 0;
}
static int redsocks_onexit(parser_section *section)
{
/* FIXME: Rewrite in bullet-proof style. There are memory leaks if config
* file is not correct, so correct on-the-fly config reloading is
* currently impossible.
*/
redsocks_instance *instance = section->data;
section->data = NULL;
for (parser_entry *entry = §ion->entries[0]; entry->key; entry++)
entry->addr = NULL;
instance->config.bindaddr.sin_port = htons(instance->config.bindaddr.sin_port);
instance->config.relayaddr.sin_port = htons(instance->config.relayaddr.sin_port);
if (instance->config.type) {
relay_subsys **ss;
FOREACH(ss, relay_subsystems) {
if (!strcmp((*ss)->name, instance->config.type)) {
instance->relay_ss = *ss;
list_add(&instance->list, &instances);
break;
}
}
if (!instance->relay_ss) {
parser_error(section->context, "invalid `type` <%s> for redsocks", instance->config.type);
return -1;
}
}
else {
parser_error(section->context, "no `type` for redsocks");
return -1;
}
if (instance->config.disclose_src != DISCLOSE_NONE && instance->relay_ss != &http_connect_subsys) {
parser_error(section->context, "only `http-connect` supports `disclose_src` at the moment");
return -1;
}
if (instance->config.on_proxy_fail != ONFAIL_CLOSE && instance->relay_ss != &http_connect_subsys) {
parser_error(section->context, "only `http-connect` supports `on_proxy_fail` at the moment");
return -1;
}
return 0;
}
static parser_section redsocks_conf_section =
{
.name = "redsocks",
.entries = redsocks_entries,
.onenter = redsocks_onenter,
.onexit = redsocks_onexit
};
void redsocks_log_write_plain(
const char *file, int line, const char *func, int do_errno,
const struct sockaddr_in *clientaddr, const struct sockaddr_in *destaddr,
int priority, const char *orig_fmt, ...
) {
if (!should_log(priority))
return;
int saved_errno = errno;
struct evbuffer *fmt = evbuffer_new();
va_list ap;
char clientaddr_str[RED_INET_ADDRSTRLEN], destaddr_str[RED_INET_ADDRSTRLEN];
if (!fmt) {
log_errno(LOG_ERR, "evbuffer_new()");
// no return, as I have to call va_start/va_end
}
if (fmt) {
evbuffer_add_printf(fmt, "[%s->%s]: %s",
red_inet_ntop(clientaddr, clientaddr_str, sizeof(clientaddr_str)),
red_inet_ntop(destaddr, destaddr_str, sizeof(destaddr_str)),
orig_fmt);
}
va_start(ap, orig_fmt);
if (fmt) {
errno = saved_errno;
_log_vwrite(file, line, func, do_errno, priority, (const char*)evbuffer_pullup(fmt, -1), ap);
evbuffer_free(fmt);
}
va_end(ap);
}
void redsocks_touch_client(redsocks_client *client)
{
redsocks_gettimeofday(&client->last_event);
}
static bool shut_both(redsocks_client *client)
{
return client->relay_evshut == (EV_READ|EV_WRITE) && client->client_evshut == (EV_READ|EV_WRITE);
}
static int bufprio(redsocks_client *client, struct bufferevent *buffev)
{
// client errors are logged with LOG_INFO, server errors with LOG_NOTICE
return (buffev == client->client) ? LOG_INFO : LOG_NOTICE;
}
static const char* bufname(redsocks_client *client, struct bufferevent *buf)
{
assert(buf == client->client || buf == client->relay);
return buf == client->client ? "client" : "relay";
}
static void redsocks_relay_readcb(redsocks_client *client, struct bufferevent *from, struct bufferevent *to)
{
if (evbuffer_get_length(to->output) < to->wm_write.high) {
if (bufferevent_write_buffer(to, from->input) == -1)
redsocks_log_errno(client, LOG_ERR, "bufferevent_write_buffer");
}
else {
if (bufferevent_get_enabled(from) & EV_READ) {
redsocks_log_error(client, LOG_DEBUG, "backpressure: bufferevent_disable(%s, EV_READ)", bufname(client, from));
if (bufferevent_disable(from, EV_READ) == -1)
redsocks_log_errno(client, LOG_ERR, "bufferevent_disable");
}
}
}
static void redsocks_relay_writecb(redsocks_client *client, struct bufferevent *from, struct bufferevent *to)
{
assert(from == client->client || from == client->relay);
char from_eof = (from == client->client ? client->client_evshut : client->relay_evshut) & EV_READ;
if (evbuffer_get_length(from->input) == 0 && from_eof) {
redsocks_shutdown(client, to, SHUT_WR);
}
else if (evbuffer_get_length(to->output) < to->wm_write.high) {
if (bufferevent_write_buffer(to, from->input) == -1)
redsocks_log_errno(client, LOG_ERR, "bufferevent_write_buffer");
if (!from_eof && !(bufferevent_get_enabled(from) & EV_READ)) {
redsocks_log_error(client, LOG_DEBUG, "backpressure: bufferevent_enable(%s, EV_READ)", bufname(client, from));
if (bufferevent_enable(from, EV_READ) == -1)
redsocks_log_errno(client, LOG_ERR, "bufferevent_enable");
}
}
}
static void redsocks_relay_relayreadcb(struct bufferevent *from, void *_client)
{
redsocks_client *client = _client;
redsocks_touch_client(client);
redsocks_relay_readcb(client, client->relay, client->client);
}
static void redsocks_relay_relaywritecb(struct bufferevent *to, void *_client)
{
redsocks_client *client = _client;
redsocks_touch_client(client);
redsocks_relay_writecb(client, client->client, client->relay);
}
static void redsocks_relay_clientreadcb(struct bufferevent *from, void *_client)
{
redsocks_client *client = _client;
redsocks_touch_client(client);
redsocks_relay_readcb(client, client->client, client->relay);
}
static void redsocks_relay_clientwritecb(struct bufferevent *to, void *_client)
{
redsocks_client *client = _client;
redsocks_touch_client(client);
redsocks_relay_writecb(client, client->relay, client->client);
}
void redsocks_start_relay(redsocks_client *client)
{
if (client->instance->relay_ss->fini)
client->instance->relay_ss->fini(client);
client->state = pump_active;
int error = ((client->instance->config.use_splice) ? redsocks_start_splicepump : redsocks_start_bufferpump)(client);
if (!error)
redsocks_log_error(client, LOG_DEBUG, "data relaying started");
else
redsocks_drop_client(client);
}
static int redsocks_start_bufferpump(redsocks_client *client)
{
// wm_write.high is respected by libevent-2.0.22 only for ssl and filters,
// so it's implemented in redsocks callbacks. wm_read.high works as expected.
bufferevent_setwatermark(client->client, EV_READ|EV_WRITE, 0, REDSOCKS_RELAY_HALFBUFF);
bufferevent_setwatermark(client->relay, EV_READ|EV_WRITE, 0, REDSOCKS_RELAY_HALFBUFF);
client->client->readcb = redsocks_relay_clientreadcb;
client->client->writecb = redsocks_relay_clientwritecb;
client->relay->readcb = redsocks_relay_relayreadcb;
client->relay->writecb = redsocks_relay_relaywritecb;
int error = bufferevent_enable(client->client, (EV_READ|EV_WRITE) & ~(client->client_evshut));
if (!error)
error = bufferevent_enable(client->relay, (EV_READ|EV_WRITE) & ~(client->relay_evshut));
if (error)
redsocks_log_errno(client, LOG_ERR, "bufferevent_enable");
return error;
}
static int pipeprio(redsocks_pump *pump, int fd)
{
// client errors are logged with LOG_INFO, server errors with LOG_NOTICE
return (fd == event_get_fd(&pump->client_read)) ? LOG_INFO : LOG_NOTICE;
}
static const char* pipename(redsocks_pump *pump, int fd)
{
return (fd == event_get_fd(&pump->client_read)) ? "client" : "relay";
}
static void bufferevent_free_unused(struct bufferevent **p) {
if (*p && !evbuffer_get_length((*p)->input) && !evbuffer_get_length((*p)->output)) {
bufferevent_free(*p);
*p = NULL;
}
}
static bool would_block(int e) {
return e == EAGAIN || e == EWOULDBLOCK;
}
typedef struct redsplice_write_ctx_t {
// drain ebsrc[0], ebsrc[1], pisrc in that order
struct evbuffer *ebsrc[2];
splice_pipe *pisrc;
struct event *evsrc;
struct event *evdst;
const evshut_t *shut_src;
evshut_t *shut_dst;
} redsplice_write_ctx;
static void redsplice_write_cb(redsocks_pump *pump, redsplice_write_ctx *c, int out)
{
bool has_data = false; // there is some pending data to be written
bool can_write = true; // socket SEEMS TO BE writable
// short write -- goto read/write management
// write error -- drop client alltogether
// full write -- take next buffer
// got EOF & no data -- relay EOF
for (int i = 0; i < SIZEOF_ARRAY(c->ebsrc); ++i) {
struct evbuffer *ebsrc = c->ebsrc[i];
if (ebsrc) {
const size_t avail = evbuffer_get_length(ebsrc);
has_data = !!avail;
if (avail) {
const ssize_t sent = evbuffer_write(ebsrc, out);
if (sent == -1) {
if (would_block(errno)) { // short (zero) write
can_write = false;
goto decide;
} else {
redsocks_log_errno(&pump->c, pipeprio(pump, out), "evbuffer_write(to %s, %zu)", pipename(pump, out), avail);
redsocks_drop_client(&pump->c);
return;
}
} else if (avail == sent) {
has_data = false; // unless stated otherwise
} else { // short write
can_write = false;
goto decide;
}
}
}
}
do {
has_data = !!c->pisrc->size;
const size_t avail = c->pisrc->size;
if (avail) {
const ssize_t sent = splice(c->pisrc->read, NULL, out, NULL, avail, SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
if (sent == -1) {
if (would_block(errno)) { // short (zero) write
can_write = false;
goto decide;
} else {
redsocks_log_errno(&pump->c, pipeprio(pump, out), "splice(to %s)", pipename(pump, out));
redsocks_drop_client(&pump->c);
return;
}
} else {
c->pisrc->size -= sent;
if (avail == sent) {
has_data = false;
} else { // short write
can_write = false;
goto decide;
}
}
}
} while (0);
decide:
if (!has_data && (*c->shut_src & EV_READ) && !(*c->shut_dst & EV_WRITE)) {
if (shutdown(out, SHUT_WR) != 0) {
redsocks_log_errno(&pump->c, LOG_ERR, "shutdown(%s, SHUT_WR)", pipename(pump, out));
}
*c->shut_dst |= EV_WRITE;
can_write = false;
assert(!c->pisrc->size);
redsocks_close(c->pisrc->read);
c->pisrc->read = -1;
redsocks_close(c->pisrc->write);
c->pisrc->write = -1;
if (shut_both(&pump->c)) {
redsocks_drop_client(&pump->c);
return;
}
}
assert(!(can_write && has_data)); // incomplete write to writable socket
if (!can_write && has_data) {
if (event_pending(c->evsrc, EV_READ, NULL))
redsocks_log_error(&pump->c, LOG_DEBUG, "backpressure: event_del(%s_read)", pipename(pump, event_get_fd(c->evsrc)));
redsocks_event_del(&pump->c, c->evsrc);
redsocks_event_add(&pump->c, c->evdst);
} else if (can_write && !has_data) {
if (!event_pending(c->evsrc, EV_READ, NULL))
redsocks_log_error(&pump->c, LOG_DEBUG, "backpressure: event_add(%s_read)", pipename(pump, event_get_fd(c->evsrc)));
redsocks_event_add(&pump->c, c->evsrc);
redsocks_event_del(&pump->c, c->evdst);
} else if (!can_write && !has_data) { // something like EOF
redsocks_event_del(&pump->c, c->evsrc);
redsocks_event_del(&pump->c, c->evdst);
}
}
typedef struct redsplice_read_ctx_t {
splice_pipe *dst;
struct event *evsrc;
struct event *evdst;
evshut_t *shut_src;
} redsplice_read_ctx;
static void redsplice_read_cb(redsocks_pump *pump, redsplice_read_ctx *c, int in)
{
const size_t pipesize = 1048576; // some default value from fs.pipe-max-size
const ssize_t got = splice(in, NULL, c->dst->write, NULL, pipesize, SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
if (got == -1) {
if (would_block(errno)) {
// there is data at `in', but pipe is full
if (!event_pending(c->evsrc, EV_READ, NULL))
redsocks_log_error(&pump->c, LOG_DEBUG, "backpressure: event_del(%s_read)", pipename(pump, event_get_fd(c->evsrc)));
redsocks_event_del(&pump->c, c->evsrc);
} else {
redsocks_log_errno(&pump->c, pipeprio(pump, in), "splice(from %s)", pipename(pump, in));
redsocks_drop_client(&pump->c);
}
return;
}
if (got == 0) { // got EOF
if (shutdown(in, SHUT_RD) != 0) {
if (errno != ENOTCONN) { // do not log common case for splice()
redsocks_log_errno(&pump->c, LOG_DEBUG, "shutdown(%s, SHUT_RD) after EOF", pipename(pump, in));
}
}
*c->shut_src |= EV_READ;
redsocks_event_del(&pump->c, c->evsrc);
} else {
c->dst->size += got;
}
event_active(c->evdst, EV_WRITE, 0);
}
static void redsocks_touch_pump(redsocks_pump *pump)
{
redsocks_touch_client(&pump->c);
bufferevent_free_unused(&pump->c.client);
bufferevent_free_unused(&pump->c.relay);
}
static void redsplice_relay_read(int fd, short what, void *_pump)
{
redsocks_pump *pump = _pump;
assert(fd == event_get_fd(&pump->relay_read) && (what & EV_READ));
redsocks_touch_pump(pump);
redsplice_read_ctx c = {
.dst = &pump->reply,
.evsrc = &pump->relay_read,
.evdst = &pump->client_write,
.shut_src = &pump->c.relay_evshut,
};
redsplice_read_cb(pump, &c, fd);
}
static void redsplice_client_read(int fd, short what, void *_pump)
{
redsocks_pump *pump = _pump;
assert(fd == event_get_fd(&pump->client_read) && (what & EV_READ));
redsocks_touch_pump(pump);
redsplice_read_ctx c = {
.dst = &pump->request,
.evsrc = &pump->client_read,
.evdst = &pump->relay_write,
.shut_src = &pump->c.client_evshut,
};
redsplice_read_cb(pump, &c, fd);
}
static void redsplice_relay_write(int fd, short what, void *_pump)
{
redsocks_pump *pump = _pump;
assert(fd == event_get_fd(&pump->relay_write) && (what & EV_WRITE));
redsocks_touch_pump(pump);
redsplice_write_ctx c = {
.ebsrc = {
pump->c.relay ? pump->c.relay->output : NULL,
pump->c.client ? pump->c.client->input : NULL,
},
.pisrc = &pump->request,
.evsrc = &pump->client_read,
.evdst = &pump->relay_write,
.shut_src = &pump->c.client_evshut,
.shut_dst = &pump->c.relay_evshut,
};
redsplice_write_cb(pump, &c, fd);
}
static void redsplice_client_write(int fd, short what, void *_pump)
{
redsocks_pump *pump = _pump;
assert(fd == event_get_fd(&pump->client_write) && (what & EV_WRITE));
redsocks_touch_pump(pump);
redsplice_write_ctx c = {
.ebsrc = {
pump->c.client ? pump->c.client->output : NULL,
pump->c.relay ? pump->c.relay->input : NULL,
},
.pisrc = &pump->reply,
.evsrc = &pump->relay_read,
.evdst = &pump->client_write,
.shut_src = &pump->c.relay_evshut,
.shut_dst = &pump->c.client_evshut,
};
redsplice_write_cb(pump, &c, fd);
}
static int redsocks_start_splicepump(redsocks_client *client)
{
int error = bufferevent_disable(client->client, EV_READ|EV_WRITE);
if (!error)
error = bufferevent_disable(client->relay, EV_READ|EV_WRITE);
if (error) {
redsocks_log_errno(client, LOG_ERR, "bufferevent_disable");
return error;
}
// going to steal this buffers to the socket
evbuffer_unfreeze(client->client->input, 0);
evbuffer_unfreeze(client->client->output, 1);
evbuffer_unfreeze(client->relay->input, 0);
evbuffer_unfreeze(client->relay->output, 1);
redsocks_pump *pump = red_pump(client);
if (!error)
error = pipe2(&pump->request.read, O_NONBLOCK);
if (!error)
error = pipe2(&pump->reply.read, O_NONBLOCK);
if (error) {
redsocks_log_errno(client, LOG_ERR, "pipe2");
return error;
}
struct event_base *base = NULL;
const int relay_fd = bufferevent_getfd(client->relay);
const int client_fd = bufferevent_getfd(client->client);
if (!error)
error = event_assign(&pump->client_read, base, client_fd, EV_READ|EV_PERSIST, redsplice_client_read, pump);
if (!error)
error = event_assign(&pump->client_write, base, client_fd, EV_WRITE|EV_PERSIST, redsplice_client_write, pump);
if (!error)
error = event_assign(&pump->relay_read, base, relay_fd, EV_READ|EV_PERSIST, redsplice_relay_read, pump);
if (!error)
error = event_assign(&pump->relay_write, base, relay_fd, EV_WRITE|EV_PERSIST, redsplice_relay_write, pump);
if (error) {
redsocks_log_errno(client, LOG_ERR, "event_assign");
return error;
}
redsocks_bufferevent_dropfd(client, client->relay);
redsocks_bufferevent_dropfd(client, client->client);
// flush buffers (if any) and enable EV_READ callbacks
event_active(&pump->client_write, EV_WRITE, 0);
event_active(&pump->relay_write, EV_WRITE, 0);
redsocks_event_add(&pump->c, &pump->client_read);
redsocks_event_add(&pump->c, &pump->relay_read);
return 0;
}
static bool has_loopback_destination(redsocks_client *client)
{
const uint32_t net = ntohl(client->destaddr.sin_addr.s_addr) >> 24;
return 0 == memcmp(&client->destaddr.sin_addr, &client->instance->config.relayaddr.sin_addr, sizeof(client->destaddr.sin_addr))
|| net == 127 || net == 0;
}
void redsocks_drop_client(redsocks_client *client)
{
if (shut_both(client)) {
redsocks_log_error(client, LOG_INFO, "connection closed");
} else {
if (has_loopback_destination(client)) {
static time_t last = 0;
const time_t now = redsocks_time(NULL);
if (now - last >= 3600) {
// log this warning once an hour to save some debugging time, OTOH it may be valid traffic in some cases
redsocks_log_error(client, LOG_NOTICE, "client tries to connect to the proxy using proxy! Usual proxy security policy is to drop alike connection");
last = now;
}
}
struct timeval now, idle;
redsocks_gettimeofday(&now); // FIXME: use CLOCK_MONOTONIC
timersub(&now, &client->last_event, &idle);
redsocks_log_error(client, LOG_INFO, "dropping client (%s), relay (%s), idle %ld.%06lds",
redsocks_event_str( (~client->client_evshut) & (EV_READ|EV_WRITE) ),
redsocks_event_str( (~client->relay_evshut) & (EV_READ|EV_WRITE) ),
idle.tv_sec, idle.tv_usec);
}
if (client->instance->relay_ss->fini)
client->instance->relay_ss->fini(client);
if (client->client)
redsocks_bufferevent_free(client->client);
if (client->relay)
redsocks_bufferevent_free(client->relay);
if (client->instance->config.use_splice) {
redsocks_pump *pump = red_pump(client);
if (pump->request.read != -1)
redsocks_close(pump->request.read);
if (pump->request.write != -1)
redsocks_close(pump->request.write);
if (pump->reply.read != -1)
redsocks_close(pump->reply.read);
if (pump->reply.write != -1)
redsocks_close(pump->reply.write);
// redsocks_close MAY log error if some of events was not properly initialized
int fd = -1;
if (event_initialized(&pump->client_read)) {
fd = event_get_fd(&pump->client_read);
redsocks_event_del(&pump->c, &pump->client_read);
}
if (event_initialized(&pump->client_write)) {
redsocks_event_del(&pump->c, &pump->client_write);
}
if (fd != -1)
redsocks_close(fd);
fd = -1;
if (event_initialized(&pump->relay_read)) {
fd = event_get_fd(&pump->relay_read);
redsocks_event_del(&pump->c, &pump->relay_read);
}
if (event_initialized(&pump->relay_write)) {
redsocks_event_del(&pump->c, &pump->relay_write);
}
if (fd != -1) {
redsocks_close(fd);
}
}
redsocks_conn_list_del(client);
free(client);
}
void redsocks_shutdown(redsocks_client *client, struct bufferevent *buffev, int how)
{
short evhow = 0;
const char *strev, *strhow = NULL, *strevhow = NULL;
unsigned short *pevshut;
assert(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR);
assert(buffev == client->client || buffev == client->relay);
assert(event_get_fd(&buffev->ev_read) == event_get_fd(&buffev->ev_write));
if (how == SHUT_RD) {
strhow = "SHUT_RD";
evhow = EV_READ;
strevhow = "EV_READ";
}
else if (how == SHUT_WR) {
strhow = "SHUT_WR";
evhow = EV_WRITE;
strevhow = "EV_WRITE";
}
else if (how == SHUT_RDWR) {
strhow = "SHUT_RDWR";
evhow = EV_READ|EV_WRITE;
strevhow = "EV_READ|EV_WRITE";
}
assert(strhow && strevhow);
strev = bufname(client, buffev);
pevshut = buffev == client->client ? &client->client_evshut : &client->relay_evshut;
// if EV_WRITE is already shut and we're going to shutdown read then
// we're either going to abort data flow (bad behaviour) or confirm EOF
// and in this case socket is already SHUT_RD'ed
if ( !(how == SHUT_RD && (*pevshut & EV_WRITE)) ) {
if (shutdown(event_get_fd(&buffev->ev_read), how) != 0)
redsocks_log_errno(client, LOG_ERR, "shutdown(%s, %s)", strev, strhow);
} else {
redsocks_log_error(client, LOG_DEBUG, "ignored shutdown(%s, %s)", strev, strhow);
}
redsocks_log_error(client, LOG_DEBUG, "shutdown: bufferevent_disable(%s, %s)", strev, strevhow);
if (bufferevent_disable(buffev, evhow) != 0)
redsocks_log_errno(client, LOG_ERR, "bufferevent_disable(%s, %s)", strev, strevhow);
*pevshut |= evhow;
if (shut_both(client)) {
redsocks_log_error(client, LOG_DEBUG, "both client and server disconnected");
redsocks_drop_client(client);
}
}
// I assume that -1 is invalid errno value
static int redsocks_socket_geterrno(redsocks_client *client, struct bufferevent *buffev)
{
int pseudo_errno = red_socket_geterrno(buffev);
if (pseudo_errno == -1) {
redsocks_log_errno(client, LOG_ERR, "red_socket_geterrno");
return -1;
}
return pseudo_errno;
}
static void redsocks_event_error(struct bufferevent *buffev, short what, void *_arg)
{
redsocks_client *client = _arg;
assert(buffev == client->relay || buffev == client->client);
const int bakerrno = errno;
redsocks_touch_client(client);
if (what == (EVBUFFER_READ|EVBUFFER_EOF)) {
struct bufferevent *antiev;
if (buffev == client->relay)
antiev = client->client;
else
antiev = client->relay;
redsocks_shutdown(client, buffev, SHUT_RD);
// If the client has already sent EOF and the pump is not active
// (relay is activating), the code should not shutdown write-pipe.
if (client->state == pump_active && antiev != NULL && evbuffer_get_length(antiev->output) == 0)
redsocks_shutdown(client, antiev, SHUT_WR);
}
else {
const int sockrrno = redsocks_socket_geterrno(client, buffev);
const char *errsrc = "";
if (sockrrno != -1 && sockrrno != 0) {
errno = sockrrno;
errsrc = "socket ";
} else {
errno = bakerrno;
}
redsocks_log_errno(client, bufprio(client, buffev), "%s %serror, code " event_fmt_str,
bufname(client, buffev),
errsrc,
event_fmt(what));
redsocks_drop_client(client);
}
}
int sizes_equal(size_t a, size_t b)
{
return a == b;
}
int sizes_greater_equal(size_t a, size_t b)
{
return a >= b;
}
int redsocks_read_expected(redsocks_client *client, struct evbuffer *input, void *data, size_comparator comparator, size_t expected)
{
size_t len = evbuffer_get_length(input);
if (comparator(len, expected)) {
int read = evbuffer_remove(input, data, expected);
UNUSED(read);
assert(read == expected);
return 0;
}
else {
redsocks_log_error(client, LOG_NOTICE, "Can't get expected amount of data");
redsocks_drop_client(client);
return -1;
}
}
struct evbuffer *mkevbuffer(void *data, size_t len)
{
struct evbuffer *buff = NULL, *retval = NULL;
buff = evbuffer_new();
if (!buff) {
log_errno(LOG_ERR, "evbuffer_new");
goto fail;
}
if (evbuffer_add(buff, data, len) < 0) {
log_errno(LOG_ERR, "evbuffer_add");
goto fail;
}
retval = buff;
buff = NULL;
fail:
if (buff)
evbuffer_free(buff);
return retval;
}
int redsocks_write_helper_ex(
struct bufferevent *buffev, redsocks_client *client,
redsocks_message_maker mkmessage, int state, size_t wm_low, size_t wm_high)
{
assert(client);
return redsocks_write_helper_ex_plain(buffev, client, (redsocks_message_maker_plain)mkmessage,
client, state, wm_low, wm_high);
}
int redsocks_write_helper_ex_plain(
struct bufferevent *buffev, redsocks_client *client,
redsocks_message_maker_plain mkmessage, void *p, int state, size_t wm_low, size_t wm_high)
{
int len;
struct evbuffer *buff = NULL;
int drop = 1;
if (mkmessage) {
buff = mkmessage(p);
if (!buff)
goto fail;
assert(!client || buffev == client->relay);
len = bufferevent_write_buffer(buffev, buff);
if (len < 0) {
if (client)
redsocks_log_errno(client, LOG_ERR, "bufferevent_write_buffer");
else
log_errno(LOG_ERR, "bufferevent_write_buffer");
goto fail;
}
}
if (client)
client->state = state;
bufferevent_setwatermark(buffev, EV_READ, wm_low, wm_high);
bufferevent_enable(buffev, EV_READ);
drop = 0;
fail:
if (buff)
evbuffer_free(buff);
if (drop && client)
redsocks_drop_client(client);
return drop ? -1 : 0;
}
int redsocks_write_helper(
struct bufferevent *buffev, redsocks_client *client,
redsocks_message_maker mkmessage, int state, size_t wm_only)
{
assert(client);
return redsocks_write_helper_ex(buffev, client, mkmessage, state, wm_only, wm_only);
}
static void redsocks_relay_connected(struct bufferevent *buffev, void *_arg)
{
redsocks_client *client = _arg;
assert(buffev == client->relay);
redsocks_touch_client(client);
if (!red_is_socket_connected_ok(buffev)) {
redsocks_log_errno(client, LOG_NOTICE, "red_is_socket_connected_ok");
goto fail;
}
client->relay->readcb = client->instance->relay_ss->readcb;
client->relay->writecb = client->instance->relay_ss->writecb;
client->relay->writecb(buffev, _arg);
return;
fail:
redsocks_drop_client(client);
}
void redsocks_connect_relay(redsocks_client *client)
{
client->relay = red_connect_relay(&client->instance->config.relayaddr,
redsocks_relay_connected, redsocks_event_error, client);
if (!client->relay) {
redsocks_log_errno(client, LOG_ERR, "red_connect_relay");
redsocks_drop_client(client);
}
}
static struct timeval drop_idle_connections()
{
assert(connpres_idle_timeout() > 0);
struct timeval now, zero, max_idle, best_next;
gettimeofday(&now, NULL); // FIXME: use CLOCK_MONOTONIC
timerclear(&zero);
timerclear(&max_idle);
max_idle.tv_sec = connpres_idle_timeout();
best_next = max_idle;
redsocks_instance *instance;
list_for_each_entry(instance, &instances, list) {
redsocks_client *tmp, *client;
list_for_each_entry_safe(client, tmp, &instance->clients, list) {
struct timeval idle;
timersub(&now, &client->last_event, &idle);
if (timercmp(&idle, &zero, <=) || timercmp(&max_idle, &idle, <=)) {
redsocks_drop_client(client);
best_next = zero;
} else {