2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 88 Client-side Reply Routines */
12 #include "acl/FilledChecklist.h"
13 #include "acl/Gadgets.h"
14 #include "anyp/PortCfg.h"
15 #include "client_side_reply.h"
16 #include "errorpage.h"
20 #include "format/Token.h"
23 #include "http/Stream.h"
24 #include "HttpHeaderTools.h"
25 #include "HttpReply.h"
26 #include "HttpRequest.h"
27 #include "ip/QosConfig.h"
29 #include "log/access_log.h"
30 #include "MemObject.h"
31 #include "mime_header.h"
32 #include "neighbors.h"
34 #include "RequestFlags.h"
35 #include "SquidConfig.h"
36 #include "SquidTime.h"
42 #include "auth/UserRequest.h"
45 #include "DelayPools.h"
53 CBDATA_CLASS_INIT(clientReplyContext
);
56 extern "C" CSS clientReplyStatus
;
57 ErrorState
*clientBuildError(err_type
, Http::StatusCode
, char const *, Ip::Address
&, HttpRequest
*);
61 clientReplyContext::~clientReplyContext()
64 /* This may trigger a callback back into SendMoreData as the cbdata
67 removeClientStoreReference(&sc
, http
);
68 /* old_entry might still be set if we didn't yet get the reply
69 * code in HandleIMSReply() */
70 removeStoreReference(&old_sc
, &old_entry
);
71 safe_free(tempBuffer
.data
);
72 cbdataReferenceDone(http
);
76 clientReplyContext::clientReplyContext(ClientHttpRequest
*clientContext
) :
77 purgeStatus(Http::scNone
),
79 http(cbdataReference(clientContext
)),
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 ErrorState
*errstate
= clientBuildError(err
, status
, uri
, addr
, failedrequest
);
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_reqsize
= reqsize
;
208 tempBuffer
.offset
= reqofs
;
209 /* Prevent accessing the now saved entries */
210 http
->storeEntry(NULL
);
217 clientReplyContext::restoreState()
219 assert(old_sc
!= NULL
);
220 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
221 removeClientStoreReference(&sc
, http
);
222 http
->storeEntry(old_entry
);
224 reqsize
= old_reqsize
;
225 reqofs
= tempBuffer
.offset
;
226 /* Prevent accessed the old saved entries */
230 tempBuffer
.offset
= 0;
234 clientReplyContext::startError(ErrorState
* err
)
236 createStoreEntry(http
->request
->method
, RequestFlags());
237 triggerInitialStoreRead();
238 errorAppendEntry(http
->storeEntry(), err
);
242 clientReplyContext::getNextNode() const
244 return (clientStreamNode
*)ourNode
->node
.next
->data
;
247 /* This function is wrong - the client parameters don't include the
251 clientReplyContext::triggerInitialStoreRead()
253 /* when confident, 0 becomes reqofs, and then this factors into
257 StoreIOBuffer
localTempBuffer (next()->readBuffer
.length
, 0, next()->readBuffer
.data
);
258 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, SendMoreData
, this);
261 /* there is an expired entry in the store.
262 * setup a temporary buffer area and perform an IMS to the origin
265 clientReplyContext::processExpired()
267 const char *url
= storeId();
268 debugs(88, 3, "clientReplyContext::processExpired: '" << http
->uri
<< "'");
269 assert(http
->storeEntry()->lastmod
>= 0);
271 * check if we are allowed to contact other servers
272 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
273 * a stale entry *if* it matches client requirements
276 if (http
->onlyIfCached()) {
277 processOnlyIfCachedMiss();
281 http
->logType
= LOG_TCP_REFRESH
;
282 http
->request
->flags
.refresh
= true;
283 #if STORE_CLIENT_LIST_DEBUG
284 /* Prevent a race with the store client memory free routines
286 assert(storeClientIsThisAClient(sc
, this));
288 /* Prepare to make a new temporary request */
291 // TODO: support collapsed revalidation for Vary-controlled entries
292 const bool collapsingAllowed
= Config
.onoff
.collapsed_forwarding
&&
293 !Store::Root().smpAware() &&
294 http
->request
->vary_headers
.isEmpty();
296 StoreEntry
*entry
= nullptr;
297 if (collapsingAllowed
) {
298 if ((entry
= storeGetPublicByRequest(http
->request
, ksRevalidation
)))
299 entry
->lock("clientReplyContext::processExpired#alreadyRevalidating");
303 debugs(88, 5, "collapsed on existing revalidation entry: " << *entry
);
304 collapsedRevalidation
= crSlave
;
306 entry
= storeCreateEntry(url
,
307 http
->log_uri
, http
->request
->flags
, http
->request
->method
);
308 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
310 if (collapsingAllowed
) {
311 debugs(88, 5, "allow other revalidation requests to collapse on " << *entry
);
312 Store::Root().allowCollapsing(entry
, http
->request
->flags
,
313 http
->request
->method
);
314 collapsedRevalidation
= crInitiator
;
316 collapsedRevalidation
= crNone
;
320 sc
= storeClientListAdd(entry
, this);
322 /* delay_id is already set on original store client */
323 sc
->setDelayId(DelayId::DelayClient(http
));
326 http
->request
->lastmod
= old_entry
->lastmod
;
328 if (!http
->request
->header
.has(Http::HdrType::IF_NONE_MATCH
)) {
329 ETag etag
= {NULL
, -1}; // TODO: make that a default ETag constructor
330 if (old_entry
->hasEtag(etag
) && !etag
.weak
)
331 http
->request
->etag
= etag
.str
;
334 debugs(88, 5, "clientReplyContext::processExpired : lastmod " << entry
->lastmod
);
335 http
->storeEntry(entry
);
336 assert(http
->out
.offset
== 0);
337 assert(http
->request
->clientConnectionManager
== http
->getConn());
339 if (collapsedRevalidation
!= crSlave
) {
341 * A refcounted pointer so that FwdState stays around as long as
342 * this clientReplyContext does
344 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
345 FwdState::Start(conn
, http
->storeEntry(), http
->request
, http
->al
);
347 /* Register with storage manager to receive updates when data comes in. */
349 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
350 debugs(88, DBG_CRITICAL
, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
353 /* start counting the length from 0 */
354 StoreIOBuffer
localTempBuffer(HTTP_REQBUF_SZ
, 0, tempbuf
);
355 storeClientCopy(sc
, entry
, localTempBuffer
, HandleIMSReply
, this);
360 clientReplyContext::sendClientUpstreamResponse()
362 StoreIOBuffer tempresult
;
363 removeStoreReference(&old_sc
, &old_entry
);
364 /* here the data to send is the data we just received */
365 tempBuffer
.offset
= 0;
367 /* sendMoreData tracks the offset as well.
368 * Force it back to zero */
370 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
371 /* TODO: provide sendMoreData with the ready parsed reply */
372 tempresult
.length
= reqsize
;
373 tempresult
.data
= tempbuf
;
374 sendMoreData(tempresult
);
378 clientReplyContext::HandleIMSReply(void *data
, StoreIOBuffer result
)
380 clientReplyContext
*context
= (clientReplyContext
*)data
;
381 context
->handleIMSReply(result
);
385 clientReplyContext::sendClientOldEntry()
387 /* Get the old request back */
389 /* here the data to send is in the next nodes buffers already */
390 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
391 /* sendMoreData tracks the offset as well.
392 * Force it back to zero */
394 StoreIOBuffer
tempresult (reqsize
, reqofs
, next()->readBuffer
.data
);
395 sendMoreData(tempresult
);
398 /* This is the workhorse of the HandleIMSReply callback.
400 * It is called when we've got data back from the origin following our
401 * IMS request to revalidate a stale entry.
404 clientReplyContext::handleIMSReply(StoreIOBuffer result
)
409 debugs(88, 3, "handleIMSReply: " << http
->storeEntry()->url() << ", " << (long unsigned) result
.length
<< " bytes" );
411 if (http
->storeEntry() == NULL
)
414 if (result
.flags
.error
&& !EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
))
417 /* update size of the request */
418 reqsize
= result
.length
+ reqofs
;
420 const Http::StatusCode status
= http
->storeEntry()->getReply()->sline
.status();
422 // request to origin was aborted
423 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
424 debugs(88, 3, "handleIMSReply: request to origin aborted '" << http
->storeEntry()->url() << "', sending old entry to client" );
425 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
426 sendClientOldEntry();
429 const HttpReply
*old_rep
= old_entry
->getReply();
431 // origin replied 304
432 if (status
== Http::scNotModified
) {
433 http
->logType
= LOG_TCP_REFRESH_UNMODIFIED
;
434 http
->request
->flags
.staleIfHit
= false; // old_entry is no longer stale
436 // update headers on existing entry
437 Store::Root().updateOnNotModified(old_entry
, *http
->storeEntry());
439 // if client sent IMS
441 if (http
->request
->flags
.ims
&& !old_entry
->modifiedSince(http
->request
)) {
442 // forward the 304 from origin
443 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and forwarding 304 to client");
444 sendClientUpstreamResponse();
446 // send existing entry, it's still valid
447 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and sending " <<
448 old_rep
->sline
.status() << " to client");
449 sendClientOldEntry();
453 // origin replied with a non-error code
454 else if (status
> Http::scNone
&& status
< Http::scInternalServerError
) {
455 // forward response from origin
456 http
->logType
= LOG_TCP_REFRESH_MODIFIED
;
457 debugs(88, 3, "handleIMSReply: origin replied " << status
<< ", replacing existing entry and forwarding to client");
459 if (collapsedRevalidation
)
460 http
->storeEntry()->clearPublicKeyScope();
462 sendClientUpstreamResponse();
465 // origin replied with an error
466 else if (http
->request
->flags
.failOnValidationError
) {
467 http
->logType
= LOG_TCP_REFRESH_FAIL_ERR
;
468 debugs(88, 3, "handleIMSReply: origin replied with error " << status
<<
469 ", forwarding to client due to fail_on_validation_err");
470 sendClientUpstreamResponse();
472 // ignore and let client have old entry
473 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
474 debugs(88, 3, "handleIMSReply: origin replied with error " <<
475 status
<< ", sending old entry (" << old_rep
->sline
.status() << ") to client");
476 sendClientOldEntry();
480 SQUIDCEXTERN CSR clientGetMoreData
;
481 SQUIDCEXTERN CSD clientReplyDetach
;
484 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
485 * have been parsed. Normally this should be a single call, but
486 * it might take more than one. As soon as we have the headers,
487 * we hand off to clientSendMoreData, processExpired, or
491 clientReplyContext::CacheHit(void *data
, StoreIOBuffer result
)
493 clientReplyContext
*context
= (clientReplyContext
*)data
;
494 context
->cacheHit(result
);
498 * Process a possible cache HIT.
501 clientReplyContext::cacheHit(StoreIOBuffer result
)
503 /** Ignore if the HIT object is being deleted. */
505 debugs(88, 3, "HIT object being deleted. Ignore the HIT.");
509 StoreEntry
*e
= http
->storeEntry();
511 HttpRequest
*r
= http
->request
;
513 debugs(88, 3, "clientCacheHit: " << http
->uri
<< ", " << result
.length
<< " bytes");
515 if (http
->storeEntry() == NULL
) {
516 debugs(88, 3, "clientCacheHit: request aborted");
518 } else if (result
.flags
.error
) {
519 /* swap in failure */
520 debugs(88, 3, "clientCacheHit: swapin failure for " << http
->uri
);
521 http
->logType
= LOG_TCP_SWAPFAIL_MISS
;
522 removeClientStoreReference(&sc
, http
);
527 if (result
.length
== 0) {
528 debugs(88, 5, "store IO buffer has no content. MISS");
529 /* the store couldn't get enough data from the file for us to id the
532 /* treat as a miss */
533 http
->logType
= LOG_TCP_MISS
;
538 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
539 /* update size of the request */
540 reqsize
= result
.length
+ reqofs
;
543 * Got the headers, now grok them
545 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
547 if (http
->request
->storeId().cmp(e
->mem_obj
->storeId()) != 0) {
548 debugs(33, DBG_IMPORTANT
, "clientProcessHit: URL mismatch, '" << e
->mem_obj
->storeId() << "' != '" << http
->request
->storeId() << "'");
549 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
554 switch (varyEvaluateMatch(e
, r
)) {
557 /* No variance detected. Continue as normal */
561 /* This is the correct entity for this request. Continue */
562 debugs(88, 2, "clientProcessHit: Vary MATCH!");
566 /* This is not the correct entity for this request. We need
567 * to requery the cache.
569 removeClientStoreReference(&sc
, http
);
571 /* Note: varyEvalyateMatch updates the request with vary information
572 * so we only get here once. (it also takes care of cancelling loops)
574 debugs(88, 2, "clientProcessHit: Vary detected!");
575 clientGetMoreData(ourNode
, http
);
579 /* varyEvaluateMatch found a object loop. Process as miss */
580 debugs(88, DBG_IMPORTANT
, "clientProcessHit: Vary object loop!");
581 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
586 if (r
->method
== Http::METHOD_PURGE
) {
587 debugs(88, 5, "PURGE gets a HIT");
588 removeClientStoreReference(&sc
, http
);
594 if (e
->checkNegativeHit() && !r
->flags
.noCacheHack()) {
595 debugs(88, 5, "negative-HIT");
596 http
->logType
= LOG_TCP_NEGATIVE_HIT
;
597 sendMoreData(result
);
598 } else if (blockedHit()) {
599 debugs(88, 5, "send_hit forces a MISS");
600 http
->logType
= LOG_TCP_MISS
;
603 } else if (!http
->flags
.internal
&& refreshCheckHTTP(e
, r
)) {
604 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
606 * We hold a stale copy; it needs to be validated
609 * The 'needValidation' flag is used to prevent forwarding
610 * loops between siblings. If our copy of the object is stale,
611 * then we should probably only use parents for the validation
612 * request. Otherwise two siblings could generate a loop if
613 * both have a stale version of the object.
615 r
->flags
.needValidation
= true;
617 if (e
->lastmod
< 0) {
618 debugs(88, 3, "validate HIT object? NO. Missing Last-Modified header. Do MISS.");
620 * Previous reply didn't have a Last-Modified header,
621 * we cannot revalidate it.
623 http
->logType
= LOG_TCP_MISS
;
625 } else if (r
->flags
.noCache
) {
626 debugs(88, 3, "validate HIT object? NO. Client sent CC:no-cache. Do CLIENT_REFRESH_MISS");
628 * This did not match a refresh pattern that overrides no-cache
629 * we should honour the client no-cache header.
631 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
633 } else if (r
->url
.getScheme() == AnyP::PROTO_HTTP
) {
634 debugs(88, 3, "validate HIT object? YES.");
636 * Object needs to be revalidated
637 * XXX This could apply to FTP as well, if Last-Modified is known.
641 debugs(88, 3, "validate HIT object? NO. Client protocol non-HTTP. Do MISS.");
643 * We don't know how to re-validate other protocols. Handle
644 * them as if the object has expired.
646 http
->logType
= LOG_TCP_MISS
;
649 } else if (r
->conditional()) {
650 debugs(88, 5, "conditional HIT");
651 processConditional(result
);
654 * plain ol' cache hit
656 debugs(88, 5, "plain old HIT");
659 if (e
->store_status
!= STORE_OK
)
660 http
->logType
= LOG_TCP_MISS
;
663 if (e
->mem_status
== IN_MEMORY
)
664 http
->logType
= LOG_TCP_MEM_HIT
;
665 else if (Config
.onoff
.offline
)
666 http
->logType
= LOG_TCP_OFFLINE_HIT
;
668 sendMoreData(result
);
673 * Prepare to fetch the object as it's a cache miss of some kind.
676 clientReplyContext::processMiss()
678 char *url
= http
->uri
;
679 HttpRequest
*r
= http
->request
;
680 ErrorState
*err
= NULL
;
681 debugs(88, 4, r
->method
<< ' ' << url
);
684 * We might have a left-over StoreEntry from a failed cache hit
687 if (http
->storeEntry()) {
688 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
689 debugs(88, DBG_CRITICAL
, "clientProcessMiss: miss on a special object (" << url
<< ").");
690 debugs(88, DBG_CRITICAL
, "\tlog_type = " << http
->logType
.c_str());
691 http
->storeEntry()->dump(1);
694 removeClientStoreReference(&sc
, http
);
697 /** Check if its a PURGE request to be actioned. */
698 if (r
->method
== Http::METHOD_PURGE
) {
703 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
704 if (r
->method
== Http::METHOD_OTHER
) {
708 /** Check if 'only-if-cached' flag is set. Action if so. */
709 if (http
->onlyIfCached()) {
710 processOnlyIfCachedMiss();
715 if (r
->flags
.loopDetected
) {
716 http
->al
->http
.code
= Http::scForbidden
;
717 err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
718 createStoreEntry(r
->method
, RequestFlags());
719 errorAppendEntry(http
->storeEntry(), err
);
720 triggerInitialStoreRead();
723 assert(http
->out
.offset
== 0);
724 createStoreEntry(r
->method
, r
->flags
);
725 triggerInitialStoreRead();
727 if (http
->redirect
.status
) {
728 HttpReply
*rep
= new HttpReply
;
729 http
->logType
= LOG_TCP_REDIRECT
;
730 http
->storeEntry()->releaseRequest();
731 rep
->redirect(http
->redirect
.status
, http
->redirect
.location
);
732 http
->storeEntry()->replaceHttpReply(rep
);
733 http
->storeEntry()->complete();
737 assert(r
->clientConnectionManager
== http
->getConn());
739 /** Start forwarding to get the new object from network */
740 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
741 FwdState::Start(conn
, http
->storeEntry(), r
, http
->al
);
746 * client issued a request with an only-if-cached cache-control directive;
747 * we did not find a cached object that can be returned without
748 * contacting other servers;
749 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
752 clientReplyContext::processOnlyIfCachedMiss()
754 debugs(88, 4, http
->request
->method
<< ' ' << http
->uri
);
755 http
->al
->http
.code
= Http::scGatewayTimeout
;
756 ErrorState
*err
= clientBuildError(ERR_ONLY_IF_CACHED_MISS
, Http::scGatewayTimeout
, NULL
,
757 http
->getConn()->clientConnection
->remote
, http
->request
);
758 removeClientStoreReference(&sc
, http
);
762 /// process conditional request from client
764 clientReplyContext::processConditional(StoreIOBuffer
&result
)
766 StoreEntry
*const e
= http
->storeEntry();
768 if (e
->getReply()->sline
.status() != Http::scOkay
) {
769 debugs(88, 4, "clientReplyContext::processConditional: Reply code " <<
770 e
->getReply()->sline
.status() << " != 200");
771 http
->logType
= LOG_TCP_MISS
;
776 HttpRequest
&r
= *http
->request
;
778 if (r
.header
.has(Http::HdrType::IF_MATCH
) && !e
->hasIfMatchEtag(r
)) {
779 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
780 sendPreconditionFailedError();
784 bool matchedIfNoneMatch
= false;
785 if (r
.header
.has(Http::HdrType::IF_NONE_MATCH
)) {
786 if (!e
->hasIfNoneMatchEtag(r
)) {
787 // RFC 2616: ignore IMS if If-None-Match did not match
791 r
.header
.delById(Http::HdrType::IF_MODIFIED_SINCE
);
792 http
->logType
= LOG_TCP_MISS
;
793 sendMoreData(result
);
798 // RFC 2616: if If-None-Match matched and there is no IMS,
799 // reply with 304 Not Modified or 412 Precondition Failed
800 sendNotModifiedOrPreconditionFailedError();
804 // otherwise check IMS below to decide if we reply with 304 or 412
805 matchedIfNoneMatch
= true;
809 // handle If-Modified-Since requests from the client
810 if (e
->modifiedSince(&r
)) {
811 http
->logType
= LOG_TCP_IMS_HIT
;
812 sendMoreData(result
);
816 if (matchedIfNoneMatch
) {
817 // If-None-Match matched, reply with 304 Not Modified or
818 // 412 Precondition Failed
819 sendNotModifiedOrPreconditionFailedError();
823 // otherwise reply with 304 Not Modified
828 /// whether squid.conf send_hit prevents us from serving this hit
830 clientReplyContext::blockedHit() const
832 if (!Config
.accessList
.sendHit
)
833 return false; // hits are not blocked by default
835 if (http
->flags
.internal
)
836 return false; // internal content "hits" cannot be blocked
838 if (const HttpReply
*rep
= http
->storeEntry()->getReply()) {
839 std::unique_ptr
<ACLFilledChecklist
> chl(clientAclChecklistCreate(Config
.accessList
.sendHit
, http
));
840 chl
->reply
= const_cast<HttpReply
*>(rep
); // ACLChecklist API bug
841 HTTPMSGLOCK(chl
->reply
);
842 return chl
->fastCheck() != ACCESS_ALLOWED
; // when in doubt, block
845 // This does not happen, I hope, because we are called from CacheHit, which
846 // is called via a storeClientCopy() callback, and store should initialize
847 // the reply before calling that callback.
848 debugs(88, 3, "Missing reply!");
853 clientReplyContext::purgeRequestFindObjectToPurge()
855 /* Try to find a base entry */
856 http
->flags
.purging
= true;
859 // TODO: can we use purgeAllCached() here instead of doing the
860 // getPublicByRequestMethod() dance?
861 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_GET
);
864 // Purges all entries with a given url
865 // TODO: move to SideAgent parent, when we have one
867 * We probably cannot purge Vary-affected responses because their MD5
868 * keys depend on vary headers.
871 purgeEntriesByUrl(HttpRequest
* req
, const char *url
)
874 bool get_or_head_sent
= false;
877 for (HttpRequestMethod
m(Http::METHOD_NONE
); m
!= Http::METHOD_ENUM_END
; ++m
) {
878 if (m
.respMaybeCacheable()) {
879 if (StoreEntry
*entry
= storeGetPublic(url
, m
)) {
880 debugs(88, 5, "purging " << *entry
<< ' ' << m
<< ' ' << url
);
882 neighborsHtcpClear(entry
, url
, req
, m
, HTCP_CLR_INVALIDATION
);
883 if (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
) {
884 get_or_head_sent
= true;
893 if (!get_or_head_sent
) {
894 neighborsHtcpClear(NULL
, url
, req
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_INVALIDATION
);
900 clientReplyContext::purgeAllCached()
902 // XXX: performance regression, c_str() reallocates
903 SBuf
url(http
->request
->effectiveRequestUri());
904 purgeEntriesByUrl(http
->request
, url
.c_str());
908 clientReplyContext::created(StoreEntry
*newEntry
)
910 if (lookingforstore
== 1)
911 purgeFoundGet(newEntry
);
912 else if (lookingforstore
== 2)
913 purgeFoundHead(newEntry
);
914 else if (lookingforstore
== 3)
915 purgeDoPurgeGet(newEntry
);
916 else if (lookingforstore
== 4)
917 purgeDoPurgeHead(newEntry
);
918 else if (lookingforstore
== 5)
919 identifyFoundObject(newEntry
);
923 clientReplyContext::purgeFoundGet(StoreEntry
*newEntry
)
925 if (newEntry
->isNull()) {
927 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
929 purgeFoundObject (newEntry
);
933 clientReplyContext::purgeFoundHead(StoreEntry
*newEntry
)
935 if (newEntry
->isNull())
938 purgeFoundObject (newEntry
);
942 clientReplyContext::purgeFoundObject(StoreEntry
*entry
)
944 assert (entry
&& !entry
->isNull());
946 if (EBIT_TEST(entry
->flags
, ENTRY_SPECIAL
)) {
947 http
->logType
= LOG_TCP_DENIED
;
948 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
,
949 http
->getConn()->clientConnection
->remote
, http
->request
);
951 return; // XXX: leaking unused entry if some store does not keep it
954 StoreIOBuffer localTempBuffer
;
955 /* Swap in the metadata */
956 http
->storeEntry(entry
);
958 http
->storeEntry()->lock("clientReplyContext::purgeFoundObject");
959 http
->storeEntry()->createMemObject(storeId(), http
->log_uri
,
960 http
->request
->method
);
962 sc
= storeClientListAdd(http
->storeEntry(), this);
964 http
->logType
= LOG_TCP_HIT
;
968 localTempBuffer
.offset
= http
->out
.offset
;
970 localTempBuffer
.length
= next()->readBuffer
.length
;
972 localTempBuffer
.data
= next()->readBuffer
.data
;
974 storeClientCopy(sc
, http
->storeEntry(),
975 localTempBuffer
, CacheHit
, this);
979 clientReplyContext::purgeRequest()
981 debugs(88, 3, "Config2.onoff.enable_purge = " <<
982 Config2
.onoff
.enable_purge
);
984 if (!Config2
.onoff
.enable_purge
) {
985 http
->logType
= LOG_TCP_DENIED
;
986 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
991 /* Release both IP cache */
992 ipcacheInvalidate(http
->request
->url
.host());
994 if (!http
->flags
.purging
)
995 purgeRequestFindObjectToPurge();
1001 clientReplyContext::purgeDoMissPurge()
1003 http
->logType
= LOG_TCP_MISS
;
1004 lookingforstore
= 3;
1005 StoreEntry::getPublicByRequestMethod(this,http
->request
, Http::METHOD_GET
);
1009 clientReplyContext::purgeDoPurgeGet(StoreEntry
*newEntry
)
1012 /* Move to new() when that is created */
1013 purgeStatus
= Http::scNotFound
;
1015 if (!newEntry
->isNull()) {
1016 /* Release the cached URI */
1017 debugs(88, 4, "clientPurgeRequest: GET '" << newEntry
->url() << "'" );
1019 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1021 newEntry
->release();
1022 purgeStatus
= Http::scOkay
;
1025 lookingforstore
= 4;
1026 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
1030 clientReplyContext::purgeDoPurgeHead(StoreEntry
*newEntry
)
1032 if (newEntry
&& !newEntry
->isNull()) {
1033 debugs(88, 4, "HEAD " << newEntry
->url());
1035 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1037 newEntry
->release();
1038 purgeStatus
= Http::scOkay
;
1041 /* And for Vary, release the base URI if none of the headers was included in the request */
1042 if (!http
->request
->vary_headers
.isEmpty()
1043 && http
->request
->vary_headers
.find('=') != SBuf::npos
) {
1044 // XXX: performance regression, c_str() reallocates
1045 SBuf
tmp(http
->request
->effectiveRequestUri());
1046 StoreEntry
*entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_GET
);
1049 debugs(88, 4, "Vary GET " << entry
->url());
1051 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1054 purgeStatus
= Http::scOkay
;
1057 entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_HEAD
);
1060 debugs(88, 4, "Vary HEAD " << entry
->url());
1062 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1065 purgeStatus
= Http::scOkay
;
1070 * Make a new entry to hold the reply to be written
1073 /* FIXME: This doesn't need to go through the store. Simply
1074 * push down the client chain
1076 createStoreEntry(http
->request
->method
, RequestFlags());
1078 triggerInitialStoreRead();
1080 HttpReply
*rep
= new HttpReply
;
1081 rep
->setHeaders(purgeStatus
, NULL
, NULL
, 0, 0, -1);
1082 http
->storeEntry()->replaceHttpReply(rep
);
1083 http
->storeEntry()->complete();
1087 clientReplyContext::traceReply(clientStreamNode
* node
)
1089 clientStreamNode
*nextNode
= (clientStreamNode
*)node
->node
.next
->data
;
1090 StoreIOBuffer localTempBuffer
;
1091 createStoreEntry(http
->request
->method
, RequestFlags());
1092 localTempBuffer
.offset
= nextNode
->readBuffer
.offset
+ headers_sz
;
1093 localTempBuffer
.length
= nextNode
->readBuffer
.length
;
1094 localTempBuffer
.data
= nextNode
->readBuffer
.data
;
1095 storeClientCopy(sc
, http
->storeEntry(),
1096 localTempBuffer
, SendMoreData
, this);
1097 http
->storeEntry()->releaseRequest();
1098 http
->storeEntry()->buffer();
1099 HttpReply
*rep
= new HttpReply
;
1100 rep
->setHeaders(Http::scOkay
, NULL
, "text/plain", http
->request
->prefixLen(), 0, squid_curtime
);
1101 http
->storeEntry()->replaceHttpReply(rep
);
1102 http
->request
->swapOut(http
->storeEntry());
1103 http
->storeEntry()->complete();
1106 #define SENDING_BODY 0
1107 #define SENDING_HDRSONLY 1
1109 clientReplyContext::checkTransferDone()
1111 StoreEntry
*entry
= http
->storeEntry();
1117 * For now, 'done_copying' is used for special cases like
1118 * Range and HEAD requests.
1120 if (http
->flags
.done_copying
)
1123 if (http
->request
->flags
.chunkedReply
&& !flags
.complete
) {
1124 // last-chunk was not sent
1129 * Handle STORE_OK objects.
1130 * objectLen(entry) will be set proprely.
1131 * RC: Does objectLen(entry) include the Headers?
1134 if (entry
->store_status
== STORE_OK
) {
1135 return storeOKTransferDone();
1137 return storeNotOKTransferDone();
1142 clientReplyContext::storeOKTransferDone() const
1144 assert(http
->storeEntry()->objectLen() >= 0);
1145 assert(http
->storeEntry()->objectLen() >= headers_sz
);
1146 if (http
->out
.offset
>= http
->storeEntry()->objectLen() - headers_sz
) {
1147 debugs(88,3,HERE
<< "storeOKTransferDone " <<
1148 " out.offset=" << http
->out
.offset
<<
1149 " objectLen()=" << http
->storeEntry()->objectLen() <<
1150 " headers_sz=" << headers_sz
);
1158 clientReplyContext::storeNotOKTransferDone() const
1161 * Now, handle STORE_PENDING objects
1163 MemObject
*mem
= http
->storeEntry()->mem_obj
;
1164 assert(mem
!= NULL
);
1165 assert(http
->request
!= NULL
);
1166 /* mem->reply was wrong because it uses the UPSTREAM header length!!! */
1167 HttpReply
const *curReply
= mem
->getReply();
1169 if (headers_sz
== 0)
1170 /* haven't found end of headers yet */
1174 * Figure out how much data we are supposed to send.
1175 * If we are sending a body and we don't have a content-length,
1176 * then we must wait for the object to become STORE_OK.
1178 if (curReply
->content_length
< 0)
1181 uint64_t expectedLength
= curReply
->content_length
+ http
->out
.headers_sz
;
1183 if (http
->out
.size
< expectedLength
)
1186 debugs(88,3,HERE
<< "storeNotOKTransferDone " <<
1187 " out.size=" << http
->out
.size
<<
1188 " expectedLength=" << expectedLength
);
1193 /* A write has completed, what is the next status based on the
1194 * canonical request data?
1195 * 1 something is wrong
1196 * 0 nothing is wrong.
1200 clientHttpRequestStatus(int fd
, ClientHttpRequest
const *http
)
1202 #if SIZEOF_INT64_T == 4
1203 if (http
->out
.size
> 0x7FFF0000) {
1204 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
<< " to prevent out.size counter overflow");
1205 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1206 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes");
1207 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1211 if (http
->out
.offset
> 0x7FFF0000) {
1212 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
< " to prevent out.offset counter overflow");
1213 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1214 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes, offset " << http
->out
.offset
);
1215 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1224 * *http is a valid structure.
1225 * fd is either -1, or an open fd.
1227 * TODO: enumify this
1229 * This function is used by any http request sink, to determine the status
1232 clientStream_status_t
1233 clientReplyStatus(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1235 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1237 assert (context
->http
== http
);
1238 return context
->replyStatus();
1241 clientStream_status_t
1242 clientReplyContext::replyStatus()
1245 /* Here because lower nodes don't need it */
1247 if (http
->storeEntry() == NULL
) {
1248 debugs(88, 5, "clientReplyStatus: no storeEntry");
1249 return STREAM_FAILED
; /* yuck, but what can we do? */
1252 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
1253 /* TODO: Could upstream read errors (result.flags.error) be
1254 * lost, and result in undersize requests being considered
1255 * complete. Should we tcp reset such connections ?
1257 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
1258 return STREAM_FAILED
;
1261 if ((done
= checkTransferDone()) != 0 || flags
.complete
) {
1262 debugs(88, 5, "clientReplyStatus: transfer is DONE: " << done
<< flags
.complete
);
1263 /* Ok we're finished, but how? */
1265 const int64_t expectedBodySize
=
1266 http
->storeEntry()->getReply()->bodySize(http
->request
->method
);
1267 if (!http
->request
->flags
.proxyKeepalive
&& expectedBodySize
< 0) {
1268 debugs(88, 5, "clientReplyStatus: closing, content_length < 0");
1269 return STREAM_FAILED
;
1272 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_BAD_LENGTH
)) {
1273 debugs(88, 5, "clientReplyStatus: truncated response body");
1274 return STREAM_UNPLANNED_COMPLETE
;
1278 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
1279 return STREAM_FAILED
;
1282 if (expectedBodySize
>= 0 && !http
->gotEnough()) {
1283 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
1284 return STREAM_UNPLANNED_COMPLETE
;
1287 debugs(88, 5, "clientReplyStatus: stream complete; keepalive=" <<
1288 http
->request
->flags
.proxyKeepalive
);
1289 return STREAM_COMPLETE
;
1292 // XXX: Should this be checked earlier? We could return above w/o checking.
1293 if (reply
->receivedBodyTooLarge(*http
->request
, http
->out
.offset
- 4096)) {
1294 /* 4096 is a margin for the HTTP headers included in out.offset */
1295 debugs(88, 5, "clientReplyStatus: client reply body is too large");
1296 return STREAM_FAILED
;
1302 /* Responses with no body will not have a content-type header,
1303 * which breaks the rep_mime_type acl, which
1304 * coincidentally, is the most common acl for reply access lists.
1305 * A better long term fix for this is to allow acl matchs on the various
1306 * status codes, and then supply a default ruleset that puts these
1307 * codes before any user defines access entries. That way the user
1308 * can choose to block these responses where appropriate, but won't get
1309 * mysterious breakages.
1312 clientReplyContext::alwaysAllowResponse(Http::StatusCode sline
) const
1318 case Http::scContinue
:
1320 case Http::scSwitchingProtocols
:
1322 case Http::scProcessing
:
1324 case Http::scNoContent
:
1326 case Http::scNotModified
:
1338 * Generate the reply headers sent to client.
1340 * Filters out unwanted entries and hop-by-hop from original reply header
1341 * then adds extra entries if we have more info than origin server
1342 * then adds Squid specific entries
1345 clientReplyContext::buildReplyHeader()
1347 HttpHeader
*hdr
= &reply
->header
;
1348 const bool is_hit
= http
->logType
.isTcpHit();
1349 HttpRequest
*request
= http
->request
;
1350 #if DONT_FILTER_THESE
1351 /* but you might want to if you run Squid as an HTTP accelerator */
1352 /* hdr->delById(HDR_ACCEPT_RANGES); */
1353 hdr
->delById(HDR_ETAG
);
1357 hdr
->delById(Http::HdrType::SET_COOKIE
);
1358 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
1360 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
1361 // remove the Proxy-Authenticate header
1362 if ( !request
->peer_login
|| (strcmp(request
->peer_login
,"PASS") != 0 && strcmp(request
->peer_login
,"PASSTHRU") != 0))
1363 reply
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1365 reply
->header
.removeHopByHopEntries();
1367 // if (request->range)
1368 // clientBuildRangeHeader(http, reply);
1371 * Add a estimated Age header on cache hits.
1375 * Remove any existing Age header sent by upstream caches
1376 * (note that the existing header is passed along unmodified
1379 hdr
->delById(Http::HdrType::AGE
);
1381 * This adds the calculated object age. Note that the details of the
1382 * age calculation is performed by adjusting the timestamp in
1383 * StoreEntry::timestampsSet(), not here.
1385 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
1386 hdr
->delById(Http::HdrType::DATE
);
1387 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1388 } else if (http
->getConn() && http
->getConn()->port
->actAsOrigin
) {
1389 // Swap the Date: header to current time if we are simulating an origin
1390 HttpHeaderEntry
*h
= hdr
->findEntry(Http::HdrType::DATE
);
1392 hdr
->putExt("X-Origin-Date", h
->value
.termedBuf());
1393 hdr
->delById(Http::HdrType::DATE
);
1394 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1395 h
= hdr
->findEntry(Http::HdrType::EXPIRES
);
1396 if (h
&& http
->storeEntry()->expires
>= 0) {
1397 hdr
->putExt("X-Origin-Expires", h
->value
.termedBuf());
1398 hdr
->delById(Http::HdrType::EXPIRES
);
1399 hdr
->putTime(Http::HdrType::EXPIRES
, squid_curtime
+ http
->storeEntry()->expires
- http
->storeEntry()->timestamp
);
1401 if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1402 // put X-Cache-Age: instead of Age:
1404 snprintf(age
, sizeof(age
), "%" PRId64
, static_cast<int64_t>(squid_curtime
- http
->storeEntry()->timestamp
));
1405 hdr
->putExt("X-Cache-Age", age
);
1407 } else if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1408 hdr
->putInt(Http::HdrType::AGE
,
1409 squid_curtime
- http
->storeEntry()->timestamp
);
1410 /* Signal old objects. NB: rfc 2616 is not clear,
1411 * by implication, on whether we should do this to all
1412 * responses, or only cache hits.
1413 * 14.46 states it ONLY applys for heuristically caclulated
1414 * freshness values, 13.2.4 doesn't specify the same limitation.
1415 * We interpret RFC 2616 under the combination.
1417 /* TODO: if maxage or s-maxage is present, don't do this */
1419 if (squid_curtime
- http
->storeEntry()->timestamp
>= 86400) {
1421 snprintf (tbuf
, sizeof(tbuf
), "%s %s %s",
1423 "This cache hit is still fresh and more than 1 day old");
1424 hdr
->putStr(Http::HdrType::WARNING
, tbuf
);
1429 /* RFC 2616: Section 14.18
1431 * Add a Date: header if missing.
1432 * We have access to a clock therefore are required to amend any shortcoming in servers.
1434 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1436 if ( !hdr
->has(Http::HdrType::DATE
) ) {
1437 if (!http
->storeEntry())
1438 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1439 else if (http
->storeEntry()->timestamp
> 0)
1440 hdr
->putTime(Http::HdrType::DATE
, http
->storeEntry()->timestamp
);
1442 debugs(88,DBG_IMPORTANT
,"BUG 3279: HTTP reply without Date:");
1443 /* dump something useful about the problem */
1444 http
->storeEntry()->dump(DBG_IMPORTANT
);
1448 // add Warnings required by RFC 2616 if serving a stale hit
1449 if (http
->request
->flags
.staleIfHit
&& http
->logType
.isTcpHit()) {
1450 hdr
->putWarning(110, "Response is stale");
1451 if (http
->request
->flags
.needValidation
)
1452 hdr
->putWarning(111, "Revalidation failed");
1455 /* Filter unproxyable authentication types */
1456 if (http
->logType
.oldType
!= LOG_TCP_DENIED
&&
1457 hdr
->has(Http::HdrType::WWW_AUTHENTICATE
)) {
1458 HttpHeaderPos pos
= HttpHeaderInitPos
;
1461 int connection_auth_blocked
= 0;
1462 while ((e
= hdr
->getEntry(&pos
))) {
1463 if (e
->id
== Http::HdrType::WWW_AUTHENTICATE
) {
1464 const char *value
= e
->value
.rawBuf();
1466 if ((strncasecmp(value
, "NTLM", 4) == 0 &&
1467 (value
[4] == '\0' || value
[4] == ' '))
1469 (strncasecmp(value
, "Negotiate", 9) == 0 &&
1470 (value
[9] == '\0' || value
[9] == ' '))
1472 (strncasecmp(value
, "Kerberos", 8) == 0 &&
1473 (value
[8] == '\0' || value
[8] == ' '))) {
1474 if (request
->flags
.connectionAuthDisabled
) {
1475 hdr
->delAt(pos
, connection_auth_blocked
);
1478 request
->flags
.mustKeepalive
= true;
1479 if (!request
->flags
.accelerated
&& !request
->flags
.intercepted
) {
1480 httpHeaderPutStrf(hdr
, Http::HdrType::PROXY_SUPPORT
, "Session-Based-Authentication");
1482 We send "Connection: Proxy-Support" header to mark
1483 Proxy-Support as a hop-by-hop header for intermediaries that do not
1484 understand the semantics of this header. The RFC should have included
1485 this recommendation.
1487 httpHeaderPutStrf(hdr
, Http::HdrType::CONNECTION
, "Proxy-support");
1494 if (connection_auth_blocked
)
1499 /* Handle authentication headers */
1500 if (http
->logType
.oldType
== LOG_TCP_DENIED
&&
1501 ( reply
->sline
.status() == Http::scProxyAuthenticationRequired
||
1502 reply
->sline
.status() == Http::scUnauthorized
)
1504 /* Add authentication header */
1505 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1506 * depends on authenticate behaviour: all schemes to date send no extra
1507 * data on 407/401 responses, and do not check the accel state on 401/407
1510 authenticateFixHeader(reply
, request
->auth_user_request
, request
, 0, 1);
1511 } else if (request
->auth_user_request
!= NULL
)
1512 authenticateFixHeader(reply
, request
->auth_user_request
, request
, http
->flags
.accel
, 0);
1515 /* Append X-Cache */
1516 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE
, "%s from %s",
1517 is_hit
? "HIT" : "MISS", getMyHostname());
1519 #if USE_CACHE_DIGESTS
1520 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1521 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE_LOOKUP
, "%s from %s:%d",
1522 lookup_type
? lookup_type
: "NONE",
1523 getMyHostname(), getMyPort());
1527 const bool maySendChunkedReply
= !request
->multipartRangeRequest() &&
1528 reply
->sline
.protocol
== AnyP::PROTO_HTTP
&& // response is HTTP
1529 (request
->http_ver
>= Http::ProtocolVersion(1,1));
1531 /* Check whether we should send keep-alive */
1532 if (!Config
.onoff
.error_pconns
&& reply
->sline
.status() >= 400 && !request
->flags
.mustKeepalive
) {
1533 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
1534 request
->flags
.proxyKeepalive
= false;
1535 } else if (!Config
.onoff
.client_pconns
&& !request
->flags
.mustKeepalive
) {
1536 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
1537 request
->flags
.proxyKeepalive
= false;
1538 } else if (request
->flags
.proxyKeepalive
&& shutting_down
) {
1539 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
1540 request
->flags
.proxyKeepalive
= false;
1541 } else if (request
->flags
.connectionAuth
&& !reply
->keep_alive
) {
1542 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
1543 request
->flags
.proxyKeepalive
= false;
1544 } else if (reply
->bodySize(request
->method
) < 0 && !maySendChunkedReply
) {
1545 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
1546 request
->flags
.proxyKeepalive
= false;
1547 } else if (fdUsageHigh()&& !request
->flags
.mustKeepalive
) {
1548 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
1549 request
->flags
.proxyKeepalive
= false;
1550 } else if (request
->flags
.sslBumped
&& !reply
->persistent()) {
1551 // We do not really have to close, but we pretend we are a tunnel.
1552 debugs(88, 3, "clientBuildReplyHeader: bumped reply forces close");
1553 request
->flags
.proxyKeepalive
= false;
1554 } else if (request
->pinnedConnection() && !reply
->persistent()) {
1555 // The peer wants to close the pinned connection
1556 debugs(88, 3, "pinned reply forces close");
1557 request
->flags
.proxyKeepalive
= false;
1558 } else if (http
->getConn()) {
1559 ConnStateData
* conn
= http
->getConn();
1560 if (!Comm::IsConnOpen(conn
->port
->listenConn
)) {
1561 // The listening port closed because of a reconfigure
1562 debugs(88, 3, "listening port closed");
1563 request
->flags
.proxyKeepalive
= false;
1567 // Decide if we send chunked reply
1568 if (maySendChunkedReply
&& reply
->bodySize(request
->method
) < 0) {
1569 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
1570 request
->flags
.chunkedReply
= true;
1571 hdr
->putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
1575 if (Config
.onoff
.via
) {
1576 LOCAL_ARRAY(char, bbuf
, MAX_URL
+ 32);
1578 hdr
->getList(Http::HdrType::VIA
, &strVia
);
1579 snprintf(bbuf
, MAX_URL
+ 32, "%d.%d %s",
1580 reply
->sline
.version
.major
,
1581 reply
->sline
.version
.minor
,
1583 strListAdd(&strVia
, bbuf
, ',');
1584 hdr
->delById(Http::HdrType::VIA
);
1585 hdr
->putStr(Http::HdrType::VIA
, strVia
.termedBuf());
1587 /* Signal keep-alive or close explicitly */
1588 hdr
->putStr(Http::HdrType::CONNECTION
, request
->flags
.proxyKeepalive
? "keep-alive" : "close");
1590 #if ADD_X_REQUEST_URI
1592 * Knowing the URI of the request is useful when debugging persistent
1593 * connections in a client; we cannot guarantee the order of http headers,
1594 * but X-Request-URI is likely to be the very last header to ease use from a
1595 * debugger [hdr->entries.count-1].
1597 hdr
->putStr(Http::HdrType::X_REQUEST_URI
,
1598 http
->memOjbect()->url
? http
->memObject()->url
: http
->uri
);
1602 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1603 if ( hdr
->has(Http::HdrType::SURROGATE_CONTROL
) ) {
1604 if (!request
->header
.has(Http::HdrType::SURROGATE_CAPABILITY
)) {
1605 hdr
->delById(Http::HdrType::SURROGATE_CONTROL
);
1607 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1610 httpHdrMangleList(hdr
, request
, http
->al
, ROR_REPLY
);
1614 clientReplyContext::cloneReply()
1616 assert(reply
== NULL
);
1618 reply
= http
->storeEntry()->getReply()->clone();
1621 if (reply
->sline
.protocol
== AnyP::PROTO_HTTP
) {
1622 /* RFC 2616 requires us to advertise our version (but only on real HTTP traffic) */
1623 reply
->sline
.version
= Http::ProtocolVersion();
1626 /* do header conversions */
1630 /// Safely disposes of an entry pointing to a cache hit that we do not want.
1631 /// We cannot just ignore the entry because it may be locking or otherwise
1632 /// holding an associated cache resource of some sort.
1634 clientReplyContext::forgetHit()
1636 StoreEntry
*e
= http
->storeEntry();
1637 assert(e
); // or we are not dealing with a hit
1638 // We probably have not locked the entry earlier, unfortunately. We lock it
1639 // now so that we can unlock two lines later (and trigger cleanup).
1640 // Ideally, ClientHttpRequest::storeEntry() should lock/unlock, but it is
1641 // used so inconsistently that simply adding locking there leads to bugs.
1642 e
->lock("clientReplyContext::forgetHit");
1643 http
->storeEntry(NULL
);
1644 e
->unlock("clientReplyContext::forgetHit"); // may delete e
1648 clientReplyContext::identifyStoreObject()
1650 HttpRequest
*r
= http
->request
;
1652 if (r
->flags
.cachable
|| r
->flags
.internal
) {
1653 lookingforstore
= 5;
1654 StoreEntry::getPublicByRequest (this, r
);
1656 identifyFoundObject (NullStoreEntry::getInstance());
1661 * Check state of the current StoreEntry object.
1662 * to see if we can determine the final status of the request.
1665 clientReplyContext::identifyFoundObject(StoreEntry
*newEntry
)
1667 StoreEntry
*e
= newEntry
;
1668 HttpRequest
*r
= http
->request
;
1670 /** \li If the entry received isNull() then we ignore it. */
1672 http
->storeEntry(NULL
);
1674 http
->storeEntry(e
);
1677 e
= http
->storeEntry();
1679 /* Release IP-cache entries on reload */
1680 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
1681 * 'invalidate' the cached IP entries for this request ???
1683 if (r
->flags
.noCache
|| r
->flags
.noCacheHack())
1684 ipcacheInvalidateNegative(r
->url
.host());
1686 #if USE_CACHE_DIGESTS
1687 lookup_type
= http
->storeEntry() ? "HIT" : "MISS";
1690 if (NULL
== http
->storeEntry()) {
1691 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
1692 debugs(85, 3, "StoreEntry is NULL - MISS");
1693 http
->logType
= LOG_TCP_MISS
;
1698 if (Config
.onoff
.offline
) {
1699 /** \li If we are running in offline mode set to HIT */
1700 debugs(85, 3, "offline HIT " << *e
);
1701 http
->logType
= LOG_TCP_HIT
;
1706 if (http
->redirect
.status
) {
1707 /** \li If redirection status is True force this to be a MISS */
1708 debugs(85, 3, "REDIRECT status forced StoreEntry to NULL (no body on 3XX responses) " << *e
);
1710 http
->logType
= LOG_TCP_REDIRECT
;
1715 if (!e
->validToSend()) {
1716 debugs(85, 3, "!storeEntryValidToSend MISS " << *e
);
1718 http
->logType
= LOG_TCP_MISS
;
1723 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1724 /* \li Special entries are always hits, no matter what the client says */
1725 debugs(85, 3, "ENTRY_SPECIAL HIT " << *e
);
1726 http
->logType
= LOG_TCP_HIT
;
1731 if (r
->flags
.noCache
) {
1732 debugs(85, 3, "no-cache REFRESH MISS " << *e
);
1734 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
1739 debugs(85, 3, "default HIT " << *e
);
1740 http
->logType
= LOG_TCP_HIT
;
1745 * Request more data from the store for the client Stream
1746 * This is *the* entry point to this module.
1749 * - This is the head of the list.
1750 * - There is at least one more node.
1751 * - Data context is not null
1754 clientGetMoreData(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1756 /* Test preconditions */
1757 assert(aNode
!= NULL
);
1758 assert(cbdataReferenceValid(aNode
));
1759 assert(aNode
->node
.prev
== NULL
);
1760 assert(aNode
->node
.next
!= NULL
);
1761 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1763 assert(context
->http
== http
);
1765 clientStreamNode
*next
= ( clientStreamNode
*)aNode
->node
.next
->data
;
1767 if (!context
->ourNode
)
1768 context
->ourNode
= aNode
;
1770 /* no cbdatareference, this is only used once, and safely */
1771 if (context
->flags
.storelogiccomplete
) {
1772 StoreIOBuffer tempBuffer
;
1773 tempBuffer
.offset
= next
->readBuffer
.offset
+ context
->headers_sz
;
1774 tempBuffer
.length
= next
->readBuffer
.length
;
1775 tempBuffer
.data
= next
->readBuffer
.data
;
1777 storeClientCopy(context
->sc
, http
->storeEntry(),
1778 tempBuffer
, clientReplyContext::SendMoreData
, context
);
1782 if (context
->http
->request
->method
== Http::METHOD_PURGE
) {
1783 context
->purgeRequest();
1787 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
1789 if (context
->http
->request
->method
== Http::METHOD_TRACE
) {
1790 if (context
->http
->request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0) {
1791 context
->traceReply(aNode
);
1795 /* continue forwarding, not finished yet. */
1796 http
->logType
= LOG_TCP_MISS
;
1798 context
->doGetMoreData();
1800 context
->identifyStoreObject();
1804 clientReplyContext::doGetMoreData()
1806 /* We still have to do store logic processing - vary, cache hit etc */
1807 if (http
->storeEntry() != NULL
) {
1808 /* someone found the object in the cache for us */
1809 StoreIOBuffer localTempBuffer
;
1811 http
->storeEntry()->lock("clientReplyContext::doGetMoreData");
1813 MemObject
*mem_obj
= http
->storeEntry()->makeMemObject();
1814 if (!mem_obj
->hasUris()) {
1816 * This if-block exists because we don't want to clobber
1817 * a preexiting mem_obj->method value if the mem_obj
1818 * already exists. For example, when a HEAD request
1819 * is a cache hit for a GET response, we want to keep
1820 * the method as GET.
1822 mem_obj
->setUris(storeId(), http
->log_uri
, http
->request
->method
);
1824 * Here we can see if the object was
1825 * created using URL or alternative StoreID from helper.
1827 debugs(88, 3, "storeId: " << http
->storeEntry()->mem_obj
->storeId());
1830 sc
= storeClientListAdd(http
->storeEntry(), this);
1832 sc
->setDelayId(DelayId::DelayClient(http
));
1835 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
1837 /* guarantee nothing has been sent yet! */
1838 assert(http
->out
.size
== 0);
1839 assert(http
->out
.offset
== 0);
1841 if (Ip::Qos::TheConfig
.isHitTosActive()) {
1842 Ip::Qos::doTosLocalHit(http
->getConn()->clientConnection
);
1845 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
1846 Ip::Qos::doNfmarkLocalHit(http
->getConn()->clientConnection
);
1849 localTempBuffer
.offset
= reqofs
;
1850 localTempBuffer
.length
= getNextNode()->readBuffer
.length
;
1851 localTempBuffer
.data
= getNextNode()->readBuffer
.data
;
1852 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, CacheHit
, this);
1854 /* MISS CASE, http->logType is already set! */
1859 /** The next node has removed itself from the stream. */
1861 clientReplyDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1863 /** detach from the stream */
1864 clientStreamDetach(node
, http
);
1868 * Accepts chunk of a http message in buf, parses prefix, filters headers and
1869 * such, writes processed message to the message recipient
1872 clientReplyContext::SendMoreData(void *data
, StoreIOBuffer result
)
1874 clientReplyContext
*context
= static_cast<clientReplyContext
*>(data
);
1875 context
->sendMoreData (result
);
1879 clientReplyContext::makeThisHead()
1881 /* At least, I think thats what this does */
1882 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1883 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1887 clientReplyContext::errorInStream(StoreIOBuffer
const &result
, size_t const &sizeToProcess
)const
1889 return /* aborted request */
1890 (http
->storeEntry() && EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) ||
1891 /* Upstream read error */ (result
.flags
.error
) ||
1892 /* Upstream EOF */ (sizeToProcess
== 0);
1896 clientReplyContext::sendStreamError(StoreIOBuffer
const &result
)
1898 /** call clientWriteComplete so the client socket gets closed
1900 * We call into the stream, because we don't know that there is a
1903 debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.");
1904 StoreIOBuffer localTempBuffer
;
1906 http
->request
->flags
.streamError
= true;
1907 localTempBuffer
.flags
.error
= result
.flags
.error
;
1908 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1913 clientReplyContext::pushStreamData(StoreIOBuffer
const &result
, char *source
)
1915 StoreIOBuffer localTempBuffer
;
1917 if (result
.length
== 0) {
1918 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
1922 assert(result
.offset
- headers_sz
== next()->readBuffer
.offset
);
1923 localTempBuffer
.offset
= result
.offset
- headers_sz
;
1924 localTempBuffer
.length
= result
.length
;
1926 if (localTempBuffer
.length
)
1927 localTempBuffer
.data
= source
;
1929 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1934 clientReplyContext::next() const
1936 assert ( (clientStreamNode
*)http
->client_stream
.head
->next
->data
== getNextNode());
1937 return getNextNode();
1941 clientReplyContext::sendBodyTooLargeError()
1943 Ip::Address tmp_noaddr
;
1944 tmp_noaddr
.setNoAddr(); // TODO: make a global const
1945 http
->logType
= LOG_TCP_DENIED_REPLY
;
1946 ErrorState
*err
= clientBuildError(ERR_TOO_BIG
, Http::scForbidden
, NULL
,
1947 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
1949 removeClientStoreReference(&(sc
), http
);
1950 HTTPMSGUNLOCK(reply
);
1955 /// send 412 (Precondition Failed) to client
1957 clientReplyContext::sendPreconditionFailedError()
1959 http
->logType
= LOG_TCP_HIT
;
1960 ErrorState
*const err
=
1961 clientBuildError(ERR_PRECONDITION_FAILED
, Http::scPreconditionFailed
,
1962 NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
1963 removeClientStoreReference(&sc
, http
);
1964 HTTPMSGUNLOCK(reply
);
1968 /// send 304 (Not Modified) to client
1970 clientReplyContext::sendNotModified()
1972 StoreEntry
*e
= http
->storeEntry();
1973 const time_t timestamp
= e
->timestamp
;
1974 HttpReply
*const temprep
= e
->getReply()->make304();
1975 http
->logType
= LOG_TCP_IMS_HIT
;
1976 removeClientStoreReference(&sc
, http
);
1977 createStoreEntry(http
->request
->method
, RequestFlags());
1978 e
= http
->storeEntry();
1979 // Copy timestamp from the original entry so the 304
1980 // reply has a meaningful Age: header.
1982 e
->timestamp
= timestamp
;
1983 e
->replaceHttpReply(temprep
);
1986 * TODO: why put this in the store and then serialise it and
1987 * then parse it again. Simply mark the request complete in
1988 * our context and write the reply struct to the client side.
1990 triggerInitialStoreRead();
1993 /// send 304 (Not Modified) or 412 (Precondition Failed) to client
1994 /// depending on request method
1996 clientReplyContext::sendNotModifiedOrPreconditionFailedError()
1998 if (http
->request
->method
== Http::METHOD_GET
||
1999 http
->request
->method
== Http::METHOD_HEAD
)
2002 sendPreconditionFailedError();
2006 clientReplyContext::processReplyAccess ()
2008 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
2011 /** Don't block our own responses or HTTP status messages */
2012 if (http
->logType
.oldType
== LOG_TCP_DENIED
||
2013 http
->logType
.oldType
== LOG_TCP_DENIED_REPLY
||
2014 alwaysAllowResponse(reply
->sline
.status())) {
2015 headers_sz
= reply
->hdr_sz
;
2016 processReplyAccessResult(ACCESS_ALLOWED
);
2020 /** Check for reply to big error */
2021 if (reply
->expectedBodyTooLarge(*http
->request
)) {
2022 sendBodyTooLargeError();
2026 headers_sz
= reply
->hdr_sz
;
2028 /** check for absent access controls (permit by default) */
2029 if (!Config
.accessList
.reply
) {
2030 processReplyAccessResult(ACCESS_ALLOWED
);
2034 /** Process http_reply_access lists */
2035 ACLFilledChecklist
*replyChecklist
=
2036 clientAclChecklistCreate(Config
.accessList
.reply
, http
);
2037 replyChecklist
->reply
= reply
;
2038 HTTPMSGLOCK(replyChecklist
->reply
);
2039 replyChecklist
->nonBlockingCheck(ProcessReplyAccessResult
, this);
2043 clientReplyContext::ProcessReplyAccessResult(allow_t rv
, void *voidMe
)
2045 clientReplyContext
*me
= static_cast<clientReplyContext
*>(voidMe
);
2046 me
->processReplyAccessResult(rv
);
2050 clientReplyContext::processReplyAccessResult(const allow_t
&accessAllowed
)
2052 debugs(88, 2, "The reply for " << http
->request
->method
2053 << ' ' << http
->uri
<< " is " << accessAllowed
<< ", because it matched "
2054 << (AclMatchedName
? AclMatchedName
: "NO ACL's"));
2056 if (accessAllowed
!= ACCESS_ALLOWED
) {
2059 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, 1);
2061 http
->logType
= LOG_TCP_DENIED_REPLY
;
2063 if (page_id
== ERR_NONE
)
2064 page_id
= ERR_ACCESS_DENIED
;
2066 Ip::Address tmp_noaddr
;
2067 tmp_noaddr
.setNoAddr();
2068 err
= clientBuildError(page_id
, Http::scForbidden
, NULL
,
2069 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
2072 removeClientStoreReference(&sc
, http
);
2074 HTTPMSGUNLOCK(reply
);
2081 /* Ok, the reply is allowed, */
2082 http
->loggingEntry(http
->storeEntry());
2084 ssize_t body_size
= reqofs
- reply
->hdr_sz
;
2085 if (body_size
< 0) {
2086 reqofs
= reply
->hdr_sz
;
2090 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
2091 (int) body_size
<< " bytes after " << reply
->hdr_sz
<<
2092 " bytes of headers");
2096 if (http
->flags
.accel
&& reply
->sline
.status() != Http::scForbidden
&&
2097 !alwaysAllowResponse(reply
->sline
.status()) &&
2098 esiEnableProcessing(reply
)) {
2099 debugs(88, 2, "Enabling ESI processing for " << http
->uri
);
2100 clientStreamInsertHead(&http
->client_stream
, esiStreamRead
,
2101 esiProcessStream
, esiStreamDetach
, esiStreamStatus
, NULL
);
2106 if (http
->request
->method
== Http::METHOD_HEAD
) {
2107 /* do not forward body for HEAD replies */
2109 http
->flags
.done_copying
= true;
2113 assert (!flags
.headersSent
);
2114 flags
.headersSent
= true;
2116 StoreIOBuffer localTempBuffer
;
2117 char *buf
= next()->readBuffer
.data
;
2118 char *body_buf
= buf
+ reply
->hdr_sz
;
2120 //Server side may disable ranges under some circumstances.
2122 if ((!http
->request
->range
))
2123 next()->readBuffer
.offset
= 0;
2125 body_buf
-= next()->readBuffer
.offset
;
2127 if (next()->readBuffer
.offset
!= 0) {
2128 if (next()->readBuffer
.offset
> body_size
) {
2129 /* Can't use any of the body we received. send nothing */
2130 localTempBuffer
.length
= 0;
2131 localTempBuffer
.data
= NULL
;
2133 localTempBuffer
.length
= body_size
- next()->readBuffer
.offset
;
2134 localTempBuffer
.data
= body_buf
+ next()->readBuffer
.offset
;
2137 localTempBuffer
.length
= body_size
;
2138 localTempBuffer
.data
= body_buf
;
2141 /* TODO??: move the data in the buffer back by the request header size */
2142 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
,
2143 http
, reply
, localTempBuffer
);
2149 clientReplyContext::sendMoreData (StoreIOBuffer result
)
2154 StoreEntry
*entry
= http
->storeEntry();
2156 if (ConnStateData
* conn
= http
->getConn()) {
2157 if (!conn
->isOpen()) {
2158 debugs(33,3, "not sending more data to closing connection " << conn
->clientConnection
);
2161 if (conn
->pinning
.zeroReply
) {
2162 debugs(33,3, "not sending more data after a pinned zero reply " << conn
->clientConnection
);
2166 if (reqofs
==0 && !http
->logType
.isTcpHit()) {
2167 if (Ip::Qos::TheConfig
.isHitTosActive()) {
2168 Ip::Qos::doTosLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2170 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
2171 Ip::Qos::doNfmarkLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2175 debugs(88, 5, conn
->clientConnection
<<
2176 " '" << entry
->url() << "'" <<
2177 " out.offset=" << http
->out
.offset
);
2180 char *buf
= next()->readBuffer
.data
;
2182 if (buf
!= result
.data
) {
2183 /* we've got to copy some data */
2184 assert(result
.length
<= next()->readBuffer
.length
);
2185 memcpy(buf
, result
.data
, result
.length
);
2188 /* We've got the final data to start pushing... */
2189 flags
.storelogiccomplete
= 1;
2191 reqofs
+= result
.length
;
2193 assert(reqofs
<= HTTP_REQBUF_SZ
|| flags
.headersSent
);
2195 assert(http
->request
!= NULL
);
2197 /* ESI TODO: remove this assert once everything is stable */
2198 assert(http
->client_stream
.head
->data
2199 && cbdataReferenceValid(http
->client_stream
.head
->data
));
2203 debugs(88, 5, "clientReplyContext::sendMoreData: " << http
->uri
<< ", " <<
2204 reqofs
<< " bytes (" << result
.length
<<
2207 /* update size of the request */
2210 if (errorInStream(result
, reqofs
)) {
2211 sendStreamError(result
);
2215 if (flags
.headersSent
) {
2216 pushStreamData (result
, buf
);
2224 sc
->setDelayId(DelayId::DelayClient(http
,reply
));
2227 /* handle headers */
2229 if (Config
.onoff
.log_mime_hdrs
) {
2232 if ((k
= headersEnd(buf
, reqofs
))) {
2233 safe_free(http
->al
->headers
.reply
);
2234 http
->al
->headers
.reply
= (char *)xcalloc(k
+ 1, 1);
2235 xstrncpy(http
->al
->headers
.reply
, buf
, k
);
2239 holdingBuffer
= result
;
2240 processReplyAccess();
2244 /* Using this breaks the client layering just a little!
2247 clientReplyContext::createStoreEntry(const HttpRequestMethod
& m
, RequestFlags reqFlags
)
2249 assert(http
!= NULL
);
2251 * For erroneous requests, we might not have a h->request,
2252 * so make a fake one.
2255 if (http
->request
== NULL
) {
2256 http
->request
= new HttpRequest(m
, AnyP::PROTO_NONE
, null_string
);
2257 HTTPMSGLOCK(http
->request
);
2260 StoreEntry
*e
= storeCreateEntry(storeId(), http
->log_uri
, reqFlags
, m
);
2262 // Make entry collapsable ASAP, to increase collapsing chances for others,
2263 // TODO: every must-revalidate and similar request MUST reach the origin,
2264 // but do we have to prohibit others from collapsing on that request?
2265 if (Config
.onoff
.collapsed_forwarding
&& reqFlags
.cachable
&&
2266 !reqFlags
.needValidation
&&
2267 (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
)) {
2268 // make the entry available for future requests now
2269 Store::Root().allowCollapsing(e
, reqFlags
, m
);
2272 sc
= storeClientListAdd(e
, this);
2275 sc
->setDelayId(DelayId::DelayClient(http
));
2282 /* I don't think this is actually needed! -- adrian */
2283 /* http->reqbuf = http->norm_reqbuf; */
2284 // assert(http->reqbuf == http->norm_reqbuf);
2285 /* The next line is illegal because we don't know if the client stream
2286 * buffers have been set up
2288 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2289 // SendMoreData, this);
2290 /* So, we mark the store logic as complete */
2291 flags
.storelogiccomplete
= 1;
2293 /* and get the caller to request a read, from whereever they are */
2294 /* NOTE: after ANY data flows down the pipe, even one step,
2295 * this function CAN NOT be used to manage errors
2297 http
->storeEntry(e
);
2301 clientBuildError(err_type page_id
, Http::StatusCode status
, char const *url
,
2302 Ip::Address
&src_addr
, HttpRequest
* request
)
2304 ErrorState
*err
= new ErrorState(page_id
, status
, request
);
2305 err
->src_addr
= src_addr
;
2308 err
->url
= xstrdup(url
);