-
Notifications
You must be signed in to change notification settings - Fork 39
/
client.c
4146 lines (3682 loc) · 140 KB
/
client.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
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <inttypes.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/queue.h>
#include <Block.h>
#include <sodium.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>
#include <event2/http.h>
#include "libevent/http-internal.h"
#include <parson.h>
#include "dht/dht.h"
#include "nn_features.h"
#include "ui.h"
#include "log.h"
#include "lsd.h"
#include "d2d.h"
#include "utp.h"
#include "http.h"
#include "timer.h"
#include "obfoo.h"
#include "thread.h"
#include "base64.h"
#include "network.h"
#include "newnode.h"
#include "constants.h"
#include "bev_splice.h"
#include "hash_table.h"
#include "bufferevent_utp.h"
#include "dns_prefetch.h"
#include "g_https_cb.h"
#ifdef ANDROID
#include <sys/system_properties.h>
#endif
#define NO_DIRECT 0
#define NO_CACHE 0
typedef struct {
in_addr_t ip;
port_t port;
} PACKED packed_ipv4;
static_assert(sizeof(packed_ipv4) == 6, "packed_ipv4 should be 6 bytes");
typedef struct {
in6_addr ip;
port_t port;
} PACKED packed_ipv6;
static_assert(sizeof(packed_ipv6) == 18, "packed_ipv6 should be 18 bytes");
typedef struct {
sockaddr_storage addr;
time_t last_verified;
time_t last_connect;
time_t last_connect_attempt;
char via;
uint8_t loop;
bool is_injector:1;
} peer;
typedef struct {
network *n;
peer *peer;
bufferevent *bev;
evhttp_connection *evcon;
} peer_connection;
typedef struct {
bool failed:1;
int64_t last_connect_attempt;
int64_t time_since_verified;
bool never_connected:1;
uint8_t loop;
uint8_t salt;
peer *peer;
} PACKED peer_sort;
#define CACHE_PATH "./cache/"
#define CACHE_NAME CACHE_PATH "cache.XXXXXXXX"
typedef bool (^peer_filter)(peer *p);
typedef void (^peer_connected)(peer_connection *p);
typedef struct pending_request {
char *via;
peer_connected on_connect;
TAILQ_ENTRY(pending_request) next;
} pending_request;
struct proxy_request;
typedef struct proxy_request proxy_request;
typedef struct {
uint64_t start;
uint64_t end;
uint64_t chunk_index;
evbuffer *chunk_buffer;
} chunked_range;
typedef struct {
pending_request r;
peer_connection *pc;
evhttp_request *req;
proxy_request *p;
chunked_range range;
} peer_request;
typedef struct {
evhttp_request *req;
evhttp_connection *evcon;
proxy_request *p;
chunked_range range;
} direct_request;
#define rdelta(r) ((double)(us_clock() - r->start_time) / 1000.0)
struct proxy_request {
network *n;
evhttp_request *server_req;
uint64 start_time;
char *uri;
evhttp_cmd_type http_method;
char *authority;
char *etag;
direct_request direct_requests[2];
int direct_code;
char *direct_code_line;
evkeyvalq direct_headers;
evkeyvalq output_headers;
merkle_tree *m;
uint8_t root_hash[crypto_generichash_BYTES];
peer_request requests[10];
uint64_t range_start;
uint64_t range_end;
char cache_name[sizeof(CACHE_NAME)];
int cache_file;
evbuffer *header_buf;
uint64_t content_length;
uint64_t total_length;
uint64_t byte_playhead;
bool *have_bitfield;
bool chunked:1;
bool merkle_tree_finished:1;
bool dont_free:1;
bool localhost:1;
};
typedef hash_table peer_array;
typedef struct {
uint64_t from_browser;
uint64_t to_browser;
uint64_t from_peer;
uint64_t to_peer;
uint64_t from_direct;
uint64_t to_direct;
uint64_t from_p2p;
uint64_t to_p2p;
uint64_t last_reported;
} byte_counts;
hash_table *byte_count_per_authority;
timer *stats_report_timer;
network *g_stats_n;
evconnlistener *g_listener;
uint64_t g_cid;
uint64_t g_all_peer;
uint64_t g_all_direct;
typedef struct {
uint64_t attempts; // num tryfirst attempts
uint64_t successes; // num successful attempts
uint64_t blocked; // num likely blocked attempts
uint64_t bytes_xferred; // total bytes transferred in tryfirst
uint64_t xfer_time_us; // total time required to transfer
uint64_t last_attempt; // time of last attempt
uint64_t last_success; // time of last successful attempt
uint64_t last_blocked; // time of last blocked attempt
} tryfirst_stats;
hash_table *tryfirst_per_origin_server;
char g_ip[INET6_ADDRSTRLEN];
char g_country[3]; // 2-letter ISO country code + '\0'
int g_asn = -1; // autonomous system number (if returned by ipinfo)
time_t g_ipinfo_timestamp = 0; // timestamp of last ipinfo request
time_t g_ipinfo_logged_timestamp = 0; // last logged g_ipinfo_timestamp
timer *g_ifchange_timer;
unsigned int g_tryfirst_timeout = 7; // seconds
unsigned int g_tryfirst_bufsize = 10240; // max bytes accepted on a try first attempt
// (even if we're always doing Range:bytes=0,1
// some servers ignore or refuse to do this)
peer_array *injectors;
peer_array *injector_proxies;
peer_array *all_peers;
peer_connection *peer_connections[20];
char via_tag[] = "1.1 _.newnode";
time_t injector_reachable;
time_t last_request;
timer *saving_peers;
uint16_t g_port;
const char *g_app_name;
const char *g_app_id;
https_callback g_https_cb;
static_assert(20 >= crypto_generichash_BYTES_MIN, "dht hash must fit in generichash size");
uint8_t encrypted_injector_swarm_m1[20];
uint8_t encrypted_injector_swarm_p0[20];
uint8_t encrypted_injector_swarm_p1[20];
uint8_t encrypted_injector_proxy_swarm_m1[20];
uint8_t encrypted_injector_proxy_swarm_p0[20];
uint8_t encrypted_injector_proxy_swarm_p1[20];
size_t pending_requests_len;
TAILQ_HEAD(, pending_request) pending_requests;
void save_peers(network *n);
int mkpath(char *file_path)
{
for (char *p = strchr(file_path + 1, '/'); p; p = strchr(p + 1, '/')) {
*p = '\0';
if (mkdir(file_path, 0755) == -1) {
if (errno != EEXIST) {
*p = '/';
return -1;
}
}
*p = '/';
}
return 0;
}
void connect_more_injectors(network *n, bool injector_preference);
void pending_request_complete(pending_request *r, peer_connection *pc)
{
peer_connected on_connect = r->on_connect;
free(r->via);
r->via = NULL;
r->on_connect = NULL;
evhttp_connection_set_closecb(pc->evcon, NULL, NULL);
on_connect(pc);
Block_release(on_connect);
}
bool via_contains(const char *via, char v)
{
if (!via || !v) {
return false;
}
char vtag[] = "_.newnode";
vtag[0] = v;
return !!strstr(via, vtag);
}
void peer_disconnect(peer_connection *pc)
{
debug("disconnecting pc:%p\n", pc);
if (pc->evcon) {
evhttp_connection_set_closecb(pc->evcon, NULL, NULL);
evhttp_connection_free(pc->evcon);
}
if (pc->bev) {
bufferevent_free(pc->bev);
}
free(pc);
}
void peer_connection_remove(peer_connection *pc)
{
bool found = false;
for (uint i = 0; i < lenof(peer_connections); i++) {
if (peer_connections[i] == pc) {
peer_connections[i] = NULL;
found = true;
break;
}
}
assert(found);
}
void peer_evcon_close_cb(evhttp_connection *evcon, void *ctx)
{
peer_connection *pc = (peer_connection *)ctx;
evhttp_connection_set_closecb(evcon, NULL, NULL);
evhttp_connection_free_on_completion(evcon);
pc->evcon = NULL;
peer_connection_remove(pc);
peer_disconnect(pc);
}
pending_request* pending_request_pop(peer_connection *pc)
{
pending_request *r;
TAILQ_FOREACH(r, &pending_requests, next) {
if (via_contains(r->via, pc->peer->via)) {
continue;
}
TAILQ_REMOVE(&pending_requests, r, next);
pending_requests_len--;
debug("%s request:%p (outstanding:%zu)\n", __func__, r, pending_requests_len);
return r;
}
return NULL;
}
void on_utp_connect(network *n, peer_connection *pc)
{
const sockaddr *ss = (const sockaddr *)&pc->peer->addr;
char host[NI_MAXHOST];
getnameinfo(ss, sockaddr_get_length(ss), host, sizeof(host), NULL, 0, NI_NUMERICHOST);
bufferevent *bev = pc->bev;
pc->bev = NULL;
// XXX: hack around evhttp requiring fd != -1 to assume the bev is connected. it doesn't have to be a valid fd, though.
// https://github.com/libevent/libevent/issues/1268
bufferevent_setfd(bev, -2);
pc->evcon = evhttp_connection_base_bufferevent_new(n->evbase, n->evdns, bev, host, sockaddr_get_port(ss));
bufferevent_setfd(bev, EVUTIL_INVALID_SOCKET);
debug("%s %s bev:%p evcon:%p\n", __func__, sockaddr_str(ss), bev, pc->evcon);
pc->evcon->flags |= EVHTTP_CON_CLOSEDETECT;
evhttp_connection_set_closecb(pc->evcon, peer_evcon_close_cb, pc);
bufferevent_disable(bev, EV_WRITE);
bufferevent_enable(bev, EV_READ);
pending_request *r = pending_request_pop(pc);
if (!r) {
return;
}
debug("using new pc:%p evcon:%p via:%c (%s) for request:%p\n", pc, pc->evcon, pc->peer->via ? pc->peer->via : ' ', r->via, r);
peer_connection_remove(pc);
pending_request_complete(r, pc);
if (!TAILQ_EMPTY(&pending_requests)) {
connect_more_injectors(n, false);
}
}
void utp_connect_event_cb(bufferevent *bufev, short events, void *arg)
{
peer_connection *pc = (peer_connection *)arg;
assert(pc->bev == bufev);
time_t delta = time(NULL) - pc->peer->last_connect_attempt;
debug("%s pc:%p peer:%p (%lds) events:0x%x %s\n", __func__, pc, pc->peer, delta, events, bev_events_to_str(events));
if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR|BEV_EVENT_TIMEOUT)) {
bufferevent_free(pc->bev);
pc->bev = NULL;
if (pc->peer->is_injector) {
injector_reachable = 0;
}
for (uint i = 0; i < lenof(peer_connections); i++) {
if (peer_connections[i] == pc) {
peer_connections[i] = NULL;
break;
}
}
assert(!pc->evcon);
pending_request *r = TAILQ_FIRST(&pending_requests);
if (r && time(NULL) - last_request < 30) {
connect_more_injectors(pc->n, false);
}
free(pc);
} else if (events & BEV_EVENT_CONNECTED) {
on_utp_connect(pc->n, pc);
}
}
const char* peer_addr_str(const peer *p)
{
return sockaddr_str((const sockaddr *)&p->addr);
}
peer_connection* evhttp_utp_connect(network *n, peer *p)
{
utp_socket *s = utp_create_socket(n->utp);
debug("%s %s\n", __func__, peer_addr_str(p));
p->last_connect_attempt = time(NULL);
peer_connection *pc = alloc(peer_connection);
pc->n = n;
pc->peer = p;
pc->bev = bufferevent_utp_new(n->evbase, n->utp, NULL, BEV_OPT_CLOSE_ON_FREE);
if (!pc->bev) {
free(pc);
return NULL;
}
bufferevent_setcb(pc->bev, NULL, NULL, utp_connect_event_cb, pc);
bufferevent_utp_connect(pc->bev, (const sockaddr*)&p->addr, sockaddr_get_length((const sockaddr*)&p->addr));
return pc;
}
peer* get_peer(peer_array *pa, const sockaddr *a)
{
return hash_get(pa, sockaddr_str(a));
}
peer* add_peer(peer_array **pa, const sockaddr *a, create_fn c)
{
return hash_get_or_insert(*pa, sockaddr_str(a), ^void* {
dht_ping_node((const sockaddr *)a, sockaddr_get_length(a));
return c();
});
}
void add_address(network *n, peer_array **pa, const sockaddr *addr, socklen_t addrlen)
{
// paper over a bug in some DHT implementation that winds up with 1 for the port
if (sockaddr_get_port(addr) == 1) {
return;
}
__block bool inserted = false;
peer *p = add_peer(pa, addr, ^void* {
inserted = true;
peer *np = alloc(peer);
memcpy(&np->addr, addr, addrlen);
return np;
});
if (!inserted) {
return;
}
const char *label = "peer";
if (*pa == injectors) {
label = "injector";
p->is_injector = true;
} else if (*pa == injector_proxies) {
label = "injector proxy";
} else {
assert(*pa == all_peers);
}
ddebug("new %s %s\n", label, peer_addr_str(p));
if (!TAILQ_EMPTY(&pending_requests)) {
for (uint k = 0; k < lenof(peer_connections); k++) {
if (peer_connections[k]) {
continue;
}
peer_connections[k] = evhttp_utp_connect(n, p);
break;
}
}
save_peers(n);
}
void add_v4_addresses(network *n, peer_array **pa, const uint8_t *addrs, size_t num_addrs)
{
for (uint i = 0; i < num_addrs; i++) {
sockaddr_storage addr;
packed_ipv4 *a = (packed_ipv4 *)&addrs[sizeof(packed_ipv4) * i];
sockaddr_in *sin = (sockaddr_in*)&addr;
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = a->ip;
sin->sin_port = a->port;
#ifdef __APPLE__
sin->sin_len = sizeof(sockaddr_in);
#endif
add_address(n, pa, (const sockaddr*)&addr, sockaddr_get_length((const sockaddr*)&addr));
if (o_debug >= 2) {
if (i + 1 != num_addrs) {
printf(", ");
}
}
}
}
void add_v6_addresses(network *n, peer_array **pa, const uint8_t *addrs, size_t num_addrs)
{
for (uint i = 0; i < num_addrs; i++) {
sockaddr_storage addr;
packed_ipv6 *a = (packed_ipv6 *)&addrs[sizeof(packed_ipv6) * i];
sockaddr_in6 *sin6 = (sockaddr_in6*)&addr;
sin6->sin6_family = AF_INET6;
memcpy(&sin6->sin6_addr, &a->ip, sizeof(a->ip));
sin6->sin6_port = a->port;
#ifdef __APPLE__
sin6->sin6_len = sizeof(sockaddr_in6);
#endif
add_address(n, pa, (const sockaddr*)&addr, sockaddr_get_length((const sockaddr*)&addr));
if (o_debug >= 2) {
if (i + 1 != num_addrs) {
printf(", ");
}
}
}
}
static void add_sockaddr(network *n, const sockaddr *addr, socklen_t addrlen)
{
dht_ping_node(addr, addrlen);
add_address(n, &all_peers, addr, addrlen);
}
void dht_event(network *n, int event, const unsigned char *info_hash, const void *data, size_t data_len)
{
peer_array **peer_list = NULL;
if (memeq(info_hash, encrypted_injector_swarm_m1, sizeof(encrypted_injector_swarm_m1)) ||
memeq(info_hash, encrypted_injector_swarm_p0, sizeof(encrypted_injector_swarm_p0)) ||
memeq(info_hash, encrypted_injector_swarm_p1, sizeof(encrypted_injector_swarm_p1))) {
peer_list = &injectors;
} else if (memeq(info_hash, encrypted_injector_proxy_swarm_m1, sizeof(encrypted_injector_proxy_swarm_m1)) ||
memeq(info_hash, encrypted_injector_proxy_swarm_p0, sizeof(encrypted_injector_proxy_swarm_p0)) ||
memeq(info_hash, encrypted_injector_proxy_swarm_p1, sizeof(encrypted_injector_proxy_swarm_p1))) {
peer_list = &injector_proxies;
} else {
peer_list = &all_peers;
}
const uint8_t* peers = data;
size_t num_peers = data_len / (event == DHT_EVENT_VALUES ? sizeof(packed_ipv4) : sizeof(packed_ipv6));
if (o_debug >= 2) {
printf("{\"");
for (int j = 0; j < 20; j++) {
printf("%02x", info_hash[j]);
}
printf("\": [");
}
if (event == DHT_EVENT_VALUES) {
ddebug("%s num_peers:%zu\n", __func__, num_peers);
add_v4_addresses(n, peer_list, peers, num_peers);
} else if (event == DHT_EVENT_VALUES6) {
ddebug("%s v6 num_peers:%zu\n", __func__, num_peers);
add_v6_addresses(n, peer_list, peers, num_peers);
} else {
ddebug("%s event:%d\n", __func__, event);
}
if (o_debug >= 2) {
printf("]}\n");
}
}
void update_injector_proxy_swarm(network *n)
{
time_t t = time(NULL);
tm *tm = gmtime(&t);
char name[1024];
if (injector_reachable) {
snprintf(name, sizeof(name), "injector proxy %d-%d", tm->tm_year, (tm->tm_yday - 1));
crypto_generichash(encrypted_injector_proxy_swarm_m1, sizeof(encrypted_injector_proxy_swarm_m1), (uint8_t*)name, strlen(name), NULL, 0);
dht_announce(n->dht, (const uint8_t *)encrypted_injector_proxy_swarm_m1);
snprintf(name, sizeof(name), "injector proxy %d-%d", tm->tm_year, (tm->tm_yday + 0));
crypto_generichash(encrypted_injector_proxy_swarm_p0, sizeof(encrypted_injector_proxy_swarm_p0), (uint8_t*)name, strlen(name), NULL, 0);
dht_announce(n->dht, (const uint8_t *)encrypted_injector_proxy_swarm_p0);
snprintf(name, sizeof(name), "injector proxy %d-%d", tm->tm_year, (tm->tm_yday + 1));
crypto_generichash(encrypted_injector_proxy_swarm_p1, sizeof(encrypted_injector_proxy_swarm_p1), (uint8_t*)name, strlen(name), NULL, 0);
dht_announce(n->dht, (const uint8_t *)encrypted_injector_proxy_swarm_p1);
} else {
snprintf(name, sizeof(name), "injector proxy %d-%d", tm->tm_year, (tm->tm_yday - 1));
crypto_generichash(encrypted_injector_proxy_swarm_m1, sizeof(encrypted_injector_proxy_swarm_m1), (uint8_t*)name, strlen(name), NULL, 0);
dht_get_peers(n->dht, (const uint8_t *)encrypted_injector_proxy_swarm_m1);
snprintf(name, sizeof(name), "injector proxy %d-%d", tm->tm_year, (tm->tm_yday + 0));
crypto_generichash(encrypted_injector_proxy_swarm_p0, sizeof(encrypted_injector_proxy_swarm_p0), (uint8_t*)name, strlen(name), NULL, 0);
dht_get_peers(n->dht, (const uint8_t *)encrypted_injector_proxy_swarm_p0);
snprintf(name, sizeof(name), "injector proxy %d-%d", tm->tm_year, (tm->tm_yday + 1));
crypto_generichash(encrypted_injector_proxy_swarm_p1, sizeof(encrypted_injector_proxy_swarm_p1), (uint8_t*)name, strlen(name), NULL, 0);
dht_get_peers(n->dht, (const uint8_t *)encrypted_injector_proxy_swarm_p1);
}
}
void abort_connect(pending_request *r)
{
if (!r->on_connect) {
return;
}
debug("aborting request:%p\n", r);
free(r->via);
r->via = NULL;
Block_release(r->on_connect);
r->on_connect = NULL;
TAILQ_REMOVE(&pending_requests, r, next);
pending_requests_len--;
debug("abort_connect request:%p (outstanding:%zu)\n", r, pending_requests_len);
}
void proxy_cache_delete(proxy_request *p)
{
if (p->cache_file != -1) {
close(p->cache_file);
p->cache_file = -1;
unlink(p->cache_name);
}
}
bool proxy_request_any_direct(const proxy_request *p)
{
for (size_t i = 0; i < lenof(p->direct_requests); i++) {
if (p->direct_requests[i].req) {
return true;
}
}
return false;
}
bool proxy_request_any_peers(const proxy_request *p)
{
for (size_t i = 0; i < lenof(p->requests); i++) {
if (p->requests[i].req || p->requests[i].r.on_connect) {
return true;
}
}
return false;
}
void proxy_send_error(proxy_request *p, int error, const char *reason)
{
if (proxy_request_any_direct(p) || proxy_request_any_peers(p)) {
return;
}
if (p->server_req) {
if (p->server_req->evcon) {
evhttp_connection_set_closecb(p->server_req->evcon, NULL, NULL);
}
if (p->server_req->response_code) {
debug("p:%p req:%p evcon:%p (%.2fms) responding can't send error, terminating connection. %d %s\n",
p, p->server_req, p->server_req->evcon, rdelta(p), error, reason);
evhttp_send_reply_end(p->server_req);
} else {
debug("p:%p req:%p evcon:%p (%.2fms) responding with %d %s\n",
p, p->server_req, p->server_req->evcon, rdelta(p),
error, reason);
evhttp_send_error(p->server_req, error, reason);
}
p->server_req = NULL;
}
}
void proxy_request_cleanup(proxy_request *p, const char *reason)
{
size_t num_peers = 0;
size_t num_direct = 0;
for (size_t i = 0; i < lenof(p->direct_requests); i++) {
if (p->direct_requests[i].req) {
num_direct++;
}
}
for (size_t i = 0; i < lenof(p->requests); i++) {
if (p->requests[i].req || p->requests[i].r.on_connect) {
num_peers++;
}
}
debug("%s:%d peers:%zu direct:%zu\n", __func__, __LINE__, num_peers, num_direct);
if (p->dont_free || proxy_request_any_peers(p) || proxy_request_any_direct(p)) {
return;
}
if (p->server_req) {
char buf[1024];
snprintf(buf, sizeof(buf), "Bad Gateway (%s)", reason);
proxy_send_error(p, 502, buf);
}
for (size_t i = 0; i < lenof(p->requests); i++) {
peer_request *r = &p->requests[i];
if (r->pc) {
peer_disconnect(r->pc);
r->pc = NULL;
}
assert(!r->range.chunk_buffer);
}
for (size_t i = 0; i < lenof(p->direct_requests); i++) {
direct_request *d = &p->direct_requests[i];
if (d->evcon) {
evhttp_connection_free(d->evcon);
d->evcon = NULL;
}
if (d->range.chunk_buffer) {
evbuffer_free(d->range.chunk_buffer);
d->range.chunk_buffer = NULL;
}
}
free(p->direct_code_line);
evhttp_clear_headers(&p->direct_headers);
evhttp_clear_headers(&p->output_headers);
if (p->header_buf) {
evbuffer_free(p->header_buf);
}
merkle_tree_free(p->m);
free(p->have_bitfield);
proxy_cache_delete(p);
free(p->authority);
free(p->etag);
free(p->uri);
free(p);
}
void peer_request_cleanup(peer_request *r, const char *reason)
{
if (r->req) {
return;
}
if (r->pc) {
peer_disconnect(r->pc);
r->pc = NULL;
}
if (r->range.chunk_buffer) {
evbuffer_free(r->range.chunk_buffer);
r->range.chunk_buffer = NULL;
}
proxy_request_cleanup(r->p, reason);
}
void peer_reuse(network *n, peer_connection *pc)
{
if (pc->evcon) {
evhttp_connection_set_closecb(pc->evcon, peer_evcon_close_cb, pc);
}
// handle waiting requests first
pending_request *r = pending_request_pop(pc);
if (r) {
debug("reusing pc:%p evcon:%p via:%c (%s) for request:%p (outstanding:%zu)\n",
pc, pc->evcon, pc->peer->via ? pc->peer->via : ' ', r->via, r, pending_requests_len);
pending_request_complete(r, pc);
return;
}
// add to the pool if there's a slot
for (uint i = 0; i < lenof(peer_connections); i++) {
if (!peer_connections[i]) {
debug("saving pc:%p for reuse\n", pc);
peer_connections[i] = pc;
return;
}
}
// replace an in-progress connection if there is one
for (uint i = 0; i < lenof(peer_connections); i++) {
peer_connection *old_pc = peer_connections[i];
if (!old_pc->evcon) {
debug("replacing old_pc:%p with pc:%p\n", old_pc, pc);
peer_disconnect(old_pc);
peer_connections[i] = pc;
return;
}
}
// oh well
peer_disconnect(pc);
}
void direct_request_cancel(direct_request *d)
{
if (d->req) {
evhttp_cancel_request(d->req);
d->req = NULL;
}
}
void proxy_direct_requests_cancel(proxy_request *p)
{
for (size_t i = 0; i < lenof(p->direct_requests); i++) {
if (p->direct_requests[i].req) {
direct_request_cancel(&p->direct_requests[i]);
}
}
}
void peer_request_cancel(peer_request *r)
{
if (r->req) {
debug("r:%p %s:%d p:%p\n", r, __func__, __LINE__, r->p);
evhttp_cancel_request(r->req);
r->req = NULL;
}
if (!r->pc) {
abort_connect(&r->r);
} else {
peer_disconnect(r->pc);
debug("r:%p %s:%d r->pc = NULL\n", r, __func__, __LINE__);
r->pc = NULL;
}
if (r->range.chunk_buffer) {
evbuffer_free(r->range.chunk_buffer);
r->range.chunk_buffer = NULL;
}
}
void proxy_peer_requests_cancel(proxy_request *p)
{
for (size_t i = 0; i < lenof(p->requests); i++) {
peer_request_cancel(&p->requests[i]);
}
}
bool write_header_to_file(int headers_file, int code, const char *code_line, evkeyvalq *input_headers)
{
evbuffer_auto_free evbuffer *buf = evbuffer_new();
evbuffer_add_printf(buf, "HTTP/1.1 %d %s\r\n", code, code_line);
const char *headers[] = hashed_headers;
for (int i = 0; i < (int)lenof(headers); i++) {
const char *key = headers[i];
const char *value = evhttp_find_header(input_headers, key);
if (!value) {
continue;
}
evbuffer_add_printf(buf, "%s: %s\r\n", key, value);
}
const char *sign_headers[] = {"X-MSign", "X-Hashes"};
for (int i = 0; i < (int)lenof(sign_headers); i++) {
const char *key = sign_headers[i];
const char *value = evhttp_find_header(input_headers, key);
evbuffer_add_printf(buf, "%s: %s\r\n", key, value);
}
evbuffer_add_printf(buf, "\r\n");
return evbuffer_write_to_file(buf, headers_file);
}
bool evcon_is_localhost(evhttp_connection *evcon)
{
return bufferevent_is_localhost(evhttp_connection_get_bufferevent(evcon));
}
bool evcon_is_utp(evhttp_connection *evcon)
{
return BEV_IS_UTP(evhttp_connection_get_bufferevent(evcon));
}
void copy_response_headers(evhttp_request *from, evhttp_request *to)
{
const char *response_header_whitelist[] = hashed_headers;
for (uint i = 0; i < lenof(response_header_whitelist); i++) {
copy_header(from, to, response_header_whitelist[i]);
}
copy_header(from, to, "Content-Length");
if (!evcon_is_localhost(to->evcon)) {
copy_header(from, to, "Content-Location");
copy_header(from, to, "X-MSign");
copy_header(from, to, "X-Hashes");
}
}
uint64_t num_chunks(const proxy_request *p)
{
return DIV_ROUND_UP(p->total_length, LEAF_CHUNK_SIZE);
}
uint64_t chunk_length(const proxy_request *p, uint64_t chunk_index)
{
if (p->chunked) {
return LEAF_CHUNK_SIZE;
}
if ((chunk_index + 1) * LEAF_CHUNK_SIZE <= p->total_length) {
return LEAF_CHUNK_SIZE;
}
return p->total_length % LEAF_CHUNK_SIZE;
}
void direct_submit_request(proxy_request *p);
void direct_chunked_cb(evhttp_request *req, void *arg);
void proxy_submit_request(proxy_request *p);
void proxy_set_length(proxy_request *p, uint64_t total_length)
{
debug("%s p:%p total_length:%"PRIu64" num_chunks:%"PRIu64"\n", __func__, p, total_length, num_chunks(p));
uint64_t old_length = num_chunks(p);
uint64_t old_chunks = DIV_ROUND_UP(old_length, LEAF_CHUNK_SIZE);
p->total_length = total_length;
if (!p->have_bitfield) {
p->have_bitfield = calloc(1, num_chunks(p));
return;
}
if (num_chunks(p) == old_chunks) {
return;
}
bool *have_bitfield = realloc(p->have_bitfield, num_chunks(p));
if (num_chunks(p) > old_chunks && have_bitfield) {
uint64_t diff = num_chunks(p) - old_chunks;
bzero(&have_bitfield[old_chunks], diff);
}
p->have_bitfield = have_bitfield;
}
int proxy_setup_range(proxy_request *p, evhttp_request *req, chunked_range *range)
{
if (p->cache_file == -1) {
snprintf(p->cache_name, sizeof(p->cache_name), CACHE_NAME);
mkpath(p->cache_name);
p->cache_file = mkstemp(p->cache_name);
debug("start cache:%s\n", p->cache_name);
}
if (!p->etag) {
const char *etag = evhttp_find_header(req->input_headers, "ETag");
p->etag = etag?strdup(etag):NULL;
}
uint64_t total_length = 0;
const char *content_range = evhttp_find_header(req->input_headers, "Content-Range");
const char *content_length = evhttp_find_header(req->input_headers, "Content-Length");
const char *transfer_encoding = evhttp_find_header(req->input_headers, "Transfer-Encoding");
if (content_range) {
debug("Content-Range: %s\n", content_range);
sscanf(content_range, "bytes %"PRIu64"-%"PRIu64"/%"PRIu64, &range->start, &range->end, &total_length);
uint64_t header_prefix = p->header_buf ? evbuffer_get_length(p->header_buf) : 0;
range->chunk_index = (range->start + header_prefix) / LEAF_CHUNK_SIZE;
debug("p:%p start:%"PRIu64" chunk_index:%"PRIu64"\n", p, range->start, range->chunk_index);
} else if (content_length) {
debug("Content-Length: %s\n", content_length);
char *endp;
ev_int64_t clen = evutil_strtoll(content_length, &endp, 10);
if (*content_length == '\0' || *endp != '\0' || clen < 0) {
debug("%s: illegal content length: %s", __func__, content_length);
proxy_send_error(p, 502, "Invalid Gateway Content-Length");
return -1;
}
total_length = (uint64_t)clen;
range->end = clen - 1;
} else if (transfer_encoding && strstr(transfer_encoding, "chunked")) {
debug("Transfer-Encoding: %s\n", transfer_encoding);
// oh, bother.
p->chunked = true;
}
if (!p->header_buf) {
int code = req->response_code;
const char *rangeh = evhttp_find_header(p->server_req->input_headers, "Range");
if (code == 206 && !rangeh) {
code = 200;
}
p->direct_code = code;
p->direct_code_line = strdup(req->response_code_line);
p->header_buf = build_request_buffer(code, req->input_headers);
uint64_t header_prefix = p->header_buf ? evbuffer_get_length(p->header_buf) : 0;
range->chunk_index = (range->start + header_prefix) / LEAF_CHUNK_SIZE;
}
if (p->content_length && p->content_length != total_length) {
proxy_send_error(p, 502, "Incorrect Gateway Content-Length");
return -1;
}
p->content_length = total_length;
if (!p->range_end && p->content_length > 0) {
p->range_end = p->content_length - 1;
}
if (req->type == EVHTTP_REQ_HEAD) {
total_length = 0;
}
total_length += evbuffer_get_length(p->header_buf);
if (p->total_length && p->total_length != total_length) {
proxy_send_error(p, 502, "Incorrect Gateway Range");
return -1;
}
proxy_set_length(p, total_length);
return 1;
}
int direct_header_cb(evhttp_request *req, void *arg)
{
direct_request *d = (direct_request*)arg;
proxy_request *p = d->p;
debug("d:%p (%.2fms) direct_header_cb %d %s %s\n", d, rdelta(p), req->response_code, req->response_code_line, p->uri);