-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttp.cpp
More file actions
4290 lines (4148 loc) · 186 KB
/
Copy pathHttp.cpp
File metadata and controls
4290 lines (4148 loc) · 186 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
#include "Http.hpp"
#include "Http3.hpp"
#include "Http3Probe.hpp"
#ifdef DEBUGFASTCGI
#include "Https.hpp"
#endif
#include "Client.hpp"
#include "Cache.hpp"
#include "Backend.hpp"
#include "Common.hpp"
#include "Dns.hpp"
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
#include <sstream>
#include <algorithm>
#include <fcntl.h>
#include <chrono>
#ifdef DEBUGFASTCGI
#include <arpa/inet.h>
#include <sys/time.h>
#endif
#ifdef DEBUGFASTCGI
std::unordered_set<Http *> Http::httpToDebug;
#endif
std::unordered_set<Http *> Http::httpToDelete;
//ETag -> If-None-Match
const char rChar[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const size_t &rCharSize=sizeof(rChar)-1;
//Todo: limit max file size 9GB
//reuse cache stale for file <20KB
std::unordered_map<std::string,Http *> Http::pathToHttp;
int Http::fdRandom=-1;
char Http::buffer[];
bool Http::useCompression=true;
bool Http::allowStreaming=false;
bool Http::http3Enabled=false;
uint16_t Http::http3Port=443;
uint64_t Http::http3DeadlineMs=8000;
char Http::fastcgiheaderend[];
char Http::fastcgiheaderstdout[];
std::string gen_random(const int len) {
static const char alphanum[] =
"123456789"
"ABCDEFGHJKMNPQRSTUVWXYZ"
"abcdefghijkmnpqrstuvwxyz";
std::string tmp_s;
tmp_s.reserve(len);
for (int i = 0; i < len; ++i) {
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
}
return tmp_s;
}
Http::Http(const int &cachefd, //0 if no old cache file found
const std::string &cachePath, Client *client) :
cachePath(cachePath),//to remove from Http::pathToHttp
tempCache(nullptr),
finalCache(nullptr),
parsedHeader(false),
lastReceivedBytesTimestamps(0),
contentsize(-1),
contentwritten(0),
http_code(0),
parsing(Parsing_None),
gzip(false),
retryCount(0),
pending(false),
requestSended(false),
headerWriten(false),
backend(nullptr),
backendList(nullptr),
contentLengthPos(-1),
chunkLength(-1),
http3Conn(nullptr),
http3StartedMs(0),
resumeOffset(-1),
skipBytes(0)
{
memset(&m_socket,0,sizeof(m_socket));
memset(&m_socket.sin6_addr,0,sizeof(m_socket.sin6_addr));
status=Status_Idle;
#ifdef DEBUGFASTCGI
httpToDebug.insert(this);
#endif
endDetected=false;
fileMoved=false;
streamingDetected=false;
lastReceivedBytesTimestamps=Common::msFrom1970();
#ifdef DEBUGFASTCGI
if(&pathToHttpList()==&Http::pathToHttp)
std::cerr << "contructor http " << this << " uri: " << uri << " lastReceivedBytesTimestamps: " << lastReceivedBytesTimestamps << ": " << __FILE__ << ":" << __LINE__ << std::endl;
else
std::cerr << "contructor https " << this << " uri: " << uri << " lastReceivedBytesTimestamps: " << lastReceivedBytesTimestamps << ": " << __FILE__ << ":" << __LINE__ << std::endl;
if(cachePath.empty())
{
std::cerr << "critical error cachePath.empty() " << this << " uri: " << uri << ": " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
#endif
if(cachefd<=0)
{
#ifdef DEBUGFASTCGI
std::cerr << "Http::Http() cachefd==0 then tempCache(nullptr): " << this << std::endl;
#endif
}
else
{
#ifdef DEBUGFASTCGI
std::cerr << "Http::Http() cachefd!=0: " << this << std::endl;
#endif
finalCache=new Cache(cachefd,nullptr);
}
/*
//while receive write to cache
//when finish
//unset Http to all future listener
//Close all listener
*/
/* simplified addClient()
* this prevent:
* Http::tryConnect() before addClient()
* Http::dnsError()
* Http::disconnectFrontend()
* Http::checkIngrityHttpClient()
* abort();
* */
clientsList.push_back(client);
client->http=this;
}
/// \bug never call! memory leak
Http::~Http()
{
if(!uri.empty() && !endDetected)
std::cerr << "Client::~Client() !uri.empty() && !endTriggered: " << uri << std::endl;
#ifdef DEBUGFASTCGI
if(httpToDebug.find(this)!=httpToDebug.cend())
httpToDebug.erase(this);
else
{
std::cerr << this << ": " << __FILE__ << ":" << __LINE__ << " Http Entry not found into global list, abort()" << std::endl;
abort();
}
#endif
#ifdef DEBUGFASTCGI
std::cerr << "Http::~Http(): destructor " << this << " uri: " << uri << " status: " << (int)status << " " << __FILE__ << ":" << __LINE__ << std::endl;
Backend *b=backend;
#endif
if(status==Status_WaitDns)
{
#ifdef DEBUGFASTCGI
std::cerr << "disconnectFrontend client " << this << ": " << __FILE__ << ":" << __LINE__ << " host: " << host << std::endl;
#endif
//Call to virtual method 'Http::isHttps' during destruction bypasses virtual dispatch [clang-analyzer-optin.cplusplus.VirtualCall]
//Dns::dns->cancelClient(this,host,isHttps(),true);-> done over destructor
#ifdef DEBUGFASTCGI
std::cerr << "disconnectFrontend client " << this << ": " << __FILE__ << ":" << __LINE__ << " host: " << host << std::endl;
#endif
status=Status_Idle;
#ifdef DEBUGFASTCGI
Http::checkIngrityHttpClient();
#endif
}
#ifdef DEBUGDNS
//very heavy check
if(Dns::dns->queryHaveThisClient(this))
{
std::cerr << "Http::disconnectBackend(): remain http " << this << " on dns " << __FILE__ << ":" << __LINE__ << " (abort)" << std::endl;
abort();
}
#endif
#ifdef DEBUGFASTCGI
checkBackend();
#endif
if(tempCache!=nullptr)
{
delete tempCache;
tempCache=nullptr;
}
if(http3Conn!=nullptr)
{
delete http3Conn;
http3Conn=nullptr;
}
disconnectFrontend(true);
disconnectBackend(true);
for(Client * client : clientsList)
{
#ifdef DEBUGFASTCGI
std::cerr << __FILE__ << ":" << __LINE__ << " " << this << " http destructor, client " << client << std::endl;
#endif
client->disconnect();
}
clientsList.clear();
#ifdef DEBUGFASTCGI
for(const Client * client : Client::clients)
{
if(client->http==this)
{
std::cerr << "Http::~Http(): destructor, remain client on this http " << __FILE__ << ":" << __LINE__ << " " << this << " client: " << client << " destructor (abort)" << std::endl;
abort();
}
}
{
std::unordered_map<std::string/* example: 29E7336BDEA3327B */,Http *> pathToHttp=Http::pathToHttp;
for( const auto &n : pathToHttp )
if(n.second==this)
{
std::cerr << "Http::~Http(): destructor post opt this " << this << " can't be into Http::pathToHttp at " << n.first << " " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
{
std::unordered_map<std::string/* example: 29E7336BDEA3327B */,Http *> pathToHttp=Https::pathToHttps;
for( const auto &n : pathToHttp )
if(n.second==this)
{
std::cerr << "Http::~Http(): destructor post opt this " << this << " can't be into Https::pathToHttps at " << n.first << " " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
if(Http::httpToDelete.find(this)!=Http::httpToDelete.cend())
{
std::cerr << "Http::~Http(): destructor post opt can't have this into Http::httpToDelete " << this << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
Http::httpToDelete.erase(this);
if(b!=nullptr)
{
if(b->http==this)
{
std::cerr << "Http::~Http(): destructor post backend " << (void *)b << " remain on this Http " << this << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
#endif
//to be safe, delete when all is stable
for( const auto &n : Backend::addressToHttp )
{
for( const auto &m : n.second->busy )
{
if(m->http==this)
{
std::cerr << (void *)m << " p->http==" << this << " into busy list, error http (abort)" << ": " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
for( const auto &m : n.second->idle )
{
if(m->http==this)
{
std::cerr << (void *)m << " p->http==" << this << " into idle list, error http (abort)" << ": " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
unsigned int index=0;
while(index<n.second->pending.size())
{
if(n.second->pending.at(index)==this)
{
std::cerr << this << " " << __FILE__ << ":" << __LINE__ << " workaround activated, ERROR should not be exists, backend not correctly unregistred" << std::endl;
n.second->pending.erase(n.second->pending.cbegin()+index);
}
else
index++;
}
}
for( const auto &n : Backend::addressToHttps )
{
for( const auto &m : n.second->busy )
{
if(m->http==this)
{
std::cerr << (void *)m << " p->http==" << this << " into busy list, error http (abort)" << ": " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
for( const auto &m : n.second->idle )
{
if(m->http==this)
{
std::cerr << (void *)m << " p->http==" << this << " into idle list, error http (abort)" << ": " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
unsigned int index=0;
while(index<n.second->pending.size())
{
if(n.second->pending.at(index)==this)
{
std::cerr << this << " " << __FILE__ << ":" << __LINE__ << " workaround activated, ERROR should not be exists, backend not correctly unregistred" << std::endl;
n.second->pending.erase(n.second->pending.cbegin()+index);
}
else
index++;
}
}
}
bool Http::tryConnect(const std::string &host, const std::string &uri, const bool &gzip, const std::string &etag)
{
if(status!=Status_Idle)
{
std::cerr << "Http::tryConnect() status!=Status_Idle " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
#ifdef DEBUGFASTCGI
const auto p1 = std::chrono::system_clock::now();
std::cerr << std::chrono::duration_cast<std::chrono::seconds>(p1.time_since_epoch()).count() << " try connect " << this << " uri: " << uri << ": " << __FILE__ << ":" << __LINE__ << std::endl;
if(etag.find('\0')!=std::string::npos)
std::cerr << "etag contain \\0 abort" << __FILE__ << ":" << __LINE__ << std::endl;
#endif
this->gzip=gzip;
this->host=host;
this->uri=uri;
this->etagBackend=etag;
#ifdef DEBUGFASTCGI
std::cerr << __FILE__ << ":" << __LINE__ << " " << this << " status=Status_WaitDns" << std::endl;
#endif
status=Status_WaitDns;
if(!Dns::dns->getAAAA(this,host,isHttps()))
{
#ifdef DEBUGFASTCGI
std::cerr << __FILE__ << ":" << __LINE__ << " " << this << " CDN dns overloaded" << std::endl;
#endif
parseNonHttpError(Backend::NonHttpError_DnsOverloaded);
disconnectFrontend(true);
#ifdef DEBUGFASTCGI
std::cerr << __FILE__ << ":" << __LINE__ << " " << this << " call disconnectBackend()" << std::endl;
#endif
disconnectBackend();
#ifdef DEBUGFASTCGI
Http::checkIngrityHttpClient();
#endif
return false;
}
#ifdef DEBUGFASTCGI
Http::checkIngrityHttpClient();
#endif
return true;
}
//always drop query in dns before this, then call WITHOUT reference HTTP object
void Http::dnsError()
{
if(status!=Status_WaitDns)
{
/*std::cerr << "Http::dnsError() status!=Status_WaitDns " << __FILE__ << ":" << __LINE__ << std::endl;
abort();*/
//now it's just a warning
std::cerr << "Http::dnsError() status!=Status_WaitDns: " << (int)status << " " << __FILE__ << ":" << __LINE__ << " " << this << std::endl;
return;
}
status=Status_WaitTheContent;
if(!isAlive())
return;
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
#ifdef DEBUGFASTCGI
std::cerr << __FILE__ << ":" << __LINE__ << " " << this << std::endl;
#endif
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
parseNonHttpError(Backend::NonHttpError_DnsError);
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
disconnectFrontend(true);
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
#ifdef DEBUGFASTCGI
std::cerr << __FILE__ << ":" << __LINE__ << " " << this << " call disconnectBackend()" << std::endl;
#endif
disconnectBackend();
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
}
//always drop query in dns before this, then call WITHOUT reference HTTP object
void Http::dnsWrong()
{
if(status!=Status_WaitDns)
{
/*std::cerr << "Http::dnsWrong() status!=Status_WaitDns " << __FILE__ << ":" << __LINE__ << std::endl;
abort();*/
//now it's just a warning
std::cerr << "Http::dnsWrong() status!=Status_WaitDns: " << (int)status << " " << __FILE__ << ":" << __LINE__ << " " << this << std::endl;
return;
}
status=Status_WaitTheContent;
if(!isAlive())
return;
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
#ifdef DEBUGFASTCGI
std::cerr << __FILE__ << ":" << __LINE__ << " " << this << std::endl;
#endif
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
parseNonHttpError(Backend::NonHttpError_DnsWrong);
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
disconnectFrontend(true);
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
#ifdef DEBUGFASTCGI
std::cerr << __FILE__ << ":" << __LINE__ << " " << this << " call disconnectBackend()" << std::endl;
#endif
disconnectBackend();
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
}
void Http::dnsRight(const sockaddr_in6 &sIPv6)
{
if(status!=Status_WaitDns)
{
/*std::cerr << "Http::dnsRight() status!=Status_WaitDns " << __FILE__ << ":" << __LINE__ << std::endl;
abort();*/
//now it's just a warning
std::cerr << "Http::dnsRight() status!=Status_WaitDns: " << (int)status << " " << __FILE__ << ":" << __LINE__ << " " << this << " time: " << Common::msFrom1970() << std::endl;
return;
}
status=Status_WaitTheContent;
if(!isAlive())
return;
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
lastReceivedBytesTimestamps=Common::msFrom1970();
#ifdef DEBUGFASTCGI
char str[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &sIPv6.sin6_addr, str, INET6_ADDRSTRLEN);
#ifdef DEBUGDNS
if(Dns::dns->hardcodedDns.find(host)!=Dns::dns->hardcodedDns.cend())
if(std::string(str)!=Dns::dns->hardcodedDns.at(host))
{
std::cerr << host << ": " << str << " corruption detected by hard coded value (abort) " << __FILE__ << ":" << __LINE__ << " time: " << Common::msFrom1970() << std::endl;
abort();
}
#endif
std::cerr << this << ": Http::dnsRight() " << host << ": " << str << " url: " << getUrl() << " " << __FILE__ << ":" << __LINE__ << " time: " << Common::msFrom1970() << std::endl;
#endif
m_socket=sIPv6;
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
// Telemetry-only HTTP/3 probe. Runs in parallel with the HTTPS leg
// when --http3-probe is set. Never affects the HTTPS path.
if(Http3Probe::enabled && isHttps())
{
sockaddr_in6 h3target = m_socket;
h3target.sin6_port = Backend::https_portBE;
std::string probePath = uri;
if(probePath.empty() || probePath[0] != '/')
probePath = "/" + probePath;
Http3Probe::launch(h3target, host, probePath);
}
// HTTP/3 + HTTP/1.1 race. Both legs start in parallel when the
// flag is on and the origin isn't in the failure cache. checkH3
// arbitrates each detectTimeout tick:
// * H1.1 reached client-emit (headerWriten || tempCache!=null)
// before H3 finished -> H1 wins, drop H3, normal flow.
// * H3 reached allStreamsDone+200 first -> H3 wins, adopt
// response, disconnect H1.1 backend.
// * H3 connFailed / deadline / non-2xx -> drop H3, H1.1
// continues unaffected (no fallback dispatch needed since H1.1
// is already running).
//
// The failure cache gates whether we even attempt H3 — if the
// origin failed H3 recently we skip starting the leg and save the
// UDP packets.
if(Http::http3Enabled && isHttps())
{
sockaddr_in6 h3target = m_socket;
h3target.sin6_port = htobe16(Http::http3Port);
if(!Http3::isOriginRecentlyFailed(h3target))
startH3();
}
tryConnectInternal(m_socket);
#ifdef DEBUGFASTCGI
checkIngrityHttpClient();
#endif
}
bool Http::isHttps()
{
return false;
}
bool Http::tryConnectInternal(const sockaddr_in6 &s)
{
if(status!=Status_WaitTheContent)
{
std::cerr << "Http::tryConnectInternal() status!=Status_WaitTheContent " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
bool connectInternal=false;
#ifdef DEBUGFASTCGI
char str[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &s.sin6_addr, str, INET6_ADDRSTRLEN);
std::cerr << this << ": Http::tryConnectInternal " << host << ": " << str << " url: " << getUrl() << " " << __FILE__ << ":" << __LINE__ << std::endl;
#endif
if(backend!=nullptr)
{
#ifdef DEBUGFASTCGI
//if this can be located into another backend, then error
for( const auto& n : Backend::addressToHttp )
{
const Backend::BackendList * list=n.second;
for(const Backend * b : list->busy)
if(b->http==this)
{
std::cerr << this << ": backend->http==this, http backend: " << backend << " " << getUrl() << " (abort)" << std::endl;
abort();
}
}
for( const auto& n : Backend::addressToHttps )
{
const Backend::BackendList * list=n.second;
for(const Backend * b : list->busy)
if(b->http==this)
{
std::cerr << this << ": backend->http==this, https backend: " << backend << " " << getUrl() << " (abort)" << " " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
#endif
#ifdef DEBUGFASTCGI
std::cerr << __FILE__ << ":" << __LINE__ << " " << this << " call disconnectBackend()" << std::endl;
#endif
disconnectBackend();
}
backend=Backend::tryConnectHttp(s,this,connectInternal,&backendList);
if(backendList==nullptr)
{
std::cerr << this << " Http::tryConnectInternal() call Backend::tryConnectHttp() should at least set backendList" << " " << __FILE__ << ":" << __LINE__ << " (abort)" << std::endl;
abort();
}
if(backend==nullptr)
{
#ifdef DEBUGFASTCGI
std::string host2="Unknown IPv6";
char str[INET6_ADDRSTRLEN];
if (inet_ntop(AF_INET6, &m_socket.sin6_addr, str, INET6_ADDRSTRLEN) != NULL)
host2=str;
std::cerr << Common::msFrom1970() << " " << this << ": unable to get backend for " << host << uri << " Backend::addressToHttp[" << host2 << "] then put in pending" << " " << __FILE__ << ":" << __LINE__ << std::endl;
//check here if not backend AND free backend or backend count < max
std::string addr((char *)&m_socket.sin6_addr,16);
//if have already connected backend on this ip
if(Backend::addressToHttp.find(addr)!=Backend::addressToHttp.cend())
{
Backend::BackendList *list=Backend::addressToHttp[addr];
if(!list->idle.empty())
{
std::cerr << this << " backend==nullptr and !list->idle.empty(), isAlive(): " << std::to_string((int)isAlive()) << ", clientsList size: " << std::to_string(clientsList.size()) << " (abort)" << std::endl;
abort();
}
if(list->busy.size()<Backend::maxBackend)
{
std::cerr << this << " backend==nullptr and list->busy.size()<Backend::maxBackend, isAlive(): " << std::to_string((int)isAlive()) << ", clientsList size: " << std::to_string(clientsList.size()) << " (abort)" << std::endl;
abort();
}
unsigned int index=0;
while(index<list->pending.size())
{
if(list->pending.at(index)==this)
break;
index++;
}
if(index>=list->pending.size())
{
std::cerr << this << " backend==nullptr and this " << this << " not found into pending, isAlive(): " << std::to_string((int)isAlive()) << ", clientsList size: " << std::to_string(clientsList.size()) << " (abort) " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
else if(Backend::addressToHttps.find(addr)!=Backend::addressToHttps.cend())
{
Backend::BackendList *list=Backend::addressToHttps[addr];
if(!list->idle.empty())
{
std::cerr << this << " backend==nullptr and !list->idle.empty(), isAlive(): " << std::to_string((int)isAlive()) << ", clientsList size: " << std::to_string(clientsList.size()) << " (abort) " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
if(list->busy.size()<Backend::maxBackend)
{
std::cerr << this << " backend==nullptr and list->busy.size()<Backend::maxBackend, isAlive(): " << std::to_string((int)isAlive()) << ", clientsList size: " << std::to_string(clientsList.size()) << " (abort) " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
unsigned int index=0;
while(index<list->pending.size())
{
if(list->pending.at(index)==this)
break;
index++;
}
if(index>=list->pending.size())
{
std::cerr << this << " backend==nullptr and this " << this << " not found into pending, isAlive(): " << std::to_string((int)isAlive()) << ", clientsList size: " << std::to_string(clientsList.size()) << " (abort) " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
else
{
std::string host="Unknown IPv6";
std::string host2="Unknown IPv6";
char str[INET6_ADDRSTRLEN];
if (inet_ntop(AF_INET6, &m_socket.sin6_addr, str, INET6_ADDRSTRLEN) != NULL)
host=str;
if (inet_ntop(AF_INET6, &m_socket.sin6_addr, str, INET6_ADDRSTRLEN) != NULL)
host2=str;
std::cerr << this << " backend==nullptr into tryConnectInternal(), put in queue?, backendList: " << backendList << ", isAlive(): " << std::to_string((int)isAlive()) << ", clientsList size: " << std::to_string(clientsList.size()) << " " << host << " " << host2 << " (abort) " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
#endif
}
#ifdef DEBUGFASTCGI
std::cerr << "[" << Common::msFrom1970() << "] " << this << ": http->backend=" << backend << " " << __FILE__ << ":" << __LINE__ << std::endl;
#endif
return connectInternal && backend!=nullptr;
}
const std::string &Http::getCachePath() const
{
return cachePath;
}
void Http::resetRequestSended()
{
if(http_code!=0)
return;
parsedHeader=false;
contentsize=-1;
contentwritten=0;
parsing=Parsing_None;
requestSended=false;
contentLengthPos=-1;
chunkLength=-1;
}
bool Http::get_requestSended()
{
return requestSended;
}
Http::Status Http::get_status() const
{
return status;
}
void Http::sendRequest()
{
if(status!=Status_WaitTheContent)
{
std::cerr << "Http::sendRequest() status!=Status_WaitTheContent " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
//reset lastReceivedBytesTimestamps when come from busy to pending
lastReceivedBytesTimestamps=Common::msFrom1970();
#ifdef DEBUGFASTCGI
std::cerr << "[" << Common::msFrom1970() << "] " << "Http::sendRequest() " << this << " " << __FILE__ << ":" << __LINE__ << " uri: " << uri << " lastReceivedBytesTimestamps: " << lastReceivedBytesTimestamps << std::endl;
if(uri.empty())
{
std::cerr << "Http::readyToWrite(): but uri.empty()" << std::endl;
flushRead();
return;
}
#endif
requestSended=true;
{
std::string h(std::string("GET ")+uri);
if(Backend::forceHttpClose)
h+=" HTTP/1.1\r\nConnection: close\r\nHost: ";
else
h+=" HTTP/1.1\r\nHost: ";
h+=host+"\r\nEPNOERFT: ysff43Uy\r\n";
// Resume after mid-body disconnect: ask origin for `bytes=N-`. If origin
// honours Range it replies 206 Partial Content and we append the suffix
// to the partial cache; if origin replies 200 (Range ignored) we discard
// the head bytes from the new body to avoid duplicating to the client.
// Don't combine If-None-Match with Range — the semantics around 304 vs
// 206 collisions are murky, and the client has already started receiving
// body from the previous attempt so a 304 here is unhelpful.
if(resumeOffset>0)
{
h+="Range: bytes="+std::to_string(resumeOffset)+"-\r\n";
#ifdef DEBUGFASTCGI
std::cerr << this << " " << __FILE__ << ":" << __LINE__ << " Http::sendRequest() Range: bytes=" << resumeOffset << "-" << std::endl;
#endif
}
else if(!etagBackend.empty())
{
h+="If-None-Match: "+etagBackend+"\r\n";
#ifdef DEBUGFASTCGI
std::cerr << this << " " << __FILE__ << ":" << __LINE__ << " Http::sendRequest() etagBackend set to \"" << etagBackend << "\" (cache found)" << std::endl;
#endif
}
else
{
#ifdef DEBUGFASTCGI
std::cerr << this << " " << __FILE__ << ":" << __LINE__ << " Http::sendRequest() etagBackend.empty() (no cache)" << std::endl;
#endif
}
if(Http::useCompression && gzip)
h+="Accept-Encoding: gzip\r\n";
h+="\r\n";
if(!socketWrite(h.data(),h.size()))
{
#ifdef DEBUGFASTCGI
std::cerr << "ERROR to write: " << h << " errno: " << errno << std::endl;
#endif
startReadFromCacheAfter304();
}
}
/*used for retry host.clear();
uri.clear();*/
}
char Http::randomETagChar(uint8_t r)
{
#ifdef DEBUGFASTCGI
if(rCharSize!=65)
std::cerr << __FILE__ << ":" << __LINE__ << " wrong rChar size abort" << std::endl;
#endif
return rChar[r%rCharSize];
}
//true if have read something
bool Http::readyToRead()
{
/* if(var=="content-length")
if(var=="content-type")*/
//::read(Http::buffer
//load into buffer the previous content
if(backend!=nullptr && /*if file end send*/ endDetected)
{
int size=socketRead(Http::buffer,sizeof(Http::buffer));
while(size>0)
{
#ifdef DEBUGFASTCGI
std::cerr << this << " Received data while not connected to http " << __FILE__ << ":" << __LINE__ << " data: " << Common::binarytoHexa(buffer,size) << std::endl;
#endif
size=socketRead(Http::buffer,sizeof(Http::buffer));
}
return false;
}
bool haveReadSomething=false;
uint16_t offset=0;
if(!headerBuff.empty())
{
offset=headerBuff.size();
memcpy(buffer,headerBuff.data(),headerBuff.size());
}
#ifdef DEBUGFASTCGI
//std::cerr << this << " " << __FILE__ << ":" << __LINE__ << std::endl;
#endif
ssize_t readSize=0;
do
{
errno=0;
if(backend==nullptr)//stop, finish to read, else you will have problem in check into socketRead()
return true;
//disable to debug
const ssize_t size=socketRead(buffer+offset,sizeof(buffer)-offset);
readSize=size;
#ifdef DEBUGFASTCGI
if(readSize!=-1 || offset!=0) {std::cout << __FILE__ << ":" << __LINE__ << " " << readSize << " offset: " << offset << std::endl;}
#endif
if(size>0)
{
haveReadSomething=true;
if(status!=Status_WaitTheContent)
{
std::cerr << "Http::readyToRead() status!=Status_WaitTheContent " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
lastReceivedBytesTimestamps=Common::msFrom1970();
#ifdef DEBUGFASTCGI
//std::cout << "Stream block: " << Common::binarytoHexa(buffer,size) << " lastReceivedBytesTimestamps: " << lastReceivedBytesTimestamps << " " << __FILE__ << ":" << __LINE__ << std::endl;
#endif
if(parsing==Parsing_Content)
{
writeToCache(buffer,size);
if(endDetected)
return haveReadSomething;
}
else
{
uint16_t pos=0;
if(http_code==0)
{
//HTTP/1.1 200 OK
void *fh=nullptr;
while(pos<size && buffer[pos]!='\n')
{
char &c=buffer[pos];
if(http_code==0 && c==' ')
{
if(fh==nullptr)
{
pos++;
fh=buffer+pos;
}
else
{
c=0x00;
http_code=atoi((char *)fh);
#ifdef DEBUGFASTCGI
//std::cerr << this << " " << __FILE__ << ":" << __LINE__ << " http code: " << http_code << " (" << fh << ") headerBuff.empty(): " << std::to_string(headerBuff.empty()) << " data (" << buffer << "," << size << "): " << Common::binarytoHexa(buffer,size) << std::endl;
std::cerr << this << " " << __FILE__ << ":" << __LINE__ << " http code: " << http_code << " (" << fh << ") backend: " << backend << std::endl;
#endif
if(backend!=nullptr)
backend->wasTCPConnected=true;
if(!HttpReturnCode(http_code))
{
#ifdef DEBUGFASTCGI
std::cout << __FILE__ << ":" << __LINE__ << " readyToRead() !HttpReturnCode(http_code) backend: " << backend << " http_code: " << http_code << std::endl;
#endif
if(backend!=nullptr)
flushRead();
return haveReadSomething;
}
pos++;
}
}
else
pos++;
}
}
// For 200 / 206 (Range resume) / 3xx (forwarded redirect) we continue to
// header parsing — 30x needs Location, 206 needs Content-Range. All others
// were already handled inside HttpReturnCode (404/500/etc. send a Status to
// the client; 304 reads from cache).
const bool keepParsingHeaders =
(http_code==200) || (http_code==206) ||
(http_code==301) || (http_code==302) || (http_code==303) ||
(http_code==307) || (http_code==308);
if(!keepParsingHeaders)
{
if(backend!=nullptr)
flushRead();
#ifdef DEBUGFASTCGI
std::cout << __FILE__ << ":" << __LINE__ << " http code !=200 then flushRead, backend: " << backend << std::endl;
#endif
return haveReadSomething;
}
#ifdef DEBUGFASTCGI
std::cerr << this << " " << __FILE__ << ":" << __LINE__ << " finish get http code" << std::endl;
#endif
pos++;
parsing=Parsing_HeaderVar;
uint16_t pos2=pos;
//content-length: 5000
if(http_code!=0)
{
while(pos<size)
{
char &c=buffer[pos];
if(c==':' && parsing==Parsing_HeaderVar)
{
if((pos-pos2)==4)
{
std::string var(buffer+pos2,pos-pos2);
std::transform(var.begin(), var.end(), var.begin(),[](unsigned char c){return std::tolower(c);});
if(var=="etag")
{
parsing=Parsing_ETag;
pos++;
#ifdef DEBUGFASTCGI
std::cout << "get backend etag" << std::endl;
#endif
}
else
{
parsing=Parsing_HeaderVal;
//std::cout << "1a) " << std::string(buffer+pos2,pos-pos2) << " (" << pos-pos2 << ")" << std::endl;
pos++;
}
}
else if((pos-pos2)==16)
{
std::string var(buffer+pos2,pos-pos2);
std::transform(var.begin(), var.end(), var.begin(),[](unsigned char c){return std::tolower(c);});
if(Http::useCompression && gzip && var=="content-encoding")
{
parsing=Parsing_ContentEncoding;
pos++;
#ifdef DEBUGFASTCGI
//std::cout << "get backend content-encoding" << std::endl;
#endif
}
else
{
parsing=Parsing_HeaderVal;
//std::cout << "1a) " << std::string(buffer+pos2,pos-pos2) << " (" << pos-pos2 << ")" << std::endl;
pos++;
}
}
else if((pos-pos2)==14)
{
std::string var(buffer+pos2,pos-pos2);
std::transform(var.begin(), var.end(), var.begin(),[](unsigned char c){return std::tolower(c);});
if(var=="content-length")
{
parsing=Parsing_ContentLength;
pos++;
#ifdef DEBUGFASTCGI
//std::cout << "get backend content-length" << std::endl;
#endif
}
else
{
parsing=Parsing_HeaderVal;
//std::cout << "1a) " << std::string(buffer+pos2,pos-pos2) << " (" << pos-pos2 << ")" << std::endl;
pos++;
}
}
else if((pos-pos2)==8)
{
std::string var(buffer+pos2,pos-pos2);
std::transform(var.begin(), var.end(), var.begin(),[](unsigned char c){return std::tolower(c);});
if(var=="location")
{
// captured for 3xx redirect forwarding
parsing=Parsing_Location;
pos++;
}
else
{
parsing=Parsing_HeaderVal;
pos++;
}
}
else if((pos-pos2)==12)
{
std::string var(buffer+pos2,pos-pos2);
std::transform(var.begin(), var.end(), var.begin(),[](unsigned char c){return std::tolower(c);});
if(var=="content-type")
{
parsing=Parsing_ContentType;
pos++;
#ifdef DEBUGFASTCGI
//std::cout << "get backend content-type" << std::endl;
#endif
}
else
{
parsing=Parsing_HeaderVal;
//std::cout << "1a) " << std::string(buffer+pos2,pos-pos2) << " (" << pos-pos2 << ")" << std::endl;
pos++;
}
}
else if((pos-pos2)==13)
{
std::string var(buffer+pos2,pos-pos2);
std::transform(var.begin(), var.end(), var.begin(),[](unsigned char c){return std::tolower(c);});
if(var=="cache-control")
{
parsing=Parsing_CacheControl;
pos++;
#ifdef DEBUGFASTCGI
//std::cout << "get backend cache-control" << std::endl;
#endif
}
else if(Http::allowStreaming && var=="accept-ranges")
{
parsing=Parsing_AcceptRanges;