5 * AUTHOR: Duane Wessels
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
38 #include "HttpRequest.h"
39 #include "HttpReply.h"
40 #include "TextException.h"
41 #include "errorpage.h"
42 #include "SquidTime.h"
45 #include "adaptation/AccessCheck.h"
46 #include "adaptation/Iterator.h"
49 // implemented in client_side_reply.cc until sides have a common parent
50 extern void purgeEntriesByUrl(HttpRequest
* req
, const char *url
);
53 ServerStateData::ServerStateData(FwdState
*theFwdState
): AsyncJob("ServerStateData"),requestSender(NULL
)
55 , adaptedHeadSource(NULL
)
56 , adaptationAccessCheckPending(false)
57 , startedAdaptation(false)
65 request
= HTTPMSGLOCK(fwd
->request
);
68 ServerStateData::~ServerStateData()
70 // paranoid: check that swanSong has been called
71 assert(!requestBodySource
);
73 assert(!virginBodyDestination
);
74 assert(!adaptedBodySource
);
79 HTTPMSGUNLOCK(request
);
80 HTTPMSGUNLOCK(theVirginReply
);
81 HTTPMSGUNLOCK(theFinalReply
);
83 fwd
= NULL
; // refcounted
85 if (responseBodyBuffer
!= NULL
) {
86 delete responseBodyBuffer
;
87 responseBodyBuffer
= NULL
;
92 ServerStateData::swanSong()
94 // get rid of our piping obligations
95 if (requestBodySource
!= NULL
)
96 stopConsumingFrom(requestBodySource
);
102 BodyConsumer::swanSong();
104 Initiator::swanSong();
105 BodyProducer::swanSong();
108 // paranoid: check that swanSong has been called
109 // extra paranoid: yeah, I really mean it. they MUST pass here.
110 assert(!requestBodySource
);
112 assert(!virginBodyDestination
);
113 assert(!adaptedBodySource
);
119 ServerStateData::virginReply()
121 assert(theVirginReply
);
122 return theVirginReply
;
126 ServerStateData::virginReply() const
128 assert(theVirginReply
);
129 return theVirginReply
;
133 ServerStateData::setVirginReply(HttpReply
*rep
)
135 debugs(11,5, HERE
<< this << " setting virgin reply to " << rep
);
136 assert(!theVirginReply
);
138 theVirginReply
= HTTPMSGLOCK(rep
);
139 return theVirginReply
;
143 ServerStateData::finalReply()
145 assert(theFinalReply
);
146 return theFinalReply
;
150 ServerStateData::setFinalReply(HttpReply
*rep
)
152 debugs(11,5, HERE
<< this << " setting final reply to " << rep
);
154 assert(!theFinalReply
);
156 theFinalReply
= HTTPMSGLOCK(rep
);
158 entry
->replaceHttpReply(theFinalReply
);
159 haveParsedReplyHeaders();
161 return theFinalReply
;
164 // called when no more server communication is expected; may quit
166 ServerStateData::serverComplete()
168 debugs(11,5,HERE
<< "serverComplete " << this);
170 if (!doneWithServer()) {
172 assert(doneWithServer());
177 HttpRequest
*r
= originalRequest();
178 r
->hier
.total_response_time
= r
->hier
.first_conn_start
.tv_sec
?
179 tvSubMsec(r
->hier
.first_conn_start
, current_time
) : -1;
181 if (requestBodySource
!= NULL
)
182 stopConsumingFrom(requestBodySource
);
184 if (responseBodyBuffer
!= NULL
)
191 ServerStateData::serverComplete2()
193 debugs(11,5,HERE
<< "serverComplete2 " << this);
196 if (virginBodyDestination
!= NULL
)
197 stopProducingFor(virginBodyDestination
, true);
199 if (!doneWithAdaptation())
203 completeForwarding();
207 // When we are done talking to the primary server, we may be still talking
208 // to the ICAP service. And vice versa. Here, we quit only if we are done
210 void ServerStateData::quitIfAllDone()
213 if (!doneWithAdaptation()) {
214 debugs(11,5, HERE
<< "transaction not done: still talking to ICAP");
219 if (!doneWithServer()) {
220 debugs(11,5, HERE
<< "transaction not done: still talking to server");
224 debugs(11,3, HERE
<< "transaction done");
226 deleteThis("ServerStateData::quitIfAllDone");
229 // FTP side overloads this to work around multiple calls to fwd->complete
231 ServerStateData::completeForwarding()
233 debugs(11,5, HERE
<< "completing forwarding for " << fwd
);
238 // Register to receive request body
239 bool ServerStateData::startRequestBodyFlow()
241 HttpRequest
*r
= originalRequest();
242 assert(r
->body_pipe
!= NULL
);
243 requestBodySource
= r
->body_pipe
;
244 if (requestBodySource
->setConsumerIfNotLate(this)) {
245 debugs(11,3, HERE
<< "expecting request body from " <<
246 requestBodySource
->status());
250 debugs(11,3, HERE
<< "aborting on partially consumed request body: " <<
251 requestBodySource
->status());
252 requestBodySource
= NULL
;
256 // Entry-dependent callbacks use this check to quit if the entry went bad
258 ServerStateData::abortOnBadEntry(const char *abortReason
)
260 if (entry
->isAccepting())
263 debugs(11,5, HERE
<< "entry is not Accepting!");
264 abortTransaction(abortReason
);
268 // more request or adapted response body is available
270 ServerStateData::noteMoreBodyDataAvailable(BodyPipe::Pointer bp
)
273 if (adaptedBodySource
== bp
) {
274 handleMoreAdaptedBodyAvailable();
278 handleMoreRequestBodyAvailable();
281 // the entire request or adapted response body was provided, successfully
283 ServerStateData::noteBodyProductionEnded(BodyPipe::Pointer bp
)
286 if (adaptedBodySource
== bp
) {
287 handleAdaptedBodyProductionEnded();
291 handleRequestBodyProductionEnded();
294 // premature end of the request or adapted response body production
296 ServerStateData::noteBodyProducerAborted(BodyPipe::Pointer bp
)
299 if (adaptedBodySource
== bp
) {
300 handleAdaptedBodyProducerAborted();
304 handleRequestBodyProducerAborted();
308 // more origin request body data is available
310 ServerStateData::handleMoreRequestBodyAvailable()
313 sendMoreRequestBody();
315 debugs(9,3, HERE
<< "waiting for request body write to complete");
318 // there will be no more handleMoreRequestBodyAvailable calls
320 ServerStateData::handleRequestBodyProductionEnded()
323 doneSendingRequestBody();
325 debugs(9,3, HERE
<< "waiting for request body write to complete");
328 // called when we are done sending request body; kids extend this
330 ServerStateData::doneSendingRequestBody()
332 debugs(9,3, HERE
<< "done sending request body");
333 assert(requestBodySource
!= NULL
);
334 stopConsumingFrom(requestBodySource
);
339 // called when body producers aborts; kids extend this
341 ServerStateData::handleRequestBodyProducerAborted()
343 if (requestSender
!= NULL
)
344 debugs(9,3, HERE
<< "fyi: request body aborted while we were sending");
346 fwd
->dontRetry(true); // the problem is not with the server
347 stopConsumingFrom(requestBodySource
); // requestSender, if any, will notice
352 // called when we wrote request headers(!) or a part of the body
354 ServerStateData::sentRequestBody(const CommIoCbParams
&io
)
356 debugs(11, 5, "sentRequestBody: FD " << io
.fd
<< ": size " << io
.size
<< ": errflag " << io
.flag
<< ".");
357 debugs(32,3,HERE
<< "sentRequestBody called");
359 requestSender
= NULL
;
362 fd_bytes(io
.fd
, io
.size
, FD_WRITE
);
363 kb_incr(&statCounter
.server
.all
.kbytes_out
, io
.size
);
364 // kids should increment their counters
367 if (io
.flag
== COMM_ERR_CLOSING
)
370 if (!requestBodySource
) {
371 debugs(9,3, HERE
<< "detected while-we-were-sending abort");
372 return; // do nothing;
376 debugs(11, 1, "sentRequestBody error: FD " << io
.fd
<< ": " << xstrerr(errno
));
378 err
= errorCon(ERR_WRITE_ERROR
, HTTP_BAD_GATEWAY
, fwd
->request
);
381 abortTransaction("I/O error while sending request body");
385 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
386 abortTransaction("store entry aborted while sending request body");
390 if (requestBodySource
->exhausted())
391 doneSendingRequestBody();
393 sendMoreRequestBody();
397 ServerStateData::sendMoreRequestBody()
399 assert(requestBodySource
!= NULL
);
400 assert(!requestSender
);
402 if (requestBodySource
->getMoreData(buf
)) {
403 debugs(9,3, HERE
<< "will write " << buf
.contentSize() << " request body bytes");
404 typedef CommCbMemFunT
<ServerStateData
, CommIoCbParams
> Dialer
;
405 requestSender
= asyncCall(93,3, "ServerStateData::sentRequestBody",
406 Dialer(this, &ServerStateData::sentRequestBody
));
407 comm_write_mbuf(dataDescriptor(), &buf
, requestSender
);
409 debugs(9,3, HERE
<< "will wait for more request body bytes or eof");
410 requestSender
= NULL
;
414 // Compares hosts in urls, returns false if different, no sheme, or no host.
416 sameUrlHosts(const char *url1
, const char *url2
)
418 // XXX: Want urlHostname() here, but it uses static storage and copying
419 const char *host1
= strchr(url1
, ':');
420 const char *host2
= strchr(url2
, ':');
422 if (host1
&& host2
) {
423 // skip scheme slashes
427 } while (*host1
== '/' && *host2
== '/');
430 return false; // no host
432 // increment while the same until we reach the end of the URL/host
433 while (*host1
&& *host1
!= '/' && *host1
== *host2
) {
437 return *host1
== *host2
;
440 return false; // no URL scheme
443 // purges entries that match the value of a given HTTP [response] header
445 purgeEntriesByHeader(HttpRequest
*req
, const char *reqUrl
, HttpMsg
*rep
, http_hdr_type hdr
)
447 const char *hdrUrl
, *absUrl
;
450 hdrUrl
= rep
->header
.getStr(hdr
);
451 if (hdrUrl
== NULL
) {
456 * If the URL is relative, make it absolute so we can find it.
457 * If it's absolute, make sure the host parts match to avoid DOS attacks
458 * as per RFC 2616 13.10.
460 if (urlIsRelative(hdrUrl
)) {
461 absUrl
= urlMakeAbsolute(req
, hdrUrl
);
462 if (absUrl
!= NULL
) {
465 } else if (!sameUrlHosts(reqUrl
, hdrUrl
)) {
469 purgeEntriesByUrl(req
, hdrUrl
);
471 if (absUrl
!= NULL
) {
476 // some HTTP methods should purge matching cache entries
478 ServerStateData::maybePurgeOthers()
480 // only some HTTP methods should purge matching cache entries
481 if (!request
->method
.purgesOthers())
484 // and probably only if the response was successful
485 if (theFinalReply
->sline
.status
>= 400)
488 // XXX: should we use originalRequest() here?
489 const char *reqUrl
= urlCanonical(request
);
490 debugs(88, 5, "maybe purging due to " << RequestMethodStr(request
->method
) << ' ' << reqUrl
);
491 purgeEntriesByUrl(request
, reqUrl
);
492 purgeEntriesByHeader(request
, reqUrl
, theFinalReply
, HDR_LOCATION
);
493 purgeEntriesByHeader(request
, reqUrl
, theFinalReply
, HDR_CONTENT_LOCATION
);
496 // called (usually by kids) when we have final (possibly adapted) reply headers
498 ServerStateData::haveParsedReplyHeaders()
505 ServerStateData::originalRequest()
511 /// Initiate an asynchronous adaptation transaction which will call us back.
513 ServerStateData::startAdaptation(const Adaptation::ServiceGroupPointer
&group
, HttpRequest
*cause
)
515 debugs(11, 5, "ServerStateData::startAdaptation() called");
516 // check whether we should be sending a body as well
517 // start body pipe to feed ICAP transaction if needed
518 assert(!virginBodyDestination
);
519 HttpReply
*vrep
= virginReply();
520 assert(!vrep
->body_pipe
);
522 if (vrep
->expectingBody(cause
->method
, size
) && size
) {
523 virginBodyDestination
= new BodyPipe(this);
524 vrep
->body_pipe
= virginBodyDestination
;
525 debugs(93, 6, HERE
<< "will send virgin reply body to " <<
526 virginBodyDestination
<< "; size: " << size
);
528 virginBodyDestination
->setBodySize(size
);
531 adaptedHeadSource
= initiateAdaptation(
532 new Adaptation::Iterator(this, vrep
, cause
, group
));
533 startedAdaptation
= adaptedHeadSource
!= NULL
;
534 Must(startedAdaptation
);
537 // properly cleans up ICAP-related state
538 // may be called multiple times
539 void ServerStateData::cleanAdaptation()
541 debugs(11,5, HERE
<< "cleaning ICAP; ACL: " << adaptationAccessCheckPending
);
543 if (virginBodyDestination
!= NULL
)
544 stopProducingFor(virginBodyDestination
, false);
546 announceInitiatorAbort(adaptedHeadSource
);
548 if (adaptedBodySource
!= NULL
)
549 stopConsumingFrom(adaptedBodySource
);
551 if (!adaptationAccessCheckPending
) // we cannot cancel a pending callback
552 assert(doneWithAdaptation()); // make sure the two methods are in sync
556 ServerStateData::doneWithAdaptation() const
558 return !adaptationAccessCheckPending
&&
559 !virginBodyDestination
&& !adaptedHeadSource
&& !adaptedBodySource
;
562 // sends virgin reply body to ICAP, buffering excesses if needed
564 ServerStateData::adaptVirginReplyBody(const char *data
, ssize_t len
)
566 assert(startedAdaptation
);
568 if (!virginBodyDestination
) {
569 debugs(11,3, HERE
<< "ICAP does not want more virgin body");
573 // grow overflow area if already overflowed
574 if (responseBodyBuffer
) {
575 responseBodyBuffer
->append(data
, len
);
576 data
= responseBodyBuffer
->content();
577 len
= responseBodyBuffer
->contentSize();
580 const ssize_t putSize
= virginBodyDestination
->putMoreData(data
, len
);
584 // if we had overflow area, shrink it as necessary
585 if (responseBodyBuffer
) {
586 if (putSize
== responseBodyBuffer
->contentSize()) {
587 delete responseBodyBuffer
;
588 responseBodyBuffer
= NULL
;
590 responseBodyBuffer
->consume(putSize
);
595 // if we did not have an overflow area, create it as needed
597 assert(!responseBodyBuffer
);
598 responseBodyBuffer
= new MemBuf
;
599 responseBodyBuffer
->init(4096, SQUID_TCP_SO_RCVBUF
* 10);
600 responseBodyBuffer
->append(data
, len
);
604 // can supply more virgin response body data
606 ServerStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
608 if (responseBodyBuffer
) {
609 addVirginReplyBody(NULL
, 0); // kick the buffered fragment alive again
610 if (completed
&& !responseBodyBuffer
) {
615 maybeReadVirginBody();
618 // the consumer of our virgin response body aborted
620 ServerStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
622 stopProducingFor(virginBodyDestination
, false);
624 // do not force closeServer here in case we need to bypass AdaptationQueryAbort
626 if (doneWithAdaptation()) // we may still be receiving adapted response
627 handleAdaptationCompleted();
630 // received adapted response headers (body may follow)
632 ServerStateData::noteAdaptationAnswer(HttpMsg
*msg
)
634 clearAdaptation(adaptedHeadSource
); // we do not expect more messages
636 if (abortOnBadEntry("entry went bad while waiting for adapted headers"))
639 HttpReply
*rep
= dynamic_cast<HttpReply
*>(msg
);
641 debugs(11,5, HERE
<< this << " setting adapted reply to " << rep
);
644 assert(!adaptedBodySource
);
645 if (rep
->body_pipe
!= NULL
) {
646 // subscribe to receive adapted body
647 adaptedBodySource
= rep
->body_pipe
;
648 // assume that ICAP does not auto-consume on failures
649 assert(adaptedBodySource
->setConsumerIfNotLate(this));
652 if (doneWithAdaptation()) // we may still be sending virgin response
653 handleAdaptationCompleted();
657 // will not receive adapted response headers (and, hence, body)
659 ServerStateData::noteAdaptationQueryAbort(bool final
)
661 clearAdaptation(adaptedHeadSource
);
662 handleAdaptationAborted(!final
);
665 // more adapted response body is available
667 ServerStateData::handleMoreAdaptedBodyAvailable()
669 const size_t contentSize
= adaptedBodySource
->buf().contentSize();
671 debugs(11,5, HERE
<< "consuming " << contentSize
<< " bytes of adapted " <<
672 "response body at offset " << adaptedBodySource
->consumedSize());
674 if (abortOnBadEntry("entry refuses adapted body"))
678 BodyPipeCheckout
bpc(*adaptedBodySource
);
679 const StoreIOBuffer
ioBuf(&bpc
.buf
, currentOffset
);
680 currentOffset
+= bpc
.buf
.size
;
682 bpc
.buf
.consume(contentSize
);
686 // the entire adapted response body was produced, successfully
688 ServerStateData::handleAdaptedBodyProductionEnded()
690 stopConsumingFrom(adaptedBodySource
);
692 if (abortOnBadEntry("entry went bad while waiting for adapted body eof"))
695 handleAdaptationCompleted();
698 // premature end of the adapted response body
699 void ServerStateData::handleAdaptedBodyProducerAborted()
701 stopConsumingFrom(adaptedBodySource
);
702 handleAdaptationAborted();
705 // common part of noteAdaptationAnswer and handleAdaptedBodyProductionEnded
707 ServerStateData::handleAdaptationCompleted()
709 debugs(11,5, HERE
<< "handleAdaptationCompleted");
712 // We stop reading origin response because we have no place to put it and
713 // cannot use it. If some origin servers do not like that or if we want to
714 // reuse more pconns, we can add code to discard unneeded origin responses.
715 if (!doneWithServer()) {
716 debugs(11,3, HERE
<< "closing origin conn due to ICAP completion");
720 completeForwarding();
725 // common part of noteAdaptation*Aborted and noteBodyConsumerAborted methods
727 ServerStateData::handleAdaptationAborted(bool bypassable
)
729 debugs(11,5, HERE
<< "handleAdaptationAborted; bypassable: " << bypassable
<<
730 ", entry empty: " << entry
->isEmpty());
732 if (abortOnBadEntry("entry went bad while ICAP aborted"))
735 // TODO: bypass if possible
737 if (entry
->isEmpty()) {
738 debugs(11,9, HERE
<< "creating ICAP error entry after ICAP failure");
739 ErrorState
*err
= errorCon(ERR_ICAP_FAILURE
, HTTP_INTERNAL_SERVER_ERROR
, request
);
742 fwd
->dontRetry(true);
745 abortTransaction("ICAP failure");
749 ServerStateData::adaptationAclCheckDone(Adaptation::ServiceGroupPointer group
)
751 adaptationAccessCheckPending
= false;
753 if (abortOnBadEntry("entry went bad while waiting for ICAP ACL check"))
756 // TODO: Should nonICAP and postICAP path check this on the server-side?
757 // That check now only happens on client-side, in processReplyAccess().
758 if (virginReply()->expectedBodyTooLarge(*request
)) {
759 sendBodyIsTooLargeError();
762 // TODO: Should we check receivedBodyTooLarge on the server-side as well?
765 debugs(11,3, HERE
<< "no adapation needed");
766 setFinalReply(virginReply());
771 startAdaptation(group
, originalRequest());
776 ServerStateData::adaptationAclCheckDoneWrapper(Adaptation::ServiceGroupPointer group
, void *data
)
778 ServerStateData
*state
= (ServerStateData
*)data
;
779 state
->adaptationAclCheckDone(group
);
784 ServerStateData::sendBodyIsTooLargeError()
786 ErrorState
*err
= errorCon(ERR_TOO_BIG
, HTTP_FORBIDDEN
, request
);
789 fwd
->dontRetry(true);
790 abortTransaction("Virgin body too large.");
793 // TODO: when HttpStateData sends all errors to ICAP,
794 // we should be able to move this at the end of setVirginReply().
796 ServerStateData::adaptOrFinalizeReply()
799 // TODO: merge with client side and return void to hide the on/off logic?
800 // The callback can be called with a NULL service if adaptation is off.
801 adaptationAccessCheckPending
= Adaptation::AccessCheck::Start(
802 Adaptation::methodRespmod
, Adaptation::pointPreCache
,
803 request
, virginReply(), adaptationAclCheckDoneWrapper
, this);
804 debugs(11,5, HERE
<< "adaptationAccessCheckPending=" << adaptationAccessCheckPending
);
805 if (adaptationAccessCheckPending
)
809 setFinalReply(virginReply());
813 ServerStateData::addVirginReplyBody(const char *data
, ssize_t len
)
816 assert(!adaptationAccessCheckPending
); // or would need to buffer while waiting
817 if (startedAdaptation
) {
818 adaptVirginReplyBody(data
, len
);
822 storeReplyBody(data
, len
);
825 // writes virgin or adapted reply body to store
827 ServerStateData::storeReplyBody(const char *data
, ssize_t len
)
829 // write even if len is zero to push headers towards the client side
830 entry
->write (StoreIOBuffer(len
, currentOffset
, (char*)data
));
832 currentOffset
+= len
;
835 size_t ServerStateData::replyBodySpace(size_t space
)
838 if (responseBodyBuffer
) {
839 return 0; // Stop reading if already overflowed waiting for ICAP to catch up
842 if (virginBodyDestination
!= NULL
) {
844 * BodyPipe buffer has a finite size limit. We
845 * should not read more data from the network than will fit
846 * into the pipe buffer or we _lose_ what did not fit if
847 * the response ends sooner that BodyPipe frees up space:
848 * There is no code to keep pumping data into the pipe once
849 * response ends and serverComplete() is called.
851 * If the pipe is totally full, don't register the read handler.
852 * The BodyPipe will call our noteMoreBodySpaceAvailable() method
853 * when it has free space again.
855 size_t adaptation_space
=
856 virginBodyDestination
->buf().potentialSpaceSize();
858 debugs(11,9, "ServerStateData may read up to min(" <<
859 adaptation_space
<< ", " << space
<< ") bytes");
861 if (adaptation_space
< space
)
862 space
= adaptation_space
;