2 * Copyright (C) 1996-2017 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.
9 /* DEBUG: section 88 Client-side Reply Routines */
12 #include "acl/FilledChecklist.h"
13 #include "acl/Gadgets.h"
14 #include "anyp/PortCfg.h"
15 #include "client_side_reply.h"
16 #include "errorpage.h"
20 #include "format/Token.h"
23 #include "http/Stream.h"
24 #include "HttpHeaderTools.h"
25 #include "HttpReply.h"
26 #include "HttpRequest.h"
27 #include "ip/QosConfig.h"
29 #include "log/access_log.h"
30 #include "MemObject.h"
31 #include "mime_header.h"
32 #include "neighbors.h"
34 #include "RequestFlags.h"
35 #include "SquidConfig.h"
36 #include "SquidTime.h"
42 #include "auth/UserRequest.h"
45 #include "DelayPools.h"
53 CBDATA_CLASS_INIT(clientReplyContext
);
56 extern "C" CSS clientReplyStatus
;
57 ErrorState
*clientBuildError(err_type
, Http::StatusCode
, char const *, Ip::Address
&, HttpRequest
*);
61 clientReplyContext::~clientReplyContext()
64 /* This may trigger a callback back into SendMoreData as the cbdata
67 removeClientStoreReference(&sc
, http
);
68 /* old_entry might still be set if we didn't yet get the reply
69 * code in HandleIMSReply() */
70 removeStoreReference(&old_sc
, &old_entry
);
71 safe_free(tempBuffer
.data
);
72 cbdataReferenceDone(http
);
76 clientReplyContext::clientReplyContext(ClientHttpRequest
*clientContext
) :
77 purgeStatus(Http::scNone
),
79 http(cbdataReference(clientContext
)),
94 collapsedRevalidation(crNone
)
99 /** Create an error in the store awaiting the client side to read it.
101 * This may be better placed in the clientStream logic, but it has not been
102 * relocated there yet
105 clientReplyContext::setReplyToError(
106 err_type err
, Http::StatusCode status
, const HttpRequestMethod
& method
, char const *uri
,
107 Ip::Address
&addr
, HttpRequest
* failedrequest
, const char *unparsedrequest
,
109 Auth::UserRequest::Pointer auth_user_request
115 ErrorState
*errstate
= clientBuildError(err
, status
, uri
, addr
, failedrequest
);
118 errstate
->request_hdrs
= xstrdup(unparsedrequest
);
121 errstate
->auth_user_request
= auth_user_request
;
123 setReplyToError(method
, errstate
);
126 void clientReplyContext::setReplyToError(const HttpRequestMethod
& method
, ErrorState
*errstate
)
128 if (errstate
->httpStatus
== Http::scNotImplemented
&& http
->request
)
129 /* prevent confusion over whether we default to persistent or not */
130 http
->request
->flags
.proxyKeepalive
= false;
132 http
->al
->http
.code
= errstate
->httpStatus
;
135 http
->request
->ignoreRange("responding with a Squid-generated error");
137 createStoreEntry(method
, RequestFlags());
138 assert(errstate
->callback_data
== NULL
);
139 errorAppendEntry(http
->storeEntry(), errstate
);
140 /* Now the caller reads to get this */
144 clientReplyContext::setReplyToReply(HttpReply
*futureReply
)
147 http
->al
->http
.code
= futureReply
->sline
.status();
149 HttpRequestMethod method
;
150 if (http
->request
) { // nil on responses to unparsable requests
151 http
->request
->ignoreRange("responding with a Squid-generated reply");
152 method
= http
->request
->method
;
155 createStoreEntry(method
, RequestFlags());
157 http
->storeEntry()->storeErrorResponse(futureReply
);
158 /* Now the caller reads to get futureReply */
161 // Assumes that the entry contains an error response without Content-Range.
162 // To use with regular entries, make HTTP Range header removal conditional.
163 void clientReplyContext::setReplyToStoreEntry(StoreEntry
*entry
, const char *reason
)
165 entry
->lock("clientReplyContext::setReplyToStoreEntry"); // removeClientStoreReference() unlocks
166 sc
= storeClientListAdd(entry
, this);
168 sc
->setDelayId(DelayId::DelayClient(http
));
173 http
->request
->ignoreRange(reason
);
174 flags
.storelogiccomplete
= 1;
175 http
->storeEntry(entry
);
179 clientReplyContext::removeStoreReference(store_client
** scp
,
183 store_client
*sc_tmp
= *scp
;
185 if ((e
= *ep
) != NULL
) {
187 storeUnregister(sc_tmp
, e
, this);
189 e
->unlock("clientReplyContext::removeStoreReference");
194 clientReplyContext::removeClientStoreReference(store_client
**scp
, ClientHttpRequest
*aHttpRequest
)
196 StoreEntry
*reference
= aHttpRequest
->storeEntry();
197 removeStoreReference(scp
, &reference
);
198 aHttpRequest
->storeEntry(reference
);
202 clientReplyContext::saveState()
204 assert(old_sc
== NULL
);
205 debugs(88, 3, "clientReplyContext::saveState: saving store context");
206 old_entry
= http
->storeEntry();
208 old_lastmod
= http
->request
->lastmod
;
209 old_etag
= http
->request
->etag
;
210 old_reqsize
= reqsize
;
211 tempBuffer
.offset
= reqofs
;
212 /* Prevent accessing the now saved entries */
213 http
->storeEntry(NULL
);
220 clientReplyContext::restoreState()
222 assert(old_sc
!= NULL
);
223 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
224 removeClientStoreReference(&sc
, http
);
225 http
->storeEntry(old_entry
);
227 reqsize
= old_reqsize
;
228 reqofs
= tempBuffer
.offset
;
229 http
->request
->lastmod
= old_lastmod
;
230 http
->request
->etag
= old_etag
;
231 /* Prevent accessed the old saved entries */
237 tempBuffer
.offset
= 0;
241 clientReplyContext::startError(ErrorState
* err
)
243 createStoreEntry(http
->request
->method
, RequestFlags());
244 triggerInitialStoreRead();
245 errorAppendEntry(http
->storeEntry(), err
);
249 clientReplyContext::getNextNode() const
251 return (clientStreamNode
*)ourNode
->node
.next
->data
;
254 /* This function is wrong - the client parameters don't include the
258 clientReplyContext::triggerInitialStoreRead()
260 /* when confident, 0 becomes reqofs, and then this factors into
264 StoreIOBuffer
localTempBuffer (next()->readBuffer
.length
, 0, next()->readBuffer
.data
);
265 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, SendMoreData
, this);
268 /* there is an expired entry in the store.
269 * setup a temporary buffer area and perform an IMS to the origin
272 clientReplyContext::processExpired()
274 const char *url
= storeId();
275 debugs(88, 3, "clientReplyContext::processExpired: '" << http
->uri
<< "'");
276 const time_t lastmod
= http
->storeEntry()->lastModified();
277 assert(lastmod
>= 0);
279 * check if we are allowed to contact other servers
280 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
281 * a stale entry *if* it matches client requirements
284 if (http
->onlyIfCached()) {
285 processOnlyIfCachedMiss();
289 http
->logType
= LOG_TCP_REFRESH
;
290 http
->request
->flags
.refresh
= true;
291 #if STORE_CLIENT_LIST_DEBUG
292 /* Prevent a race with the store client memory free routines
294 assert(storeClientIsThisAClient(sc
, this));
296 /* Prepare to make a new temporary request */
299 // TODO: support collapsed revalidation for Vary-controlled entries
300 const bool collapsingAllowed
= Config
.onoff
.collapsed_forwarding
&&
301 !Store::Root().smpAware() &&
302 http
->request
->vary_headers
.isEmpty();
304 StoreEntry
*entry
= nullptr;
305 if (collapsingAllowed
) {
306 if ((entry
= storeGetPublicByRequest(http
->request
, ksRevalidation
)))
307 entry
->lock("clientReplyContext::processExpired#alreadyRevalidating");
311 debugs(88, 5, "collapsed on existing revalidation entry: " << *entry
);
312 collapsedRevalidation
= crSlave
;
314 entry
= storeCreateEntry(url
,
315 http
->log_uri
, http
->request
->flags
, http
->request
->method
);
316 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
318 if (collapsingAllowed
) {
319 debugs(88, 5, "allow other revalidation requests to collapse on " << *entry
);
320 Store::Root().allowCollapsing(entry
, http
->request
->flags
,
321 http
->request
->method
);
322 collapsedRevalidation
= crInitiator
;
324 collapsedRevalidation
= crNone
;
328 sc
= storeClientListAdd(entry
, this);
330 /* delay_id is already set on original store client */
331 sc
->setDelayId(DelayId::DelayClient(http
));
334 http
->request
->lastmod
= lastmod
;
336 if (!http
->request
->header
.has(Http::HdrType::IF_NONE_MATCH
)) {
337 ETag etag
= {NULL
, -1}; // TODO: make that a default ETag constructor
338 if (old_entry
->hasEtag(etag
) && !etag
.weak
)
339 http
->request
->etag
= etag
.str
;
342 debugs(88, 5, "lastmod " << entry
->lastModified());
343 http
->storeEntry(entry
);
344 assert(http
->out
.offset
== 0);
345 assert(http
->request
->clientConnectionManager
== http
->getConn());
347 if (collapsedRevalidation
!= crSlave
) {
349 * A refcounted pointer so that FwdState stays around as long as
350 * this clientReplyContext does
352 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
353 FwdState::Start(conn
, http
->storeEntry(), http
->request
, http
->al
);
355 /* Register with storage manager to receive updates when data comes in. */
357 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
358 debugs(88, DBG_CRITICAL
, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
361 /* start counting the length from 0 */
362 StoreIOBuffer
localTempBuffer(HTTP_REQBUF_SZ
, 0, tempbuf
);
363 storeClientCopy(sc
, entry
, localTempBuffer
, HandleIMSReply
, this);
368 clientReplyContext::sendClientUpstreamResponse()
370 StoreIOBuffer tempresult
;
371 removeStoreReference(&old_sc
, &old_entry
);
372 /* here the data to send is the data we just received */
373 tempBuffer
.offset
= 0;
375 /* sendMoreData tracks the offset as well.
376 * Force it back to zero */
378 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
379 /* TODO: provide sendMoreData with the ready parsed reply */
380 tempresult
.length
= reqsize
;
381 tempresult
.data
= tempbuf
;
382 sendMoreData(tempresult
);
386 clientReplyContext::HandleIMSReply(void *data
, StoreIOBuffer result
)
388 clientReplyContext
*context
= (clientReplyContext
*)data
;
389 context
->handleIMSReply(result
);
393 clientReplyContext::sendClientOldEntry()
395 /* Get the old request back */
397 /* here the data to send is in the next nodes buffers already */
398 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
399 /* sendMoreData tracks the offset as well.
400 * Force it back to zero */
402 StoreIOBuffer
tempresult (reqsize
, reqofs
, next()->readBuffer
.data
);
403 sendMoreData(tempresult
);
406 /* This is the workhorse of the HandleIMSReply callback.
408 * It is called when we've got data back from the origin following our
409 * IMS request to revalidate a stale entry.
412 clientReplyContext::handleIMSReply(StoreIOBuffer result
)
417 debugs(88, 3, http
->storeEntry()->url() << ", " << (long unsigned) result
.length
<< " bytes");
419 if (http
->storeEntry() == NULL
)
422 if (result
.flags
.error
&& !EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
))
425 if (collapsedRevalidation
== crSlave
&& !http
->storeEntry()->mayStartHitting()) {
426 debugs(88, 3, "CF slave hit private non-shareable " << *http
->storeEntry() << ". MISS");
427 // restore context to meet processMiss() expectations
429 http
->logType
= LOG_TCP_MISS
;
434 /* update size of the request */
435 reqsize
= result
.length
+ reqofs
;
437 const Http::StatusCode status
= http
->storeEntry()->getReply()->sline
.status();
439 // request to origin was aborted
440 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
441 debugs(88, 3, "request to origin aborted '" << http
->storeEntry()->url() << "', sending old entry to client");
442 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
443 sendClientOldEntry();
446 const HttpReply
*old_rep
= old_entry
->getReply();
448 // origin replied 304
449 if (status
== Http::scNotModified
) {
450 http
->logType
= LOG_TCP_REFRESH_UNMODIFIED
;
451 http
->request
->flags
.staleIfHit
= false; // old_entry is no longer stale
453 // update headers on existing entry
454 Store::Root().updateOnNotModified(old_entry
, *http
->storeEntry());
456 // if client sent IMS
458 if (http
->request
->flags
.ims
&& !old_entry
->modifiedSince(http
->request
->ims
, http
->request
->imslen
)) {
459 // forward the 304 from origin
460 debugs(88, 3, "origin replied 304, revalidating existing entry and forwarding 304 to client");
461 sendClientUpstreamResponse();
463 // send existing entry, it's still valid
464 debugs(88, 3, "origin replied 304, revalidating existing entry and sending " <<
465 old_rep
->sline
.status() << " to client");
466 sendClientOldEntry();
470 // origin replied with a non-error code
471 else if (status
> Http::scNone
&& status
< Http::scInternalServerError
) {
472 const HttpReply
*new_rep
= http
->storeEntry()->getReply();
473 // RFC 7234 section 4: a cache MUST use the most recent response
474 // (as determined by the Date header field)
475 if (new_rep
->olderThan(old_rep
)) {
476 http
->logType
.err
.ignored
= true;
477 debugs(88, 3, "origin replied " << status
<<
478 " but with an older date header, sending old entry (" <<
479 old_rep
->sline
.status() << ") to client");
480 sendClientOldEntry();
482 http
->logType
= LOG_TCP_REFRESH_MODIFIED
;
483 debugs(88, 3, "origin replied " << status
<<
484 ", replacing existing entry and forwarding to client");
486 if (collapsedRevalidation
)
487 http
->storeEntry()->clearPublicKeyScope();
489 sendClientUpstreamResponse();
493 // origin replied with an error
494 else if (http
->request
->flags
.failOnValidationError
) {
495 http
->logType
= LOG_TCP_REFRESH_FAIL_ERR
;
496 debugs(88, 3, "origin replied with error " << status
<<
497 ", forwarding to client due to fail_on_validation_err");
498 sendClientUpstreamResponse();
500 // ignore and let client have old entry
501 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
502 debugs(88, 3, "origin replied with error " <<
503 status
<< ", sending old entry (" << old_rep
->sline
.status() << ") to client");
504 sendClientOldEntry();
508 SQUIDCEXTERN CSR clientGetMoreData
;
509 SQUIDCEXTERN CSD clientReplyDetach
;
512 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
513 * have been parsed. Normally this should be a single call, but
514 * it might take more than one. As soon as we have the headers,
515 * we hand off to clientSendMoreData, processExpired, or
519 clientReplyContext::CacheHit(void *data
, StoreIOBuffer result
)
521 clientReplyContext
*context
= (clientReplyContext
*)data
;
522 context
->cacheHit(result
);
526 * Process a possible cache HIT.
529 clientReplyContext::cacheHit(StoreIOBuffer result
)
531 /** Ignore if the HIT object is being deleted. */
533 debugs(88, 3, "HIT object being deleted. Ignore the HIT.");
537 StoreEntry
*e
= http
->storeEntry();
539 HttpRequest
*r
= http
->request
;
541 debugs(88, 3, "clientCacheHit: " << http
->uri
<< ", " << result
.length
<< " bytes");
543 if (http
->storeEntry() == NULL
) {
544 debugs(88, 3, "clientCacheHit: request aborted");
546 } else if (result
.flags
.error
) {
547 /* swap in failure */
548 debugs(88, 3, "clientCacheHit: swapin failure for " << http
->uri
);
549 http
->logType
= LOG_TCP_SWAPFAIL_MISS
;
550 removeClientStoreReference(&sc
, http
);
555 // The previously identified hit suddenly became unsharable!
556 // This is common for collapsed forwarding slaves but might also
557 // happen to regular hits because we are called asynchronously.
558 if (!e
->mayStartHitting()) {
559 debugs(88, 3, "unsharable " << *e
<< ". MISS");
560 http
->logType
= LOG_TCP_MISS
;
565 if (result
.length
== 0) {
566 debugs(88, 5, "store IO buffer has no content. MISS");
567 /* the store couldn't get enough data from the file for us to id the
570 /* treat as a miss */
571 http
->logType
= LOG_TCP_MISS
;
576 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
577 /* update size of the request */
578 reqsize
= result
.length
+ reqofs
;
581 * Got the headers, now grok them
583 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
585 if (http
->request
->storeId().cmp(e
->mem_obj
->storeId()) != 0) {
586 debugs(33, DBG_IMPORTANT
, "clientProcessHit: URL mismatch, '" << e
->mem_obj
->storeId() << "' != '" << http
->request
->storeId() << "'");
587 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
592 switch (varyEvaluateMatch(e
, r
)) {
595 /* No variance detected. Continue as normal */
599 /* This is the correct entity for this request. Continue */
600 debugs(88, 2, "clientProcessHit: Vary MATCH!");
604 /* This is not the correct entity for this request. We need
605 * to requery the cache.
607 removeClientStoreReference(&sc
, http
);
609 /* Note: varyEvalyateMatch updates the request with vary information
610 * so we only get here once. (it also takes care of cancelling loops)
612 debugs(88, 2, "clientProcessHit: Vary detected!");
613 clientGetMoreData(ourNode
, http
);
617 /* varyEvaluateMatch found a object loop. Process as miss */
618 debugs(88, DBG_IMPORTANT
, "clientProcessHit: Vary object loop!");
619 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
624 if (r
->method
== Http::METHOD_PURGE
) {
625 debugs(88, 5, "PURGE gets a HIT");
626 removeClientStoreReference(&sc
, http
);
632 if (e
->checkNegativeHit() && !r
->flags
.noCacheHack()) {
633 debugs(88, 5, "negative-HIT");
634 http
->logType
= LOG_TCP_NEGATIVE_HIT
;
635 sendMoreData(result
);
637 } else if (blockedHit()) {
638 debugs(88, 5, "send_hit forces a MISS");
639 http
->logType
= LOG_TCP_MISS
;
642 } else if (!http
->flags
.internal
&& refreshCheckHTTP(e
, r
)) {
643 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
645 * We hold a stale copy; it needs to be validated
648 * The 'needValidation' flag is used to prevent forwarding
649 * loops between siblings. If our copy of the object is stale,
650 * then we should probably only use parents for the validation
651 * request. Otherwise two siblings could generate a loop if
652 * both have a stale version of the object.
654 r
->flags
.needValidation
= true;
656 if (e
->lastModified() < 0) {
657 debugs(88, 3, "validate HIT object? NO. Can't calculate entry modification time. Do MISS.");
659 * We cannot revalidate entries without knowing their
661 * XXX: BUG 1890 objects without Date do not get one added.
663 http
->logType
= LOG_TCP_MISS
;
665 } else if (r
->flags
.noCache
) {
666 debugs(88, 3, "validate HIT object? NO. Client sent CC:no-cache. Do CLIENT_REFRESH_MISS");
668 * This did not match a refresh pattern that overrides no-cache
669 * we should honour the client no-cache header.
671 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
673 } else if (r
->url
.getScheme() == AnyP::PROTO_HTTP
) {
674 debugs(88, 3, "validate HIT object? YES.");
676 * Object needs to be revalidated
677 * XXX This could apply to FTP as well, if Last-Modified is known.
681 debugs(88, 3, "validate HIT object? NO. Client protocol non-HTTP. Do MISS.");
683 * We don't know how to re-validate other protocols. Handle
684 * them as if the object has expired.
686 http
->logType
= LOG_TCP_MISS
;
690 } else if (r
->conditional()) {
691 debugs(88, 5, "conditional HIT");
692 if (processConditional(result
))
697 * plain ol' cache hit
699 debugs(88, 5, "plain old HIT");
702 if (e
->store_status
!= STORE_OK
)
703 http
->logType
= LOG_TCP_MISS
;
706 if (e
->mem_status
== IN_MEMORY
)
707 http
->logType
= LOG_TCP_MEM_HIT
;
708 else if (Config
.onoff
.offline
)
709 http
->logType
= LOG_TCP_OFFLINE_HIT
;
711 sendMoreData(result
);
715 * Prepare to fetch the object as it's a cache miss of some kind.
718 clientReplyContext::processMiss()
720 char *url
= http
->uri
;
721 HttpRequest
*r
= http
->request
;
722 ErrorState
*err
= NULL
;
723 debugs(88, 4, r
->method
<< ' ' << url
);
726 * We might have a left-over StoreEntry from a failed cache hit
729 if (http
->storeEntry()) {
730 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
731 debugs(88, DBG_CRITICAL
, "clientProcessMiss: miss on a special object (" << url
<< ").");
732 debugs(88, DBG_CRITICAL
, "\tlog_type = " << http
->logType
.c_str());
733 http
->storeEntry()->dump(1);
736 removeClientStoreReference(&sc
, http
);
739 /** Check if its a PURGE request to be actioned. */
740 if (r
->method
== Http::METHOD_PURGE
) {
745 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
746 if (r
->method
== Http::METHOD_OTHER
) {
750 /** Check if 'only-if-cached' flag is set. Action if so. */
751 if (http
->onlyIfCached()) {
752 processOnlyIfCachedMiss();
756 Comm::ConnectionPointer conn
= http
->getConn() != nullptr ? http
->getConn()->clientConnection
: nullptr;
758 if (r
->flags
.loopDetected
) {
759 http
->al
->http
.code
= Http::scForbidden
;
760 Ip::Address tmp_noaddr
;
761 tmp_noaddr
.setNoAddr();
762 err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, nullptr, conn
? conn
->remote
: tmp_noaddr
, http
->request
);
763 createStoreEntry(r
->method
, RequestFlags());
764 errorAppendEntry(http
->storeEntry(), err
);
765 triggerInitialStoreRead();
768 assert(http
->out
.offset
== 0);
769 createStoreEntry(r
->method
, r
->flags
);
770 triggerInitialStoreRead();
772 if (http
->redirect
.status
) {
773 HttpReply
*rep
= new HttpReply
;
774 http
->logType
= LOG_TCP_REDIRECT
;
775 http
->storeEntry()->releaseRequest();
776 rep
->redirect(http
->redirect
.status
, http
->redirect
.location
);
777 http
->storeEntry()->replaceHttpReply(rep
);
778 http
->storeEntry()->complete();
782 assert(r
->clientConnectionManager
== http
->getConn());
784 /** Start forwarding to get the new object from network */
785 FwdState::Start(conn
, http
->storeEntry(), r
, http
->al
);
790 * client issued a request with an only-if-cached cache-control directive;
791 * we did not find a cached object that can be returned without
792 * contacting other servers;
793 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
796 clientReplyContext::processOnlyIfCachedMiss()
798 debugs(88, 4, http
->request
->method
<< ' ' << http
->uri
);
799 http
->al
->http
.code
= Http::scGatewayTimeout
;
800 Ip::Address tmp_noaddr
;
801 tmp_noaddr
.setNoAddr();
802 ErrorState
*err
= clientBuildError(ERR_ONLY_IF_CACHED_MISS
, Http::scGatewayTimeout
, NULL
,
803 http
->getConn() ? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
805 removeClientStoreReference(&sc
, http
);
809 /// process conditional request from client
811 clientReplyContext::processConditional(StoreIOBuffer
&result
)
813 StoreEntry
*const e
= http
->storeEntry();
815 if (e
->getReply()->sline
.status() != Http::scOkay
) {
816 debugs(88, 4, "Reply code " << e
->getReply()->sline
.status() << " != 200");
817 http
->logType
= LOG_TCP_MISS
;
822 HttpRequest
&r
= *http
->request
;
824 if (r
.header
.has(Http::HdrType::IF_MATCH
) && !e
->hasIfMatchEtag(r
)) {
825 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
826 sendPreconditionFailedError();
830 if (r
.header
.has(Http::HdrType::IF_NONE_MATCH
)) {
831 // RFC 7232: If-None-Match recipient MUST ignore IMS
835 r
.header
.delById(Http::HdrType::IF_MODIFIED_SINCE
);
837 if (e
->hasIfNoneMatchEtag(r
)) {
838 sendNotModifiedOrPreconditionFailedError();
842 // None-Match is true (no ETag matched); treat as an unconditional hit
847 // handle If-Modified-Since requests from the client
848 if (e
->modifiedSince(r
.ims
, r
.imslen
)) {
849 // Modified-Since is true; treat as an unconditional hit
853 // otherwise reply with 304 Not Modified
862 /// whether squid.conf send_hit prevents us from serving this hit
864 clientReplyContext::blockedHit() const
866 if (!Config
.accessList
.sendHit
)
867 return false; // hits are not blocked by default
869 if (http
->flags
.internal
)
870 return false; // internal content "hits" cannot be blocked
872 if (const HttpReply
*rep
= http
->storeEntry()->getReply()) {
873 std::unique_ptr
<ACLFilledChecklist
> chl(clientAclChecklistCreate(Config
.accessList
.sendHit
, http
));
874 chl
->reply
= const_cast<HttpReply
*>(rep
); // ACLChecklist API bug
875 HTTPMSGLOCK(chl
->reply
);
876 return !chl
->fastCheck().allowed(); // when in doubt, block
879 // This does not happen, I hope, because we are called from CacheHit, which
880 // is called via a storeClientCopy() callback, and store should initialize
881 // the reply before calling that callback.
882 debugs(88, 3, "Missing reply!");
887 clientReplyContext::purgeRequestFindObjectToPurge()
889 /* Try to find a base entry */
890 http
->flags
.purging
= true;
893 // TODO: can we use purgeAllCached() here instead of doing the
894 // getPublicByRequestMethod() dance?
895 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_GET
);
898 // Purges all entries with a given url
899 // TODO: move to SideAgent parent, when we have one
901 * We probably cannot purge Vary-affected responses because their MD5
902 * keys depend on vary headers.
905 purgeEntriesByUrl(HttpRequest
* req
, const char *url
)
908 bool get_or_head_sent
= false;
911 for (HttpRequestMethod
m(Http::METHOD_NONE
); m
!= Http::METHOD_ENUM_END
; ++m
) {
912 if (m
.respMaybeCacheable()) {
913 if (StoreEntry
*entry
= storeGetPublic(url
, m
)) {
914 debugs(88, 5, "purging " << *entry
<< ' ' << m
<< ' ' << url
);
916 neighborsHtcpClear(entry
, url
, req
, m
, HTCP_CLR_INVALIDATION
);
917 if (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
) {
918 get_or_head_sent
= true;
927 if (!get_or_head_sent
) {
928 neighborsHtcpClear(NULL
, url
, req
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_INVALIDATION
);
934 clientReplyContext::purgeAllCached()
936 // XXX: performance regression, c_str() reallocates
937 SBuf
url(http
->request
->effectiveRequestUri());
938 purgeEntriesByUrl(http
->request
, url
.c_str());
942 clientReplyContext::created(StoreEntry
*newEntry
)
944 if (lookingforstore
== 1)
945 purgeFoundGet(newEntry
);
946 else if (lookingforstore
== 2)
947 purgeFoundHead(newEntry
);
948 else if (lookingforstore
== 3)
949 purgeDoPurgeGet(newEntry
);
950 else if (lookingforstore
== 4)
951 purgeDoPurgeHead(newEntry
);
952 else if (lookingforstore
== 5)
953 identifyFoundObject(newEntry
);
957 clientReplyContext::purgeFoundGet(StoreEntry
*newEntry
)
959 if (newEntry
->isNull()) {
961 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
963 purgeFoundObject (newEntry
);
967 clientReplyContext::purgeFoundHead(StoreEntry
*newEntry
)
969 if (newEntry
->isNull())
972 purgeFoundObject (newEntry
);
976 clientReplyContext::purgeFoundObject(StoreEntry
*entry
)
978 assert (entry
&& !entry
->isNull());
980 if (EBIT_TEST(entry
->flags
, ENTRY_SPECIAL
)) {
981 http
->logType
= LOG_TCP_DENIED
;
982 Ip::Address tmp_noaddr
;
983 tmp_noaddr
.setNoAddr(); // TODO: make a global const
984 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
,
985 http
->getConn() ? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
988 return; // XXX: leaking unused entry if some store does not keep it
991 StoreIOBuffer localTempBuffer
;
992 /* Swap in the metadata */
993 http
->storeEntry(entry
);
995 http
->storeEntry()->lock("clientReplyContext::purgeFoundObject");
996 http
->storeEntry()->createMemObject(storeId(), http
->log_uri
,
997 http
->request
->method
);
999 sc
= storeClientListAdd(http
->storeEntry(), this);
1001 http
->logType
= LOG_TCP_HIT
;
1005 localTempBuffer
.offset
= http
->out
.offset
;
1007 localTempBuffer
.length
= next()->readBuffer
.length
;
1009 localTempBuffer
.data
= next()->readBuffer
.data
;
1011 storeClientCopy(sc
, http
->storeEntry(),
1012 localTempBuffer
, CacheHit
, this);
1016 clientReplyContext::purgeRequest()
1018 debugs(88, 3, "Config2.onoff.enable_purge = " <<
1019 Config2
.onoff
.enable_purge
);
1021 if (!Config2
.onoff
.enable_purge
) {
1022 http
->logType
= LOG_TCP_DENIED
;
1023 Ip::Address tmp_noaddr
;
1024 tmp_noaddr
.setNoAddr();
1025 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
,
1026 http
->getConn() ? http
->getConn()->clientConnection
->remote
: tmp_noaddr
, http
->request
);
1031 /* Release both IP cache */
1032 ipcacheInvalidate(http
->request
->url
.host());
1034 if (!http
->flags
.purging
)
1035 purgeRequestFindObjectToPurge();
1041 clientReplyContext::purgeDoMissPurge()
1043 http
->logType
= LOG_TCP_MISS
;
1044 lookingforstore
= 3;
1045 StoreEntry::getPublicByRequestMethod(this,http
->request
, Http::METHOD_GET
);
1049 clientReplyContext::purgeDoPurgeGet(StoreEntry
*newEntry
)
1052 /* Move to new() when that is created */
1053 purgeStatus
= Http::scNotFound
;
1055 if (!newEntry
->isNull()) {
1056 /* Release the cached URI */
1057 debugs(88, 4, "clientPurgeRequest: GET '" << newEntry
->url() << "'" );
1059 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1061 newEntry
->release();
1062 purgeStatus
= Http::scOkay
;
1065 lookingforstore
= 4;
1066 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
1070 clientReplyContext::purgeDoPurgeHead(StoreEntry
*newEntry
)
1072 if (newEntry
&& !newEntry
->isNull()) {
1073 debugs(88, 4, "HEAD " << newEntry
->url());
1075 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1077 newEntry
->release();
1078 purgeStatus
= Http::scOkay
;
1081 /* And for Vary, release the base URI if none of the headers was included in the request */
1082 if (!http
->request
->vary_headers
.isEmpty()
1083 && http
->request
->vary_headers
.find('=') != SBuf::npos
) {
1084 // XXX: performance regression, c_str() reallocates
1085 SBuf
tmp(http
->request
->effectiveRequestUri());
1086 StoreEntry
*entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_GET
);
1089 debugs(88, 4, "Vary GET " << entry
->url());
1091 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1094 purgeStatus
= Http::scOkay
;
1097 entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_HEAD
);
1100 debugs(88, 4, "Vary HEAD " << entry
->url());
1102 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1105 purgeStatus
= Http::scOkay
;
1110 * Make a new entry to hold the reply to be written
1113 /* FIXME: This doesn't need to go through the store. Simply
1114 * push down the client chain
1116 createStoreEntry(http
->request
->method
, RequestFlags());
1118 triggerInitialStoreRead();
1120 HttpReply
*rep
= new HttpReply
;
1121 rep
->setHeaders(purgeStatus
, NULL
, NULL
, 0, 0, -1);
1122 http
->storeEntry()->replaceHttpReply(rep
);
1123 http
->storeEntry()->complete();
1127 clientReplyContext::traceReply(clientStreamNode
* node
)
1129 clientStreamNode
*nextNode
= (clientStreamNode
*)node
->node
.next
->data
;
1130 StoreIOBuffer localTempBuffer
;
1131 createStoreEntry(http
->request
->method
, RequestFlags());
1132 localTempBuffer
.offset
= nextNode
->readBuffer
.offset
+ headers_sz
;
1133 localTempBuffer
.length
= nextNode
->readBuffer
.length
;
1134 localTempBuffer
.data
= nextNode
->readBuffer
.data
;
1135 storeClientCopy(sc
, http
->storeEntry(),
1136 localTempBuffer
, SendMoreData
, this);
1137 http
->storeEntry()->releaseRequest();
1138 http
->storeEntry()->buffer();
1139 HttpReply
*rep
= new HttpReply
;
1140 rep
->setHeaders(Http::scOkay
, NULL
, "text/plain", http
->request
->prefixLen(), 0, squid_curtime
);
1141 http
->storeEntry()->replaceHttpReply(rep
);
1142 http
->request
->swapOut(http
->storeEntry());
1143 http
->storeEntry()->complete();
1146 #define SENDING_BODY 0
1147 #define SENDING_HDRSONLY 1
1149 clientReplyContext::checkTransferDone()
1151 StoreEntry
*entry
= http
->storeEntry();
1157 * For now, 'done_copying' is used for special cases like
1158 * Range and HEAD requests.
1160 if (http
->flags
.done_copying
)
1163 if (http
->request
->flags
.chunkedReply
&& !flags
.complete
) {
1164 // last-chunk was not sent
1169 * Handle STORE_OK objects.
1170 * objectLen(entry) will be set proprely.
1171 * RC: Does objectLen(entry) include the Headers?
1174 if (entry
->store_status
== STORE_OK
) {
1175 return storeOKTransferDone();
1177 return storeNotOKTransferDone();
1182 clientReplyContext::storeOKTransferDone() const
1184 assert(http
->storeEntry()->objectLen() >= 0);
1185 assert(http
->storeEntry()->objectLen() >= headers_sz
);
1186 if (http
->out
.offset
>= http
->storeEntry()->objectLen() - headers_sz
) {
1187 debugs(88,3,HERE
<< "storeOKTransferDone " <<
1188 " out.offset=" << http
->out
.offset
<<
1189 " objectLen()=" << http
->storeEntry()->objectLen() <<
1190 " headers_sz=" << headers_sz
);
1198 clientReplyContext::storeNotOKTransferDone() const
1201 * Now, handle STORE_PENDING objects
1203 MemObject
*mem
= http
->storeEntry()->mem_obj
;
1204 assert(mem
!= NULL
);
1205 assert(http
->request
!= NULL
);
1207 /* mem->reply was wrong because it uses the UPSTREAM header length!!! */
1208 if (headers_sz
== 0)
1209 /* haven't found end of headers yet */
1212 const HttpReplyPointer
curReply(mem
->getReply());
1215 * Figure out how much data we are supposed to send.
1216 * If we are sending a body and we don't have a content-length,
1217 * then we must wait for the object to become STORE_OK.
1219 if (curReply
->content_length
< 0)
1222 uint64_t expectedLength
= curReply
->content_length
+ http
->out
.headers_sz
;
1224 if (http
->out
.size
< expectedLength
)
1227 debugs(88,3,HERE
<< "storeNotOKTransferDone " <<
1228 " out.size=" << http
->out
.size
<<
1229 " expectedLength=" << expectedLength
);
1234 /* A write has completed, what is the next status based on the
1235 * canonical request data?
1236 * 1 something is wrong
1237 * 0 nothing is wrong.
1241 clientHttpRequestStatus(int fd
, ClientHttpRequest
const *http
)
1243 #if SIZEOF_INT64_T == 4
1244 if (http
->out
.size
> 0x7FFF0000) {
1245 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
<< " to prevent out.size counter overflow");
1246 if (http
->getConn())
1247 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1248 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes");
1249 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1253 if (http
->out
.offset
> 0x7FFF0000) {
1254 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
< " to prevent out.offset counter overflow");
1255 if (http
->getConn())
1256 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1257 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes, offset " << http
->out
.offset
);
1258 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1267 * *http is a valid structure.
1268 * fd is either -1, or an open fd.
1270 * TODO: enumify this
1272 * This function is used by any http request sink, to determine the status
1275 clientStream_status_t
1276 clientReplyStatus(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1278 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1280 assert (context
->http
== http
);
1281 return context
->replyStatus();
1284 clientStream_status_t
1285 clientReplyContext::replyStatus()
1288 /* Here because lower nodes don't need it */
1290 if (http
->storeEntry() == NULL
) {
1291 debugs(88, 5, "clientReplyStatus: no storeEntry");
1292 return STREAM_FAILED
; /* yuck, but what can we do? */
1295 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
1296 /* TODO: Could upstream read errors (result.flags.error) be
1297 * lost, and result in undersize requests being considered
1298 * complete. Should we tcp reset such connections ?
1300 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
1301 return STREAM_FAILED
;
1304 if ((done
= checkTransferDone()) != 0 || flags
.complete
) {
1305 debugs(88, 5, "clientReplyStatus: transfer is DONE: " << done
<< flags
.complete
);
1306 /* Ok we're finished, but how? */
1308 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_BAD_LENGTH
)) {
1309 debugs(88, 5, "clientReplyStatus: truncated response body");
1310 return STREAM_UNPLANNED_COMPLETE
;
1314 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
1315 return STREAM_FAILED
;
1318 const int64_t expectedBodySize
=
1319 http
->storeEntry()->getReply()->bodySize(http
->request
->method
);
1320 if (expectedBodySize
>= 0 && !http
->gotEnough()) {
1321 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
1322 return STREAM_UNPLANNED_COMPLETE
;
1325 debugs(88, 5, "clientReplyStatus: stream complete; keepalive=" <<
1326 http
->request
->flags
.proxyKeepalive
);
1327 return STREAM_COMPLETE
;
1330 // XXX: Should this be checked earlier? We could return above w/o checking.
1331 if (reply
->receivedBodyTooLarge(*http
->request
, http
->out
.offset
- 4096)) {
1332 /* 4096 is a margin for the HTTP headers included in out.offset */
1333 debugs(88, 5, "clientReplyStatus: client reply body is too large");
1334 return STREAM_FAILED
;
1340 /* Responses with no body will not have a content-type header,
1341 * which breaks the rep_mime_type acl, which
1342 * coincidentally, is the most common acl for reply access lists.
1343 * A better long term fix for this is to allow acl matchs on the various
1344 * status codes, and then supply a default ruleset that puts these
1345 * codes before any user defines access entries. That way the user
1346 * can choose to block these responses where appropriate, but won't get
1347 * mysterious breakages.
1350 clientReplyContext::alwaysAllowResponse(Http::StatusCode sline
) const
1356 case Http::scContinue
:
1358 case Http::scSwitchingProtocols
:
1360 case Http::scProcessing
:
1362 case Http::scNoContent
:
1364 case Http::scNotModified
:
1376 * Generate the reply headers sent to client.
1378 * Filters out unwanted entries and hop-by-hop from original reply header
1379 * then adds extra entries if we have more info than origin server
1380 * then adds Squid specific entries
1383 clientReplyContext::buildReplyHeader()
1385 HttpHeader
*hdr
= &reply
->header
;
1386 const bool is_hit
= http
->logType
.isTcpHit();
1387 HttpRequest
*request
= http
->request
;
1388 #if DONT_FILTER_THESE
1389 /* but you might want to if you run Squid as an HTTP accelerator */
1390 /* hdr->delById(HDR_ACCEPT_RANGES); */
1391 hdr
->delById(HDR_ETAG
);
1394 if (is_hit
|| collapsedRevalidation
== crSlave
)
1395 hdr
->delById(Http::HdrType::SET_COOKIE
);
1396 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
1398 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
1399 // remove the Proxy-Authenticate header
1400 if ( !request
->peer_login
|| (strcmp(request
->peer_login
,"PASS") != 0 && strcmp(request
->peer_login
,"PASSTHRU") != 0)) {
1402 // but allow adaptation services to authenticate clients
1403 // via request satisfaction
1404 if (!http
->requestSatisfactionMode())
1406 reply
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1409 reply
->header
.removeHopByHopEntries();
1411 // if (request->range)
1412 // clientBuildRangeHeader(http, reply);
1415 * Add a estimated Age header on cache hits.
1419 * Remove any existing Age header sent by upstream caches
1420 * (note that the existing header is passed along unmodified
1423 hdr
->delById(Http::HdrType::AGE
);
1425 * This adds the calculated object age. Note that the details of the
1426 * age calculation is performed by adjusting the timestamp in
1427 * StoreEntry::timestampsSet(), not here.
1429 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
1430 hdr
->delById(Http::HdrType::DATE
);
1431 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1432 } else if (http
->getConn() && http
->getConn()->port
->actAsOrigin
) {
1433 // Swap the Date: header to current time if we are simulating an origin
1434 HttpHeaderEntry
*h
= hdr
->findEntry(Http::HdrType::DATE
);
1436 hdr
->putExt("X-Origin-Date", h
->value
.termedBuf());
1437 hdr
->delById(Http::HdrType::DATE
);
1438 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1439 h
= hdr
->findEntry(Http::HdrType::EXPIRES
);
1440 if (h
&& http
->storeEntry()->expires
>= 0) {
1441 hdr
->putExt("X-Origin-Expires", h
->value
.termedBuf());
1442 hdr
->delById(Http::HdrType::EXPIRES
);
1443 hdr
->putTime(Http::HdrType::EXPIRES
, squid_curtime
+ http
->storeEntry()->expires
- http
->storeEntry()->timestamp
);
1445 if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1446 // put X-Cache-Age: instead of Age:
1448 snprintf(age
, sizeof(age
), "%" PRId64
, static_cast<int64_t>(squid_curtime
- http
->storeEntry()->timestamp
));
1449 hdr
->putExt("X-Cache-Age", age
);
1451 } else if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1452 hdr
->putInt(Http::HdrType::AGE
,
1453 squid_curtime
- http
->storeEntry()->timestamp
);
1454 /* Signal old objects. NB: rfc 2616 is not clear,
1455 * by implication, on whether we should do this to all
1456 * responses, or only cache hits.
1457 * 14.46 states it ONLY applys for heuristically caclulated
1458 * freshness values, 13.2.4 doesn't specify the same limitation.
1459 * We interpret RFC 2616 under the combination.
1461 /* TODO: if maxage or s-maxage is present, don't do this */
1463 if (squid_curtime
- http
->storeEntry()->timestamp
>= 86400) {
1465 snprintf (tbuf
, sizeof(tbuf
), "%s %s %s",
1467 "This cache hit is still fresh and more than 1 day old");
1468 hdr
->putStr(Http::HdrType::WARNING
, tbuf
);
1473 /* RFC 2616: Section 14.18
1475 * Add a Date: header if missing.
1476 * We have access to a clock therefore are required to amend any shortcoming in servers.
1478 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1480 if ( !hdr
->has(Http::HdrType::DATE
) ) {
1481 if (!http
->storeEntry())
1482 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1483 else if (http
->storeEntry()->timestamp
> 0)
1484 hdr
->putTime(Http::HdrType::DATE
, http
->storeEntry()->timestamp
);
1486 debugs(88,DBG_IMPORTANT
,"BUG 3279: HTTP reply without Date:");
1487 /* dump something useful about the problem */
1488 http
->storeEntry()->dump(DBG_IMPORTANT
);
1492 // add Warnings required by RFC 2616 if serving a stale hit
1493 if (http
->request
->flags
.staleIfHit
&& http
->logType
.isTcpHit()) {
1494 hdr
->putWarning(110, "Response is stale");
1495 if (http
->request
->flags
.needValidation
)
1496 hdr
->putWarning(111, "Revalidation failed");
1499 /* Filter unproxyable authentication types */
1500 if (http
->logType
.oldType
!= LOG_TCP_DENIED
&&
1501 hdr
->has(Http::HdrType::WWW_AUTHENTICATE
)) {
1502 HttpHeaderPos pos
= HttpHeaderInitPos
;
1505 int connection_auth_blocked
= 0;
1506 while ((e
= hdr
->getEntry(&pos
))) {
1507 if (e
->id
== Http::HdrType::WWW_AUTHENTICATE
) {
1508 const char *value
= e
->value
.rawBuf();
1510 if ((strncasecmp(value
, "NTLM", 4) == 0 &&
1511 (value
[4] == '\0' || value
[4] == ' '))
1513 (strncasecmp(value
, "Negotiate", 9) == 0 &&
1514 (value
[9] == '\0' || value
[9] == ' '))
1516 (strncasecmp(value
, "Kerberos", 8) == 0 &&
1517 (value
[8] == '\0' || value
[8] == ' '))) {
1518 if (request
->flags
.connectionAuthDisabled
) {
1519 hdr
->delAt(pos
, connection_auth_blocked
);
1522 request
->flags
.mustKeepalive
= true;
1523 if (!request
->flags
.accelerated
&& !request
->flags
.intercepted
) {
1524 httpHeaderPutStrf(hdr
, Http::HdrType::PROXY_SUPPORT
, "Session-Based-Authentication");
1526 We send "Connection: Proxy-Support" header to mark
1527 Proxy-Support as a hop-by-hop header for intermediaries that do not
1528 understand the semantics of this header. The RFC should have included
1529 this recommendation.
1531 httpHeaderPutStrf(hdr
, Http::HdrType::CONNECTION
, "Proxy-support");
1538 if (connection_auth_blocked
)
1543 /* Handle authentication headers */
1544 if (http
->logType
.oldType
== LOG_TCP_DENIED
&&
1545 ( reply
->sline
.status() == Http::scProxyAuthenticationRequired
||
1546 reply
->sline
.status() == Http::scUnauthorized
)
1548 /* Add authentication header */
1549 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1550 * depends on authenticate behaviour: all schemes to date send no extra
1551 * data on 407/401 responses, and do not check the accel state on 401/407
1554 Auth::UserRequest::AddReplyAuthHeader(reply
, request
->auth_user_request
, request
, 0, 1);
1555 } else if (request
->auth_user_request
!= NULL
)
1556 Auth::UserRequest::AddReplyAuthHeader(reply
, request
->auth_user_request
, request
, http
->flags
.accel
, 0);
1559 /* Append X-Cache */
1560 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE
, "%s from %s",
1561 is_hit
? "HIT" : "MISS", getMyHostname());
1563 #if USE_CACHE_DIGESTS
1564 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1565 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE_LOOKUP
, "%s from %s:%d",
1566 lookup_type
? lookup_type
: "NONE",
1567 getMyHostname(), getMyPort());
1571 const bool maySendChunkedReply
= !request
->multipartRangeRequest() &&
1572 reply
->sline
.protocol
== AnyP::PROTO_HTTP
&& // response is HTTP
1573 (request
->http_ver
>= Http::ProtocolVersion(1,1));
1575 /* Check whether we should send keep-alive */
1576 if (!Config
.onoff
.error_pconns
&& reply
->sline
.status() >= 400 && !request
->flags
.mustKeepalive
) {
1577 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
1578 request
->flags
.proxyKeepalive
= false;
1579 } else if (!Config
.onoff
.client_pconns
&& !request
->flags
.mustKeepalive
) {
1580 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
1581 request
->flags
.proxyKeepalive
= false;
1582 } else if (request
->flags
.proxyKeepalive
&& shutting_down
) {
1583 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
1584 request
->flags
.proxyKeepalive
= false;
1585 } else if (request
->flags
.connectionAuth
&& !reply
->keep_alive
) {
1586 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
1587 request
->flags
.proxyKeepalive
= false;
1588 } else if (reply
->bodySize(request
->method
) < 0 && !maySendChunkedReply
) {
1589 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
1590 request
->flags
.proxyKeepalive
= false;
1591 } else if (fdUsageHigh()&& !request
->flags
.mustKeepalive
) {
1592 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
1593 request
->flags
.proxyKeepalive
= false;
1594 } else if (request
->flags
.sslBumped
&& !reply
->persistent()) {
1595 // We do not really have to close, but we pretend we are a tunnel.
1596 debugs(88, 3, "clientBuildReplyHeader: bumped reply forces close");
1597 request
->flags
.proxyKeepalive
= false;
1598 } else if (request
->pinnedConnection() && !reply
->persistent()) {
1599 // The peer wants to close the pinned connection
1600 debugs(88, 3, "pinned reply forces close");
1601 request
->flags
.proxyKeepalive
= false;
1602 } else if (http
->getConn()) {
1603 ConnStateData
* conn
= http
->getConn();
1604 if (!Comm::IsConnOpen(conn
->port
->listenConn
)) {
1605 // The listening port closed because of a reconfigure
1606 debugs(88, 3, "listening port closed");
1607 request
->flags
.proxyKeepalive
= false;
1611 // Decide if we send chunked reply
1612 if (maySendChunkedReply
&& reply
->bodySize(request
->method
) < 0) {
1613 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
1614 request
->flags
.chunkedReply
= true;
1615 hdr
->putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
1618 hdr
->addVia(reply
->sline
.version
);
1620 /* Signal keep-alive or close explicitly */
1621 hdr
->putStr(Http::HdrType::CONNECTION
, request
->flags
.proxyKeepalive
? "keep-alive" : "close");
1623 #if ADD_X_REQUEST_URI
1625 * Knowing the URI of the request is useful when debugging persistent
1626 * connections in a client; we cannot guarantee the order of http headers,
1627 * but X-Request-URI is likely to be the very last header to ease use from a
1628 * debugger [hdr->entries.count-1].
1630 hdr
->putStr(Http::HdrType::X_REQUEST_URI
,
1631 http
->memOjbect()->url
? http
->memObject()->url
: http
->uri
);
1635 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1636 if ( hdr
->has(Http::HdrType::SURROGATE_CONTROL
) ) {
1637 if (!request
->header
.has(Http::HdrType::SURROGATE_CAPABILITY
)) {
1638 hdr
->delById(Http::HdrType::SURROGATE_CONTROL
);
1640 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1643 httpHdrMangleList(hdr
, request
, http
->al
, ROR_REPLY
);
1647 clientReplyContext::cloneReply()
1649 assert(reply
== NULL
);
1651 reply
= http
->storeEntry()->getReply()->clone();
1654 if (reply
->sline
.protocol
== AnyP::PROTO_HTTP
) {
1655 /* RFC 2616 requires us to advertise our version (but only on real HTTP traffic) */
1656 reply
->sline
.version
= Http::ProtocolVersion();
1659 /* do header conversions */
1663 /// Safely disposes of an entry pointing to a cache hit that we do not want.
1664 /// We cannot just ignore the entry because it may be locking or otherwise
1665 /// holding an associated cache resource of some sort.
1667 clientReplyContext::forgetHit()
1669 StoreEntry
*e
= http
->storeEntry();
1670 assert(e
); // or we are not dealing with a hit
1671 // We probably have not locked the entry earlier, unfortunately. We lock it
1672 // now so that we can unlock two lines later (and trigger cleanup).
1673 // Ideally, ClientHttpRequest::storeEntry() should lock/unlock, but it is
1674 // used so inconsistently that simply adding locking there leads to bugs.
1675 e
->lock("clientReplyContext::forgetHit");
1676 http
->storeEntry(NULL
);
1677 e
->unlock("clientReplyContext::forgetHit"); // may delete e
1681 clientReplyContext::identifyStoreObject()
1683 HttpRequest
*r
= http
->request
;
1685 // client sent CC:no-cache or some other condition has been
1686 // encountered which prevents delivering a public/cached object.
1687 if (!r
->flags
.noCache
|| r
->flags
.internal
) {
1688 lookingforstore
= 5;
1689 StoreEntry::getPublicByRequest (this, r
);
1691 identifyFoundObject (NullStoreEntry::getInstance());
1696 * Check state of the current StoreEntry object.
1697 * to see if we can determine the final status of the request.
1700 clientReplyContext::identifyFoundObject(StoreEntry
*newEntry
)
1702 StoreEntry
*e
= newEntry
;
1703 HttpRequest
*r
= http
->request
;
1705 /** \li If the entry received isNull() then we ignore it. */
1707 http
->storeEntry(NULL
);
1709 http
->storeEntry(e
);
1712 e
= http
->storeEntry();
1714 /* Release IP-cache entries on reload */
1715 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
1716 * 'invalidate' the cached IP entries for this request ???
1718 if (r
->flags
.noCache
|| r
->flags
.noCacheHack())
1719 ipcacheInvalidateNegative(r
->url
.host());
1721 #if USE_CACHE_DIGESTS
1722 lookup_type
= http
->storeEntry() ? "HIT" : "MISS";
1725 if (NULL
== http
->storeEntry()) {
1726 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
1727 debugs(85, 3, "StoreEntry is NULL - MISS");
1728 http
->logType
= LOG_TCP_MISS
;
1733 if (Config
.onoff
.offline
) {
1734 /** \li If we are running in offline mode set to HIT */
1735 debugs(85, 3, "offline HIT " << *e
);
1736 http
->logType
= LOG_TCP_HIT
;
1741 if (http
->redirect
.status
) {
1742 /** \li If redirection status is True force this to be a MISS */
1743 debugs(85, 3, "REDIRECT status forced StoreEntry to NULL (no body on 3XX responses) " << *e
);
1745 http
->logType
= LOG_TCP_REDIRECT
;
1750 if (!e
->validToSend()) {
1751 debugs(85, 3, "!storeEntryValidToSend MISS " << *e
);
1753 http
->logType
= LOG_TCP_MISS
;
1758 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1759 /* \li Special entries are always hits, no matter what the client says */
1760 debugs(85, 3, "ENTRY_SPECIAL HIT " << *e
);
1761 http
->logType
= LOG_TCP_HIT
;
1766 if (r
->flags
.noCache
) {
1767 debugs(85, 3, "no-cache REFRESH MISS " << *e
);
1769 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
1774 debugs(85, 3, "default HIT " << *e
);
1775 http
->logType
= LOG_TCP_HIT
;
1780 * Request more data from the store for the client Stream
1781 * This is *the* entry point to this module.
1784 * - This is the head of the list.
1785 * - There is at least one more node.
1786 * - Data context is not null
1789 clientGetMoreData(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1791 /* Test preconditions */
1792 assert(aNode
!= NULL
);
1793 assert(cbdataReferenceValid(aNode
));
1794 assert(aNode
->node
.prev
== NULL
);
1795 assert(aNode
->node
.next
!= NULL
);
1796 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1798 assert(context
->http
== http
);
1800 clientStreamNode
*next
= ( clientStreamNode
*)aNode
->node
.next
->data
;
1802 if (!context
->ourNode
)
1803 context
->ourNode
= aNode
;
1805 /* no cbdatareference, this is only used once, and safely */
1806 if (context
->flags
.storelogiccomplete
) {
1807 StoreIOBuffer tempBuffer
;
1808 tempBuffer
.offset
= next
->readBuffer
.offset
+ context
->headers_sz
;
1809 tempBuffer
.length
= next
->readBuffer
.length
;
1810 tempBuffer
.data
= next
->readBuffer
.data
;
1812 storeClientCopy(context
->sc
, http
->storeEntry(),
1813 tempBuffer
, clientReplyContext::SendMoreData
, context
);
1817 if (context
->http
->request
->method
== Http::METHOD_PURGE
) {
1818 context
->purgeRequest();
1822 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
1824 if (context
->http
->request
->method
== Http::METHOD_TRACE
) {
1825 if (context
->http
->request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0) {
1826 context
->traceReply(aNode
);
1830 /* continue forwarding, not finished yet. */
1831 http
->logType
= LOG_TCP_MISS
;
1833 context
->doGetMoreData();
1835 context
->identifyStoreObject();
1839 clientReplyContext::doGetMoreData()
1841 /* We still have to do store logic processing - vary, cache hit etc */
1842 if (http
->storeEntry() != NULL
) {
1843 /* someone found the object in the cache for us */
1844 StoreIOBuffer localTempBuffer
;
1846 http
->storeEntry()->lock("clientReplyContext::doGetMoreData");
1848 MemObject
*mem_obj
= http
->storeEntry()->makeMemObject();
1849 if (!mem_obj
->hasUris()) {
1851 * This if-block exists because we don't want to clobber
1852 * a preexiting mem_obj->method value if the mem_obj
1853 * already exists. For example, when a HEAD request
1854 * is a cache hit for a GET response, we want to keep
1855 * the method as GET.
1857 mem_obj
->setUris(storeId(), http
->log_uri
, http
->request
->method
);
1859 * Here we can see if the object was
1860 * created using URL or alternative StoreID from helper.
1862 debugs(88, 3, "storeId: " << http
->storeEntry()->mem_obj
->storeId());
1865 sc
= storeClientListAdd(http
->storeEntry(), this);
1867 sc
->setDelayId(DelayId::DelayClient(http
));
1870 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
1872 /* guarantee nothing has been sent yet! */
1873 assert(http
->out
.size
== 0);
1874 assert(http
->out
.offset
== 0);
1876 if (ConnStateData
*conn
= http
->getConn()) {
1877 if (Ip::Qos::TheConfig
.isHitTosActive()) {
1878 Ip::Qos::doTosLocalHit(conn
->clientConnection
);
1881 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
1882 Ip::Qos::doNfmarkLocalHit(conn
->clientConnection
);
1886 localTempBuffer
.offset
= reqofs
;
1887 localTempBuffer
.length
= getNextNode()->readBuffer
.length
;
1888 localTempBuffer
.data
= getNextNode()->readBuffer
.data
;
1889 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, CacheHit
, this);
1891 /* MISS CASE, http->logType is already set! */
1896 /** The next node has removed itself from the stream. */
1898 clientReplyDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1900 /** detach from the stream */
1901 clientStreamDetach(node
, http
);
1905 * Accepts chunk of a http message in buf, parses prefix, filters headers and
1906 * such, writes processed message to the message recipient
1909 clientReplyContext::SendMoreData(void *data
, StoreIOBuffer result
)
1911 clientReplyContext
*context
= static_cast<clientReplyContext
*>(data
);
1912 context
->sendMoreData (result
);
1916 clientReplyContext::makeThisHead()
1918 /* At least, I think thats what this does */
1919 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1920 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1924 clientReplyContext::errorInStream(StoreIOBuffer
const &result
, size_t const &sizeToProcess
)const
1926 return /* aborted request */
1927 (http
->storeEntry() && EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) ||
1928 /* Upstream read error */ (result
.flags
.error
) ||
1929 /* Upstream EOF */ (sizeToProcess
== 0);
1933 clientReplyContext::sendStreamError(StoreIOBuffer
const &result
)
1935 /** call clientWriteComplete so the client socket gets closed
1937 * We call into the stream, because we don't know that there is a
1940 debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.");
1941 StoreIOBuffer localTempBuffer
;
1943 http
->request
->flags
.streamError
= true;
1944 localTempBuffer
.flags
.error
= result
.flags
.error
;
1945 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1950 clientReplyContext::pushStreamData(StoreIOBuffer
const &result
, char *source
)
1952 StoreIOBuffer localTempBuffer
;
1954 if (result
.length
== 0) {
1955 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
1959 assert(result
.offset
- headers_sz
== next()->readBuffer
.offset
);
1960 localTempBuffer
.offset
= result
.offset
- headers_sz
;
1961 localTempBuffer
.length
= result
.length
;
1963 if (localTempBuffer
.length
)
1964 localTempBuffer
.data
= source
;
1966 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1971 clientReplyContext::next() const
1973 assert ( (clientStreamNode
*)http
->client_stream
.head
->next
->data
== getNextNode());
1974 return getNextNode();
1978 clientReplyContext::sendBodyTooLargeError()
1980 Ip::Address tmp_noaddr
;
1981 tmp_noaddr
.setNoAddr(); // TODO: make a global const
1982 http
->logType
= LOG_TCP_DENIED_REPLY
;
1983 ErrorState
*err
= clientBuildError(ERR_TOO_BIG
, Http::scForbidden
, NULL
,
1984 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
1986 removeClientStoreReference(&(sc
), http
);
1987 HTTPMSGUNLOCK(reply
);
1992 /// send 412 (Precondition Failed) to client
1994 clientReplyContext::sendPreconditionFailedError()
1996 http
->logType
= LOG_TCP_HIT
;
1997 Ip::Address tmp_noaddr
;
1998 tmp_noaddr
.setNoAddr();
1999 ErrorState
*const err
=
2000 clientBuildError(ERR_PRECONDITION_FAILED
, Http::scPreconditionFailed
,
2001 NULL
, http
->getConn() ? http
->getConn()->clientConnection
->remote
: tmp_noaddr
, http
->request
);
2002 removeClientStoreReference(&sc
, http
);
2003 HTTPMSGUNLOCK(reply
);
2007 /// send 304 (Not Modified) to client
2009 clientReplyContext::sendNotModified()
2011 StoreEntry
*e
= http
->storeEntry();
2012 const time_t timestamp
= e
->timestamp
;
2013 HttpReply
*const temprep
= e
->getReply()->make304();
2014 // log as TCP_INM_HIT if code 304 generated for
2015 // If-None-Match request
2016 if (!http
->request
->flags
.ims
)
2017 http
->logType
= LOG_TCP_INM_HIT
;
2019 http
->logType
= LOG_TCP_IMS_HIT
;
2020 removeClientStoreReference(&sc
, http
);
2021 createStoreEntry(http
->request
->method
, RequestFlags());
2022 e
= http
->storeEntry();
2023 // Copy timestamp from the original entry so the 304
2024 // reply has a meaningful Age: header.
2026 e
->timestamp
= timestamp
;
2027 e
->replaceHttpReply(temprep
);
2030 * TODO: why put this in the store and then serialise it and
2031 * then parse it again. Simply mark the request complete in
2032 * our context and write the reply struct to the client side.
2034 triggerInitialStoreRead();
2037 /// send 304 (Not Modified) or 412 (Precondition Failed) to client
2038 /// depending on request method
2040 clientReplyContext::sendNotModifiedOrPreconditionFailedError()
2042 if (http
->request
->method
== Http::METHOD_GET
||
2043 http
->request
->method
== Http::METHOD_HEAD
)
2046 sendPreconditionFailedError();
2050 clientReplyContext::processReplyAccess ()
2052 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
2055 /** Don't block our own responses or HTTP status messages */
2056 if (http
->logType
.oldType
== LOG_TCP_DENIED
||
2057 http
->logType
.oldType
== LOG_TCP_DENIED_REPLY
||
2058 alwaysAllowResponse(reply
->sline
.status())) {
2059 headers_sz
= reply
->hdr_sz
;
2060 processReplyAccessResult(ACCESS_ALLOWED
);
2064 /** Check for reply to big error */
2065 if (reply
->expectedBodyTooLarge(*http
->request
)) {
2066 sendBodyTooLargeError();
2070 headers_sz
= reply
->hdr_sz
;
2072 /** check for absent access controls (permit by default) */
2073 if (!Config
.accessList
.reply
) {
2074 processReplyAccessResult(ACCESS_ALLOWED
);
2078 /** Process http_reply_access lists */
2079 ACLFilledChecklist
*replyChecklist
=
2080 clientAclChecklistCreate(Config
.accessList
.reply
, http
);
2081 replyChecklist
->reply
= reply
;
2082 HTTPMSGLOCK(replyChecklist
->reply
);
2083 replyChecklist
->nonBlockingCheck(ProcessReplyAccessResult
, this);
2087 clientReplyContext::ProcessReplyAccessResult(allow_t rv
, void *voidMe
)
2089 clientReplyContext
*me
= static_cast<clientReplyContext
*>(voidMe
);
2090 me
->processReplyAccessResult(rv
);
2094 clientReplyContext::processReplyAccessResult(const allow_t
&accessAllowed
)
2096 debugs(88, 2, "The reply for " << http
->request
->method
2097 << ' ' << http
->uri
<< " is " << accessAllowed
<< ", because it matched "
2098 << (AclMatchedName
? AclMatchedName
: "NO ACL's"));
2100 if (!accessAllowed
.allowed()) {
2103 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, 1);
2105 http
->logType
= LOG_TCP_DENIED_REPLY
;
2107 if (page_id
== ERR_NONE
)
2108 page_id
= ERR_ACCESS_DENIED
;
2110 Ip::Address tmp_noaddr
;
2111 tmp_noaddr
.setNoAddr();
2112 err
= clientBuildError(page_id
, Http::scForbidden
, NULL
,
2113 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
2116 removeClientStoreReference(&sc
, http
);
2118 HTTPMSGUNLOCK(reply
);
2125 /* Ok, the reply is allowed, */
2126 http
->loggingEntry(http
->storeEntry());
2128 ssize_t body_size
= reqofs
- reply
->hdr_sz
;
2129 if (body_size
< 0) {
2130 reqofs
= reply
->hdr_sz
;
2134 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
2135 (int) body_size
<< " bytes after " << reply
->hdr_sz
<<
2136 " bytes of headers");
2140 if (http
->flags
.accel
&& reply
->sline
.status() != Http::scForbidden
&&
2141 !alwaysAllowResponse(reply
->sline
.status()) &&
2142 esiEnableProcessing(reply
)) {
2143 debugs(88, 2, "Enabling ESI processing for " << http
->uri
);
2144 clientStreamInsertHead(&http
->client_stream
, esiStreamRead
,
2145 esiProcessStream
, esiStreamDetach
, esiStreamStatus
, NULL
);
2150 if (http
->request
->method
== Http::METHOD_HEAD
) {
2151 /* do not forward body for HEAD replies */
2153 http
->flags
.done_copying
= true;
2157 assert (!flags
.headersSent
);
2158 flags
.headersSent
= true;
2160 StoreIOBuffer localTempBuffer
;
2161 char *buf
= next()->readBuffer
.data
;
2162 char *body_buf
= buf
+ reply
->hdr_sz
;
2164 //Server side may disable ranges under some circumstances.
2166 if ((!http
->request
->range
))
2167 next()->readBuffer
.offset
= 0;
2169 body_buf
-= next()->readBuffer
.offset
;
2171 if (next()->readBuffer
.offset
!= 0) {
2172 if (next()->readBuffer
.offset
> body_size
) {
2173 /* Can't use any of the body we received. send nothing */
2174 localTempBuffer
.length
= 0;
2175 localTempBuffer
.data
= NULL
;
2177 localTempBuffer
.length
= body_size
- next()->readBuffer
.offset
;
2178 localTempBuffer
.data
= body_buf
+ next()->readBuffer
.offset
;
2181 localTempBuffer
.length
= body_size
;
2182 localTempBuffer
.data
= body_buf
;
2185 /* TODO??: move the data in the buffer back by the request header size */
2186 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
,
2187 http
, reply
, localTempBuffer
);
2193 clientReplyContext::sendMoreData (StoreIOBuffer result
)
2198 StoreEntry
*entry
= http
->storeEntry();
2200 if (ConnStateData
* conn
= http
->getConn()) {
2201 if (!conn
->isOpen()) {
2202 debugs(33,3, "not sending more data to closing connection " << conn
->clientConnection
);
2205 if (conn
->pinning
.zeroReply
) {
2206 debugs(33,3, "not sending more data after a pinned zero reply " << conn
->clientConnection
);
2210 if (reqofs
==0 && !http
->logType
.isTcpHit()) {
2211 if (Ip::Qos::TheConfig
.isHitTosActive()) {
2212 Ip::Qos::doTosLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2214 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
2215 Ip::Qos::doNfmarkLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2219 debugs(88, 5, conn
->clientConnection
<<
2220 " '" << entry
->url() << "'" <<
2221 " out.offset=" << http
->out
.offset
);
2224 char *buf
= next()->readBuffer
.data
;
2226 if (buf
!= result
.data
) {
2227 /* we've got to copy some data */
2228 assert(result
.length
<= next()->readBuffer
.length
);
2229 memcpy(buf
, result
.data
, result
.length
);
2232 /* We've got the final data to start pushing... */
2233 flags
.storelogiccomplete
= 1;
2235 reqofs
+= result
.length
;
2237 assert(reqofs
<= HTTP_REQBUF_SZ
|| flags
.headersSent
);
2239 assert(http
->request
!= NULL
);
2241 /* ESI TODO: remove this assert once everything is stable */
2242 assert(http
->client_stream
.head
->data
2243 && cbdataReferenceValid(http
->client_stream
.head
->data
));
2247 debugs(88, 5, "clientReplyContext::sendMoreData: " << http
->uri
<< ", " <<
2248 reqofs
<< " bytes (" << result
.length
<<
2251 /* update size of the request */
2254 if (errorInStream(result
, reqofs
)) {
2255 sendStreamError(result
);
2259 if (flags
.headersSent
) {
2260 pushStreamData (result
, buf
);
2268 sc
->setDelayId(DelayId::DelayClient(http
,reply
));
2271 /* handle headers */
2273 if (Config
.onoff
.log_mime_hdrs
) {
2276 if ((k
= headersEnd(buf
, reqofs
))) {
2277 safe_free(http
->al
->headers
.reply
);
2278 http
->al
->headers
.reply
= (char *)xcalloc(k
+ 1, 1);
2279 xstrncpy(http
->al
->headers
.reply
, buf
, k
);
2283 holdingBuffer
= result
;
2284 processReplyAccess();
2288 /* Using this breaks the client layering just a little!
2291 clientReplyContext::createStoreEntry(const HttpRequestMethod
& m
, RequestFlags reqFlags
)
2293 assert(http
!= NULL
);
2295 * For erroneous requests, we might not have a h->request,
2296 * so make a fake one.
2299 if (http
->request
== NULL
) {
2300 const MasterXaction::Pointer mx
= new MasterXaction(XactionInitiator::initClient
);
2301 http
->request
= new HttpRequest(m
, AnyP::PROTO_NONE
, "http", null_string
, mx
);
2302 HTTPMSGLOCK(http
->request
);
2305 StoreEntry
*e
= storeCreateEntry(storeId(), http
->log_uri
, reqFlags
, m
);
2307 // Make entry collapsable ASAP, to increase collapsing chances for others,
2308 // TODO: every must-revalidate and similar request MUST reach the origin,
2309 // but do we have to prohibit others from collapsing on that request?
2310 if (Config
.onoff
.collapsed_forwarding
&& reqFlags
.cachable
&&
2311 !reqFlags
.needValidation
&&
2312 (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
)) {
2313 // make the entry available for future requests now
2314 Store::Root().allowCollapsing(e
, reqFlags
, m
);
2317 sc
= storeClientListAdd(e
, this);
2320 sc
->setDelayId(DelayId::DelayClient(http
));
2327 /* I don't think this is actually needed! -- adrian */
2328 /* http->reqbuf = http->norm_reqbuf; */
2329 // assert(http->reqbuf == http->norm_reqbuf);
2330 /* The next line is illegal because we don't know if the client stream
2331 * buffers have been set up
2333 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2334 // SendMoreData, this);
2335 /* So, we mark the store logic as complete */
2336 flags
.storelogiccomplete
= 1;
2338 /* and get the caller to request a read, from whereever they are */
2339 /* NOTE: after ANY data flows down the pipe, even one step,
2340 * this function CAN NOT be used to manage errors
2342 http
->storeEntry(e
);
2346 clientBuildError(err_type page_id
, Http::StatusCode status
, char const *url
,
2347 Ip::Address
&src_addr
, HttpRequest
* request
)
2349 ErrorState
*err
= new ErrorState(page_id
, status
, request
);
2350 err
->src_addr
= src_addr
;
2353 err
->url
= xstrdup(url
);