2 * Copyright (C) 1996-2020 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"
41 #include "auth/UserRequest.h"
44 #include "DelayPools.h"
52 CBDATA_CLASS_INIT(clientReplyContext
);
55 extern "C" CSS clientReplyStatus
;
56 ErrorState
*clientBuildError(err_type
, Http::StatusCode
, char const *, Ip::Address
&, HttpRequest
*, const AccessLogEntry::Pointer
&);
60 clientReplyContext::~clientReplyContext()
63 /* This may trigger a callback back into SendMoreData as the cbdata
66 removeClientStoreReference(&sc
, http
);
67 /* old_entry might still be set if we didn't yet get the reply
68 * code in HandleIMSReply() */
69 removeStoreReference(&old_sc
, &old_entry
);
70 safe_free(tempBuffer
.data
);
71 cbdataReferenceDone(http
);
75 clientReplyContext::clientReplyContext(ClientHttpRequest
*clientContext
) :
76 purgeStatus(Http::scNone
),
78 http(cbdataReference(clientContext
)),
93 collapsedRevalidation(crNone
)
98 /** Create an error in the store awaiting the client side to read it.
100 * This may be better placed in the clientStream logic, but it has not been
101 * relocated there yet
104 clientReplyContext::setReplyToError(
105 err_type err
, Http::StatusCode status
, const HttpRequestMethod
& method
, char const *uri
,
106 Ip::Address
&addr
, HttpRequest
* failedrequest
, const char *unparsedrequest
,
108 Auth::UserRequest::Pointer auth_user_request
114 auto errstate
= clientBuildError(err
, status
, uri
, addr
, failedrequest
, http
->al
);
117 errstate
->request_hdrs
= xstrdup(unparsedrequest
);
120 errstate
->auth_user_request
= auth_user_request
;
122 setReplyToError(method
, errstate
);
125 void clientReplyContext::setReplyToError(const HttpRequestMethod
& method
, ErrorState
*errstate
)
127 if (errstate
->httpStatus
== Http::scNotImplemented
&& http
->request
)
128 /* prevent confusion over whether we default to persistent or not */
129 http
->request
->flags
.proxyKeepalive
= false;
131 http
->al
->http
.code
= errstate
->httpStatus
;
134 http
->request
->ignoreRange("responding with a Squid-generated error");
136 createStoreEntry(method
, RequestFlags());
137 assert(errstate
->callback_data
== NULL
);
138 errorAppendEntry(http
->storeEntry(), errstate
);
139 /* Now the caller reads to get this */
143 clientReplyContext::setReplyToReply(HttpReply
*futureReply
)
146 http
->al
->http
.code
= futureReply
->sline
.status();
148 HttpRequestMethod method
;
149 if (http
->request
) { // nil on responses to unparsable requests
150 http
->request
->ignoreRange("responding with a Squid-generated reply");
151 method
= http
->request
->method
;
154 createStoreEntry(method
, RequestFlags());
156 http
->storeEntry()->storeErrorResponse(futureReply
);
157 /* Now the caller reads to get futureReply */
160 // Assumes that the entry contains an error response without Content-Range.
161 // To use with regular entries, make HTTP Range header removal conditional.
162 void clientReplyContext::setReplyToStoreEntry(StoreEntry
*entry
, const char *reason
)
164 entry
->lock("clientReplyContext::setReplyToStoreEntry"); // removeClientStoreReference() unlocks
165 sc
= storeClientListAdd(entry
, this);
167 sc
->setDelayId(DelayId::DelayClient(http
));
172 http
->request
->ignoreRange(reason
);
173 flags
.storelogiccomplete
= 1;
174 http
->storeEntry(entry
);
178 clientReplyContext::removeStoreReference(store_client
** scp
,
182 store_client
*sc_tmp
= *scp
;
184 if ((e
= *ep
) != NULL
) {
186 storeUnregister(sc_tmp
, e
, this);
188 e
->unlock("clientReplyContext::removeStoreReference");
193 clientReplyContext::removeClientStoreReference(store_client
**scp
, ClientHttpRequest
*aHttpRequest
)
195 StoreEntry
*reference
= aHttpRequest
->storeEntry();
196 removeStoreReference(scp
, &reference
);
197 aHttpRequest
->storeEntry(reference
);
201 clientReplyContext::saveState()
203 assert(old_sc
== NULL
);
204 debugs(88, 3, "clientReplyContext::saveState: saving store context");
205 old_entry
= http
->storeEntry();
207 old_lastmod
= http
->request
->lastmod
;
208 old_etag
= http
->request
->etag
;
209 old_reqsize
= reqsize
;
210 tempBuffer
.offset
= reqofs
;
211 /* Prevent accessing the now saved entries */
212 http
->storeEntry(NULL
);
219 clientReplyContext::restoreState()
221 assert(old_sc
!= NULL
);
222 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
223 removeClientStoreReference(&sc
, http
);
224 http
->storeEntry(old_entry
);
226 reqsize
= old_reqsize
;
227 reqofs
= tempBuffer
.offset
;
228 http
->request
->lastmod
= old_lastmod
;
229 http
->request
->etag
= old_etag
;
230 /* Prevent accessed the old saved entries */
236 tempBuffer
.offset
= 0;
240 clientReplyContext::startError(ErrorState
* err
)
242 createStoreEntry(http
->request
->method
, RequestFlags());
243 triggerInitialStoreRead();
244 errorAppendEntry(http
->storeEntry(), err
);
248 clientReplyContext::getNextNode() const
250 return (clientStreamNode
*)ourNode
->node
.next
->data
;
253 /* This function is wrong - the client parameters don't include the
257 clientReplyContext::triggerInitialStoreRead()
259 /* when confident, 0 becomes reqofs, and then this factors into
263 StoreIOBuffer
localTempBuffer (next()->readBuffer
.length
, 0, next()->readBuffer
.data
);
264 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, SendMoreData
, this);
267 /* there is an expired entry in the store.
268 * setup a temporary buffer area and perform an IMS to the origin
271 clientReplyContext::processExpired()
273 const char *url
= storeId();
274 debugs(88, 3, "clientReplyContext::processExpired: '" << http
->uri
<< "'");
275 const time_t lastmod
= http
->storeEntry()->lastModified();
276 assert(lastmod
>= 0);
278 * check if we are allowed to contact other servers
279 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
280 * a stale entry *if* it matches client requirements
283 if (http
->onlyIfCached()) {
284 processOnlyIfCachedMiss();
288 http
->logType
.update(LOG_TCP_REFRESH
);
289 http
->request
->flags
.refresh
= true;
290 #if STORE_CLIENT_LIST_DEBUG
291 /* Prevent a race with the store client memory free routines
293 assert(storeClientIsThisAClient(sc
, this));
295 /* Prepare to make a new temporary request */
298 // TODO: Consider also allowing regular (non-collapsed) revalidation hits.
299 // TODO: support collapsed revalidation for Vary-controlled entries
300 bool collapsingAllowed
= Config
.onoff
.collapsed_forwarding
&&
301 !Store::Controller::SmpAware() &&
302 http
->request
->vary_headers
.isEmpty();
304 StoreEntry
*entry
= nullptr;
305 if (collapsingAllowed
) {
306 if (const auto e
= storeGetPublicByRequest(http
->request
, ksRevalidation
)) {
307 if (e
->hittingRequiresCollapsing() && startCollapsingOn(*e
, true)) {
309 entry
->lock("clientReplyContext::processExpired#alreadyRevalidating");
311 e
->abandon(__FUNCTION__
);
312 // assume mayInitiateCollapsing() would fail too
313 collapsingAllowed
= false;
319 entry
->ensureMemObject(url
, http
->log_uri
, http
->request
->method
);
320 debugs(88, 5, "collapsed on existing revalidation entry: " << *entry
);
321 collapsedRevalidation
= crSlave
;
323 entry
= storeCreateEntry(url
,
324 http
->log_uri
, http
->request
->flags
, http
->request
->method
);
325 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
327 if (collapsingAllowed
&& mayInitiateCollapsing() &&
328 Store::Root().allowCollapsing(entry
, http
->request
->flags
, http
->request
->method
)) {
329 debugs(88, 5, "allow other revalidation requests to collapse on " << *entry
);
330 collapsedRevalidation
= crInitiator
;
332 collapsedRevalidation
= crNone
;
336 sc
= storeClientListAdd(entry
, this);
338 /* delay_id is already set on original store client */
339 sc
->setDelayId(DelayId::DelayClient(http
));
342 http
->request
->lastmod
= lastmod
;
344 if (!http
->request
->header
.has(Http::HdrType::IF_NONE_MATCH
)) {
345 ETag etag
= {NULL
, -1}; // TODO: make that a default ETag constructor
346 if (old_entry
->hasEtag(etag
) && !etag
.weak
)
347 http
->request
->etag
= etag
.str
;
350 debugs(88, 5, "lastmod " << entry
->lastModified());
351 http
->storeEntry(entry
);
352 assert(http
->out
.offset
== 0);
353 assert(http
->request
->clientConnectionManager
== http
->getConn());
355 if (collapsedRevalidation
!= crSlave
) {
357 * A refcounted pointer so that FwdState stays around as long as
358 * this clientReplyContext does
360 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
361 FwdState::Start(conn
, http
->storeEntry(), http
->request
, http
->al
);
363 /* Register with storage manager to receive updates when data comes in. */
365 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
366 debugs(88, DBG_CRITICAL
, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
369 /* start counting the length from 0 */
370 StoreIOBuffer
localTempBuffer(HTTP_REQBUF_SZ
, 0, tempbuf
);
371 storeClientCopy(sc
, entry
, localTempBuffer
, HandleIMSReply
, this);
376 clientReplyContext::sendClientUpstreamResponse()
378 StoreIOBuffer tempresult
;
379 removeStoreReference(&old_sc
, &old_entry
);
380 /* here the data to send is the data we just received */
381 tempBuffer
.offset
= 0;
383 /* sendMoreData tracks the offset as well.
384 * Force it back to zero */
386 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
387 /* TODO: provide sendMoreData with the ready parsed reply */
388 tempresult
.length
= reqsize
;
389 tempresult
.data
= tempbuf
;
390 sendMoreData(tempresult
);
394 clientReplyContext::HandleIMSReply(void *data
, StoreIOBuffer result
)
396 clientReplyContext
*context
= (clientReplyContext
*)data
;
397 context
->handleIMSReply(result
);
401 clientReplyContext::sendClientOldEntry()
403 /* Get the old request back */
405 /* here the data to send is in the next nodes buffers already */
406 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
407 /* sendMoreData tracks the offset as well.
408 * Force it back to zero */
410 StoreIOBuffer
tempresult (reqsize
, reqofs
, next()->readBuffer
.data
);
411 sendMoreData(tempresult
);
414 /* This is the workhorse of the HandleIMSReply callback.
416 * It is called when we've got data back from the origin following our
417 * IMS request to revalidate a stale entry.
420 clientReplyContext::handleIMSReply(StoreIOBuffer result
)
425 debugs(88, 3, http
->storeEntry()->url() << ", " << (long unsigned) result
.length
<< " bytes");
427 if (http
->storeEntry() == NULL
)
430 if (result
.flags
.error
&& !EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
))
433 if (collapsedRevalidation
== crSlave
&& !http
->storeEntry()->mayStartHitting()) {
434 debugs(88, 3, "CF slave hit private non-shareable " << *http
->storeEntry() << ". MISS");
435 // restore context to meet processMiss() expectations
437 http
->logType
.update(LOG_TCP_MISS
);
442 /* update size of the request */
443 reqsize
= result
.length
+ reqofs
;
445 // request to origin was aborted
446 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
447 debugs(88, 3, "request to origin aborted '" << http
->storeEntry()->url() << "', sending old entry to client");
448 http
->logType
.update(LOG_TCP_REFRESH_FAIL_OLD
);
449 sendClientOldEntry();
452 const auto oldStatus
= old_entry
->mem().freshestReply().sline
.status();
453 const auto &new_rep
= http
->storeEntry()->mem().freshestReply();
454 const auto status
= new_rep
.sline
.status();
456 // origin replied 304
457 if (status
== Http::scNotModified
) {
458 http
->logType
.update(LOG_TCP_REFRESH_UNMODIFIED
);
459 http
->request
->flags
.staleIfHit
= false; // old_entry is no longer stale
461 // TODO: The update may not be instantaneous. Should we wait for its
462 // completion to avoid spawning too much client-disassociated work?
463 Store::Root().updateOnNotModified(old_entry
, *http
->storeEntry());
465 // if client sent IMS
467 if (http
->request
->flags
.ims
&& !old_entry
->modifiedSince(http
->request
->ims
, http
->request
->imslen
)) {
468 // forward the 304 from origin
469 debugs(88, 3, "origin replied 304, revalidating existing entry and forwarding 304 to client");
470 sendClientUpstreamResponse();
472 // send existing entry, it's still valid
473 debugs(88, 3, "origin replied 304, revalidating existing entry and sending " <<
474 oldStatus
<< " to client");
475 sendClientOldEntry();
479 // origin replied with a non-error code
480 else if (status
> Http::scNone
&& status
< Http::scInternalServerError
) {
481 // RFC 7234 section 4: a cache MUST use the most recent response
482 // (as determined by the Date header field)
483 if (new_rep
.olderThan(&old_entry
->mem().freshestReply())) {
484 http
->logType
.err
.ignored
= true;
485 debugs(88, 3, "origin replied " << status
<<
486 " but with an older date header, sending old entry (" <<
487 oldStatus
<< ") to client");
488 sendClientOldEntry();
490 http
->logType
.update(LOG_TCP_REFRESH_MODIFIED
);
491 debugs(88, 3, "origin replied " << status
<<
492 ", replacing existing entry and forwarding to client");
494 if (collapsedRevalidation
)
495 http
->storeEntry()->clearPublicKeyScope();
497 sendClientUpstreamResponse();
501 // origin replied with an error
502 else if (http
->request
->flags
.failOnValidationError
) {
503 http
->logType
.update(LOG_TCP_REFRESH_FAIL_ERR
);
504 debugs(88, 3, "origin replied with error " << status
<<
505 ", forwarding to client due to fail_on_validation_err");
506 sendClientUpstreamResponse();
508 // ignore and let client have old entry
509 http
->logType
.update(LOG_TCP_REFRESH_FAIL_OLD
);
510 debugs(88, 3, "origin replied with error " <<
511 status
<< ", sending old entry (" << oldStatus
<< ") to client");
512 sendClientOldEntry();
516 SQUIDCEXTERN CSR clientGetMoreData
;
517 SQUIDCEXTERN CSD clientReplyDetach
;
520 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
521 * have been parsed. Normally this should be a single call, but
522 * it might take more than one. As soon as we have the headers,
523 * we hand off to clientSendMoreData, processExpired, or
527 clientReplyContext::CacheHit(void *data
, StoreIOBuffer result
)
529 clientReplyContext
*context
= (clientReplyContext
*)data
;
530 context
->cacheHit(result
);
534 * Process a possible cache HIT.
537 clientReplyContext::cacheHit(StoreIOBuffer result
)
539 /** Ignore if the HIT object is being deleted. */
541 debugs(88, 3, "HIT object being deleted. Ignore the HIT.");
545 StoreEntry
*e
= http
->storeEntry();
547 HttpRequest
*r
= http
->request
;
549 debugs(88, 3, "clientCacheHit: " << http
->uri
<< ", " << result
.length
<< " bytes");
551 if (http
->storeEntry() == NULL
) {
552 debugs(88, 3, "clientCacheHit: request aborted");
554 } else if (result
.flags
.error
) {
555 /* swap in failure */
556 debugs(88, 3, "clientCacheHit: swapin failure for " << http
->uri
);
557 http
->logType
.update(LOG_TCP_SWAPFAIL_MISS
);
558 removeClientStoreReference(&sc
, http
);
563 // The previously identified hit suddenly became unshareable!
564 // This is common for collapsed forwarding slaves but might also
565 // happen to regular hits because we are called asynchronously.
566 if (!e
->mayStartHitting()) {
567 debugs(88, 3, "unshareable " << *e
<< ". MISS");
568 http
->logType
.update(LOG_TCP_MISS
);
573 if (result
.length
== 0) {
574 debugs(88, 5, "store IO buffer has no content. MISS");
575 /* the store couldn't get enough data from the file for us to id the
578 /* treat as a miss */
579 http
->logType
.update(LOG_TCP_MISS
);
584 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
585 /* update size of the request */
586 reqsize
= result
.length
+ reqofs
;
589 * Got the headers, now grok them
591 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
593 if (http
->request
->storeId().cmp(e
->mem_obj
->storeId()) != 0) {
594 debugs(33, DBG_IMPORTANT
, "clientProcessHit: URL mismatch, '" << e
->mem_obj
->storeId() << "' != '" << http
->request
->storeId() << "'");
595 http
->logType
.update(LOG_TCP_MISS
); // we lack a more precise LOG_*_MISS code
600 switch (varyEvaluateMatch(e
, r
)) {
603 /* No variance detected. Continue as normal */
607 /* This is the correct entity for this request. Continue */
608 debugs(88, 2, "clientProcessHit: Vary MATCH!");
612 /* This is not the correct entity for this request. We need
613 * to requery the cache.
615 removeClientStoreReference(&sc
, http
);
617 /* Note: varyEvalyateMatch updates the request with vary information
618 * so we only get here once. (it also takes care of cancelling loops)
620 debugs(88, 2, "clientProcessHit: Vary detected!");
621 clientGetMoreData(ourNode
, http
);
625 /* varyEvaluateMatch found a object loop. Process as miss */
626 debugs(88, DBG_IMPORTANT
, "clientProcessHit: Vary object loop!");
627 http
->logType
.update(LOG_TCP_MISS
); // we lack a more precise LOG_*_MISS code
632 if (r
->method
== Http::METHOD_PURGE
) {
633 debugs(88, 5, "PURGE gets a HIT");
634 removeClientStoreReference(&sc
, http
);
640 if (e
->checkNegativeHit() && !r
->flags
.noCacheHack()) {
641 debugs(88, 5, "negative-HIT");
642 http
->logType
.update(LOG_TCP_NEGATIVE_HIT
);
643 sendMoreData(result
);
645 } else if (blockedHit()) {
646 debugs(88, 5, "send_hit forces a MISS");
647 http
->logType
.update(LOG_TCP_MISS
);
650 } else if (!http
->flags
.internal
&& refreshCheckHTTP(e
, r
)) {
651 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
653 * We hold a stale copy; it needs to be validated
656 * The 'needValidation' flag is used to prevent forwarding
657 * loops between siblings. If our copy of the object is stale,
658 * then we should probably only use parents for the validation
659 * request. Otherwise two siblings could generate a loop if
660 * both have a stale version of the object.
662 r
->flags
.needValidation
= true;
664 if (e
->lastModified() < 0) {
665 debugs(88, 3, "validate HIT object? NO. Can't calculate entry modification time. Do MISS.");
667 * We cannot revalidate entries without knowing their
669 * XXX: BUG 1890 objects without Date do not get one added.
671 http
->logType
.update(LOG_TCP_MISS
);
673 } else if (r
->flags
.noCache
) {
674 debugs(88, 3, "validate HIT object? NO. Client sent CC:no-cache. Do CLIENT_REFRESH_MISS");
676 * This did not match a refresh pattern that overrides no-cache
677 * we should honour the client no-cache header.
679 http
->logType
.update(LOG_TCP_CLIENT_REFRESH_MISS
);
681 } else if (r
->url
.getScheme() == AnyP::PROTO_HTTP
|| r
->url
.getScheme() == AnyP::PROTO_HTTPS
) {
682 debugs(88, 3, "validate HIT object? YES.");
684 * Object needs to be revalidated
685 * XXX This could apply to FTP as well, if Last-Modified is known.
689 debugs(88, 3, "validate HIT object? NO. Client protocol non-HTTP. Do MISS.");
691 * We don't know how to re-validate other protocols. Handle
692 * them as if the object has expired.
694 http
->logType
.update(LOG_TCP_MISS
);
698 } else if (r
->conditional()) {
699 debugs(88, 5, "conditional HIT");
700 if (processConditional(result
))
705 * plain ol' cache hit
707 debugs(88, 5, "plain old HIT");
710 if (e
->store_status
!= STORE_OK
)
711 http
->logType
.update(LOG_TCP_MISS
);
714 if (e
->mem_status
== IN_MEMORY
)
715 http
->logType
.update(LOG_TCP_MEM_HIT
);
716 else if (Config
.onoff
.offline
)
717 http
->logType
.update(LOG_TCP_OFFLINE_HIT
);
719 sendMoreData(result
);
723 * Prepare to fetch the object as it's a cache miss of some kind.
726 clientReplyContext::processMiss()
728 char *url
= http
->uri
;
729 HttpRequest
*r
= http
->request
;
730 ErrorState
*err
= NULL
;
731 debugs(88, 4, r
->method
<< ' ' << url
);
734 * We might have a left-over StoreEntry from a failed cache hit
737 if (http
->storeEntry()) {
738 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
739 debugs(88, DBG_CRITICAL
, "clientProcessMiss: miss on a special object (" << url
<< ").");
740 debugs(88, DBG_CRITICAL
, "\tlog_type = " << http
->logType
.c_str());
741 http
->storeEntry()->dump(1);
744 removeClientStoreReference(&sc
, http
);
747 /** Check if its a PURGE request to be actioned. */
748 if (r
->method
== Http::METHOD_PURGE
) {
753 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
754 if (r
->method
== Http::METHOD_OTHER
) {
758 /** Check if 'only-if-cached' flag is set. Action if so. */
759 if (http
->onlyIfCached()) {
760 processOnlyIfCachedMiss();
764 Comm::ConnectionPointer conn
= http
->getConn() != nullptr ? http
->getConn()->clientConnection
: nullptr;
766 if (r
->flags
.loopDetected
) {
767 http
->al
->http
.code
= Http::scForbidden
;
768 Ip::Address tmp_noaddr
;
769 tmp_noaddr
.setNoAddr();
770 err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, nullptr, conn
? conn
->remote
: tmp_noaddr
, http
->request
, http
->al
);
771 createStoreEntry(r
->method
, RequestFlags());
772 errorAppendEntry(http
->storeEntry(), err
);
773 triggerInitialStoreRead();
776 assert(http
->out
.offset
== 0);
777 createStoreEntry(r
->method
, r
->flags
);
778 triggerInitialStoreRead();
780 if (http
->redirect
.status
) {
781 const HttpReplyPointer
rep(new HttpReply
);
782 http
->logType
.update(LOG_TCP_REDIRECT
);
783 http
->storeEntry()->releaseRequest();
784 rep
->redirect(http
->redirect
.status
, http
->redirect
.location
);
785 http
->storeEntry()->replaceHttpReply(rep
);
786 http
->storeEntry()->complete();
790 assert(r
->clientConnectionManager
== http
->getConn());
792 /** Start forwarding to get the new object from network */
793 FwdState::Start(conn
, http
->storeEntry(), r
, http
->al
);
798 * client issued a request with an only-if-cached cache-control directive;
799 * we did not find a cached object that can be returned without
800 * contacting other servers;
801 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
804 clientReplyContext::processOnlyIfCachedMiss()
806 debugs(88, 4, http
->request
->method
<< ' ' << http
->uri
);
807 http
->al
->http
.code
= Http::scGatewayTimeout
;
808 Ip::Address tmp_noaddr
;
809 tmp_noaddr
.setNoAddr();
810 ErrorState
*err
= clientBuildError(ERR_ONLY_IF_CACHED_MISS
, Http::scGatewayTimeout
, NULL
,
811 http
->getConn() ? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
812 http
->request
, http
->al
);
813 removeClientStoreReference(&sc
, http
);
817 /// process conditional request from client
819 clientReplyContext::processConditional(StoreIOBuffer
&result
)
821 StoreEntry
*const e
= http
->storeEntry();
823 const auto replyStatusCode
= e
->mem().baseReply().sline
.status();
824 if (replyStatusCode
!= Http::scOkay
) {
825 debugs(88, 4, "miss because " << replyStatusCode
<< " != 200");
826 http
->logType
.update(LOG_TCP_MISS
);
831 HttpRequest
&r
= *http
->request
;
833 if (r
.header
.has(Http::HdrType::IF_MATCH
) && !e
->hasIfMatchEtag(r
)) {
834 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
835 sendPreconditionFailedError();
839 if (r
.header
.has(Http::HdrType::IF_NONE_MATCH
)) {
840 // RFC 7232: If-None-Match recipient MUST ignore IMS
844 r
.header
.delById(Http::HdrType::IF_MODIFIED_SINCE
);
846 if (e
->hasIfNoneMatchEtag(r
)) {
847 sendNotModifiedOrPreconditionFailedError();
851 // None-Match is true (no ETag matched); treat as an unconditional hit
856 // handle If-Modified-Since requests from the client
857 if (e
->modifiedSince(r
.ims
, r
.imslen
)) {
858 // Modified-Since is true; treat as an unconditional hit
862 // otherwise reply with 304 Not Modified
871 /// whether squid.conf send_hit prevents us from serving this hit
873 clientReplyContext::blockedHit() const
875 if (!Config
.accessList
.sendHit
)
876 return false; // hits are not blocked by default
878 if (http
->flags
.internal
)
879 return false; // internal content "hits" cannot be blocked
881 const auto &rep
= http
->storeEntry()->mem().freshestReply();
883 std::unique_ptr
<ACLFilledChecklist
> chl(clientAclChecklistCreate(Config
.accessList
.sendHit
, http
));
884 chl
->reply
= const_cast<HttpReply
*>(&rep
); // ACLChecklist API bug
885 HTTPMSGLOCK(chl
->reply
);
886 return !chl
->fastCheck().allowed(); // when in doubt, block
891 clientReplyContext::purgeRequestFindObjectToPurge()
893 /* Try to find a base entry */
894 http
->flags
.purging
= true;
897 // TODO: can we use purgeAllCached() here instead of doing the
898 // getPublicByRequestMethod() dance?
899 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_GET
);
902 // Purges all entries with a given url
903 // TODO: move to SideAgent parent, when we have one
905 * We probably cannot purge Vary-affected responses because their MD5
906 * keys depend on vary headers.
909 purgeEntriesByUrl(HttpRequest
* req
, const char *url
)
911 for (HttpRequestMethod
m(Http::METHOD_NONE
); m
!= Http::METHOD_ENUM_END
; ++m
) {
912 if (m
.respMaybeCacheable()) {
913 const cache_key
*key
= storeKeyPublic(url
, m
);
914 debugs(88, 5, m
<< ' ' << url
<< ' ' << storeKeyText(key
));
916 neighborsHtcpClear(nullptr, req
, m
, HTCP_CLR_INVALIDATION
);
918 Store::Root().evictIfFound(key
);
924 clientReplyContext::purgeAllCached()
926 // XXX: performance regression, c_str() reallocates
927 SBuf
url(http
->request
->effectiveRequestUri());
928 purgeEntriesByUrl(http
->request
, url
.c_str());
932 clientReplyContext::created(StoreEntry
*newEntry
)
934 if (lookingforstore
== 1)
935 purgeFoundGet(newEntry
);
936 else if (lookingforstore
== 2)
937 purgeFoundHead(newEntry
);
938 else if (lookingforstore
== 3)
939 purgeDoPurgeGet(newEntry
);
940 else if (lookingforstore
== 4)
941 purgeDoPurgeHead(newEntry
);
942 else if (lookingforstore
== 5)
943 identifyFoundObject(newEntry
);
947 clientReplyContext::loggingTags()
949 // XXX: clientReplyContext code assumes that http cbdata is always valid.
950 // TODO: Either add cbdataReferenceValid(http) checks in all the relevant
951 // places, like this one, or remove cbdata protection of the http member.
952 return &http
->logType
;
956 clientReplyContext::purgeFoundGet(StoreEntry
*newEntry
)
960 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
962 purgeFoundObject (newEntry
);
966 clientReplyContext::purgeFoundHead(StoreEntry
*newEntry
)
971 purgeFoundObject (newEntry
);
975 clientReplyContext::purgeFoundObject(StoreEntry
*entry
)
979 if (EBIT_TEST(entry
->flags
, ENTRY_SPECIAL
)) {
980 http
->logType
.update(LOG_TCP_DENIED
);
981 Ip::Address tmp_noaddr
;
982 tmp_noaddr
.setNoAddr(); // TODO: make a global const
983 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
,
984 http
->getConn() ? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
985 http
->request
, http
->al
);
987 return; // XXX: leaking unused entry if some store does not keep it
990 StoreIOBuffer localTempBuffer
;
991 /* Swap in the metadata */
992 http
->storeEntry(entry
);
994 http
->storeEntry()->lock("clientReplyContext::purgeFoundObject");
995 http
->storeEntry()->ensureMemObject(storeId(), http
->log_uri
,
996 http
->request
->method
);
998 sc
= storeClientListAdd(http
->storeEntry(), this);
1000 http
->logType
.update(LOG_TCP_HIT
);
1004 localTempBuffer
.offset
= http
->out
.offset
;
1006 localTempBuffer
.length
= next()->readBuffer
.length
;
1008 localTempBuffer
.data
= next()->readBuffer
.data
;
1010 storeClientCopy(sc
, http
->storeEntry(),
1011 localTempBuffer
, CacheHit
, this);
1015 clientReplyContext::purgeRequest()
1017 debugs(88, 3, "Config2.onoff.enable_purge = " <<
1018 Config2
.onoff
.enable_purge
);
1020 if (!Config2
.onoff
.enable_purge
) {
1021 http
->logType
.update(LOG_TCP_DENIED
);
1022 Ip::Address tmp_noaddr
;
1023 tmp_noaddr
.setNoAddr();
1024 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
,
1025 http
->getConn() ? http
->getConn()->clientConnection
->remote
: tmp_noaddr
, http
->request
, http
->al
);
1030 /* Release both IP cache */
1031 ipcacheInvalidate(http
->request
->url
.host());
1033 if (!http
->flags
.purging
)
1034 purgeRequestFindObjectToPurge();
1040 clientReplyContext::purgeDoMissPurge()
1042 http
->logType
.update(LOG_TCP_MISS
);
1043 lookingforstore
= 3;
1044 StoreEntry::getPublicByRequestMethod(this,http
->request
, Http::METHOD_GET
);
1048 clientReplyContext::purgeDoPurgeGet(StoreEntry
*newEntry
)
1051 /* Release the cached URI */
1052 debugs(88, 4, "clientPurgeRequest: GET '" << newEntry
->url() << "'" );
1054 neighborsHtcpClear(newEntry
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1056 newEntry
->release(true);
1057 purgeStatus
= Http::scOkay
;
1060 lookingforstore
= 4;
1061 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
1065 clientReplyContext::purgeDoPurgeHead(StoreEntry
*newEntry
)
1068 debugs(88, 4, "HEAD " << newEntry
->url());
1070 neighborsHtcpClear(newEntry
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1072 newEntry
->release(true);
1073 purgeStatus
= Http::scOkay
;
1076 /* And for Vary, release the base URI if none of the headers was included in the request */
1077 if (!http
->request
->vary_headers
.isEmpty()
1078 && http
->request
->vary_headers
.find('=') != SBuf::npos
) {
1079 // XXX: performance regression, c_str() reallocates
1080 SBuf
tmp(http
->request
->effectiveRequestUri());
1081 StoreEntry
*entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_GET
);
1084 debugs(88, 4, "Vary GET " << entry
->url());
1086 neighborsHtcpClear(entry
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1088 entry
->release(true);
1089 purgeStatus
= Http::scOkay
;
1092 entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_HEAD
);
1095 debugs(88, 4, "Vary HEAD " << entry
->url());
1097 neighborsHtcpClear(entry
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1099 entry
->release(true);
1100 purgeStatus
= Http::scOkay
;
1104 if (purgeStatus
== Http::scNone
)
1105 purgeStatus
= Http::scNotFound
;
1108 * Make a new entry to hold the reply to be written
1111 /* FIXME: This doesn't need to go through the store. Simply
1112 * push down the client chain
1114 createStoreEntry(http
->request
->method
, RequestFlags());
1116 triggerInitialStoreRead();
1118 const HttpReplyPointer
rep(new HttpReply
);
1119 rep
->setHeaders(purgeStatus
, NULL
, NULL
, 0, 0, -1);
1120 http
->storeEntry()->replaceHttpReply(rep
);
1121 http
->storeEntry()->complete();
1125 clientReplyContext::traceReply(clientStreamNode
* node
)
1127 clientStreamNode
*nextNode
= (clientStreamNode
*)node
->node
.next
->data
;
1128 StoreIOBuffer localTempBuffer
;
1129 createStoreEntry(http
->request
->method
, RequestFlags());
1130 localTempBuffer
.offset
= nextNode
->readBuffer
.offset
+ headers_sz
;
1131 localTempBuffer
.length
= nextNode
->readBuffer
.length
;
1132 localTempBuffer
.data
= nextNode
->readBuffer
.data
;
1133 storeClientCopy(sc
, http
->storeEntry(),
1134 localTempBuffer
, SendMoreData
, this);
1135 http
->storeEntry()->releaseRequest();
1136 http
->storeEntry()->buffer();
1137 const HttpReplyPointer
rep(new HttpReply
);
1138 rep
->setHeaders(Http::scOkay
, NULL
, "text/plain", http
->request
->prefixLen(), 0, squid_curtime
);
1139 http
->storeEntry()->replaceHttpReply(rep
);
1140 http
->request
->swapOut(http
->storeEntry());
1141 http
->storeEntry()->complete();
1144 #define SENDING_BODY 0
1145 #define SENDING_HDRSONLY 1
1147 clientReplyContext::checkTransferDone()
1149 StoreEntry
*entry
= http
->storeEntry();
1155 * For now, 'done_copying' is used for special cases like
1156 * Range and HEAD requests.
1158 if (http
->flags
.done_copying
)
1161 if (http
->request
->flags
.chunkedReply
&& !flags
.complete
) {
1162 // last-chunk was not sent
1167 * Handle STORE_OK objects.
1168 * objectLen(entry) will be set proprely.
1169 * RC: Does objectLen(entry) include the Headers?
1172 if (entry
->store_status
== STORE_OK
) {
1173 return storeOKTransferDone();
1175 return storeNotOKTransferDone();
1180 clientReplyContext::storeOKTransferDone() const
1182 assert(http
->storeEntry()->objectLen() >= 0);
1183 assert(http
->storeEntry()->objectLen() >= headers_sz
);
1184 if (http
->out
.offset
>= http
->storeEntry()->objectLen() - headers_sz
) {
1185 debugs(88,3,HERE
<< "storeOKTransferDone " <<
1186 " out.offset=" << http
->out
.offset
<<
1187 " objectLen()=" << http
->storeEntry()->objectLen() <<
1188 " headers_sz=" << headers_sz
);
1196 clientReplyContext::storeNotOKTransferDone() const
1199 * Now, handle STORE_PENDING objects
1201 MemObject
*mem
= http
->storeEntry()->mem_obj
;
1202 assert(mem
!= NULL
);
1203 assert(http
->request
!= NULL
);
1205 /* mem->reply was wrong because it uses the UPSTREAM header length!!! */
1206 if (headers_sz
== 0)
1207 /* haven't found end of headers yet */
1210 // TODO: Use MemObject::expectedReplySize(method) after resolving XXX below.
1211 const auto expectedBodySize
= mem
->baseReply().content_length
;
1213 // XXX: The code below talks about sending data, and checks stats about
1214 // bytes written to the client connection, but this method must determine
1215 // whether we are done _receiving_ data from Store. This code should work OK
1216 // when expectedBodySize is unknown or matches written data, but it may
1217 // malfunction when we are writing ranges while receiving a full response.
1220 * Figure out how much data we are supposed to send.
1221 * If we are sending a body and we don't have a content-length,
1222 * then we must wait for the object to become STORE_OK.
1224 if (expectedBodySize
< 0)
1227 const uint64_t expectedLength
= expectedBodySize
+ http
->out
.headers_sz
;
1229 if (http
->out
.size
< expectedLength
)
1232 debugs(88,3,HERE
<< "storeNotOKTransferDone " <<
1233 " out.size=" << http
->out
.size
<<
1234 " expectedLength=" << expectedLength
);
1239 /* A write has completed, what is the next status based on the
1240 * canonical request data?
1241 * 1 something is wrong
1242 * 0 nothing is wrong.
1246 clientHttpRequestStatus(int fd
, ClientHttpRequest
const *http
)
1248 #if SIZEOF_INT64_T == 4
1249 if (http
->out
.size
> 0x7FFF0000) {
1250 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
<< " to prevent out.size counter overflow");
1251 if (http
->getConn())
1252 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1253 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes");
1254 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1258 if (http
->out
.offset
> 0x7FFF0000) {
1259 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
< " to prevent out.offset counter overflow");
1260 if (http
->getConn())
1261 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1262 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes, offset " << http
->out
.offset
);
1263 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1272 * *http is a valid structure.
1273 * fd is either -1, or an open fd.
1275 * TODO: enumify this
1277 * This function is used by any http request sink, to determine the status
1280 clientStream_status_t
1281 clientReplyStatus(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1283 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1285 assert (context
->http
== http
);
1286 return context
->replyStatus();
1289 clientStream_status_t
1290 clientReplyContext::replyStatus()
1293 /* Here because lower nodes don't need it */
1295 if (http
->storeEntry() == NULL
) {
1296 debugs(88, 5, "clientReplyStatus: no storeEntry");
1297 return STREAM_FAILED
; /* yuck, but what can we do? */
1300 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
1301 /* TODO: Could upstream read errors (result.flags.error) be
1302 * lost, and result in undersize requests being considered
1303 * complete. Should we tcp reset such connections ?
1305 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
1306 return STREAM_FAILED
;
1309 if ((done
= checkTransferDone()) != 0 || flags
.complete
) {
1310 debugs(88, 5, "clientReplyStatus: transfer is DONE: " << done
<< flags
.complete
);
1311 /* Ok we're finished, but how? */
1313 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_BAD_LENGTH
)) {
1314 debugs(88, 5, "clientReplyStatus: truncated response body");
1315 return STREAM_UNPLANNED_COMPLETE
;
1319 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
1320 return STREAM_FAILED
;
1323 // TODO: See also (and unify with) storeNotOKTransferDone() checks.
1324 const int64_t expectedBodySize
=
1325 http
->storeEntry()->mem().baseReply().bodySize(http
->request
->method
);
1326 if (expectedBodySize
>= 0 && !http
->gotEnough()) {
1327 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
1328 return STREAM_UNPLANNED_COMPLETE
;
1331 debugs(88, 5, "clientReplyStatus: stream complete; keepalive=" <<
1332 http
->request
->flags
.proxyKeepalive
);
1333 return STREAM_COMPLETE
;
1336 // XXX: Should this be checked earlier? We could return above w/o checking.
1337 if (reply
->receivedBodyTooLarge(*http
->request
, http
->out
.offset
- 4096)) {
1338 /* 4096 is a margin for the HTTP headers included in out.offset */
1339 debugs(88, 5, "clientReplyStatus: client reply body is too large");
1340 return STREAM_FAILED
;
1346 /* Responses with no body will not have a content-type header,
1347 * which breaks the rep_mime_type acl, which
1348 * coincidentally, is the most common acl for reply access lists.
1349 * A better long term fix for this is to allow acl matches on the various
1350 * status codes, and then supply a default ruleset that puts these
1351 * codes before any user defines access entries. That way the user
1352 * can choose to block these responses where appropriate, but won't get
1353 * mysterious breakages.
1356 clientReplyContext::alwaysAllowResponse(Http::StatusCode sline
) const
1362 case Http::scContinue
:
1364 case Http::scSwitchingProtocols
:
1366 case Http::scProcessing
:
1368 case Http::scNoContent
:
1370 case Http::scNotModified
:
1382 * Generate the reply headers sent to client.
1384 * Filters out unwanted entries and hop-by-hop from original reply header
1385 * then adds extra entries if we have more info than origin server
1386 * then adds Squid specific entries
1389 clientReplyContext::buildReplyHeader()
1391 HttpHeader
*hdr
= &reply
->header
;
1392 const bool is_hit
= http
->logType
.isTcpHit();
1393 HttpRequest
*request
= http
->request
;
1394 #if DONT_FILTER_THESE
1395 /* but you might want to if you run Squid as an HTTP accelerator */
1396 /* hdr->delById(HDR_ACCEPT_RANGES); */
1397 hdr
->delById(HDR_ETAG
);
1400 if (is_hit
|| collapsedRevalidation
== crSlave
)
1401 hdr
->delById(Http::HdrType::SET_COOKIE
);
1402 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
1404 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
1405 // remove the Proxy-Authenticate header
1406 if ( !request
->peer_login
|| (strcmp(request
->peer_login
,"PASS") != 0 && strcmp(request
->peer_login
,"PASSTHRU") != 0)) {
1408 // but allow adaptation services to authenticate clients
1409 // via request satisfaction
1410 if (!http
->requestSatisfactionMode())
1412 reply
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1415 reply
->header
.removeHopByHopEntries();
1416 // paranoid: ContentLengthInterpreter has cleaned non-generated replies
1417 reply
->removeIrrelevantContentLength();
1419 // if (request->range)
1420 // clientBuildRangeHeader(http, reply);
1423 * Add a estimated Age header on cache hits.
1427 * Remove any existing Age header sent by upstream caches
1428 * (note that the existing header is passed along unmodified
1431 hdr
->delById(Http::HdrType::AGE
);
1433 * This adds the calculated object age. Note that the details of the
1434 * age calculation is performed by adjusting the timestamp in
1435 * StoreEntry::timestampsSet(), not here.
1437 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
1438 hdr
->delById(Http::HdrType::DATE
);
1439 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1440 } else if (http
->getConn() && http
->getConn()->port
->actAsOrigin
) {
1441 // Swap the Date: header to current time if we are simulating an origin
1442 HttpHeaderEntry
*h
= hdr
->findEntry(Http::HdrType::DATE
);
1444 hdr
->putExt("X-Origin-Date", h
->value
.termedBuf());
1445 hdr
->delById(Http::HdrType::DATE
);
1446 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1447 h
= hdr
->findEntry(Http::HdrType::EXPIRES
);
1448 if (h
&& http
->storeEntry()->expires
>= 0) {
1449 hdr
->putExt("X-Origin-Expires", h
->value
.termedBuf());
1450 hdr
->delById(Http::HdrType::EXPIRES
);
1451 hdr
->putTime(Http::HdrType::EXPIRES
, squid_curtime
+ http
->storeEntry()->expires
- http
->storeEntry()->timestamp
);
1453 if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1454 // put X-Cache-Age: instead of Age:
1456 snprintf(age
, sizeof(age
), "%" PRId64
, static_cast<int64_t>(squid_curtime
- http
->storeEntry()->timestamp
));
1457 hdr
->putExt("X-Cache-Age", age
);
1459 } else if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1460 hdr
->putInt(Http::HdrType::AGE
,
1461 squid_curtime
- http
->storeEntry()->timestamp
);
1462 /* Signal old objects. NB: rfc 2616 is not clear,
1463 * by implication, on whether we should do this to all
1464 * responses, or only cache hits.
1465 * 14.46 states it ONLY applies for heuristically calculated
1466 * freshness values, 13.2.4 doesn't specify the same limitation.
1467 * We interpret RFC 2616 under the combination.
1469 /* TODO: if maxage or s-maxage is present, don't do this */
1471 if (squid_curtime
- http
->storeEntry()->timestamp
>= 86400)
1472 hdr
->putWarning(113, "This cache hit is still fresh and more than 1 day old");
1476 /* RFC 2616: Section 14.18
1478 * Add a Date: header if missing.
1479 * We have access to a clock therefore are required to amend any shortcoming in servers.
1481 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1483 if ( !hdr
->has(Http::HdrType::DATE
) ) {
1484 if (!http
->storeEntry())
1485 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1486 else if (http
->storeEntry()->timestamp
> 0)
1487 hdr
->putTime(Http::HdrType::DATE
, http
->storeEntry()->timestamp
);
1489 debugs(88,DBG_IMPORTANT
,"BUG 3279: HTTP reply without Date:");
1490 /* dump something useful about the problem */
1491 http
->storeEntry()->dump(DBG_IMPORTANT
);
1495 // add Warnings required by RFC 2616 if serving a stale hit
1496 if (http
->request
->flags
.staleIfHit
&& http
->logType
.isTcpHit()) {
1497 hdr
->putWarning(110, "Response is stale");
1498 if (http
->request
->flags
.needValidation
)
1499 hdr
->putWarning(111, "Revalidation failed");
1502 /* Filter unproxyable authentication types */
1503 if (http
->logType
.oldType
!= LOG_TCP_DENIED
&&
1504 hdr
->has(Http::HdrType::WWW_AUTHENTICATE
)) {
1505 HttpHeaderPos pos
= HttpHeaderInitPos
;
1508 int connection_auth_blocked
= 0;
1509 while ((e
= hdr
->getEntry(&pos
))) {
1510 if (e
->id
== Http::HdrType::WWW_AUTHENTICATE
) {
1511 const char *value
= e
->value
.rawBuf();
1513 if ((strncasecmp(value
, "NTLM", 4) == 0 &&
1514 (value
[4] == '\0' || value
[4] == ' '))
1516 (strncasecmp(value
, "Negotiate", 9) == 0 &&
1517 (value
[9] == '\0' || value
[9] == ' '))
1519 (strncasecmp(value
, "Kerberos", 8) == 0 &&
1520 (value
[8] == '\0' || value
[8] == ' '))) {
1521 if (request
->flags
.connectionAuthDisabled
) {
1522 hdr
->delAt(pos
, connection_auth_blocked
);
1525 request
->flags
.mustKeepalive
= true;
1526 if (!request
->flags
.accelerated
&& !request
->flags
.intercepted
) {
1527 httpHeaderPutStrf(hdr
, Http::HdrType::PROXY_SUPPORT
, "Session-Based-Authentication");
1529 We send "Connection: Proxy-Support" header to mark
1530 Proxy-Support as a hop-by-hop header for intermediaries that do not
1531 understand the semantics of this header. The RFC should have included
1532 this recommendation.
1534 httpHeaderPutStrf(hdr
, Http::HdrType::CONNECTION
, "Proxy-support");
1541 if (connection_auth_blocked
)
1546 /* Handle authentication headers */
1547 if (http
->logType
.oldType
== LOG_TCP_DENIED
&&
1548 ( reply
->sline
.status() == Http::scProxyAuthenticationRequired
||
1549 reply
->sline
.status() == Http::scUnauthorized
)
1551 /* Add authentication header */
1552 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1553 * depends on authenticate behaviour: all schemes to date send no extra
1554 * data on 407/401 responses, and do not check the accel state on 401/407
1557 Auth::UserRequest::AddReplyAuthHeader(reply
, request
->auth_user_request
, request
, 0, 1);
1558 } else if (request
->auth_user_request
!= NULL
)
1559 Auth::UserRequest::AddReplyAuthHeader(reply
, request
->auth_user_request
, request
, http
->flags
.accel
, 0);
1562 /* Append X-Cache */
1563 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE
, "%s from %s",
1564 is_hit
? "HIT" : "MISS", getMyHostname());
1566 #if USE_CACHE_DIGESTS
1567 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1568 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE_LOOKUP
, "%s from %s:%d",
1569 lookup_type
? lookup_type
: "NONE",
1570 getMyHostname(), getMyPort());
1574 const bool maySendChunkedReply
= !request
->multipartRangeRequest() &&
1575 reply
->sline
.protocol
== AnyP::PROTO_HTTP
&& // response is HTTP
1576 (request
->http_ver
>= Http::ProtocolVersion(1,1));
1578 /* Check whether we should send keep-alive */
1579 if (!Config
.onoff
.error_pconns
&& reply
->sline
.status() >= 400 && !request
->flags
.mustKeepalive
) {
1580 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
1581 request
->flags
.proxyKeepalive
= false;
1582 } else if (!Config
.onoff
.client_pconns
&& !request
->flags
.mustKeepalive
) {
1583 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
1584 request
->flags
.proxyKeepalive
= false;
1585 } else if (request
->flags
.proxyKeepalive
&& shutting_down
) {
1586 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
1587 request
->flags
.proxyKeepalive
= false;
1588 } else if (request
->flags
.connectionAuth
&& !reply
->keep_alive
) {
1589 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
1590 request
->flags
.proxyKeepalive
= false;
1591 } else if (reply
->bodySize(request
->method
) < 0 && !maySendChunkedReply
) {
1592 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
1593 request
->flags
.proxyKeepalive
= false;
1594 } else if (fdUsageHigh()&& !request
->flags
.mustKeepalive
) {
1595 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
1596 request
->flags
.proxyKeepalive
= false;
1597 } else if (request
->flags
.sslBumped
&& !reply
->persistent()) {
1598 // We do not really have to close, but we pretend we are a tunnel.
1599 debugs(88, 3, "clientBuildReplyHeader: bumped reply forces close");
1600 request
->flags
.proxyKeepalive
= false;
1601 } else if (request
->pinnedConnection() && !reply
->persistent()) {
1602 // The peer wants to close the pinned connection
1603 debugs(88, 3, "pinned reply forces close");
1604 request
->flags
.proxyKeepalive
= false;
1605 } else if (http
->getConn()) {
1606 ConnStateData
* conn
= http
->getConn();
1607 if (!Comm::IsConnOpen(conn
->port
->listenConn
)) {
1608 // The listening port closed because of a reconfigure
1609 debugs(88, 3, "listening port closed");
1610 request
->flags
.proxyKeepalive
= false;
1614 // Decide if we send chunked reply
1615 if (maySendChunkedReply
&& reply
->bodySize(request
->method
) < 0) {
1616 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
1617 request
->flags
.chunkedReply
= true;
1618 hdr
->putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
1621 hdr
->addVia(reply
->sline
.version
);
1623 /* Signal keep-alive or close explicitly */
1624 hdr
->putStr(Http::HdrType::CONNECTION
, request
->flags
.proxyKeepalive
? "keep-alive" : "close");
1626 #if ADD_X_REQUEST_URI
1628 * Knowing the URI of the request is useful when debugging persistent
1629 * connections in a client; we cannot guarantee the order of http headers,
1630 * but X-Request-URI is likely to be the very last header to ease use from a
1631 * debugger [hdr->entries.count-1].
1633 hdr
->putStr(Http::HdrType::X_REQUEST_URI
,
1634 http
->memOjbect()->url
? http
->memObject()->url
: http
->uri
);
1638 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1639 if ( hdr
->has(Http::HdrType::SURROGATE_CONTROL
) ) {
1640 if (!request
->header
.has(Http::HdrType::SURROGATE_CAPABILITY
)) {
1641 hdr
->delById(Http::HdrType::SURROGATE_CONTROL
);
1643 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1646 httpHdrMangleList(hdr
, request
, http
->al
, ROR_REPLY
);
1650 clientReplyContext::cloneReply()
1652 assert(reply
== NULL
);
1654 reply
= http
->storeEntry()->mem().freshestReply().clone();
1657 http
->al
->reply
= reply
;
1659 if (reply
->sline
.protocol
== AnyP::PROTO_HTTP
) {
1660 /* RFC 2616 requires us to advertise our version (but only on real HTTP traffic) */
1661 reply
->sline
.version
= Http::ProtocolVersion();
1664 /* do header conversions */
1668 /// Safely disposes of an entry pointing to a cache hit that we do not want.
1669 /// We cannot just ignore the entry because it may be locking or otherwise
1670 /// holding an associated cache resource of some sort.
1672 clientReplyContext::forgetHit()
1674 StoreEntry
*e
= http
->storeEntry();
1675 assert(e
); // or we are not dealing with a hit
1676 // We probably have not locked the entry earlier, unfortunately. We lock it
1677 // now so that we can unlock two lines later (and trigger cleanup).
1678 // Ideally, ClientHttpRequest::storeEntry() should lock/unlock, but it is
1679 // used so inconsistently that simply adding locking there leads to bugs.
1680 e
->lock("clientReplyContext::forgetHit");
1681 http
->storeEntry(NULL
);
1682 e
->unlock("clientReplyContext::forgetHit"); // may delete e
1686 clientReplyContext::identifyStoreObject()
1688 HttpRequest
*r
= http
->request
;
1690 // client sent CC:no-cache or some other condition has been
1691 // encountered which prevents delivering a public/cached object.
1692 if (!r
->flags
.noCache
|| r
->flags
.internal
) {
1693 lookingforstore
= 5;
1694 StoreEntry::getPublicByRequest (this, r
);
1696 identifyFoundObject(nullptr);
1701 * Check state of the current StoreEntry object.
1702 * to see if we can determine the final status of the request.
1705 clientReplyContext::identifyFoundObject(StoreEntry
*newEntry
)
1707 HttpRequest
*r
= http
->request
;
1708 http
->storeEntry(newEntry
);
1709 const auto e
= http
->storeEntry();
1711 /* Release IP-cache entries on reload */
1712 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
1713 * 'invalidate' the cached IP entries for this request ???
1715 if (r
->flags
.noCache
|| r
->flags
.noCacheHack())
1716 ipcacheInvalidateNegative(r
->url
.host());
1718 #if USE_CACHE_DIGESTS
1719 lookup_type
= e
? "HIT" : "MISS";
1723 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
1724 debugs(85, 3, "StoreEntry is NULL - MISS");
1725 http
->logType
.update(LOG_TCP_MISS
);
1730 if (Config
.onoff
.offline
) {
1731 /** \li If we are running in offline mode set to HIT */
1732 debugs(85, 3, "offline HIT " << *e
);
1733 http
->logType
.update(LOG_TCP_HIT
);
1738 if (http
->redirect
.status
) {
1739 /** \li If redirection status is True force this to be a MISS */
1740 debugs(85, 3, "REDIRECT status forced StoreEntry to NULL (no body on 3XX responses) " << *e
);
1742 http
->logType
.update(LOG_TCP_REDIRECT
);
1747 if (!e
->validToSend()) {
1748 debugs(85, 3, "!storeEntryValidToSend MISS " << *e
);
1750 http
->logType
.update(LOG_TCP_MISS
);
1755 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1756 /* \li Special entries are always hits, no matter what the client says */
1757 debugs(85, 3, "ENTRY_SPECIAL HIT " << *e
);
1758 http
->logType
.update(LOG_TCP_HIT
);
1763 if (r
->flags
.noCache
) {
1764 debugs(85, 3, "no-cache REFRESH MISS " << *e
);
1766 http
->logType
.update(LOG_TCP_CLIENT_REFRESH_MISS
);
1771 if (e
->hittingRequiresCollapsing() && !startCollapsingOn(*e
, false)) {
1772 debugs(85, 3, "prohibited CF MISS " << *e
);
1774 http
->logType
.update(LOG_TCP_MISS
);
1779 debugs(85, 3, "default HIT " << *e
);
1780 http
->logType
.update(LOG_TCP_HIT
);
1785 * Request more data from the store for the client Stream
1786 * This is *the* entry point to this module.
1789 * - This is the head of the list.
1790 * - There is at least one more node.
1791 * - Data context is not null
1794 clientGetMoreData(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1796 /* Test preconditions */
1797 assert(aNode
!= NULL
);
1798 assert(cbdataReferenceValid(aNode
));
1799 assert(aNode
->node
.prev
== NULL
);
1800 assert(aNode
->node
.next
!= NULL
);
1801 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1803 assert(context
->http
== http
);
1805 clientStreamNode
*next
= ( clientStreamNode
*)aNode
->node
.next
->data
;
1807 if (!context
->ourNode
)
1808 context
->ourNode
= aNode
;
1810 /* no cbdatareference, this is only used once, and safely */
1811 if (context
->flags
.storelogiccomplete
) {
1812 StoreIOBuffer tempBuffer
;
1813 tempBuffer
.offset
= next
->readBuffer
.offset
+ context
->headers_sz
;
1814 tempBuffer
.length
= next
->readBuffer
.length
;
1815 tempBuffer
.data
= next
->readBuffer
.data
;
1817 storeClientCopy(context
->sc
, http
->storeEntry(),
1818 tempBuffer
, clientReplyContext::SendMoreData
, context
);
1822 if (context
->http
->request
->method
== Http::METHOD_PURGE
) {
1823 context
->purgeRequest();
1827 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
1829 if (context
->http
->request
->method
== Http::METHOD_TRACE
) {
1830 if (context
->http
->request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0) {
1831 context
->traceReply(aNode
);
1835 /* continue forwarding, not finished yet. */
1836 http
->logType
.update(LOG_TCP_MISS
);
1838 context
->doGetMoreData();
1840 context
->identifyStoreObject();
1844 clientReplyContext::doGetMoreData()
1846 /* We still have to do store logic processing - vary, cache hit etc */
1847 if (http
->storeEntry() != NULL
) {
1848 /* someone found the object in the cache for us */
1849 StoreIOBuffer localTempBuffer
;
1851 http
->storeEntry()->lock("clientReplyContext::doGetMoreData");
1853 http
->storeEntry()->ensureMemObject(storeId(), http
->log_uri
, http
->request
->method
);
1855 sc
= storeClientListAdd(http
->storeEntry(), this);
1857 sc
->setDelayId(DelayId::DelayClient(http
));
1860 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
1862 /* guarantee nothing has been sent yet! */
1863 assert(http
->out
.size
== 0);
1864 assert(http
->out
.offset
== 0);
1866 if (ConnStateData
*conn
= http
->getConn()) {
1867 if (Ip::Qos::TheConfig
.isHitTosActive()) {
1868 Ip::Qos::doTosLocalHit(conn
->clientConnection
);
1871 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
1872 Ip::Qos::doNfmarkLocalHit(conn
->clientConnection
);
1876 localTempBuffer
.offset
= reqofs
;
1877 localTempBuffer
.length
= getNextNode()->readBuffer
.length
;
1878 localTempBuffer
.data
= getNextNode()->readBuffer
.data
;
1879 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, CacheHit
, this);
1881 /* MISS CASE, http->logType is already set! */
1886 /** The next node has removed itself from the stream. */
1888 clientReplyDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1890 /** detach from the stream */
1891 clientStreamDetach(node
, http
);
1895 * Accepts chunk of a http message in buf, parses prefix, filters headers and
1896 * such, writes processed message to the message recipient
1899 clientReplyContext::SendMoreData(void *data
, StoreIOBuffer result
)
1901 clientReplyContext
*context
= static_cast<clientReplyContext
*>(data
);
1902 context
->sendMoreData (result
);
1906 clientReplyContext::makeThisHead()
1908 /* At least, I think that's what this does */
1909 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1910 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1914 clientReplyContext::errorInStream(StoreIOBuffer
const &result
, size_t const &sizeToProcess
)const
1916 return /* aborted request */
1917 (http
->storeEntry() && EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) ||
1918 /* Upstream read error */ (result
.flags
.error
) ||
1919 /* Upstream EOF */ (sizeToProcess
== 0);
1923 clientReplyContext::sendStreamError(StoreIOBuffer
const &result
)
1925 /** call clientWriteComplete so the client socket gets closed
1927 * We call into the stream, because we don't know that there is a
1930 debugs(88, 5, "A stream error has occurred, marking as complete and sending no data.");
1931 StoreIOBuffer localTempBuffer
;
1933 http
->request
->flags
.streamError
= true;
1934 localTempBuffer
.flags
.error
= result
.flags
.error
;
1935 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1940 clientReplyContext::pushStreamData(StoreIOBuffer
const &result
, char *source
)
1942 StoreIOBuffer localTempBuffer
;
1944 if (result
.length
== 0) {
1945 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
1949 assert(result
.offset
- headers_sz
== next()->readBuffer
.offset
);
1950 localTempBuffer
.offset
= result
.offset
- headers_sz
;
1951 localTempBuffer
.length
= result
.length
;
1953 if (localTempBuffer
.length
)
1954 localTempBuffer
.data
= source
;
1956 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1961 clientReplyContext::next() const
1963 assert ( (clientStreamNode
*)http
->client_stream
.head
->next
->data
== getNextNode());
1964 return getNextNode();
1968 clientReplyContext::sendBodyTooLargeError()
1970 Ip::Address tmp_noaddr
;
1971 tmp_noaddr
.setNoAddr(); // TODO: make a global const
1972 http
->logType
.update(LOG_TCP_DENIED_REPLY
);
1973 ErrorState
*err
= clientBuildError(ERR_TOO_BIG
, Http::scForbidden
, NULL
,
1974 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
1975 http
->request
, http
->al
);
1976 removeClientStoreReference(&(sc
), http
);
1977 HTTPMSGUNLOCK(reply
);
1982 /// send 412 (Precondition Failed) to client
1984 clientReplyContext::sendPreconditionFailedError()
1986 http
->logType
.update(LOG_TCP_HIT
);
1987 Ip::Address tmp_noaddr
;
1988 tmp_noaddr
.setNoAddr();
1989 ErrorState
*const err
=
1990 clientBuildError(ERR_PRECONDITION_FAILED
, Http::scPreconditionFailed
,
1991 NULL
, http
->getConn() ? http
->getConn()->clientConnection
->remote
: tmp_noaddr
, http
->request
, http
->al
);
1992 removeClientStoreReference(&sc
, http
);
1993 HTTPMSGUNLOCK(reply
);
1997 /// send 304 (Not Modified) to client
1999 clientReplyContext::sendNotModified()
2001 StoreEntry
*e
= http
->storeEntry();
2002 const time_t timestamp
= e
->timestamp
;
2003 const auto temprep
= e
->mem().freshestReply().make304();
2004 // log as TCP_INM_HIT if code 304 generated for
2005 // If-None-Match request
2006 if (!http
->request
->flags
.ims
)
2007 http
->logType
.update(LOG_TCP_INM_HIT
);
2009 http
->logType
.update(LOG_TCP_IMS_HIT
);
2010 removeClientStoreReference(&sc
, http
);
2011 createStoreEntry(http
->request
->method
, RequestFlags());
2012 e
= http
->storeEntry();
2013 // Copy timestamp from the original entry so the 304
2014 // reply has a meaningful Age: header.
2016 e
->timestamp
= timestamp
;
2017 e
->replaceHttpReply(temprep
);
2020 * TODO: why put this in the store and then serialise it and
2021 * then parse it again. Simply mark the request complete in
2022 * our context and write the reply struct to the client side.
2024 triggerInitialStoreRead();
2027 /// send 304 (Not Modified) or 412 (Precondition Failed) to client
2028 /// depending on request method
2030 clientReplyContext::sendNotModifiedOrPreconditionFailedError()
2032 if (http
->request
->method
== Http::METHOD_GET
||
2033 http
->request
->method
== Http::METHOD_HEAD
)
2036 sendPreconditionFailedError();
2040 clientReplyContext::processReplyAccess ()
2042 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
2045 /** Don't block our own responses or HTTP status messages */
2046 if (http
->logType
.oldType
== LOG_TCP_DENIED
||
2047 http
->logType
.oldType
== LOG_TCP_DENIED_REPLY
||
2048 alwaysAllowResponse(reply
->sline
.status())) {
2049 headers_sz
= reply
->hdr_sz
;
2050 processReplyAccessResult(ACCESS_ALLOWED
);
2054 /** Check for reply to big error */
2055 if (reply
->expectedBodyTooLarge(*http
->request
)) {
2056 sendBodyTooLargeError();
2060 headers_sz
= reply
->hdr_sz
;
2062 /** check for absent access controls (permit by default) */
2063 if (!Config
.accessList
.reply
) {
2064 processReplyAccessResult(ACCESS_ALLOWED
);
2068 /** Process http_reply_access lists */
2069 ACLFilledChecklist
*replyChecklist
=
2070 clientAclChecklistCreate(Config
.accessList
.reply
, http
);
2071 replyChecklist
->reply
= reply
;
2072 HTTPMSGLOCK(replyChecklist
->reply
);
2073 replyChecklist
->nonBlockingCheck(ProcessReplyAccessResult
, this);
2077 clientReplyContext::ProcessReplyAccessResult(Acl::Answer rv
, void *voidMe
)
2079 clientReplyContext
*me
= static_cast<clientReplyContext
*>(voidMe
);
2080 me
->processReplyAccessResult(rv
);
2084 clientReplyContext::processReplyAccessResult(const Acl::Answer
&accessAllowed
)
2086 debugs(88, 2, "The reply for " << http
->request
->method
2087 << ' ' << http
->uri
<< " is " << accessAllowed
<< ", because it matched "
2088 << (AclMatchedName
? AclMatchedName
: "NO ACL's"));
2090 if (!accessAllowed
.allowed()) {
2093 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, 1);
2095 http
->logType
.update(LOG_TCP_DENIED_REPLY
);
2097 if (page_id
== ERR_NONE
)
2098 page_id
= ERR_ACCESS_DENIED
;
2100 Ip::Address tmp_noaddr
;
2101 tmp_noaddr
.setNoAddr();
2102 err
= clientBuildError(page_id
, Http::scForbidden
, NULL
,
2103 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
2104 http
->request
, http
->al
);
2106 removeClientStoreReference(&sc
, http
);
2108 HTTPMSGUNLOCK(reply
);
2115 /* Ok, the reply is allowed, */
2116 http
->loggingEntry(http
->storeEntry());
2118 ssize_t body_size
= reqofs
- reply
->hdr_sz
;
2119 if (body_size
< 0) {
2120 reqofs
= reply
->hdr_sz
;
2124 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
2125 (int) body_size
<< " bytes after " << reply
->hdr_sz
<<
2126 " bytes of headers");
2130 if (http
->flags
.accel
&& reply
->sline
.status() != Http::scForbidden
&&
2131 !alwaysAllowResponse(reply
->sline
.status()) &&
2132 esiEnableProcessing(reply
)) {
2133 debugs(88, 2, "Enabling ESI processing for " << http
->uri
);
2134 clientStreamInsertHead(&http
->client_stream
, esiStreamRead
,
2135 esiProcessStream
, esiStreamDetach
, esiStreamStatus
, NULL
);
2140 if (http
->request
->method
== Http::METHOD_HEAD
) {
2141 /* do not forward body for HEAD replies */
2143 http
->flags
.done_copying
= true;
2147 assert (!flags
.headersSent
);
2148 flags
.headersSent
= true;
2150 StoreIOBuffer localTempBuffer
;
2151 char *buf
= next()->readBuffer
.data
;
2152 char *body_buf
= buf
+ reply
->hdr_sz
;
2154 //Server side may disable ranges under some circumstances.
2156 if ((!http
->request
->range
))
2157 next()->readBuffer
.offset
= 0;
2159 body_buf
-= next()->readBuffer
.offset
;
2161 if (next()->readBuffer
.offset
!= 0) {
2162 if (next()->readBuffer
.offset
> body_size
) {
2163 /* Can't use any of the body we received. send nothing */
2164 localTempBuffer
.length
= 0;
2165 localTempBuffer
.data
= NULL
;
2167 localTempBuffer
.length
= body_size
- next()->readBuffer
.offset
;
2168 localTempBuffer
.data
= body_buf
+ next()->readBuffer
.offset
;
2171 localTempBuffer
.length
= body_size
;
2172 localTempBuffer
.data
= body_buf
;
2175 /* TODO??: move the data in the buffer back by the request header size */
2176 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
,
2177 http
, reply
, localTempBuffer
);
2183 clientReplyContext::sendMoreData (StoreIOBuffer result
)
2188 StoreEntry
*entry
= http
->storeEntry();
2190 if (ConnStateData
* conn
= http
->getConn()) {
2191 if (!conn
->isOpen()) {
2192 debugs(33,3, "not sending more data to closing connection " << conn
->clientConnection
);
2195 if (conn
->pinning
.zeroReply
) {
2196 debugs(33,3, "not sending more data after a pinned zero reply " << conn
->clientConnection
);
2200 if (reqofs
==0 && !http
->logType
.isTcpHit()) {
2201 if (Ip::Qos::TheConfig
.isHitTosActive()) {
2202 Ip::Qos::doTosLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2204 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
2205 Ip::Qos::doNfmarkLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2209 debugs(88, 5, conn
->clientConnection
<<
2210 " '" << entry
->url() << "'" <<
2211 " out.offset=" << http
->out
.offset
);
2214 char *buf
= next()->readBuffer
.data
;
2216 if (buf
!= result
.data
) {
2217 /* we've got to copy some data */
2218 assert(result
.length
<= next()->readBuffer
.length
);
2219 memcpy(buf
, result
.data
, result
.length
);
2222 /* We've got the final data to start pushing... */
2223 flags
.storelogiccomplete
= 1;
2225 reqofs
+= result
.length
;
2227 assert(reqofs
<= HTTP_REQBUF_SZ
|| flags
.headersSent
);
2229 assert(http
->request
!= NULL
);
2231 /* ESI TODO: remove this assert once everything is stable */
2232 assert(http
->client_stream
.head
->data
2233 && cbdataReferenceValid(http
->client_stream
.head
->data
));
2237 debugs(88, 5, "clientReplyContext::sendMoreData: " << http
->uri
<< ", " <<
2238 reqofs
<< " bytes (" << result
.length
<<
2241 /* update size of the request */
2244 if (errorInStream(result
, reqofs
)) {
2245 sendStreamError(result
);
2249 if (flags
.headersSent
) {
2250 pushStreamData (result
, buf
);
2258 sc
->setDelayId(DelayId::DelayClient(http
,reply
));
2261 holdingBuffer
= result
;
2262 processReplyAccess();
2267 clientReplyContext::fillChecklist(ACLFilledChecklist
&checklist
) const
2269 clientAclChecklistFill(checklist
, http
);
2272 /* Using this breaks the client layering just a little!
2275 clientReplyContext::createStoreEntry(const HttpRequestMethod
& m
, RequestFlags reqFlags
)
2277 assert(http
!= NULL
);
2279 * For erroneous requests, we might not have a h->request,
2280 * so make a fake one.
2283 if (http
->request
== NULL
) {
2284 const MasterXaction::Pointer mx
= new MasterXaction(XactionInitiator::initClient
);
2285 // XXX: These fake URI parameters shadow the real (or error:...) URI.
2286 // TODO: Either always set the request earlier and assert here OR use
2287 // http->uri (converted to Anyp::Uri) to create this catch-all request.
2288 const_cast<HttpRequest
*&>(http
->request
) = new HttpRequest(m
, AnyP::PROTO_NONE
, "http", null_string
, mx
);
2289 HTTPMSGLOCK(http
->request
);
2292 StoreEntry
*e
= storeCreateEntry(storeId(), http
->log_uri
, reqFlags
, m
);
2294 // Make entry collapsible ASAP, to increase collapsing chances for others,
2295 // TODO: every must-revalidate and similar request MUST reach the origin,
2296 // but do we have to prohibit others from collapsing on that request?
2297 if (reqFlags
.cachable
&&
2298 !reqFlags
.needValidation
&&
2299 (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
) &&
2300 mayInitiateCollapsing()) {
2301 // make the entry available for future requests now
2302 (void)Store::Root().allowCollapsing(e
, reqFlags
, m
);
2305 sc
= storeClientListAdd(e
, this);
2308 sc
->setDelayId(DelayId::DelayClient(http
));
2315 /* I don't think this is actually needed! -- adrian */
2316 /* http->reqbuf = http->norm_reqbuf; */
2317 // assert(http->reqbuf == http->norm_reqbuf);
2318 /* The next line is illegal because we don't know if the client stream
2319 * buffers have been set up
2321 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2322 // SendMoreData, this);
2323 /* So, we mark the store logic as complete */
2324 flags
.storelogiccomplete
= 1;
2326 /* and get the caller to request a read, from wherever they are */
2327 /* NOTE: after ANY data flows down the pipe, even one step,
2328 * this function CAN NOT be used to manage errors
2330 http
->storeEntry(e
);
2334 clientBuildError(err_type page_id
, Http::StatusCode status
, char const *url
,
2335 Ip::Address
&src_addr
, HttpRequest
* request
, const AccessLogEntry::Pointer
&al
)
2337 const auto err
= new ErrorState(page_id
, status
, request
, al
);
2338 err
->src_addr
= src_addr
;
2341 err
->url
= xstrdup(url
);