forked from squid-cache/squid
/
FwdState.cc
1595 lines (1326 loc) · 49.4 KB
/
FwdState.cc
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
/*
* Copyright (C) 1996-2022 The Squid Software Foundation and contributors
*
* Squid software is distributed under GPLv2+ license and includes
* contributions from numerous individuals and organizations.
* Please see the COPYING and CONTRIBUTORS files for details.
*/
/* DEBUG: section 17 Request Forwarding */
#include "squid.h"
#include "AccessLogEntry.h"
#include "acl/Address.h"
#include "acl/FilledChecklist.h"
#include "acl/Gadgets.h"
#include "anyp/PortCfg.h"
#include "base/AsyncCallbacks.h"
#include "base/AsyncCbdataCalls.h"
#include "CacheManager.h"
#include "CachePeer.h"
#include "client_side.h"
#include "clients/forward.h"
#include "clients/HttpTunneler.h"
#include "comm/Connection.h"
#include "comm/ConnOpener.h"
#include "comm/Loops.h"
#include "CommCalls.h"
#include "errorpage.h"
#include "event.h"
#include "fd.h"
#include "fde.h"
#include "FwdState.h"
#include "globals.h"
#include "HappyConnOpener.h"
#include "hier_code.h"
#include "http.h"
#include "http/Stream.h"
#include "HttpReply.h"
#include "HttpRequest.h"
#include "icmp/net_db.h"
#include "internal.h"
#include "ip/Intercept.h"
#include "ip/NfMarkConfig.h"
#include "ip/QosConfig.h"
#include "ip/tools.h"
#include "MemObject.h"
#include "mgr/Registration.h"
#include "neighbors.h"
#include "pconn.h"
#include "PeerPoolMgr.h"
#include "ResolvedPeers.h"
#include "security/BlindPeerConnector.h"
#include "SquidConfig.h"
#include "ssl/PeekingPeerConnector.h"
#include "Store.h"
#include "StoreClient.h"
#include "urn.h"
#include "whois.h"
#if USE_OPENSSL
#include "ssl/cert_validate_message.h"
#include "ssl/Config.h"
#include "ssl/helper.h"
#include "ssl/ServerBump.h"
#include "ssl/support.h"
#else
#include "security/EncryptorAnswer.h"
#endif
#include <cerrno>
static CLCB fwdServerClosedWrapper;
static OBJH fwdStats;
#define MAX_FWD_STATS_IDX 9
static int FwdReplyCodes[MAX_FWD_STATS_IDX + 1][Http::scInvalidHeader + 1];
PconnPool *fwdPconnPool = new PconnPool("server-peers", nullptr);
CBDATA_CLASS_INIT(FwdState);
void
FwdState::HandleStoreAbort(FwdState *fwd)
{
Pointer tmp = fwd; // Grab a temporary pointer to keep the object alive during our scope.
if (Comm::IsConnOpen(fwd->serverConnection())) {
fwd->closeServerConnection("store entry aborted");
} else {
debugs(17, 7, "store entry aborted; no connection to close");
}
fwd->stopAndDestroy("store entry aborted");
}
void
FwdState::closePendingConnection(const Comm::ConnectionPointer &conn, const char *reason)
{
debugs(17, 3, "because " << reason << "; " << conn);
assert(!serverConn);
assert(!closeHandler);
if (IsConnOpen(conn)) {
fwdPconnPool->noteUses(fd_table[conn->fd].pconn.uses);
conn->close();
}
}
void
FwdState::closeServerConnection(const char *reason)
{
debugs(17, 3, "because " << reason << "; " << serverConn);
assert(Comm::IsConnOpen(serverConn));
comm_remove_close_handler(serverConn->fd, closeHandler);
closeHandler = nullptr;
fwdPconnPool->noteUses(fd_table[serverConn->fd].pconn.uses);
serverConn->close();
}
/**** PUBLIC INTERFACE ********************************************************/
FwdState::FwdState(const Comm::ConnectionPointer &client, StoreEntry * e, HttpRequest * r, const AccessLogEntryPointer &alp):
entry(e),
request(r),
al(alp),
err(nullptr),
clientConn(client),
start_t(squid_curtime),
n_tries(0),
waitingForDispatched(false),
destinations(new ResolvedPeers()),
pconnRace(raceImpossible),
storedWholeReply_(nullptr)
{
debugs(17, 2, "Forwarding client request " << client << ", url=" << e->url());
HTTPMSGLOCK(request);
e->lock("FwdState");
flags.connected_okay = false;
flags.dont_retry = false;
flags.forward_completed = false;
flags.destinationsFound = false;
debugs(17, 3, "FwdState constructed, this=" << this);
}
// Called once, right after object creation, when it is safe to set self
void FwdState::start(Pointer aSelf)
{
// Protect ourselves from being destroyed when the only Server pointing
// to us is gone (while we expect to talk to more Servers later).
// Once we set self, we are responsible for clearing it when we do not
// expect to talk to any servers.
self = aSelf; // refcounted
// We hope that either the store entry aborts or peer is selected.
// Otherwise we are going to leak our object.
// Ftp::Relay needs to preserve control connection on data aborts
// so it registers its own abort handler that calls ours when needed.
if (!request->flags.ftpNative) {
AsyncCall::Pointer call = asyncCall(17, 4, "FwdState::Abort", cbdataDialer(&FwdState::HandleStoreAbort, this));
entry->registerAbortCallback(call);
}
// just in case; should already be initialized to false
request->flags.pinned = false;
#if STRICT_ORIGINAL_DST
// Bug 3243: CVE 2009-0801
// Bypass of browser same-origin access control in intercepted communication
// To resolve this we must force DIRECT and only to the original client destination.
const bool isIntercepted = request && !request->flags.redirected && (request->flags.intercepted || request->flags.interceptTproxy);
const bool useOriginalDst = Config.onoff.client_dst_passthru || (request && !request->flags.hostVerified);
if (isIntercepted && useOriginalDst) {
selectPeerForIntercepted();
return;
}
#endif
// do full route options selection
startSelectingDestinations(request, al, entry);
}
/// ends forwarding; relies on refcounting so the effect may not be immediate
void
FwdState::stopAndDestroy(const char *reason)
{
debugs(17, 3, "for " << reason);
cancelStep(reason);
PeerSelectionInitiator::subscribed = false; // may already be false
self = nullptr; // we hope refcounting destroys us soon; may already be nil
/* do not place any code here as this object may be gone by now */
}
/// Notify a pending subtask, if any, that we no longer need its help. We do not
/// have to do this -- the subtask job will eventually end -- but ending it
/// earlier reduces waste and may reduce DoS attack surface.
void
FwdState::cancelStep(const char *reason)
{
transportWait.cancel(reason);
encryptionWait.cancel(reason);
peerWait.cancel(reason);
}
#if STRICT_ORIGINAL_DST
/// bypasses peerSelect() when dealing with intercepted requests
void
FwdState::selectPeerForIntercepted()
{
// We do not support re-wrapping inside CONNECT.
// Our only alternative is to fake a noteDestination() call.
// use pinned connection if available
if (ConnStateData *client = request->pinnedConnection()) {
// emulate the PeerSelector::selectPinned() "Skip ICP" effect
entry->ping_status = PING_DONE;
usePinned();
return;
}
// use client original destination as second preferred choice
const auto p = new Comm::Connection();
p->peerType = ORIGINAL_DST;
p->remote = clientConn->local;
getOutgoingAddress(request, p);
debugs(17, 3, "using client original destination: " << *p);
destinations->addPath(p);
destinations->destinationsFinalized = true;
PeerSelectionInitiator::subscribed = false;
useDestinations();
}
#endif
/// updates ALE when we finalize the transaction error (if any)
void
FwdState::updateAleWithFinalError()
{
if (!err || !al)
return;
LogTagsErrors lte;
lte.timedout = (err->xerrno == ETIMEDOUT || err->type == ERR_READ_TIMEOUT);
al->cache.code.err.update(lte);
if (!err->detail) {
static const auto d = MakeNamedErrorDetail("WITH_SERVER");
err->detailError(d);
}
al->updateError(Error(err->type, err->detail));
}
void
FwdState::completed()
{
if (flags.forward_completed) {
debugs(17, DBG_IMPORTANT, "ERROR: FwdState::completed called on a completed request! Bad!");
return;
}
flags.forward_completed = true;
request->hier.stopPeerClock(false);
if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
debugs(17, 3, "entry aborted");
return ;
}
#if URL_CHECKSUM_DEBUG
entry->mem_obj->checkUrlChecksum();
#endif
if (entry->store_status == STORE_PENDING) {
if (entry->isEmpty()) {
assert(!storedWholeReply_);
if (!err) {
// We quit before an error or content. XXX: Cannot distinguish:
// * ERR_READ_ERROR/Http::scBadGateway (e.g., fd closed)
// * ERR_CANNOT_FORWARD/Http::scBadGateway (e.g., cache_peers are down)
// * ERR_CANNOT_FORWARD/Http::scInternalServerError (e.g., go_to=typo)
fail(new ErrorState(ERR_READ_ERROR, Http::scBadGateway, request, al));
}
assert(err);
updateAleWithFinalError();
errorAppendEntry(entry, err);
err = nullptr;
#if USE_OPENSSL
if (request->flags.sslPeek && request->clientConnectionManager.valid()) {
CallJobHere1(17, 4, request->clientConnectionManager, ConnStateData,
ConnStateData::httpsPeeked, ConnStateData::PinnedIdleContext(Comm::ConnectionPointer(nullptr), request));
// no flags.dont_retry: completed() is a post-reforward() act
}
#endif
} else {
updateAleWithFinalError(); // if any
if (storedWholeReply_)
entry->completeSuccessfully(storedWholeReply_);
else
entry->completeTruncated("FwdState default");
}
}
if (storePendingNClients(entry) > 0)
assert(!EBIT_TEST(entry->flags, ENTRY_FWD_HDR_WAIT));
}
FwdState::~FwdState()
{
debugs(17, 3, "FwdState destructor start");
if (! flags.forward_completed)
completed();
doneWithRetries();
HTTPMSGUNLOCK(request);
delete err;
entry->unregisterAbortCallback("FwdState object destructed");
entry->unlock("FwdState");
entry = nullptr;
cancelStep("~FwdState");
if (Comm::IsConnOpen(serverConn))
closeServerConnection("~FwdState");
debugs(17, 3, "FwdState destructed, this=" << this);
}
/**
* This is the entry point for client-side to start forwarding
* a transaction. It is a static method that may or may not
* allocate a FwdState.
*/
void
FwdState::Start(const Comm::ConnectionPointer &clientConn, StoreEntry *entry, HttpRequest *request, const AccessLogEntryPointer &al)
{
/** \note
* client_addr == no_addr indicates this is an "internal" request
* from peer_digest.c, asn.c, netdb.c, etc and should always
* be allowed. yuck, I know.
*/
if ( Config.accessList.miss && !request->client_addr.isNoAddr() &&
!request->flags.internal && request->url.getScheme() != AnyP::PROTO_CACHE_OBJECT) {
/**
* Check if this host is allowed to fetch MISSES from us (miss_access).
* Intentionally replace the src_addr automatically selected by the checklist code
* we do NOT want the indirect client address to be tested here.
*/
ACLFilledChecklist ch(Config.accessList.miss, request, nullptr);
ch.al = al;
ch.src_addr = request->client_addr;
ch.syncAle(request, nullptr);
if (ch.fastCheck().denied()) {
err_type page_id;
page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, 1);
if (page_id == ERR_NONE)
page_id = ERR_FORWARDING_DENIED;
const auto anErr = new ErrorState(page_id, Http::scForbidden, request, al);
errorAppendEntry(entry, anErr); // frees anErr
return;
}
}
debugs(17, 3, "'" << entry->url() << "'");
/*
* This seems like an odd place to bind mem_obj and request.
* Might want to assert that request is NULL at this point
*/
entry->mem_obj->request = request;
#if URL_CHECKSUM_DEBUG
entry->mem_obj->checkUrlChecksum();
#endif
if (shutting_down) {
/* more yuck */
const auto anErr = new ErrorState(ERR_SHUTTING_DOWN, Http::scServiceUnavailable, request, al);
errorAppendEntry(entry, anErr); // frees anErr
return;
}
if (request->flags.internal) {
debugs(17, 2, "calling internalStart() due to request flag");
internalStart(clientConn, request, entry, al);
return;
}
switch (request->url.getScheme()) {
case AnyP::PROTO_CACHE_OBJECT:
debugs(17, 2, "calling CacheManager due to request scheme " << request->url.getScheme());
CacheManager::GetInstance()->start(clientConn, request, entry, al);
return;
case AnyP::PROTO_URN:
urnStart(request, entry, al);
return;
default:
FwdState::Pointer fwd = new FwdState(clientConn, entry, request, al);
fwd->start(fwd);
return;
}
/* NOTREACHED */
}
void
FwdState::fwdStart(const Comm::ConnectionPointer &clientConn, StoreEntry *entry, HttpRequest *request)
{
// Hides AccessLogEntry.h from code that does not supply ALE anyway.
Start(clientConn, entry, request, nullptr);
}
/// subtracts time_t values, returning zero if smaller exceeds the larger value
/// time_t might be unsigned so we need to be careful when subtracting times...
static inline time_t
diffOrZero(const time_t larger, const time_t smaller)
{
return (larger > smaller) ? (larger - smaller) : 0;
}
/// time left to finish the whole forwarding process (which started at fwdStart)
time_t
FwdState::ForwardTimeout(const time_t fwdStart)
{
// time already spent on forwarding (0 if clock went backwards)
const time_t timeSpent = diffOrZero(squid_curtime, fwdStart);
return diffOrZero(Config.Timeout.forward, timeSpent);
}
bool
FwdState::EnoughTimeToReForward(const time_t fwdStart)
{
return ForwardTimeout(fwdStart) > 0;
}
void
FwdState::useDestinations()
{
if (!destinations->empty()) {
connectStart();
} else {
if (PeerSelectionInitiator::subscribed) {
debugs(17, 4, "wait for more destinations to try");
return; // expect a noteDestination*() call
}
debugs(17, 3, "Connection failed: " << entry->url());
if (!err) {
const auto anErr = new ErrorState(ERR_CANNOT_FORWARD, Http::scInternalServerError, request, al);
fail(anErr);
} // else use actual error from last connection attempt
stopAndDestroy("tried all destinations");
}
}
void
FwdState::fail(ErrorState * errorState)
{
debugs(17, 3, err_type_str[errorState->type] << " \"" << Http::StatusCodeString(errorState->httpStatus) << "\"\n\t" << entry->url());
delete err;
err = errorState;
if (!errorState->request)
errorState->request = request;
if (err->type == ERR_ZERO_SIZE_OBJECT)
reactToZeroSizeObject();
destinationReceipt = nullptr; // may already be nil
}
/// ERR_ZERO_SIZE_OBJECT requires special adjustments
void
FwdState::reactToZeroSizeObject()
{
assert(err->type == ERR_ZERO_SIZE_OBJECT);
if (pconnRace == racePossible) {
debugs(17, 5, "pconn race happened");
pconnRace = raceHappened;
if (destinationReceipt) {
destinations->reinstatePath(destinationReceipt);
destinationReceipt = nullptr;
}
}
if (ConnStateData *pinned_connection = request->pinnedConnection()) {
pinned_connection->pinning.zeroReply = true;
debugs(17, 4, "zero reply on pinned connection");
}
}
/**
* Frees fwdState without closing FD or generating an abort
*/
void
FwdState::unregister(Comm::ConnectionPointer &conn)
{
debugs(17, 3, entry->url() );
assert(serverConnection() == conn);
assert(Comm::IsConnOpen(conn));
comm_remove_close_handler(conn->fd, closeHandler);
closeHandler = nullptr;
serverConn = nullptr;
destinationReceipt = nullptr;
}
// \deprecated use unregister(Comm::ConnectionPointer &conn) instead
void
FwdState::unregister(int fd)
{
debugs(17, 3, entry->url() );
assert(fd == serverConnection()->fd);
unregister(serverConn);
}
/**
* FooClient modules call fwdComplete() when they are done
* downloading an object. Then, we either 1) re-forward the
* request somewhere else if needed, or 2) call storeComplete()
* to finish it off
*/
void
FwdState::complete()
{
const auto replyStatus = entry->mem().baseReply().sline.status();
debugs(17, 3, *entry << " status " << replyStatus << ' ' << entry->url());
#if URL_CHECKSUM_DEBUG
entry->mem_obj->checkUrlChecksum();
#endif
logReplyStatus(n_tries, replyStatus);
// will already be false if complete() was called before/without dispatch()
waitingForDispatched = false;
if (reforward()) {
debugs(17, 3, "re-forwarding " << replyStatus << " " << entry->url());
if (Comm::IsConnOpen(serverConn))
unregister(serverConn);
serverConn = nullptr;
destinationReceipt = nullptr;
storedWholeReply_ = nullptr;
entry->reset();
useDestinations();
} else {
if (Comm::IsConnOpen(serverConn))
debugs(17, 3, "server FD " << serverConnection()->fd << " not re-forwarding status " << replyStatus);
else
debugs(17, 3, "server (FD closed) not re-forwarding status " << replyStatus);
completed();
stopAndDestroy("forwarding completed");
}
}
/// Whether a forwarding attempt to some selected destination X is in progress
/// (after successfully opening/reusing a transport connection to X).
/// See also: transportWait
bool
FwdState::transporting() const
{
return peerWait || encryptionWait || waitingForDispatched;
}
void
FwdState::markStoredReplyAsWhole(const char * const whyWeAreSure)
{
debugs(17, 5, whyWeAreSure << " for " << *entry);
// the caller wrote everything to Store, but Store may silently abort writes
if (EBIT_TEST(entry->flags, ENTRY_ABORTED))
return;
storedWholeReply_ = whyWeAreSure;
}
void
FwdState::noteDestination(Comm::ConnectionPointer path)
{
flags.destinationsFound = true;
if (!path) {
// We can call usePinned() without fear of clashing with an earlier
// forwarding attempt because PINNED must be the first destination.
assert(destinations->empty());
usePinned();
return;
}
debugs(17, 3, path);
destinations->addPath(path);
if (transportWait) {
assert(!transporting());
notifyConnOpener();
return; // and continue to wait for FwdState::noteConnection() callback
}
if (transporting())
return; // and continue to receive destinations for backup
useDestinations();
}
void
FwdState::noteDestinationsEnd(ErrorState *selectionError)
{
PeerSelectionInitiator::subscribed = false;
destinations->destinationsFinalized = true;
if (!flags.destinationsFound) {
if (selectionError) {
debugs(17, 3, "Will abort forwarding because path selection has failed.");
Must(!err); // if we tried to connect, then path selection succeeded
fail(selectionError);
}
stopAndDestroy("path selection found no paths");
return;
}
// else continue to use one of the previously noted destinations;
// if all of them fail, forwarding as whole will fail
Must(!selectionError); // finding at least one path means selection succeeded
if (transportWait) {
assert(!transporting());
notifyConnOpener();
return; // and continue to wait for FwdState::noteConnection() callback
}
if (transporting()) {
// We are already using a previously opened connection (but were also
// receiving more destinations in case we need to re-forward).
debugs(17, 7, "keep transporting");
return;
}
// destinationsFound, but none of them worked, and we were waiting for more
assert(err);
stopAndDestroy("all found paths have failed");
}
/// makes sure connection opener knows that the destinations have changed
void
FwdState::notifyConnOpener()
{
if (destinations->notificationPending) {
debugs(17, 7, "reusing pending notification about " << *destinations);
} else {
debugs(17, 7, "notifying about " << *destinations);
destinations->notificationPending = true;
CallJobHere(17, 5, transportWait.job(), HappyConnOpener, noteCandidatesChange);
}
}
/**** CALLBACK WRAPPERS ************************************************************/
static void
fwdServerClosedWrapper(const CommCloseCbParams ¶ms)
{
FwdState *fwd = (FwdState *)params.data;
fwd->serverClosed();
}
/**** PRIVATE *****************************************************************/
/*
* FwdState::checkRetry
*
* Return TRUE if the request SHOULD be retried. This method is
* called when the HTTP connection fails, or when the connection
* is closed before reading the end of HTTP headers from the server.
*/
bool
FwdState::checkRetry()
{
if (shutting_down)
return false;
if (!self) { // we have aborted before the server called us back
debugs(17, 5, "not retrying because of earlier abort");
// we will be destroyed when the server clears its Pointer to us
return false;
}
if (entry->store_status != STORE_PENDING)
return false;
if (!entry->isEmpty())
return false;
if (exhaustedTries())
return false;
if (request->flags.pinned && !pinnedCanRetry())
return false;
if (!EnoughTimeToReForward(start_t))
return false;
if (flags.dont_retry)
return false;
if (request->bodyNibbled())
return false;
// NP: not yet actually connected anywhere. retry is safe.
if (!flags.connected_okay)
return true;
if (!checkRetriable())
return false;
return true;
}
/// Whether we may try sending this request again after a failure.
bool
FwdState::checkRetriable()
{
// Optimize: A compliant proxy may retry PUTs, but Squid lacks the [rather
// complicated] code required to protect the PUT request body from being
// nibbled during the first try. Thus, Squid cannot retry some PUTs today.
if (request->body_pipe != nullptr)
return false;
// RFC2616 9.1 Safe and Idempotent Methods
return (request->method.isHttpSafe() || request->method.isIdempotent());
}
void
FwdState::serverClosed()
{
// XXX: This method logic attempts to tolerate Connection::close() called
// for serverConn earlier, by one of our dispatch()ed jobs. If that happens,
// serverConn will already be closed here or, worse, it will already be open
// for the next forwarding attempt. The current code prevents us getting
// stuck, but the long term solution is to stop sharing serverConn.
debugs(17, 2, serverConn);
if (Comm::IsConnOpen(serverConn)) {
const auto uses = fd_table[serverConn->fd].pconn.uses;
debugs(17, 3, "prior uses: " << uses);
fwdPconnPool->noteUses(uses); // XXX: May not have come from fwdPconnPool
serverConn->noteClosure();
}
serverConn = nullptr;
closeHandler = nullptr;
destinationReceipt = nullptr;
// will already be false if this closure happened before/without dispatch()
waitingForDispatched = false;
retryOrBail();
}
void
FwdState::retryOrBail()
{
if (checkRetry()) {
debugs(17, 3, "re-forwarding (" << n_tries << " tries, " << (squid_curtime - start_t) << " secs)");
useDestinations();
return;
}
// TODO: should we call completed() here and move doneWithRetries there?
doneWithRetries();
request->hier.stopPeerClock(false);
if (self != nullptr && !err && shutting_down && entry->isEmpty()) {
const auto anErr = new ErrorState(ERR_SHUTTING_DOWN, Http::scServiceUnavailable, request, al);
errorAppendEntry(entry, anErr);
}
stopAndDestroy("cannot retry");
}
// If the Server quits before nibbling at the request body, the body sender
// will not know (so that we can retry). Call this if we will not retry. We
// will notify the sender so that it does not get stuck waiting for space.
void
FwdState::doneWithRetries()
{
if (request && request->body_pipe != nullptr)
request->body_pipe->expectNoConsumption();
}
// called by the server that failed after calling unregister()
void
FwdState::handleUnregisteredServerEnd()
{
debugs(17, 2, "self=" << self << " err=" << err << ' ' << entry->url());
assert(!Comm::IsConnOpen(serverConn));
serverConn = nullptr;
destinationReceipt = nullptr;
// might already be false due to uncertainties documented in serverClosed()
waitingForDispatched = false;
retryOrBail();
}
/// starts a preparation step for an established connection; retries on failures
template <typename StepStart>
void
FwdState::advanceDestination(const char *stepDescription, const Comm::ConnectionPointer &conn, const StepStart &startStep)
{
// TODO: Extract destination-specific handling from FwdState so that all the
// awkward, limited-scope advanceDestination() calls can be replaced with a
// single simple try/catch,retry block.
try {
startStep();
// now wait for the step callback
} catch (...) {
debugs (17, 2, "exception while trying to " << stepDescription << ": " << CurrentException);
closePendingConnection(conn, "connection preparation exception");
if (!err)
fail(new ErrorState(ERR_GATEWAY_FAILURE, Http::scInternalServerError, request, al));
retryOrBail();
}
}
/// called when a to-peer connection has been successfully obtained or
/// when all candidate destinations have been tried and all have failed
void
FwdState::noteConnection(HappyConnOpener::Answer &answer)
{
assert(!destinationReceipt);
transportWait.finish();
Must(n_tries <= answer.n_tries); // n_tries cannot decrease
n_tries = answer.n_tries;
ErrorState *error = nullptr;
if ((error = answer.error.get())) {
flags.dont_retry = true; // or HappyConnOpener would not have given up
syncHierNote(answer.conn, request->url.host());
Must(!Comm::IsConnOpen(answer.conn));
answer.error.clear(); // preserve error for errorSendComplete()
} else if (!Comm::IsConnOpen(answer.conn) || fd_table[answer.conn->fd].closing()) {
// The socket could get closed while our callback was queued. Sync
// Connection. XXX: Connection::fd may already be stale/invalid here.
// We do not know exactly why the connection got closed, so we play it
// safe, allowing retries only for persistent (reused) connections
if (answer.reused) {
destinationReceipt = answer.conn;
assert(destinationReceipt);
}
syncHierNote(answer.conn, request->url.host());
closePendingConnection(answer.conn, "conn was closed while waiting for noteConnection");
error = new ErrorState(ERR_CANNOT_FORWARD, Http::scServiceUnavailable, request, al);
} else {
assert(!error);
destinationReceipt = answer.conn;
assert(destinationReceipt);
// serverConn remains nil until syncWithServerConn()
}
if (error) {
fail(error);
retryOrBail();
return;
}
if (answer.reused) {
syncWithServerConn(answer.conn, request->url.host(), answer.reused);
return dispatch();
}
// Check if we need to TLS before use
if (const auto *peer = answer.conn->getPeer()) {
// Assume that it is only possible for the client-first from the
// bumping modes to try connect to a remote server. The bumped
// requests with other modes are using pinned connections or fails.
const bool clientFirstBump = request->flags.sslBumped;
// We need a CONNECT tunnel to send encrypted traffic through a proxy,
// but we do not support TLS inside TLS, so we exclude HTTPS proxies.
const bool originWantsEncryptedTraffic =
request->method == Http::METHOD_CONNECT ||
request->flags.sslPeek ||
clientFirstBump;
if (originWantsEncryptedTraffic && // the "encrypted traffic" part
!peer->options.originserver && // the "through a proxy" part
!peer->secure.encryptTransport) // the "exclude HTTPS proxies" part
return advanceDestination("establish tunnel through proxy", answer.conn, [this,&answer] {
establishTunnelThruProxy(answer.conn);
});
}
secureConnectionToPeerIfNeeded(answer.conn);
}
void
FwdState::establishTunnelThruProxy(const Comm::ConnectionPointer &conn)
{
const auto callback = asyncCallback(17, 4, FwdState::tunnelEstablishmentDone, this);
HttpRequest::Pointer requestPointer = request;
const auto tunneler = new Http::Tunneler(conn, requestPointer, callback, connectingTimeout(conn), al);
// TODO: Replace this hack with proper Comm::Connection-Pool association
// that is not tied to fwdPconnPool and can handle disappearing pools.
tunneler->noteFwdPconnUse = true;
#if USE_DELAY_POOLS
Must(conn);
Must(conn->getPeer());
if (!conn->getPeer()->options.no_delay)
tunneler->setDelayId(entry->mem_obj->mostBytesAllowed());
#endif
peerWait.start(tunneler, callback);
}
/// resumes operations after the (possibly failed) HTTP CONNECT exchange
void
FwdState::tunnelEstablishmentDone(Http::TunnelerAnswer &answer)
{
peerWait.finish();
ErrorState *error = nullptr;
if (!answer.positive()) {
Must(!answer.conn);
error = answer.squidError.get();
Must(error);
answer.squidError.clear(); // preserve error for fail()
} else if (!Comm::IsConnOpen(answer.conn) || fd_table[answer.conn->fd].closing()) {
// The socket could get closed while our callback was queued. Sync
// Connection. XXX: Connection::fd may already be stale/invalid here.
closePendingConnection(answer.conn, "conn was closed while waiting for tunnelEstablishmentDone");
error = new ErrorState(ERR_CANNOT_FORWARD, Http::scServiceUnavailable, request, al);
} else if (!answer.leftovers.isEmpty()) {
// This should not happen because TLS servers do not speak first. If we
// have to handle this, then pass answer.leftovers via a PeerConnector
// to ServerBio. See ClientBio::setReadBufData().
static int occurrences = 0;
const auto level = (occurrences++ < 100) ? DBG_IMPORTANT : 2;
debugs(17, level, "ERROR: Early data after CONNECT response. " <<
"Found " << answer.leftovers.length() << " bytes. " <<
"Closing " << answer.conn);
error = new ErrorState(ERR_CONNECT_FAIL, Http::scBadGateway, request, al);
closePendingConnection(answer.conn, "server spoke before tunnelEstablishmentDone");
}
if (error) {
fail(error);
retryOrBail();
return;
}
secureConnectionToPeerIfNeeded(answer.conn);
}
/// handles an established TCP connection to peer (including origin servers)
void
FwdState::secureConnectionToPeerIfNeeded(const Comm::ConnectionPointer &conn)
{
assert(!request->flags.pinned);
const auto p = conn->getPeer();
const bool peerWantsTls = p && p->secure.encryptTransport;
// userWillTlsToPeerForUs assumes CONNECT == HTTPS
const bool userWillTlsToPeerForUs = p && p->options.originserver &&
request->method == Http::METHOD_CONNECT;
const bool needTlsToPeer = peerWantsTls && !userWillTlsToPeerForUs;
const bool clientFirstBump = request->flags.sslBumped; // client-first (already) bumped connection
const bool needsBump = request->flags.sslPeek || clientFirstBump;
// 'GET https://...' requests. If a peer is used the request is forwarded
// as is
const bool needTlsToOrigin = !p && request->url.getScheme() == AnyP::PROTO_HTTPS && !clientFirstBump;
if (needTlsToPeer || needTlsToOrigin || needsBump) {
return advanceDestination("secure connection to peer", conn, [this,&conn] {
secureConnectionToPeer(conn);
});
}
// if not encrypting just run the post-connect actions