2 * Copyright (C) 1996-2018 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
10 #include "acl/FilledChecklist.h"
11 #include "acl/Gadgets.h"
12 #include "base/TextException.h"
13 #include "clients/Client.h"
14 #include "comm/Connection.h"
15 #include "comm/forward.h"
16 #include "comm/Write.h"
17 #include "err_detail_type.h"
18 #include "errorpage.h"
20 #include "HttpHdrContRange.h"
21 #include "HttpReply.h"
22 #include "HttpRequest.h"
23 #include "SquidConfig.h"
24 #include "SquidTime.h"
25 #include "StatCounters.h"
31 #include "adaptation/AccessCheck.h"
32 #include "adaptation/Answer.h"
33 #include "adaptation/Iterator.h"
34 #include "base/AsyncCall.h"
37 // implemented in client_side_reply.cc until sides have a common parent
38 void purgeEntriesByUrl(HttpRequest
* req
, const char *url
);
40 Client::Client(FwdState
*theFwdState
) :
46 entry
->lock("Client");
51 // paranoid: check that swanSong has been called
52 assert(!requestBodySource
);
54 assert(!virginBodyDestination
);
55 assert(!adaptedBodySource
);
58 entry
->unlock("Client");
60 HTTPMSGUNLOCK(theVirginReply
);
61 HTTPMSGUNLOCK(theFinalReply
);
63 if (responseBodyBuffer
!= NULL
) {
64 delete responseBodyBuffer
;
65 responseBodyBuffer
= NULL
;
72 // get rid of our piping obligations
73 if (requestBodySource
!= NULL
)
74 stopConsumingFrom(requestBodySource
);
80 if (!doneWithServer())
84 doneWithFwd
= "swanSong()";
85 fwd
->handleUnregisteredServerEnd();
88 BodyConsumer::swanSong();
90 Initiator::swanSong();
91 BodyProducer::swanSong();
94 // paranoid: check that swanSong has been called
95 // extra paranoid: yeah, I really mean it. they MUST pass here.
96 assert(!requestBodySource
);
98 assert(!virginBodyDestination
);
99 assert(!adaptedBodySource
);
104 Client::virginReply()
106 assert(theVirginReply
);
107 return theVirginReply
;
111 Client::virginReply() const
113 assert(theVirginReply
);
114 return theVirginReply
;
118 Client::setVirginReply(HttpReply
*rep
)
120 debugs(11,5, HERE
<< this << " setting virgin reply to " << rep
);
121 assert(!theVirginReply
);
123 theVirginReply
= rep
;
124 HTTPMSGLOCK(theVirginReply
);
125 return theVirginReply
;
131 assert(theFinalReply
);
132 return theFinalReply
;
136 Client::setFinalReply(HttpReply
*rep
)
138 debugs(11,5, HERE
<< this << " setting final reply to " << rep
);
140 assert(!theFinalReply
);
143 HTTPMSGLOCK(theFinalReply
);
145 // give entry the reply because haveParsedReplyHeaders() expects it there
146 entry
->replaceHttpReply(theFinalReply
, false); // but do not write yet
147 haveParsedReplyHeaders(); // update the entry/reply (e.g., set timestamps)
148 if (!EBIT_TEST(entry
->flags
, RELEASE_REQUEST
) && blockCaching())
150 entry
->startWriting(); // write the updated entry to store
152 return theFinalReply
;
155 // called when no more server communication is expected; may quit
157 Client::serverComplete()
159 debugs(11,5,HERE
<< "serverComplete " << this);
161 if (!doneWithServer()) {
163 assert(doneWithServer());
167 originalRequest()->hier
.stopPeerClock(true);
169 if (requestBodySource
!= NULL
)
170 stopConsumingFrom(requestBodySource
);
172 if (responseBodyBuffer
!= NULL
)
179 Client::serverComplete2()
181 debugs(11,5,HERE
<< "serverComplete2 " << this);
184 if (virginBodyDestination
!= NULL
)
185 stopProducingFor(virginBodyDestination
, true);
187 if (!doneWithAdaptation())
191 completeForwarding();
194 bool Client::doneAll() const
196 return doneWithServer() &&
198 doneWithAdaptation() &&
199 Adaptation::Initiator::doneAll() &&
200 BodyProducer::doneAll() &&
202 BodyConsumer::doneAll();
205 // FTP side overloads this to work around multiple calls to fwd->complete
207 Client::completeForwarding()
209 debugs(11,5, HERE
<< "completing forwarding for " << fwd
);
211 doneWithFwd
= "completeForwarding()";
215 // Register to receive request body
216 bool Client::startRequestBodyFlow()
218 HttpRequestPointer
r(originalRequest());
219 assert(r
->body_pipe
!= NULL
);
220 requestBodySource
= r
->body_pipe
;
221 if (requestBodySource
->setConsumerIfNotLate(this)) {
222 debugs(11,3, HERE
<< "expecting request body from " <<
223 requestBodySource
->status());
227 debugs(11,3, HERE
<< "aborting on partially consumed request body: " <<
228 requestBodySource
->status());
229 requestBodySource
= NULL
;
233 // Entry-dependent callbacks use this check to quit if the entry went bad
235 Client::abortOnBadEntry(const char *abortReason
)
237 if (entry
->isAccepting())
240 debugs(11,5, HERE
<< "entry is not Accepting!");
241 abortOnData(abortReason
);
245 // more request or adapted response body is available
247 Client::noteMoreBodyDataAvailable(BodyPipe::Pointer bp
)
250 if (adaptedBodySource
== bp
) {
251 handleMoreAdaptedBodyAvailable();
255 if (requestBodySource
== bp
)
256 handleMoreRequestBodyAvailable();
259 // the entire request or adapted response body was provided, successfully
261 Client::noteBodyProductionEnded(BodyPipe::Pointer bp
)
264 if (adaptedBodySource
== bp
) {
265 handleAdaptedBodyProductionEnded();
269 if (requestBodySource
== bp
)
270 handleRequestBodyProductionEnded();
273 // premature end of the request or adapted response body production
275 Client::noteBodyProducerAborted(BodyPipe::Pointer bp
)
278 if (adaptedBodySource
== bp
) {
279 handleAdaptedBodyProducerAborted();
283 if (requestBodySource
== bp
)
284 handleRequestBodyProducerAborted();
288 Client::abortOnData(const char *reason
)
294 // more origin request body data is available
296 Client::handleMoreRequestBodyAvailable()
299 sendMoreRequestBody();
301 debugs(9,3, HERE
<< "waiting for request body write to complete");
304 // there will be no more handleMoreRequestBodyAvailable calls
306 Client::handleRequestBodyProductionEnded()
308 receivedWholeRequestBody
= true;
310 doneSendingRequestBody();
312 debugs(9,3, HERE
<< "waiting for request body write to complete");
315 // called when we are done sending request body; kids extend this
317 Client::doneSendingRequestBody()
319 debugs(9,3, HERE
<< "done sending request body");
320 assert(requestBodySource
!= NULL
);
321 stopConsumingFrom(requestBodySource
);
326 // called when body producers aborts; kids extend this
328 Client::handleRequestBodyProducerAborted()
330 if (requestSender
!= NULL
)
331 debugs(9,3, HERE
<< "fyi: request body aborted while we were sending");
333 fwd
->dontRetry(true); // the problem is not with the server
334 stopConsumingFrom(requestBodySource
); // requestSender, if any, will notice
339 // called when we wrote request headers(!) or a part of the body
341 Client::sentRequestBody(const CommIoCbParams
&io
)
343 debugs(11, 5, "sentRequestBody: FD " << io
.fd
<< ": size " << io
.size
<< ": errflag " << io
.flag
<< ".");
344 debugs(32,3,HERE
<< "sentRequestBody called");
346 requestSender
= NULL
;
349 fd_bytes(io
.fd
, io
.size
, FD_WRITE
);
350 statCounter
.server
.all
.kbytes_out
+= io
.size
;
351 // kids should increment their counters
354 if (io
.flag
== Comm::ERR_CLOSING
)
357 if (!requestBodySource
) {
358 debugs(9,3, HERE
<< "detected while-we-were-sending abort");
359 return; // do nothing;
362 // both successful and failed writes affect response times
363 request
->hier
.notePeerWrite();
366 debugs(11, DBG_IMPORTANT
, "sentRequestBody error: FD " << io
.fd
<< ": " << xstrerr(io
.xerrno
));
368 err
= new ErrorState(ERR_WRITE_ERROR
, Http::scBadGateway
, fwd
->request
);
369 err
->xerrno
= io
.xerrno
;
371 abortOnData("I/O error while sending request body");
375 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
376 abortOnData("store entry aborted while sending request body");
380 if (!requestBodySource
->exhausted())
381 sendMoreRequestBody();
382 else if (receivedWholeRequestBody
)
383 doneSendingRequestBody();
385 debugs(9,3, HERE
<< "waiting for body production end or abort");
389 Client::sendMoreRequestBody()
391 assert(requestBodySource
!= NULL
);
392 assert(!requestSender
);
394 const Comm::ConnectionPointer conn
= dataConnection();
396 if (!Comm::IsConnOpen(conn
)) {
397 debugs(9,3, HERE
<< "cannot send request body to closing " << conn
);
398 return; // wait for the kid's close handler; TODO: assert(closer);
402 if (getMoreRequestBody(buf
) && buf
.contentSize() > 0) {
403 debugs(9,3, HERE
<< "will write " << buf
.contentSize() << " request body bytes");
404 typedef CommCbMemFunT
<Client
, CommIoCbParams
> Dialer
;
405 requestSender
= JobCallback(93,3, Dialer
, this, Client::sentRequestBody
);
406 Comm::Write(conn
, &buf
, requestSender
);
408 debugs(9,3, HERE
<< "will wait for more request body bytes or eof");
409 requestSender
= NULL
;
413 /// either fill buf with available [encoded] request body bytes or return false
415 Client::getMoreRequestBody(MemBuf
&buf
)
417 // default implementation does not encode request body content
418 Must(requestBodySource
!= NULL
);
419 return requestBodySource
->getMoreData(buf
);
422 // Compares hosts in urls, returns false if different, no sheme, or no host.
424 sameUrlHosts(const char *url1
, const char *url2
)
426 // XXX: Want urlHostname() here, but it uses static storage and copying
427 const char *host1
= strchr(url1
, ':');
428 const char *host2
= strchr(url2
, ':');
430 if (host1
&& host2
) {
431 // skip scheme slashes
435 } while (*host1
== '/' && *host2
== '/');
438 return false; // no host
440 // increment while the same until we reach the end of the URL/host
441 while (*host1
&& *host1
!= '/' && *host1
== *host2
) {
445 return *host1
== *host2
;
448 return false; // no URL scheme
451 // purges entries that match the value of a given HTTP [response] header
453 purgeEntriesByHeader(HttpRequest
*req
, const char *reqUrl
, Http::Message
*rep
, Http::HdrType hdr
)
455 const char *hdrUrl
, *absUrl
;
458 hdrUrl
= rep
->header
.getStr(hdr
);
459 if (hdrUrl
== NULL
) {
464 * If the URL is relative, make it absolute so we can find it.
465 * If it's absolute, make sure the host parts match to avoid DOS attacks
466 * as per RFC 2616 13.10.
468 if (urlIsRelative(hdrUrl
)) {
469 absUrl
= urlMakeAbsolute(req
, hdrUrl
);
470 if (absUrl
!= NULL
) {
473 } else if (!sameUrlHosts(reqUrl
, hdrUrl
)) {
477 purgeEntriesByUrl(req
, hdrUrl
);
479 if (absUrl
!= NULL
) {
484 // some HTTP methods should purge matching cache entries
486 Client::maybePurgeOthers()
488 // only some HTTP methods should purge matching cache entries
489 if (!request
->method
.purgesOthers())
492 // and probably only if the response was successful
493 if (theFinalReply
->sline
.status() >= 400)
496 // XXX: should we use originalRequest() here?
497 SBuf
tmp(request
->effectiveRequestUri());
498 const char *reqUrl
= tmp
.c_str();
499 debugs(88, 5, "maybe purging due to " << request
->method
<< ' ' << tmp
);
500 purgeEntriesByUrl(request
.getRaw(), reqUrl
);
501 purgeEntriesByHeader(request
.getRaw(), reqUrl
, theFinalReply
, Http::HdrType::LOCATION
);
502 purgeEntriesByHeader(request
.getRaw(), reqUrl
, theFinalReply
, Http::HdrType::CONTENT_LOCATION
);
505 /// called when we have final (possibly adapted) reply headers; kids extend
507 Client::haveParsedReplyHeaders()
512 // adaptation may overwrite old offset computed using the virgin response
513 const bool partial
= theFinalReply
->contentRange();
514 currentOffset
= partial
? theFinalReply
->contentRange()->spec
.offset
: 0;
517 /// whether to prevent caching of an otherwise cachable response
519 Client::blockCaching()
521 if (const Acl::Tree
*acl
= Config
.accessList
.storeMiss
) {
522 // This relatively expensive check is not in StoreEntry::checkCachable:
523 // That method lacks HttpRequest and may be called too many times.
524 ACLFilledChecklist
ch(acl
, originalRequest().getRaw());
525 ch
.reply
= const_cast<HttpReply
*>(entry
->getReply()); // ACLFilledChecklist API bug
526 HTTPMSGLOCK(ch
.reply
);
527 if (!ch
.fastCheck().allowed()) { // when in doubt, block
528 debugs(20, 3, "store_miss prohibits caching");
536 Client::originalRequest()
542 /// Initiate an asynchronous adaptation transaction which will call us back.
544 Client::startAdaptation(const Adaptation::ServiceGroupPointer
&group
, HttpRequest
*cause
)
546 debugs(11, 5, "Client::startAdaptation() called");
547 // check whether we should be sending a body as well
548 // start body pipe to feed ICAP transaction if needed
549 assert(!virginBodyDestination
);
550 HttpReply
*vrep
= virginReply();
551 assert(!vrep
->body_pipe
);
553 if (vrep
->expectingBody(cause
->method
, size
) && size
) {
554 virginBodyDestination
= new BodyPipe(this);
555 vrep
->body_pipe
= virginBodyDestination
;
556 debugs(93, 6, HERE
<< "will send virgin reply body to " <<
557 virginBodyDestination
<< "; size: " << size
);
559 virginBodyDestination
->setBodySize(size
);
562 adaptedHeadSource
= initiateAdaptation(
563 new Adaptation::Iterator(vrep
, cause
, fwd
->al
, group
));
564 startedAdaptation
= initiated(adaptedHeadSource
);
565 Must(startedAdaptation
);
568 // properly cleans up ICAP-related state
569 // may be called multiple times
570 void Client::cleanAdaptation()
572 debugs(11,5, HERE
<< "cleaning ICAP; ACL: " << adaptationAccessCheckPending
);
574 if (virginBodyDestination
!= NULL
)
575 stopProducingFor(virginBodyDestination
, false);
577 announceInitiatorAbort(adaptedHeadSource
);
579 if (adaptedBodySource
!= NULL
)
580 stopConsumingFrom(adaptedBodySource
);
582 if (!adaptationAccessCheckPending
) // we cannot cancel a pending callback
583 assert(doneWithAdaptation()); // make sure the two methods are in sync
587 Client::doneWithAdaptation() const
589 return !adaptationAccessCheckPending
&&
590 !virginBodyDestination
&& !adaptedHeadSource
&& !adaptedBodySource
;
593 // sends virgin reply body to ICAP, buffering excesses if needed
595 Client::adaptVirginReplyBody(const char *data
, ssize_t len
)
597 assert(startedAdaptation
);
599 if (!virginBodyDestination
) {
600 debugs(11,3, HERE
<< "ICAP does not want more virgin body");
604 // grow overflow area if already overflowed
605 if (responseBodyBuffer
) {
606 responseBodyBuffer
->append(data
, len
);
607 data
= responseBodyBuffer
->content();
608 len
= responseBodyBuffer
->contentSize();
611 const ssize_t putSize
= virginBodyDestination
->putMoreData(data
, len
);
615 // if we had overflow area, shrink it as necessary
616 if (responseBodyBuffer
) {
617 if (putSize
== responseBodyBuffer
->contentSize()) {
618 delete responseBodyBuffer
;
619 responseBodyBuffer
= NULL
;
621 responseBodyBuffer
->consume(putSize
);
626 // if we did not have an overflow area, create it as needed
628 assert(!responseBodyBuffer
);
629 responseBodyBuffer
= new MemBuf
;
630 responseBodyBuffer
->init(4096, SQUID_TCP_SO_RCVBUF
* 10);
631 responseBodyBuffer
->append(data
, len
);
635 // can supply more virgin response body data
637 Client::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
639 if (responseBodyBuffer
) {
640 addVirginReplyBody(NULL
, 0); // kick the buffered fragment alive again
641 if (completed
&& !responseBodyBuffer
) {
646 maybeReadVirginBody();
649 // the consumer of our virgin response body aborted
651 Client::noteBodyConsumerAborted(BodyPipe::Pointer
)
653 stopProducingFor(virginBodyDestination
, false);
655 // do not force closeServer here in case we need to bypass AdaptationQueryAbort
657 if (doneWithAdaptation()) // we may still be receiving adapted response
658 handleAdaptationCompleted();
661 // received adapted response headers (body may follow)
663 Client::noteAdaptationAnswer(const Adaptation::Answer
&answer
)
665 clearAdaptation(adaptedHeadSource
); // we do not expect more messages
667 switch (answer
.kind
) {
668 case Adaptation::Answer::akForward
:
669 handleAdaptedHeader(const_cast<Http::Message
*>(answer
.message
.getRaw()));
672 case Adaptation::Answer::akBlock
:
673 handleAdaptationBlocked(answer
);
676 case Adaptation::Answer::akError
:
677 handleAdaptationAborted(!answer
.final
);
683 Client::handleAdaptedHeader(Http::Message
*msg
)
685 if (abortOnBadEntry("entry went bad while waiting for adapted headers")) {
686 // If the adapted response has a body, the ICAP side needs to know
687 // that nobody will consume that body. We will be destroyed upon
688 // return. Tell the ICAP side that it is on its own.
689 HttpReply
*rep
= dynamic_cast<HttpReply
*>(msg
);
691 if (rep
->body_pipe
!= NULL
)
692 rep
->body_pipe
->expectNoConsumption();
697 HttpReply
*rep
= dynamic_cast<HttpReply
*>(msg
);
699 debugs(11,5, HERE
<< this << " setting adapted reply to " << rep
);
702 assert(!adaptedBodySource
);
703 if (rep
->body_pipe
!= NULL
) {
704 // subscribe to receive adapted body
705 adaptedBodySource
= rep
->body_pipe
;
706 // assume that ICAP does not auto-consume on failures
707 const bool result
= adaptedBodySource
->setConsumerIfNotLate(this);
711 if (doneWithAdaptation()) // we may still be sending virgin response
712 handleAdaptationCompleted();
717 Client::resumeBodyStorage()
719 if (abortOnBadEntry("store entry aborted while kick producer callback"))
722 if (!adaptedBodySource
)
725 handleMoreAdaptedBodyAvailable();
727 if (adaptedBodySource
!= NULL
&& adaptedBodySource
->exhausted())
728 endAdaptedBodyConsumption();
731 // more adapted response body is available
733 Client::handleMoreAdaptedBodyAvailable()
735 if (abortOnBadEntry("entry refuses adapted body"))
740 size_t contentSize
= adaptedBodySource
->buf().contentSize();
743 return; // XXX: bytesWanted asserts on zero-size ranges
745 const size_t spaceAvailable
= entry
->bytesWanted(Range
<size_t>(0, contentSize
), true);
747 if (spaceAvailable
< contentSize
) {
748 // No or partial body data consuming
749 typedef NullaryMemFunT
<Client
> Dialer
;
750 AsyncCall::Pointer call
= asyncCall(93, 5, "Client::resumeBodyStorage",
751 Dialer(this, &Client::resumeBodyStorage
));
752 entry
->deferProducer(call
);
755 if (!spaceAvailable
) {
756 debugs(11, 5, HERE
<< "NOT storing " << contentSize
<< " bytes of adapted " <<
757 "response body at offset " << adaptedBodySource
->consumedSize());
761 if (spaceAvailable
< contentSize
) {
762 debugs(11, 5, HERE
<< "postponing storage of " <<
763 (contentSize
- spaceAvailable
) << " body bytes");
764 contentSize
= spaceAvailable
;
767 debugs(11,5, HERE
<< "storing " << contentSize
<< " bytes of adapted " <<
768 "response body at offset " << adaptedBodySource
->consumedSize());
770 BodyPipeCheckout
bpc(*adaptedBodySource
);
771 const StoreIOBuffer
ioBuf(&bpc
.buf
, currentOffset
, contentSize
);
772 currentOffset
+= ioBuf
.length
;
774 bpc
.buf
.consume(contentSize
);
778 // the entire adapted response body was produced, successfully
780 Client::handleAdaptedBodyProductionEnded()
782 if (abortOnBadEntry("entry went bad while waiting for adapted body eof"))
785 // end consumption if we consumed everything
786 if (adaptedBodySource
!= NULL
&& adaptedBodySource
->exhausted())
787 endAdaptedBodyConsumption();
788 // else resumeBodyStorage() will eventually consume the rest
792 Client::endAdaptedBodyConsumption()
794 stopConsumingFrom(adaptedBodySource
);
795 handleAdaptationCompleted();
798 // premature end of the adapted response body
799 void Client::handleAdaptedBodyProducerAborted()
801 if (abortOnBadEntry("entry went bad while waiting for the now-aborted adapted body"))
804 Must(adaptedBodySource
!= nullptr);
805 if (!adaptedBodySource
->exhausted()) {
806 debugs(11,5, "waiting to consume the remainder of the aborted adapted body");
807 return; // resumeBodyStorage() should eventually consume the rest
810 stopConsumingFrom(adaptedBodySource
);
812 if (handledEarlyAdaptationAbort())
815 entry
->lengthWentBad("body adaptation aborted");
816 handleAdaptationCompleted(); // the user should get a truncated response
819 // common part of noteAdaptationAnswer and handleAdaptedBodyProductionEnded
821 Client::handleAdaptationCompleted()
823 debugs(11,5, HERE
<< "handleAdaptationCompleted");
826 // We stop reading origin response because we have no place to put it(*) and
827 // cannot use it. If some origin servers do not like that or if we want to
828 // reuse more pconns, we can add code to discard unneeded origin responses.
829 // (*) TODO: Is it possible that the adaptation xaction is still running?
830 if (mayReadVirginReplyBody()) {
831 debugs(11,3, HERE
<< "closing origin conn due to ICAP completion");
835 completeForwarding();
838 // common part of noteAdaptation*Aborted and noteBodyConsumerAborted methods
840 Client::handleAdaptationAborted(bool bypassable
)
842 debugs(11,5, HERE
<< "handleAdaptationAborted; bypassable: " << bypassable
<<
843 ", entry empty: " << entry
->isEmpty());
845 if (abortOnBadEntry("entry went bad while ICAP aborted"))
848 // TODO: bypass if possible
849 if (!handledEarlyAdaptationAbort())
850 abortAll("adaptation failure with a filled entry");
853 /// If the store entry is still empty, fully handles adaptation abort, returning
854 /// true. Otherwise just updates the request error detail and returns false.
856 Client::handledEarlyAdaptationAbort()
858 if (entry
->isEmpty()) {
859 debugs(11,8, "adaptation failure with an empty entry: " << *entry
);
860 ErrorState
*err
= new ErrorState(ERR_ICAP_FAILURE
, Http::scInternalServerError
, request
.getRaw());
861 err
->detailError(ERR_DETAIL_ICAP_RESPMOD_EARLY
);
863 fwd
->dontRetry(true);
864 abortAll("adaptation failure with an empty entry");
865 return true; // handled
868 if (request
) // update logged info directly
869 request
->detailError(ERR_ICAP_FAILURE
, ERR_DETAIL_ICAP_RESPMOD_LATE
);
871 return false; // the caller must handle
874 // adaptation service wants us to deny HTTP client access to this response
876 Client::handleAdaptationBlocked(const Adaptation::Answer
&answer
)
878 debugs(11,5, HERE
<< answer
.ruleId
);
880 if (abortOnBadEntry("entry went bad while ICAP aborted"))
883 if (!entry
->isEmpty()) { // too late to block (should not really happen)
885 request
->detailError(ERR_ICAP_FAILURE
, ERR_DETAIL_RESPMOD_BLOCK_LATE
);
886 abortAll("late adaptation block");
890 debugs(11,7, HERE
<< "creating adaptation block response");
893 aclGetDenyInfoPage(&Config
.denyInfoList
, answer
.ruleId
.termedBuf(), 1);
894 if (page_id
== ERR_NONE
)
895 page_id
= ERR_ACCESS_DENIED
;
897 ErrorState
*err
= new ErrorState(page_id
, Http::scForbidden
, request
.getRaw());
898 err
->detailError(ERR_DETAIL_RESPMOD_BLOCK_EARLY
);
900 fwd
->dontRetry(true);
902 abortOnData("timely adaptation block");
906 Client::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer group
)
908 adaptationAccessCheckPending
= false;
910 if (abortOnBadEntry("entry went bad while waiting for ICAP ACL check"))
913 // TODO: Should non-ICAP and ICAP REPMOD pre-cache paths check this?
914 // That check now only happens on REQMOD pre-cache and REPMOD post-cache, in processReplyAccess().
915 if (virginReply()->expectedBodyTooLarge(*request
)) {
916 sendBodyIsTooLargeError();
919 // TODO: Should we check receivedBodyTooLarge as well?
922 debugs(11,3, HERE
<< "no adapation needed");
923 setFinalReply(virginReply());
928 startAdaptation(group
, originalRequest().getRaw());
934 Client::sendBodyIsTooLargeError()
936 ErrorState
*err
= new ErrorState(ERR_TOO_BIG
, Http::scForbidden
, request
.getRaw());
938 fwd
->dontRetry(true);
939 abortOnData("Virgin body too large.");
942 // TODO: when HttpStateData sends all errors to ICAP,
943 // we should be able to move this at the end of setVirginReply().
945 Client::adaptOrFinalizeReply()
948 // TODO: merge with client side and return void to hide the on/off logic?
949 // The callback can be called with a NULL service if adaptation is off.
950 adaptationAccessCheckPending
= Adaptation::AccessCheck::Start(
951 Adaptation::methodRespmod
, Adaptation::pointPreCache
,
952 originalRequest().getRaw(), virginReply(), fwd
->al
, this);
953 debugs(11,5, HERE
<< "adaptationAccessCheckPending=" << adaptationAccessCheckPending
);
954 if (adaptationAccessCheckPending
)
958 setFinalReply(virginReply());
961 /// initializes bodyBytesRead stats if needed and applies delta
963 Client::adjustBodyBytesRead(const int64_t delta
)
965 int64_t &bodyBytesRead
= originalRequest()->hier
.bodyBytesRead
;
967 // if we got here, do not log a dash even if we got nothing from the server
968 if (bodyBytesRead
< 0)
971 bodyBytesRead
+= delta
; // supports negative and zero deltas
973 // check for overflows ("infinite" response?) and undeflows (a bug)
974 Must(bodyBytesRead
>= 0);
978 Client::addVirginReplyBody(const char *data
, ssize_t len
)
980 adjustBodyBytesRead(len
);
983 assert(!adaptationAccessCheckPending
); // or would need to buffer while waiting
984 if (startedAdaptation
) {
985 adaptVirginReplyBody(data
, len
);
989 storeReplyBody(data
, len
);
992 // writes virgin or adapted reply body to store
994 Client::storeReplyBody(const char *data
, ssize_t len
)
996 // write even if len is zero to push headers towards the client side
997 entry
->write (StoreIOBuffer(len
, currentOffset
, (char*)data
));
999 currentOffset
+= len
;
1003 Client::calcBufferSpaceToReserve(size_t space
, const size_t wantSpace
) const
1005 if (space
< wantSpace
) {
1006 const size_t maxSpace
= SBuf::maxSize
; // absolute best
1007 space
= min(wantSpace
, maxSpace
); // do not promise more than asked
1011 if (responseBodyBuffer
) {
1012 return 0; // Stop reading if already overflowed waiting for ICAP to catch up
1015 if (virginBodyDestination
!= NULL
) {
1017 * BodyPipe buffer has a finite size limit. We
1018 * should not read more data from the network than will fit
1019 * into the pipe buffer or we _lose_ what did not fit if
1020 * the response ends sooner that BodyPipe frees up space:
1021 * There is no code to keep pumping data into the pipe once
1022 * response ends and serverComplete() is called.
1024 const size_t adaptor_space
= virginBodyDestination
->buf().potentialSpaceSize();
1026 debugs(11,9, "Client may read up to min(" <<
1027 adaptor_space
<< ", " << space
<< ") bytes");
1029 if (adaptor_space
< space
)
1030 space
= adaptor_space
;
1038 Client::replyBodySpace(const MemBuf
&readBuf
, const size_t minSpace
) const
1040 size_t space
= readBuf
.spaceSize(); // available space w/o heroic measures
1041 if (space
< minSpace
) {
1042 const size_t maxSpace
= readBuf
.potentialSpaceSize(); // absolute best
1043 space
= min(minSpace
, maxSpace
); // do not promise more than asked
1047 if (responseBodyBuffer
) {
1048 return 0; // Stop reading if already overflowed waiting for ICAP to catch up
1051 if (virginBodyDestination
!= NULL
) {
1053 * BodyPipe buffer has a finite size limit. We
1054 * should not read more data from the network than will fit
1055 * into the pipe buffer or we _lose_ what did not fit if
1056 * the response ends sooner that BodyPipe frees up space:
1057 * There is no code to keep pumping data into the pipe once
1058 * response ends and serverComplete() is called.
1060 * If the pipe is totally full, don't register the read handler.
1061 * The BodyPipe will call our noteMoreBodySpaceAvailable() method
1062 * when it has free space again.
1064 size_t adaptation_space
=
1065 virginBodyDestination
->buf().potentialSpaceSize();
1067 debugs(11,9, "Client may read up to min(" <<
1068 adaptation_space
<< ", " << space
<< ") bytes");
1070 if (adaptation_space
< space
)
1071 space
= adaptation_space
;