2 * Copyright (C) 1996-2025 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 "clientStream.h"
17 #include "errorpage.h"
21 #include "format/Token.h"
24 #include "HeaderMangling.h"
25 #include "http/Stream.h"
26 #include "HttpHeaderTools.h"
27 #include "HttpReply.h"
28 #include "HttpRequest.h"
29 #include "ip/QosConfig.h"
31 #include "log/access_log.h"
32 #include "MemObject.h"
33 #include "mime_header.h"
34 #include "neighbors.h"
36 #include "RequestFlags.h"
37 #include "SquidConfig.h"
38 #include "SquidMath.h"
43 #include "auth/UserRequest.h"
46 #include "DelayPools.h"
51 CBDATA_CLASS_INIT(clientReplyContext
);
54 CSS clientReplyStatus
;
55 ErrorState
*clientBuildError(err_type
, Http::StatusCode
, char const *, const ConnStateData
*, HttpRequest
*, const AccessLogEntry::Pointer
&);
59 clientReplyContext::~clientReplyContext()
62 /* This may trigger a callback back into SendMoreData as the cbdata
65 removeClientStoreReference(&sc
, http
);
66 /* old_entry might still be set if we didn't yet get the reply
67 * code in HandleIMSReply() */
68 removeStoreReference(&old_sc
, &old_entry
);
69 cbdataReferenceDone(http
);
73 clientReplyContext::clientReplyContext(ClientHttpRequest
*clientContext
) :
74 purgeStatus(Http::scNone
),
75 http(cbdataReference(clientContext
)),
83 collapsedRevalidation(crNone
)
88 /** Create an error in the store awaiting the client side to read it.
90 * This may be better placed in the clientStream logic, but it has not been
94 clientReplyContext::setReplyToError(
95 err_type err
, Http::StatusCode status
, char const *uri
,
96 const ConnStateData
*conn
, HttpRequest
*failedrequest
, const char *unparsedrequest
,
98 Auth::UserRequest::Pointer auth_user_request
104 auto errstate
= clientBuildError(err
, status
, uri
, conn
, failedrequest
, http
->al
);
107 errstate
->request_hdrs
= xstrdup(unparsedrequest
);
110 errstate
->auth_user_request
= auth_user_request
;
112 setReplyToError(failedrequest
? failedrequest
->method
: HttpRequestMethod(Http::METHOD_NONE
), errstate
);
115 void clientReplyContext::setReplyToError(const HttpRequestMethod
& method
, ErrorState
*errstate
)
117 if (errstate
->httpStatus
== Http::scNotImplemented
&& http
->request
)
118 /* prevent confusion over whether we default to persistent or not */
119 http
->request
->flags
.proxyKeepalive
= false;
121 http
->al
->http
.code
= errstate
->httpStatus
;
124 http
->request
->ignoreRange("responding with a Squid-generated error");
126 createStoreEntry(method
, RequestFlags());
127 assert(errstate
->callback_data
== nullptr);
128 errorAppendEntry(http
->storeEntry(), errstate
);
129 /* Now the caller reads to get this */
133 clientReplyContext::setReplyToReply(HttpReply
*futureReply
)
136 http
->al
->http
.code
= futureReply
->sline
.status();
138 HttpRequestMethod method
;
139 if (http
->request
) { // nil on responses to unparsable requests
140 http
->request
->ignoreRange("responding with a Squid-generated reply");
141 method
= http
->request
->method
;
144 createStoreEntry(method
, RequestFlags());
146 http
->storeEntry()->storeErrorResponse(futureReply
);
147 /* Now the caller reads to get futureReply */
150 // Assumes that the entry contains an error response without Content-Range.
151 // To use with regular entries, make HTTP Range header removal conditional.
152 void clientReplyContext::setReplyToStoreEntry(StoreEntry
*entry
, const char *reason
)
154 entry
->lock("clientReplyContext::setReplyToStoreEntry"); // removeClientStoreReference() unlocks
155 sc
= storeClientListAdd(entry
, this);
157 sc
->setDelayId(DelayId::DelayClient(http
));
160 http
->request
->ignoreRange(reason
);
161 flags
.storelogiccomplete
= 1;
162 http
->storeEntry(entry
);
166 clientReplyContext::removeStoreReference(store_client
** scp
,
170 store_client
*sc_tmp
= *scp
;
172 if ((e
= *ep
) != nullptr) {
174 storeUnregister(sc_tmp
, e
, this);
176 e
->unlock("clientReplyContext::removeStoreReference");
181 clientReplyContext::removeClientStoreReference(store_client
**scp
, ClientHttpRequest
*aHttpRequest
)
183 StoreEntry
*reference
= aHttpRequest
->storeEntry();
184 removeStoreReference(scp
, &reference
);
185 aHttpRequest
->storeEntry(reference
);
189 clientReplyContext::saveState()
191 assert(old_sc
== nullptr);
192 debugs(88, 3, "clientReplyContext::saveState: saving store context");
193 old_entry
= http
->storeEntry();
195 old_lastmod
= http
->request
->lastmod
;
196 old_etag
= http
->request
->etag
;
197 /* Prevent accessing the now saved entries */
198 http
->storeEntry(nullptr);
203 clientReplyContext::restoreState()
205 assert(old_sc
!= nullptr);
206 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
207 removeClientStoreReference(&sc
, http
);
208 http
->storeEntry(old_entry
);
210 http
->request
->lastmod
= old_lastmod
;
211 http
->request
->etag
= old_etag
;
212 /* Prevent accessed the old saved entries */
220 clientReplyContext::startError(ErrorState
* err
)
222 createStoreEntry(http
->request
->method
, RequestFlags());
223 triggerInitialStoreRead();
224 errorAppendEntry(http
->storeEntry(), err
);
228 clientReplyContext::getNextNode() const
230 return (clientStreamNode
*)ourNode
->node
.next
->data
;
233 /// Request HTTP response headers from Store, to be sent to the given recipient.
234 /// That recipient also gets zero, some, or all HTTP response body bytes (into
235 /// next()->readBuffer).
237 clientReplyContext::triggerInitialStoreRead(STCB recipient
)
239 Assure(recipient
!= HandleIMSReply
);
240 lastStreamBufferedBytes
= StoreIOBuffer(); // storeClientCopy(next()->readBuffer) invalidates
241 StoreIOBuffer
localTempBuffer (next()->readBuffer
.length
, 0, next()->readBuffer
.data
);
242 ::storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, recipient
, this);
245 /// Request HTTP response body bytes from Store into next()->readBuffer. This
246 /// method requests body bytes at readerBuffer.offset and, hence, it should only
247 /// be called after we triggerInitialStoreRead() and get the requested HTTP
248 /// response headers (using zero offset).
250 clientReplyContext::requestMoreBodyFromStore()
252 lastStreamBufferedBytes
= StoreIOBuffer(); // storeClientCopy(next()->readBuffer) invalidates
253 ::storeClientCopy(sc
, http
->storeEntry(), next()->readBuffer
, SendMoreData
, this);
256 /* there is an expired entry in the store.
257 * setup a temporary buffer area and perform an IMS to the origin
260 clientReplyContext::processExpired()
262 const char *url
= storeId();
263 debugs(88, 3, "clientReplyContext::processExpired: '" << http
->uri
<< "'");
264 const time_t lastmod
= http
->storeEntry()->lastModified();
265 assert(lastmod
>= 0);
267 * check if we are allowed to contact other servers
268 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
269 * a stale entry *if* it matches client requirements
272 if (http
->onlyIfCached()) {
273 processOnlyIfCachedMiss();
277 http
->updateLoggingTags(LOG_TCP_REFRESH
);
278 http
->request
->flags
.refresh
= true;
279 #if STORE_CLIENT_LIST_DEBUG
280 /* Prevent a race with the store client memory free routines
282 assert(storeClientIsThisAClient(sc
, this));
284 /* Prepare to make a new temporary request */
287 // TODO: Consider also allowing regular (non-collapsed) revalidation hits.
288 // TODO: support collapsed revalidation for Vary-controlled entries
289 bool collapsingAllowed
= Config
.onoff
.collapsed_forwarding
&&
290 !Store::Controller::SmpAware() &&
291 http
->request
->vary_headers
.isEmpty();
293 StoreEntry
*entry
= nullptr;
294 if (collapsingAllowed
) {
295 if (const auto e
= storeGetPublicByRequest(http
->request
, ksRevalidation
)) {
296 if (e
->hittingRequiresCollapsing() && startCollapsingOn(*e
, true)) {
298 entry
->lock("clientReplyContext::processExpired#alreadyRevalidating");
300 e
->abandon(__func__
);
301 // assume mayInitiateCollapsing() would fail too
302 collapsingAllowed
= false;
308 entry
->ensureMemObject(url
, http
->log_uri
, http
->request
->method
);
309 debugs(88, 5, "collapsed on existing revalidation entry: " << *entry
);
310 collapsedRevalidation
= crSlave
;
312 entry
= storeCreateEntry(url
,
313 http
->log_uri
, http
->request
->flags
, http
->request
->method
);
314 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
316 if (collapsingAllowed
&& mayInitiateCollapsing() &&
317 Store::Root().allowCollapsing(entry
, http
->request
->flags
, http
->request
->method
)) {
318 debugs(88, 5, "allow other revalidation requests to collapse on " << *entry
);
319 collapsedRevalidation
= crInitiator
;
321 collapsedRevalidation
= crNone
;
325 sc
= storeClientListAdd(entry
, this);
327 /* delay_id is already set on original store client */
328 sc
->setDelayId(DelayId::DelayClient(http
));
331 http
->request
->lastmod
= lastmod
;
333 if (!http
->request
->header
.has(Http::HdrType::IF_NONE_MATCH
)) {
334 ETag etag
= {nullptr, -1}; // TODO: make that a default ETag constructor
335 if (old_entry
->hasEtag(etag
) && !etag
.weak
)
336 http
->request
->etag
= etag
.str
;
339 debugs(88, 5, "lastmod " << entry
->lastModified());
340 http
->storeEntry(entry
);
341 assert(http
->out
.offset
== 0);
342 assert(http
->request
->clientConnectionManager
== http
->getConn());
344 if (collapsedRevalidation
!= crSlave
) {
346 * A refcounted pointer so that FwdState stays around as long as
347 * this clientReplyContext does
349 Comm::ConnectionPointer conn
= http
->getConn() != nullptr ? http
->getConn()->clientConnection
: nullptr;
350 FwdState::Start(conn
, http
->storeEntry(), http
->request
, http
->al
);
352 /* Register with storage manager to receive updates when data comes in. */
354 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
355 debugs(88, DBG_CRITICAL
, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
358 /* start counting the length from 0 */
359 StoreIOBuffer
localTempBuffer(HTTP_REQBUF_SZ
, 0, tempbuf
);
360 // keep lastStreamBufferedBytes: tempbuf is not a Client Stream buffer
361 ::storeClientCopy(sc
, entry
, localTempBuffer
, HandleIMSReply
, this);
366 clientReplyContext::sendClientUpstreamResponse(const StoreIOBuffer
&upstreamResponse
)
368 removeStoreReference(&old_sc
, &old_entry
);
370 if (collapsedRevalidation
)
371 http
->storeEntry()->clearPublicKeyScope();
373 /* here the data to send is the data we just received */
374 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
375 sendMoreData(upstreamResponse
);
379 clientReplyContext::HandleIMSReply(void *data
, StoreIOBuffer result
)
381 clientReplyContext
*context
= (clientReplyContext
*)data
;
382 context
->handleIMSReply(result
);
386 clientReplyContext::sendClientOldEntry()
388 /* Get the old request back */
391 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
392 debugs(88, 3, "stale entry aborted while we revalidated: " << *http
->storeEntry());
393 http
->updateLoggingTags(LOG_TCP_MISS
);
398 /* here the data to send is in the next nodes buffers already */
399 Assure(matchesStreamBodyBuffer(lastStreamBufferedBytes
));
400 Assure(!lastStreamBufferedBytes
.offset
);
401 sendMoreData(lastStreamBufferedBytes
);
404 /* This is the workhorse of the HandleIMSReply callback.
406 * It is called when we've got data back from the origin following our
407 * IMS request to revalidate a stale entry.
410 clientReplyContext::handleIMSReply(const StoreIOBuffer result
)
415 if (http
->storeEntry() == nullptr)
418 debugs(88, 3, http
->storeEntry()->url() << " got " << result
);
420 if (result
.flags
.error
&& !EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
))
423 if (collapsedRevalidation
== crSlave
&& !http
->storeEntry()->mayStartHitting()) {
424 debugs(88, 3, "CF slave hit private non-shareable " << *http
->storeEntry() << ". MISS");
425 // restore context to meet processMiss() expectations
427 http
->updateLoggingTags(LOG_TCP_MISS
);
432 // request to origin was aborted
433 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
434 debugs(88, 3, "request to origin aborted '" << http
->storeEntry()->url() << "', sending old entry to client");
435 http
->updateLoggingTags(LOG_TCP_REFRESH_FAIL_OLD
);
436 sendClientOldEntry();
440 const auto oldStatus
= old_entry
->mem().freshestReply().sline
.status();
441 const auto &new_rep
= http
->storeEntry()->mem().freshestReply();
442 const auto status
= new_rep
.sline
.status();
444 // XXX: Disregard stale incomplete (i.e. still being written) borrowed (i.e.
445 // not caused by our request) IMS responses. That new_rep may be very old!
447 // origin replied 304
448 if (status
== Http::scNotModified
) {
449 // TODO: The update may not be instantaneous. Should we wait for its
450 // completion to avoid spawning too much client-disassociated work?
451 if (!Store::Root().updateOnNotModified(old_entry
, *http
->storeEntry())) {
452 old_entry
->release(true);
454 http
->updateLoggingTags(LOG_TCP_MISS
);
459 http
->updateLoggingTags(LOG_TCP_REFRESH_UNMODIFIED
);
460 http
->request
->flags
.staleIfHit
= false; // old_entry is no longer stale
462 // if client sent IMS
463 if (http
->request
->flags
.ims
&& !old_entry
->modifiedSince(http
->request
->ims
, http
->request
->imslen
)) {
464 // forward the 304 from origin
465 debugs(88, 3, "origin replied 304, revalidated existing entry and forwarding 304 to client");
466 sendClientUpstreamResponse(result
);
470 // send existing entry, it's still valid
471 debugs(88, 3, "origin replied 304, revalidated existing entry and sending " << oldStatus
<< " to client");
472 sendClientOldEntry();
476 // origin replied with a non-error code
477 if (status
> Http::scNone
&& status
< Http::scInternalServerError
) {
478 // RFC 9111 section 4:
479 // "When more than one suitable response is stored,
480 // a cache MUST use the most recent one
481 // (as determined by the Date header field)."
482 if (new_rep
.olderThan(&old_entry
->mem().freshestReply())) {
483 http
->al
->cache
.code
.err
.ignored
= true;
484 debugs(88, 3, "origin replied " << status
<< " but with an older date header, sending old entry (" << oldStatus
<< ") to client");
485 sendClientOldEntry();
489 http
->updateLoggingTags(LOG_TCP_REFRESH_MODIFIED
);
490 debugs(88, 3, "origin replied " << status
<< ", forwarding to client");
491 sendClientUpstreamResponse(result
);
495 // origin replied with an error
496 if (http
->request
->flags
.failOnValidationError
) {
497 http
->updateLoggingTags(LOG_TCP_REFRESH_FAIL_ERR
);
498 debugs(88, 3, "origin replied with error " << status
<< ", forwarding to client due to fail_on_validation_err");
499 sendClientUpstreamResponse(result
);
503 // ignore and let client have old entry
504 http
->updateLoggingTags(LOG_TCP_REFRESH_FAIL_OLD
);
505 debugs(88, 3, "origin replied with error " << status
<< ", sending old entry (" << oldStatus
<< ") to client");
506 sendClientOldEntry();
509 CSR clientGetMoreData
;
510 CSD clientReplyDetach
;
512 /// \copydoc clientReplyContext::cacheHit()
514 clientReplyContext::CacheHit(void *data
, StoreIOBuffer result
)
516 clientReplyContext
*context
= (clientReplyContext
*)data
;
517 context
->cacheHit(result
);
520 /// Processes HTTP response headers received from Store on a suspected cache hit
521 /// path. May be called several times (e.g., a Vary marker object hit followed
522 /// by the corresponding variant hit).
524 clientReplyContext::cacheHit(const StoreIOBuffer result
)
526 /** Ignore if the HIT object is being deleted. */
528 debugs(88, 3, "HIT object being deleted. Ignore the HIT.");
532 StoreEntry
*e
= http
->storeEntry();
534 HttpRequest
*r
= http
->request
;
536 debugs(88, 3, http
->uri
<< " got " << result
);
538 if (http
->storeEntry() == nullptr) {
539 debugs(88, 3, "clientCacheHit: request aborted");
541 } else if (result
.flags
.error
) {
542 /* swap in failure */
543 debugs(88, 3, "clientCacheHit: swapin failure for " << http
->uri
);
544 http
->updateLoggingTags(LOG_TCP_SWAPFAIL_MISS
);
545 removeClientStoreReference(&sc
, http
);
550 // The previously identified hit suddenly became unshareable!
551 // This is common for collapsed forwarding slaves but might also
552 // happen to regular hits because we are called asynchronously.
553 if (!e
->mayStartHitting()) {
554 debugs(88, 3, "unshareable " << *e
<< ". MISS");
555 http
->updateLoggingTags(LOG_TCP_MISS
);
560 if (EBIT_TEST(e
->flags
, ENTRY_ABORTED
)) {
561 debugs(88, 3, "refusing aborted " << *e
);
562 http
->updateLoggingTags(LOG_TCP_MISS
);
568 * Got the headers, now grok them
570 assert(http
->loggingTags().oldType
== LOG_TCP_HIT
);
572 if (http
->request
->storeId().cmp(e
->mem_obj
->storeId()) != 0) {
573 debugs(33, DBG_IMPORTANT
, "clientProcessHit: URL mismatch, '" << e
->mem_obj
->storeId() << "' != '" << http
->request
->storeId() << "'");
574 http
->updateLoggingTags(LOG_TCP_MISS
); // we lack a more precise LOG_*_MISS code
579 noteStreamBufferredBytes(result
);
581 switch (varyEvaluateMatch(e
, r
)) {
584 /* No variance detected. Continue as normal */
588 /* This is the correct entity for this request. Continue */
589 debugs(88, 2, "clientProcessHit: Vary MATCH!");
593 /* This is not the correct entity for this request. We need
594 * to requery the cache.
596 removeClientStoreReference(&sc
, http
);
598 /* Note: varyEvalyateMatch updates the request with vary information
599 * so we only get here once. (it also takes care of cancelling loops)
601 debugs(88, 2, "clientProcessHit: Vary detected!");
602 clientGetMoreData(ourNode
, http
);
606 /* varyEvaluateMatch found a object loop. Process as miss */
607 debugs(88, DBG_IMPORTANT
, "clientProcessHit: Vary object loop!");
608 http
->updateLoggingTags(LOG_TCP_MISS
); // we lack a more precise LOG_*_MISS code
613 if (r
->method
== Http::METHOD_PURGE
) {
614 debugs(88, 5, "PURGE gets a HIT");
615 removeClientStoreReference(&sc
, http
);
621 if (e
->checkNegativeHit() && !r
->flags
.noCacheHack()) {
622 debugs(88, 5, "negative-HIT");
623 http
->updateLoggingTags(LOG_TCP_NEGATIVE_HIT
);
624 sendMoreData(result
);
626 } else if (blockedHit()) {
627 debugs(88, 5, "send_hit forces a MISS");
628 http
->updateLoggingTags(LOG_TCP_MISS
);
631 } else if (!r
->flags
.internal
&& !didCollapse
&& refreshCheckHTTP(e
, r
)) {
632 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
634 * We hold a stale copy; it needs to be validated
637 * The 'needValidation' flag is used to prevent forwarding
638 * loops between siblings. If our copy of the object is stale,
639 * then we should probably only use parents for the validation
640 * request. Otherwise two siblings could generate a loop if
641 * both have a stale version of the object.
643 r
->flags
.needValidation
= true;
645 if (e
->lastModified() < 0) {
646 debugs(88, 3, "validate HIT object? NO. Can't calculate entry modification time. Do MISS.");
648 * We cannot revalidate entries without knowing their
650 * XXX: BUG 1890 objects without Date do not get one added.
652 http
->updateLoggingTags(LOG_TCP_MISS
);
654 } else if (r
->flags
.noCache
) {
655 debugs(88, 3, "validate HIT object? NO. Client sent CC:no-cache. Do CLIENT_REFRESH_MISS");
657 * This did not match a refresh pattern that overrides no-cache
658 * we should honour the client no-cache header.
660 http
->updateLoggingTags(LOG_TCP_CLIENT_REFRESH_MISS
);
662 } else if (r
->url
.getScheme() == AnyP::PROTO_HTTP
|| r
->url
.getScheme() == AnyP::PROTO_HTTPS
) {
663 debugs(88, 3, "validate HIT object? YES.");
665 * Object needs to be revalidated
666 * XXX This could apply to FTP as well, if Last-Modified is known.
670 debugs(88, 3, "validate HIT object? NO. Client protocol non-HTTP. Do MISS.");
672 * We don't know how to re-validate other protocols. Handle
673 * them as if the object has expired.
675 http
->updateLoggingTags(LOG_TCP_MISS
);
679 } else if (r
->conditional()) {
680 debugs(88, 5, "conditional HIT");
681 if (processConditional())
686 * plain ol' cache hit
688 debugs(88, 5, "plain old HIT");
691 if (e
->store_status
!= STORE_OK
)
692 http
->updateLoggingTags(LOG_TCP_MISS
);
695 if (e
->mem_status
== IN_MEMORY
)
696 http
->updateLoggingTags(LOG_TCP_MEM_HIT
);
697 else if (Config
.onoff
.offline
)
698 http
->updateLoggingTags(LOG_TCP_OFFLINE_HIT
);
700 sendMoreData(result
);
704 * Prepare to fetch the object as it's a cache miss of some kind.
707 clientReplyContext::processMiss()
709 char *url
= http
->uri
;
710 HttpRequest
*r
= http
->request
;
711 ErrorState
*err
= nullptr;
712 debugs(88, 4, r
->method
<< ' ' << url
);
715 * We might have a left-over StoreEntry from a failed cache hit
718 if (http
->storeEntry()) {
719 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
720 debugs(88, DBG_CRITICAL
, "clientProcessMiss: miss on a special object (" << url
<< ").");
721 debugs(88, DBG_CRITICAL
, "\tlog_type = " << http
->loggingTags().c_str());
722 http
->storeEntry()->dump(1);
725 removeClientStoreReference(&sc
, http
);
728 /** Check if its a PURGE request to be actioned. */
729 if (r
->method
== Http::METHOD_PURGE
) {
734 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
735 if (r
->method
== Http::METHOD_OTHER
) {
739 /** Check if 'only-if-cached' flag is set. Action if so. */
740 if (http
->onlyIfCached()) {
741 processOnlyIfCachedMiss();
746 if (r
->flags
.loopDetected
) {
747 http
->al
->http
.code
= Http::scForbidden
;
748 err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, nullptr, http
->getConn(), http
->request
, http
->al
);
749 createStoreEntry(r
->method
, RequestFlags());
750 errorAppendEntry(http
->storeEntry(), err
);
751 triggerInitialStoreRead();
754 assert(http
->out
.offset
== 0);
755 createStoreEntry(r
->method
, r
->flags
);
756 triggerInitialStoreRead();
758 if (http
->redirect
.status
) {
759 const HttpReplyPointer
rep(new HttpReply
);
760 http
->updateLoggingTags(LOG_TCP_REDIRECT
);
761 http
->storeEntry()->releaseRequest();
762 rep
->redirect(http
->redirect
.status
, http
->redirect
.location
);
763 http
->storeEntry()->replaceHttpReply(rep
);
764 http
->storeEntry()->complete();
768 assert(r
->clientConnectionManager
== http
->getConn());
770 Comm::ConnectionPointer conn
= http
->getConn() != nullptr ? http
->getConn()->clientConnection
: nullptr;
771 /** Start forwarding to get the new object from network */
772 FwdState::Start(conn
, http
->storeEntry(), r
, http
->al
);
777 * client issued a request with an only-if-cached cache-control directive;
778 * we did not find a cached object that can be returned without
779 * contacting other servers;
780 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
783 clientReplyContext::processOnlyIfCachedMiss()
785 debugs(88, 4, http
->request
->method
<< ' ' << http
->uri
);
786 http
->al
->http
.code
= Http::scGatewayTimeout
;
787 ErrorState
*err
= clientBuildError(ERR_ONLY_IF_CACHED_MISS
, Http::scGatewayTimeout
, nullptr,
788 http
->getConn(), http
->request
, http
->al
);
789 removeClientStoreReference(&sc
, http
);
793 /// process conditional request from client
795 clientReplyContext::processConditional()
797 StoreEntry
*const e
= http
->storeEntry();
799 const auto replyStatusCode
= e
->mem().baseReply().sline
.status();
800 if (replyStatusCode
!= Http::scOkay
) {
801 debugs(88, 4, "miss because " << replyStatusCode
<< " != 200");
802 http
->updateLoggingTags(LOG_TCP_MISS
);
807 HttpRequest
&r
= *http
->request
;
809 if (r
.header
.has(Http::HdrType::IF_MATCH
) && !e
->hasIfMatchEtag(r
)) {
810 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
811 sendPreconditionFailedError();
815 if (r
.header
.has(Http::HdrType::IF_NONE_MATCH
)) {
816 // RFC 7232: If-None-Match recipient MUST ignore IMS
820 r
.header
.delById(Http::HdrType::IF_MODIFIED_SINCE
);
822 if (e
->hasIfNoneMatchEtag(r
)) {
823 sendNotModifiedOrPreconditionFailedError();
827 // None-Match is true (no ETag matched); treat as an unconditional hit
832 // handle If-Modified-Since requests from the client
833 if (e
->modifiedSince(r
.ims
, r
.imslen
)) {
834 // Modified-Since is true; treat as an unconditional hit
838 // otherwise reply with 304 Not Modified
847 /// whether squid.conf send_hit prevents us from serving this hit
849 clientReplyContext::blockedHit() const
851 if (!Config
.accessList
.sendHit
)
852 return false; // hits are not blocked by default
854 if (http
->request
->flags
.internal
)
855 return false; // internal content "hits" cannot be blocked
858 ACLFilledChecklist
chl(Config
.accessList
.sendHit
, nullptr);
859 clientAclChecklistFill(chl
, http
);
860 chl
.updateReply(&http
->storeEntry()->mem().freshestReply());
861 return !chl
.fastCheck().allowed(); // when in doubt, block
865 // Purges all entries with a given url
866 // TODO: move to SideAgent parent, when we have one
868 * We probably cannot purge Vary-affected responses because their MD5
869 * keys depend on vary headers.
872 purgeEntriesByUrl(HttpRequest
* req
, const char *url
)
874 for (HttpRequestMethod
m(Http::METHOD_NONE
); m
!= Http::METHOD_ENUM_END
; ++m
) {
875 if (m
.respMaybeCacheable()) {
876 const cache_key
*key
= storeKeyPublic(url
, m
);
877 debugs(88, 5, m
<< ' ' << url
<< ' ' << storeKeyText(key
));
879 neighborsHtcpClear(nullptr, req
, m
, HTCP_CLR_INVALIDATION
);
883 Store::Root().evictIfFound(key
);
889 clientReplyContext::purgeAllCached()
891 // XXX: performance regression, c_str() reallocates
892 SBuf
url(http
->request
->effectiveRequestUri());
893 purgeEntriesByUrl(http
->request
, url
.c_str());
897 clientReplyContext::loggingTags() const
899 // XXX: clientReplyContext code assumes that http cbdata is always valid.
900 // TODO: Either add cbdataReferenceValid(http) checks in all the relevant
901 // places, like this one, or remove cbdata protection of the http member.
902 return &http
->al
->cache
.code
;
906 clientReplyContext::purgeRequest()
908 debugs(88, 3, "Config2.onoff.enable_purge = " <<
909 Config2
.onoff
.enable_purge
);
911 if (!Config2
.onoff
.enable_purge
) {
912 http
->updateLoggingTags(LOG_TCP_DENIED
);
913 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, nullptr,
914 http
->getConn(), http
->request
, http
->al
);
919 /* Release both IP cache */
920 ipcacheInvalidate(http
->request
->url
.host());
922 // TODO: can we use purgeAllCached() here instead?
927 clientReplyContext::purgeDoPurge()
929 auto firstFound
= false;
930 if (const auto entry
= storeGetPublicByRequestMethod(http
->request
, Http::METHOD_GET
)) {
931 // special entries are only METHOD_GET entries without variance
932 if (EBIT_TEST(entry
->flags
, ENTRY_SPECIAL
)) {
933 http
->updateLoggingTags(LOG_TCP_DENIED
);
934 const auto err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, nullptr,
935 http
->getConn(), http
->request
, http
->al
);
937 entry
->abandon(__func__
);
941 if (!purgeEntry(*entry
, Http::METHOD_GET
))
945 detailStoreLookup(storeLookupString(firstFound
));
947 if (const auto entry
= storeGetPublicByRequestMethod(http
->request
, Http::METHOD_HEAD
)) {
948 if (!purgeEntry(*entry
, Http::METHOD_HEAD
))
952 /* And for Vary, release the base URI if none of the headers was included in the request */
953 if (!http
->request
->vary_headers
.isEmpty()
954 && http
->request
->vary_headers
.find('=') != SBuf::npos
) {
955 // XXX: performance regression, c_str() reallocates
956 SBuf
tmp(http
->request
->effectiveRequestUri());
958 if (const auto entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_GET
)) {
959 if (!purgeEntry(*entry
, Http::METHOD_GET
, "Vary "))
963 if (const auto entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_HEAD
)) {
964 if (!purgeEntry(*entry
, Http::METHOD_HEAD
, "Vary "))
969 if (purgeStatus
== Http::scNone
)
970 purgeStatus
= Http::scNotFound
;
973 * Make a new entry to hold the reply to be written
976 /* TODO: This doesn't need to go through the store. Simply
977 * push down the client chain
979 createStoreEntry(http
->request
->method
, RequestFlags());
981 triggerInitialStoreRead();
983 const HttpReplyPointer
rep(new HttpReply
);
984 rep
->setHeaders(purgeStatus
, nullptr, nullptr, 0, 0, -1);
985 http
->storeEntry()->replaceHttpReply(rep
);
986 http
->storeEntry()->complete();
990 clientReplyContext::purgeEntry(StoreEntry
&entry
, const Http::MethodType methodType
, const char *descriptionPrefix
)
992 debugs(88, 4, descriptionPrefix
<< Http::MethodStr(methodType
) << " '" << entry
.url() << "'" );
994 neighborsHtcpClear(&entry
, http
->request
, HttpRequestMethod(methodType
), HTCP_CLR_PURGE
);
997 purgeStatus
= Http::scOkay
;
1002 clientReplyContext::traceReply()
1004 createStoreEntry(http
->request
->method
, RequestFlags());
1005 triggerInitialStoreRead();
1006 http
->storeEntry()->releaseRequest();
1007 http
->storeEntry()->buffer();
1008 const HttpReplyPointer
rep(new HttpReply
);
1009 rep
->setHeaders(Http::scOkay
, nullptr, "text/plain", http
->request
->prefixLen(), 0, squid_curtime
);
1010 http
->storeEntry()->replaceHttpReply(rep
);
1011 http
->request
->swapOut(http
->storeEntry());
1012 http
->storeEntry()->complete();
1015 #define SENDING_BODY 0
1016 #define SENDING_HDRSONLY 1
1018 clientReplyContext::checkTransferDone()
1020 StoreEntry
*entry
= http
->storeEntry();
1022 if (entry
== nullptr)
1026 * For now, 'done_copying' is used for special cases like
1027 * Range and HEAD requests.
1029 if (http
->flags
.done_copying
)
1032 if (http
->request
->flags
.chunkedReply
&& !flags
.complete
) {
1033 // last-chunk was not sent
1038 * Handle STORE_OK objects.
1039 * objectLen(entry) will be set properly.
1040 * RC: Does objectLen(entry) include the Headers?
1043 if (entry
->store_status
== STORE_OK
) {
1044 return storeOKTransferDone();
1046 return storeNotOKTransferDone();
1051 clientReplyContext::storeOKTransferDone() const
1053 assert(http
->storeEntry()->objectLen() >= 0);
1054 const auto headers_sz
= http
->storeEntry()->mem().baseReply().hdr_sz
;
1055 assert(http
->storeEntry()->objectLen() >= headers_sz
);
1056 const auto done
= http
->out
.offset
>= http
->storeEntry()->objectLen() - headers_sz
;
1057 const auto debugLevel
= done
? 3 : 5;
1058 debugs(88, debugLevel
, done
<<
1059 " out.offset=" << http
->out
.offset
<<
1060 " objectLen()=" << http
->storeEntry()->objectLen() <<
1061 " headers_sz=" << headers_sz
);
1062 return done
? 1 : 0;
1066 clientReplyContext::storeNotOKTransferDone() const
1069 * Now, handle STORE_PENDING objects
1071 MemObject
*mem
= http
->storeEntry()->mem_obj
;
1072 assert(mem
!= nullptr);
1073 assert(http
->request
!= nullptr);
1075 if (!http
->storeEntry()->hasParsedReplyHeader())
1076 /* haven't found end of headers yet */
1079 // TODO: Use MemObject::expectedReplySize(method) after resolving XXX below.
1080 const auto expectedBodySize
= mem
->baseReply().content_length
;
1082 // XXX: The code below talks about sending data, and checks stats about
1083 // bytes written to the client connection, but this method must determine
1084 // whether we are done _receiving_ data from Store. This code should work OK
1085 // when expectedBodySize is unknown or matches written data, but it may
1086 // malfunction when we are writing ranges while receiving a full response.
1089 * Figure out how much data we are supposed to send.
1090 * If we are sending a body and we don't have a content-length,
1091 * then we must wait for the object to become STORE_OK.
1093 if (expectedBodySize
< 0)
1096 const auto done
= http
->out
.offset
>= expectedBodySize
;
1097 const auto debugLevel
= done
? 3 : 5;
1098 debugs(88, debugLevel
, done
<<
1099 " out.offset=" << http
->out
.offset
<<
1100 " expectedBodySize=" << expectedBodySize
);
1101 return done
? 1 : 0;
1105 * *http is a valid structure.
1106 * fd is either -1, or an open fd.
1108 * TODO: enumify this
1110 * This function is used by any http request sink, to determine the status
1113 clientStream_status_t
1114 clientReplyStatus(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1116 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1118 assert (context
->http
== http
);
1119 return context
->replyStatus();
1122 clientStream_status_t
1123 clientReplyContext::replyStatus()
1126 /* Here because lower nodes don't need it */
1128 if (http
->storeEntry() == nullptr) {
1129 debugs(88, 5, "clientReplyStatus: no storeEntry");
1130 return STREAM_FAILED
; /* yuck, but what can we do? */
1133 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
1134 /* TODO: Could upstream read errors (result.flags.error) be
1135 * lost, and result in undersize requests being considered
1136 * complete. Should we tcp reset such connections ?
1138 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
1139 return STREAM_FAILED
;
1142 if ((done
= checkTransferDone()) != 0 || flags
.complete
) {
1143 debugs(88, 5, "clientReplyStatus: transfer is DONE: " << done
<< flags
.complete
);
1144 /* Ok we're finished, but how? */
1146 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_BAD_LENGTH
)) {
1147 debugs(88, 5, "clientReplyStatus: truncated response body");
1148 return STREAM_UNPLANNED_COMPLETE
;
1152 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
1153 return STREAM_FAILED
;
1156 // TODO: See also (and unify with) storeNotOKTransferDone() checks.
1157 const int64_t expectedBodySize
=
1158 http
->storeEntry()->mem().baseReply().bodySize(http
->request
->method
);
1159 if (expectedBodySize
>= 0 && !http
->gotEnough()) {
1160 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
1161 return STREAM_UNPLANNED_COMPLETE
;
1164 debugs(88, 5, "clientReplyStatus: stream complete; keepalive=" <<
1165 http
->request
->flags
.proxyKeepalive
);
1166 return STREAM_COMPLETE
;
1169 // XXX: Should this be checked earlier? We could return above w/o checking.
1170 if (reply
->receivedBodyTooLarge(*http
->request
, http
->out
.offset
)) {
1171 debugs(88, 5, "clientReplyStatus: client reply body is too large");
1172 return STREAM_FAILED
;
1178 /* Responses with no body will not have a content-type header,
1179 * which breaks the rep_mime_type acl, which
1180 * coincidentally, is the most common acl for reply access lists.
1181 * A better long term fix for this is to allow acl matches on the various
1182 * status codes, and then supply a default ruleset that puts these
1183 * codes before any user defines access entries. That way the user
1184 * can choose to block these responses where appropriate, but won't get
1185 * mysterious breakages.
1188 clientReplyContext::alwaysAllowResponse(Http::StatusCode sline
) const
1194 case Http::scContinue
:
1196 case Http::scSwitchingProtocols
:
1198 case Http::scProcessing
:
1200 case Http::scNoContent
:
1202 case Http::scNotModified
:
1214 * Generate the reply headers sent to client.
1216 * Filters out unwanted entries and hop-by-hop from original reply header
1217 * then adds extra entries if we have more info than origin server
1218 * then adds Squid specific entries
1221 clientReplyContext::buildReplyHeader()
1223 HttpHeader
*hdr
= &reply
->header
;
1224 const bool is_hit
= http
->loggingTags().isTcpHit();
1225 HttpRequest
*request
= http
->request
;
1227 if (is_hit
|| collapsedRevalidation
== crSlave
)
1228 hdr
->delById(Http::HdrType::SET_COOKIE
);
1229 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
1231 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
1232 // remove the Proxy-Authenticate header
1233 if ( !request
->peer_login
|| (strcmp(request
->peer_login
,"PASS") != 0 && strcmp(request
->peer_login
,"PASSTHRU") != 0)) {
1235 // but allow adaptation services to authenticate clients
1236 // via request satisfaction
1237 if (!http
->requestSatisfactionMode())
1239 reply
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1242 reply
->header
.removeHopByHopEntries();
1243 // paranoid: ContentLengthInterpreter has cleaned non-generated replies
1244 reply
->removeIrrelevantContentLength();
1246 // if (request->range)
1247 // clientBuildRangeHeader(http, reply);
1250 * Add a estimated Age header on cache hits.
1254 * Remove any existing Age header sent by upstream caches
1255 * (note that the existing header is passed along unmodified
1258 hdr
->delById(Http::HdrType::AGE
);
1260 * This adds the calculated object age. Note that the details of the
1261 * age calculation is performed by adjusting the timestamp in
1262 * StoreEntry::timestampsSet(), not here.
1264 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
1265 hdr
->delById(Http::HdrType::DATE
);
1266 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1267 } else if (http
->getConn() && http
->getConn()->port
->actAsOrigin
) {
1268 // Swap the Date: header to current time if we are simulating an origin
1269 HttpHeaderEntry
*h
= hdr
->findEntry(Http::HdrType::DATE
);
1271 hdr
->putExt("X-Origin-Date", h
->value
.termedBuf());
1272 hdr
->delById(Http::HdrType::DATE
);
1273 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1274 h
= hdr
->findEntry(Http::HdrType::EXPIRES
);
1275 if (h
&& http
->storeEntry()->expires
>= 0) {
1276 hdr
->putExt("X-Origin-Expires", h
->value
.termedBuf());
1277 hdr
->delById(Http::HdrType::EXPIRES
);
1278 hdr
->putTime(Http::HdrType::EXPIRES
, squid_curtime
+ http
->storeEntry()->expires
- http
->storeEntry()->timestamp
);
1280 if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1281 // put X-Cache-Age: instead of Age:
1283 snprintf(age
, sizeof(age
), "%" PRId64
, static_cast<int64_t>(squid_curtime
- http
->storeEntry()->timestamp
));
1284 hdr
->putExt("X-Cache-Age", age
);
1286 } else if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1287 hdr
->putInt(Http::HdrType::AGE
,
1288 squid_curtime
- http
->storeEntry()->timestamp
);
1292 /* RFC 2616: Section 14.18
1294 * Add a Date: header if missing.
1295 * We have access to a clock therefore are required to amend any shortcoming in servers.
1297 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1299 if ( !hdr
->has(Http::HdrType::DATE
) ) {
1300 if (!http
->storeEntry())
1301 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1302 else if (http
->storeEntry()->timestamp
> 0)
1303 hdr
->putTime(Http::HdrType::DATE
, http
->storeEntry()->timestamp
);
1305 debugs(88, DBG_IMPORTANT
, "ERROR: Squid BUG #3279: HTTP reply without Date:");
1306 /* dump something useful about the problem */
1307 http
->storeEntry()->dump(DBG_IMPORTANT
);
1311 /* Filter unproxyable authentication types */
1312 if (http
->loggingTags().oldType
!= LOG_TCP_DENIED
&&
1313 hdr
->has(Http::HdrType::WWW_AUTHENTICATE
)) {
1314 HttpHeaderPos pos
= HttpHeaderInitPos
;
1317 int connection_auth_blocked
= 0;
1318 while ((e
= hdr
->getEntry(&pos
))) {
1319 if (e
->id
== Http::HdrType::WWW_AUTHENTICATE
) {
1320 const char *value
= e
->value
.rawBuf();
1322 if ((strncasecmp(value
, "NTLM", 4) == 0 &&
1323 (value
[4] == '\0' || value
[4] == ' '))
1325 (strncasecmp(value
, "Negotiate", 9) == 0 &&
1326 (value
[9] == '\0' || value
[9] == ' '))
1328 (strncasecmp(value
, "Kerberos", 8) == 0 &&
1329 (value
[8] == '\0' || value
[8] == ' '))) {
1330 if (request
->flags
.connectionAuthDisabled
) {
1331 hdr
->delAt(pos
, connection_auth_blocked
);
1334 request
->flags
.mustKeepalive
= true;
1335 if (!request
->flags
.accelerated
&& !request
->flags
.intercepted
) {
1336 httpHeaderPutStrf(hdr
, Http::HdrType::PROXY_SUPPORT
, "Session-Based-Authentication");
1338 We send "Connection: Proxy-Support" header to mark
1339 Proxy-Support as a hop-by-hop header for intermediaries that do not
1340 understand the semantics of this header. The RFC should have included
1341 this recommendation.
1343 httpHeaderPutStrf(hdr
, Http::HdrType::CONNECTION
, "Proxy-support");
1350 if (connection_auth_blocked
)
1355 /* Handle authentication headers */
1356 if (http
->loggingTags().oldType
== LOG_TCP_DENIED
&&
1357 ( reply
->sline
.status() == Http::scProxyAuthenticationRequired
||
1358 reply
->sline
.status() == Http::scUnauthorized
)
1360 /* Add authentication header */
1361 /* TODO: alter errorstate to be accel on|off aware. The 0 on the next line
1362 * depends on authenticate behaviour: all schemes to date send no extra
1363 * data on 407/401 responses, and do not check the accel state on 401/407
1366 Auth::UserRequest::AddReplyAuthHeader(reply
, request
->auth_user_request
, request
, 0, 1);
1367 } else if (request
->auth_user_request
!= nullptr)
1368 Auth::UserRequest::AddReplyAuthHeader(reply
, request
->auth_user_request
, request
, http
->flags
.accel
, 0);
1371 SBuf
cacheStatus(uniqueHostname());
1372 if (const auto hitOrFwd
= http
->loggingTags().cacheStatusSource())
1373 cacheStatus
.append(hitOrFwd
);
1374 if (firstStoreLookup_
) {
1375 cacheStatus
.append(";detail=");
1376 cacheStatus
.append(firstStoreLookup_
);
1378 // TODO: Remove c_str() after converting HttpHeaderEntry::value to SBuf
1379 hdr
->putStr(Http::HdrType::CACHE_STATUS
, cacheStatus
.c_str());
1381 const bool maySendChunkedReply
= !request
->multipartRangeRequest() &&
1382 reply
->sline
.version
.protocol
== AnyP::PROTO_HTTP
&& // response is HTTP
1383 (request
->http_ver
>= Http::ProtocolVersion(1,1));
1385 /* Check whether we should send keep-alive */
1386 if (!Config
.onoff
.error_pconns
&& reply
->sline
.status() >= 400 && !request
->flags
.mustKeepalive
) {
1387 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
1388 request
->flags
.proxyKeepalive
= false;
1389 } else if (!Config
.onoff
.client_pconns
&& !request
->flags
.mustKeepalive
) {
1390 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
1391 request
->flags
.proxyKeepalive
= false;
1392 } else if (request
->flags
.proxyKeepalive
&& shutting_down
) {
1393 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
1394 request
->flags
.proxyKeepalive
= false;
1395 } else if (request
->flags
.connectionAuth
&& !reply
->keep_alive
) {
1396 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
1397 request
->flags
.proxyKeepalive
= false;
1398 } else if (reply
->bodySize(request
->method
) < 0 && !maySendChunkedReply
) {
1399 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
1400 request
->flags
.proxyKeepalive
= false;
1401 } else if (fdUsageHigh()&& !request
->flags
.mustKeepalive
) {
1402 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
1403 request
->flags
.proxyKeepalive
= false;
1404 } else if (request
->flags
.sslBumped
&& !reply
->persistent()) {
1405 // We do not really have to close, but we pretend we are a tunnel.
1406 debugs(88, 3, "clientBuildReplyHeader: bumped reply forces close");
1407 request
->flags
.proxyKeepalive
= false;
1408 } else if (request
->pinnedConnection() && !reply
->persistent()) {
1409 // The peer wants to close the pinned connection
1410 debugs(88, 3, "pinned reply forces close");
1411 request
->flags
.proxyKeepalive
= false;
1412 } else if (http
->getConn()) {
1413 ConnStateData
* conn
= http
->getConn();
1414 if (!Comm::IsConnOpen(conn
->port
->listenConn
)) {
1415 // The listening port closed because of a reconfigure
1416 debugs(88, 3, "listening port closed");
1417 request
->flags
.proxyKeepalive
= false;
1421 // Decide if we send chunked reply
1422 if (maySendChunkedReply
&& reply
->bodySize(request
->method
) < 0) {
1423 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
1424 request
->flags
.chunkedReply
= true;
1425 hdr
->putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
1428 hdr
->addVia(reply
->sline
.version
);
1430 /* Signal keep-alive or close explicitly */
1431 hdr
->putStr(Http::HdrType::CONNECTION
, request
->flags
.proxyKeepalive
? "keep-alive" : "close");
1433 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1434 if ( hdr
->has(Http::HdrType::SURROGATE_CONTROL
) ) {
1435 if (!request
->header
.has(Http::HdrType::SURROGATE_CAPABILITY
)) {
1436 hdr
->delById(Http::HdrType::SURROGATE_CONTROL
);
1438 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1441 httpHdrMangleList(hdr
, request
, http
->al
, ROR_REPLY
);
1445 clientReplyContext::cloneReply()
1447 assert(reply
== nullptr);
1449 reply
= http
->storeEntry()->mem().freshestReply().clone();
1452 http
->al
->reply
= reply
;
1454 if (reply
->sline
.version
.protocol
== AnyP::PROTO_HTTP
) {
1455 /* RFC 2616 requires us to advertise our version (but only on real HTTP traffic) */
1456 reply
->sline
.version
= Http::ProtocolVersion();
1459 /* do header conversions */
1463 /// Safely disposes of an entry pointing to a cache hit that we do not want.
1464 /// We cannot just ignore the entry because it may be locking or otherwise
1465 /// holding an associated cache resource of some sort.
1467 clientReplyContext::forgetHit()
1469 StoreEntry
*e
= http
->storeEntry();
1470 assert(e
); // or we are not dealing with a hit
1471 // We probably have not locked the entry earlier, unfortunately. We lock it
1472 // now so that we can unlock two lines later (and trigger cleanup).
1473 // Ideally, ClientHttpRequest::storeEntry() should lock/unlock, but it is
1474 // used so inconsistently that simply adding locking there leads to bugs.
1475 e
->lock("clientReplyContext::forgetHit");
1476 http
->storeEntry(nullptr);
1477 e
->unlock("clientReplyContext::forgetHit"); // may delete e
1481 clientReplyContext::identifyStoreObject()
1483 HttpRequest
*r
= http
->request
;
1485 // client sent CC:no-cache or some other condition has been
1486 // encountered which prevents delivering a public/cached object.
1487 // XXX: The above text does not match the condition below. It might describe
1488 // the opposite condition, but the condition itself should be adjusted
1489 // (e.g., to honor flags.noCache in cache manager requests).
1490 if (!r
->flags
.noCache
|| r
->flags
.internal
) {
1491 const auto e
= storeGetPublicByRequest(r
);
1492 identifyFoundObject(e
, storeLookupString(bool(e
)));
1494 // "external" no-cache requests skip Store lookups
1495 identifyFoundObject(nullptr, "no-cache");
1500 * Check state of the current StoreEntry object.
1501 * to see if we can determine the final status of the request.
1504 clientReplyContext::identifyFoundObject(StoreEntry
*newEntry
, const char *detail
)
1506 detailStoreLookup(detail
);
1508 HttpRequest
*r
= http
->request
;
1509 http
->storeEntry(newEntry
);
1510 const auto e
= http
->storeEntry();
1512 /* Release IP-cache entries on reload */
1513 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
1514 * 'invalidate' the cached IP entries for this request ???
1516 if (r
->flags
.noCache
|| r
->flags
.noCacheHack())
1517 ipcacheInvalidateNegative(r
->url
.host());
1520 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
1521 debugs(85, 3, "StoreEntry is NULL - MISS");
1522 http
->updateLoggingTags(LOG_TCP_MISS
);
1527 if (Config
.onoff
.offline
) {
1528 /** \li If we are running in offline mode set to HIT */
1529 debugs(85, 3, "offline HIT " << *e
);
1530 http
->updateLoggingTags(LOG_TCP_HIT
);
1535 if (http
->redirect
.status
) {
1536 /** \li If redirection status is True force this to be a MISS */
1537 debugs(85, 3, "REDIRECT status forced StoreEntry to NULL (no body on 3XX responses) " << *e
);
1539 http
->updateLoggingTags(LOG_TCP_REDIRECT
);
1544 if (!e
->validToSend()) {
1545 debugs(85, 3, "!storeEntryValidToSend MISS " << *e
);
1547 http
->updateLoggingTags(LOG_TCP_MISS
);
1552 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1553 /* \li Special entries are always hits, no matter what the client says */
1554 debugs(85, 3, "ENTRY_SPECIAL HIT " << *e
);
1555 http
->updateLoggingTags(LOG_TCP_HIT
);
1560 if (r
->flags
.noCache
) {
1561 debugs(85, 3, "no-cache REFRESH MISS " << *e
);
1563 http
->updateLoggingTags(LOG_TCP_CLIENT_REFRESH_MISS
);
1568 if (e
->hittingRequiresCollapsing() && !startCollapsingOn(*e
, false)) {
1569 debugs(85, 3, "prohibited CF MISS " << *e
);
1571 http
->updateLoggingTags(LOG_TCP_MISS
);
1576 debugs(85, 3, "default HIT " << *e
);
1577 http
->updateLoggingTags(LOG_TCP_HIT
);
1581 /// remembers the very first Store lookup classification, ignoring the rest
1583 clientReplyContext::detailStoreLookup(const char *detail
)
1585 if (!firstStoreLookup_
) {
1586 debugs(85, 7, detail
);
1587 firstStoreLookup_
= detail
;
1589 debugs(85, 7, "ignores " << detail
<< " after " << firstStoreLookup_
);
1594 * Request more data from the store for the client Stream
1595 * This is *the* entry point to this module.
1598 * - This is the head of the list.
1599 * - There is at least one more node.
1600 * - Data context is not null
1603 clientGetMoreData(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1605 /* Test preconditions */
1606 assert(aNode
!= nullptr);
1607 assert(cbdataReferenceValid(aNode
));
1608 assert(aNode
->node
.prev
== nullptr);
1609 assert(aNode
->node
.next
!= nullptr);
1610 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1612 assert(context
->http
== http
);
1614 if (!context
->ourNode
)
1615 context
->ourNode
= aNode
;
1617 /* no cbdatareference, this is only used once, and safely */
1618 if (context
->flags
.storelogiccomplete
) {
1619 context
->requestMoreBodyFromStore();
1623 if (context
->http
->request
->method
== Http::METHOD_PURGE
) {
1624 context
->purgeRequest();
1628 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
1630 if (context
->http
->request
->method
== Http::METHOD_TRACE
) {
1631 if (context
->http
->request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0) {
1632 context
->traceReply();
1636 /* continue forwarding, not finished yet. */
1637 http
->updateLoggingTags(LOG_TCP_MISS
);
1639 context
->doGetMoreData();
1641 context
->identifyStoreObject();
1645 clientReplyContext::doGetMoreData()
1647 /* We still have to do store logic processing - vary, cache hit etc */
1648 if (http
->storeEntry() != nullptr) {
1649 /* someone found the object in the cache for us */
1650 StoreIOBuffer localTempBuffer
;
1652 http
->storeEntry()->lock("clientReplyContext::doGetMoreData");
1654 http
->storeEntry()->ensureMemObject(storeId(), http
->log_uri
, http
->request
->method
);
1656 sc
= storeClientListAdd(http
->storeEntry(), this);
1658 sc
->setDelayId(DelayId::DelayClient(http
));
1661 assert(http
->loggingTags().oldType
== LOG_TCP_HIT
);
1662 /* guarantee nothing has been sent yet! */
1663 assert(http
->out
.size
== 0);
1664 assert(http
->out
.offset
== 0);
1666 if (ConnStateData
*conn
= http
->getConn()) {
1667 if (Ip::Qos::TheConfig
.isHitTosActive()) {
1668 Ip::Qos::doTosLocalHit(conn
->clientConnection
);
1671 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
1672 Ip::Qos::doNfmarkLocalHit(conn
->clientConnection
);
1676 triggerInitialStoreRead(CacheHit
);
1678 /* MISS CASE, http->loggingTags() are already set! */
1683 /** The next node has removed itself from the stream. */
1685 clientReplyDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1687 /** detach from the stream */
1688 clientStreamDetach(node
, http
);
1692 * Accepts chunk of a http message in buf, parses prefix, filters headers and
1693 * such, writes processed message to the message recipient
1696 clientReplyContext::SendMoreData(void *data
, StoreIOBuffer result
)
1698 clientReplyContext
*context
= static_cast<clientReplyContext
*>(data
);
1699 context
->sendMoreData (result
);
1703 clientReplyContext::makeThisHead()
1705 /* At least, I think that's what this does */
1706 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1707 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1711 clientReplyContext::errorInStream(const StoreIOBuffer
&result
) const
1713 return /* aborted request */
1714 (http
->storeEntry() && EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) ||
1715 /* Upstream read error */ (result
.flags
.error
);
1719 clientReplyContext::sendStreamError(StoreIOBuffer
const &result
)
1721 /** call clientWriteComplete so the client socket gets closed
1723 * We call into the stream, because we don't know that there is a
1726 debugs(88, 5, "A stream error has occurred, marking as complete and sending no data.");
1727 StoreIOBuffer localTempBuffer
;
1729 http
->request
->flags
.streamError
= true;
1730 localTempBuffer
.flags
.error
= result
.flags
.error
;
1731 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, nullptr,
1736 clientReplyContext::pushStreamData(const StoreIOBuffer
&result
)
1738 if (result
.length
== 0) {
1739 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
1743 assert(!result
.length
|| result
.offset
== next()->readBuffer
.offset
);
1744 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, nullptr,
1749 clientReplyContext::next() const
1751 assert ( (clientStreamNode
*)http
->client_stream
.head
->next
->data
== getNextNode());
1752 return getNextNode();
1756 clientReplyContext::sendBodyTooLargeError()
1758 http
->updateLoggingTags(LOG_TCP_DENIED_REPLY
);
1759 ErrorState
*err
= clientBuildError(ERR_TOO_BIG
, Http::scForbidden
, nullptr,
1760 http
->getConn(), http
->request
, http
->al
);
1761 removeClientStoreReference(&(sc
), http
);
1762 HTTPMSGUNLOCK(reply
);
1767 /// send 412 (Precondition Failed) to client
1769 clientReplyContext::sendPreconditionFailedError()
1771 http
->updateLoggingTags(LOG_TCP_HIT
);
1772 ErrorState
*const err
=
1773 clientBuildError(ERR_PRECONDITION_FAILED
, Http::scPreconditionFailed
,
1774 nullptr, http
->getConn(), http
->request
, http
->al
);
1775 removeClientStoreReference(&sc
, http
);
1776 HTTPMSGUNLOCK(reply
);
1780 /// send 304 (Not Modified) to client
1782 clientReplyContext::sendNotModified()
1784 StoreEntry
*e
= http
->storeEntry();
1785 const time_t timestamp
= e
->timestamp
;
1786 const auto temprep
= e
->mem().freshestReply().make304();
1787 // log as TCP_INM_HIT if code 304 generated for
1788 // If-None-Match request
1789 if (!http
->request
->flags
.ims
)
1790 http
->updateLoggingTags(LOG_TCP_INM_HIT
);
1792 http
->updateLoggingTags(LOG_TCP_IMS_HIT
);
1793 removeClientStoreReference(&sc
, http
);
1794 createStoreEntry(http
->request
->method
, RequestFlags());
1795 e
= http
->storeEntry();
1796 // Copy timestamp from the original entry so the 304
1797 // reply has a meaningful Age: header.
1799 e
->timestamp
= timestamp
;
1800 e
->replaceHttpReply(temprep
);
1803 * TODO: why put this in the store and then serialise it and
1804 * then parse it again. Simply mark the request complete in
1805 * our context and write the reply struct to the client side.
1807 triggerInitialStoreRead();
1810 /// send 304 (Not Modified) or 412 (Precondition Failed) to client
1811 /// depending on request method
1813 clientReplyContext::sendNotModifiedOrPreconditionFailedError()
1815 if (http
->request
->method
== Http::METHOD_GET
||
1816 http
->request
->method
== Http::METHOD_HEAD
)
1819 sendPreconditionFailedError();
1823 clientReplyContext::processReplyAccess ()
1825 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
1828 /** Don't block our own responses or HTTP status messages */
1829 if (http
->loggingTags().oldType
== LOG_TCP_DENIED
||
1830 http
->loggingTags().oldType
== LOG_TCP_DENIED_REPLY
||
1831 alwaysAllowResponse(reply
->sline
.status())) {
1832 processReplyAccessResult(ACCESS_ALLOWED
);
1836 /** Check for reply to big error */
1837 if (reply
->expectedBodyTooLarge(*http
->request
)) {
1838 sendBodyTooLargeError();
1842 /** check for absent access controls (permit by default) */
1843 if (!Config
.accessList
.reply
) {
1844 processReplyAccessResult(ACCESS_ALLOWED
);
1848 /** Process http_reply_access lists */
1849 auto replyChecklist
=
1850 clientAclChecklistCreate(Config
.accessList
.reply
, http
);
1851 replyChecklist
->updateReply(reply
);
1852 ACLFilledChecklist::NonBlockingCheck(std::move(replyChecklist
), ProcessReplyAccessResult
, this);
1856 clientReplyContext::ProcessReplyAccessResult(Acl::Answer rv
, void *voidMe
)
1858 clientReplyContext
*me
= static_cast<clientReplyContext
*>(voidMe
);
1859 me
->processReplyAccessResult(rv
);
1863 clientReplyContext::processReplyAccessResult(const Acl::Answer
&accessAllowed
)
1865 debugs(88, 2, "The reply for " << http
->request
->method
1866 << ' ' << http
->uri
<< " is " << accessAllowed
<< ", because it matched "
1867 << accessAllowed
.lastCheckDescription());
1869 if (!accessAllowed
.allowed()) {
1871 auto page_id
= FindDenyInfoPage(accessAllowed
, true);
1873 http
->updateLoggingTags(LOG_TCP_DENIED_REPLY
);
1875 if (page_id
== ERR_NONE
)
1876 page_id
= ERR_ACCESS_DENIED
;
1878 err
= clientBuildError(page_id
, Http::scForbidden
, nullptr,
1879 http
->getConn(), http
->request
, http
->al
);
1881 removeClientStoreReference(&sc
, http
);
1883 HTTPMSGUNLOCK(reply
);
1890 /* Ok, the reply is allowed, */
1891 http
->loggingEntry(http
->storeEntry());
1893 Assure(matchesStreamBodyBuffer(lastStreamBufferedBytes
));
1894 Assure(!lastStreamBufferedBytes
.offset
);
1895 auto body_size
= lastStreamBufferedBytes
.length
; // may be zero
1897 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
1898 (int) body_size
<< " bytes after " << reply
->hdr_sz
<<
1899 " bytes of headers");
1901 if (http
->request
->method
== Http::METHOD_HEAD
) {
1902 /* do not forward body for HEAD replies */
1904 http
->flags
.done_copying
= true;
1908 assert (!flags
.headersSent
);
1909 flags
.headersSent
= true;
1911 // next()->readBuffer.offset may be positive for Range requests, but our
1912 // localTempBuffer initialization code assumes that next()->readBuffer.data
1913 // points to the response body at offset 0 because the first
1914 // storeClientCopy() request always has offset 0 (i.e. our first Store
1915 // request ignores next()->readBuffer.offset).
1917 // XXX: We cannot fully check that assumption: readBuffer.offset field is
1918 // often out of sync with the buffer content, and if some buggy code updates
1919 // the buffer while we were waiting for the processReplyAccessResult()
1920 // callback, we may not notice.
1922 StoreIOBuffer localTempBuffer
;
1923 const auto body_buf
= next()->readBuffer
.data
;
1925 //Server side may disable ranges under some circumstances.
1927 if ((!http
->request
->range
))
1928 next()->readBuffer
.offset
= 0;
1930 if (next()->readBuffer
.offset
> 0) {
1931 if (Less(body_size
, next()->readBuffer
.offset
)) {
1932 /* Can't use any of the body we received. send nothing */
1933 localTempBuffer
.length
= 0;
1934 localTempBuffer
.data
= nullptr;
1936 localTempBuffer
.length
= body_size
- next()->readBuffer
.offset
;
1937 localTempBuffer
.data
= body_buf
+ next()->readBuffer
.offset
;
1940 localTempBuffer
.length
= body_size
;
1941 localTempBuffer
.data
= body_buf
;
1944 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
,
1945 http
, reply
, localTempBuffer
);
1951 clientReplyContext::sendMoreData (StoreIOBuffer result
)
1956 debugs(88, 5, http
->uri
<< " got " << result
);
1958 StoreEntry
*entry
= http
->storeEntry();
1960 if (ConnStateData
* conn
= http
->getConn()) {
1961 if (!conn
->isOpen()) {
1962 debugs(33,3, "not sending more data to closing connection " << conn
->clientConnection
);
1965 if (conn
->pinning
.zeroReply
) {
1966 debugs(33,3, "not sending more data after a pinned zero reply " << conn
->clientConnection
);
1970 if (!flags
.headersSent
&& !http
->loggingTags().isTcpHit()) {
1971 // We get here twice if processReplyAccessResult() calls startError().
1972 // TODO: Revise when we check/change QoS markings to reduce syscalls.
1973 if (Ip::Qos::TheConfig
.isHitTosActive()) {
1974 Ip::Qos::doTosLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
1976 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
1977 Ip::Qos::doNfmarkLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
1981 debugs(88, 5, conn
->clientConnection
<<
1982 " '" << entry
->url() << "'" <<
1983 " out.offset=" << http
->out
.offset
);
1986 /* We've got the final data to start pushing... */
1987 flags
.storelogiccomplete
= 1;
1989 assert(http
->request
!= nullptr);
1991 /* ESI TODO: remove this assert once everything is stable */
1992 assert(http
->client_stream
.head
->data
1993 && cbdataReferenceValid(http
->client_stream
.head
->data
));
1997 if (errorInStream(result
)) {
1998 sendStreamError(result
);
2002 if (!matchesStreamBodyBuffer(result
)) {
2003 // Subsequent processing expects response body bytes to be at the start
2004 // of our Client Stream buffer. When given something else (e.g., bytes
2005 // in our tempbuf), we copy and adjust to meet those expectations.
2006 const auto &ourClientStreamsBuffer
= next()->readBuffer
;
2007 assert(result
.length
<= ourClientStreamsBuffer
.length
);
2008 memcpy(ourClientStreamsBuffer
.data
, result
.data
, result
.length
);
2009 result
.data
= ourClientStreamsBuffer
.data
;
2012 noteStreamBufferredBytes(result
);
2014 if (flags
.headersSent
) {
2015 pushStreamData(result
);
2023 sc
->setDelayId(DelayId::DelayClient(http
,reply
));
2026 processReplyAccess();
2030 /// Whether the given body area describes the start of our Client Stream buffer.
2031 /// An empty area does.
2033 clientReplyContext::matchesStreamBodyBuffer(const StoreIOBuffer
&their
) const
2035 // the answer is undefined for errors; they are not really "body buffers"
2036 Assure(!their
.flags
.error
);
2039 return true; // an empty body area always matches our body area
2041 if (their
.data
!= next()->readBuffer
.data
) {
2042 debugs(88, 7, "no: " << their
<< " vs. " << next()->readBuffer
);
2050 clientReplyContext::noteStreamBufferredBytes(const StoreIOBuffer
&result
)
2052 Assure(matchesStreamBodyBuffer(result
));
2053 lastStreamBufferedBytes
= result
; // may be unchanged and/or zero-length
2057 clientReplyContext::fillChecklist(ACLFilledChecklist
&checklist
) const
2059 clientAclChecklistFill(checklist
, http
);
2062 /* Using this breaks the client layering just a little!
2065 clientReplyContext::createStoreEntry(const HttpRequestMethod
& m
, RequestFlags reqFlags
)
2067 assert(http
!= nullptr);
2069 * For erroneous requests, we might not have a h->request,
2070 * so make a fake one.
2073 if (http
->request
== nullptr) {
2074 const auto connManager
= http
->getConn();
2075 const auto mx
= MasterXaction::MakePortful(connManager
? connManager
->port
: nullptr);
2076 // XXX: These fake URI parameters shadow the real (or error:...) URI.
2077 // TODO: Either always set the request earlier and assert here OR use
2078 // http->uri (converted to Anyp::Uri) to create this catch-all request.
2079 const_cast<HttpRequest
*&>(http
->request
) = new HttpRequest(m
, AnyP::PROTO_NONE
, "http", null_string
, mx
);
2080 HTTPMSGLOCK(http
->request
);
2083 StoreEntry
*e
= storeCreateEntry(storeId(), http
->log_uri
, reqFlags
, m
);
2085 // Make entry collapsible ASAP, to increase collapsing chances for others,
2086 // TODO: every must-revalidate and similar request MUST reach the origin,
2087 // but do we have to prohibit others from collapsing on that request?
2088 if (reqFlags
.cachable
&&
2089 !reqFlags
.needValidation
&&
2090 (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
) &&
2091 mayInitiateCollapsing()) {
2092 // make the entry available for future requests now
2093 (void)Store::Root().allowCollapsing(e
, reqFlags
, m
);
2096 sc
= storeClientListAdd(e
, this);
2099 sc
->setDelayId(DelayId::DelayClient(http
));
2102 /* The next line is illegal because we don't know if the client stream
2103 * buffers have been set up
2105 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2106 // SendMoreData, this);
2107 /* So, we mark the store logic as complete */
2108 flags
.storelogiccomplete
= 1;
2110 /* and get the caller to request a read, from wherever they are */
2111 /* NOTE: after ANY data flows down the pipe, even one step,
2112 * this function CAN NOT be used to manage errors
2114 http
->storeEntry(e
);
2118 clientBuildError(err_type page_id
, Http::StatusCode status
, char const *url
,
2119 const ConnStateData
*conn
, HttpRequest
*request
, const AccessLogEntry::Pointer
&al
)
2121 const auto err
= new ErrorState(page_id
, status
, request
, al
);
2122 err
->src_addr
= conn
&& conn
->clientConnection
? conn
->clientConnection
->remote
: Ip::Address::NoAddr();
2125 err
->url
= xstrdup(url
);