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"
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
)),
97 /** Create an error in the store awaiting the client side to read it.
99 * This may be better placed in the clientStream logic, but it has not been
100 * relocated there yet
103 clientReplyContext::setReplyToError(
104 err_type err
, Http::StatusCode status
, const HttpRequestMethod
& method
, char const *uri
,
105 Ip::Address
&addr
, HttpRequest
* failedrequest
, const char *unparsedrequest
,
107 Auth::UserRequest::Pointer auth_user_request
113 ErrorState
*errstate
= clientBuildError(err
, status
, uri
, addr
, failedrequest
);
116 errstate
->request_hdrs
= xstrdup(unparsedrequest
);
119 errstate
->auth_user_request
= auth_user_request
;
121 setReplyToError(method
, errstate
);
124 void clientReplyContext::setReplyToError(const HttpRequestMethod
& method
, ErrorState
*errstate
)
126 if (errstate
->httpStatus
== Http::scNotImplemented
&& http
->request
)
127 /* prevent confusion over whether we default to persistent or not */
128 http
->request
->flags
.proxyKeepalive
= false;
130 http
->al
->http
.code
= errstate
->httpStatus
;
133 http
->request
->ignoreRange("responding with a Squid-generated error");
135 createStoreEntry(method
, RequestFlags());
136 assert(errstate
->callback_data
== NULL
);
137 errorAppendEntry(http
->storeEntry(), errstate
);
138 /* Now the caller reads to get this */
142 clientReplyContext::setReplyToReply(HttpReply
*futureReply
)
145 http
->al
->http
.code
= futureReply
->sline
.status();
147 HttpRequestMethod method
;
148 if (http
->request
) { // nil on responses to unparsable requests
149 http
->request
->ignoreRange("responding with a Squid-generated reply");
150 method
= http
->request
->method
;
153 createStoreEntry(method
, RequestFlags());
155 http
->storeEntry()->storeErrorResponse(futureReply
);
156 /* Now the caller reads to get futureReply */
159 // Assumes that the entry contains an error response without Content-Range.
160 // To use with regular entries, make HTTP Range header removal conditional.
161 void clientReplyContext::setReplyToStoreEntry(StoreEntry
*entry
, const char *reason
)
163 entry
->lock("clientReplyContext::setReplyToStoreEntry"); // removeClientStoreReference() unlocks
164 sc
= storeClientListAdd(entry
, this);
166 sc
->setDelayId(DelayId::DelayClient(http
));
171 http
->request
->ignoreRange(reason
);
172 flags
.storelogiccomplete
= 1;
173 http
->storeEntry(entry
);
177 clientReplyContext::removeStoreReference(store_client
** scp
,
181 store_client
*sc_tmp
= *scp
;
183 if ((e
= *ep
) != NULL
) {
185 storeUnregister(sc_tmp
, e
, this);
187 e
->unlock("clientReplyContext::removeStoreReference");
192 clientReplyContext::removeClientStoreReference(store_client
**scp
, ClientHttpRequest
*aHttpRequest
)
194 StoreEntry
*reference
= aHttpRequest
->storeEntry();
195 removeStoreReference(scp
, &reference
);
196 aHttpRequest
->storeEntry(reference
);
200 clientReplyContext::saveState()
202 assert(old_sc
== NULL
);
203 debugs(88, 3, "clientReplyContext::saveState: saving store context");
204 old_entry
= http
->storeEntry();
206 old_reqsize
= reqsize
;
207 tempBuffer
.offset
= reqofs
;
208 /* Prevent accessing the now saved entries */
209 http
->storeEntry(NULL
);
216 clientReplyContext::restoreState()
218 assert(old_sc
!= NULL
);
219 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
220 removeClientStoreReference(&sc
, http
);
221 http
->storeEntry(old_entry
);
223 reqsize
= old_reqsize
;
224 reqofs
= tempBuffer
.offset
;
225 /* Prevent accessed the old saved entries */
229 tempBuffer
.offset
= 0;
233 clientReplyContext::startError(ErrorState
* err
)
235 createStoreEntry(http
->request
->method
, RequestFlags());
236 triggerInitialStoreRead();
237 errorAppendEntry(http
->storeEntry(), err
);
241 clientReplyContext::getNextNode() const
243 return (clientStreamNode
*)ourNode
->node
.next
->data
;
246 /* This function is wrong - the client parameters don't include the
250 clientReplyContext::triggerInitialStoreRead()
252 /* when confident, 0 becomes reqofs, and then this factors into
256 StoreIOBuffer
localTempBuffer (next()->readBuffer
.length
, 0, next()->readBuffer
.data
);
257 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, SendMoreData
, this);
260 /* there is an expired entry in the store.
261 * setup a temporary buffer area and perform an IMS to the origin
264 clientReplyContext::processExpired()
266 const char *url
= storeId();
267 StoreEntry
*entry
= NULL
;
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
->request
->flags
.refresh
= true;
282 #if STORE_CLIENT_LIST_DEBUG
283 /* Prevent a race with the store client memory free routines
285 assert(storeClientIsThisAClient(sc
, this));
287 /* Prepare to make a new temporary request */
289 entry
= storeCreateEntry(url
,
290 http
->log_uri
, http
->request
->flags
, http
->request
->method
);
291 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
292 sc
= storeClientListAdd(entry
, this);
294 /* delay_id is already set on original store client */
295 sc
->setDelayId(DelayId::DelayClient(http
));
298 http
->request
->lastmod
= old_entry
->lastmod
;
300 if (!http
->request
->header
.has(Http::HdrType::IF_NONE_MATCH
)) {
301 ETag etag
= {NULL
, -1}; // TODO: make that a default ETag constructor
302 if (old_entry
->hasEtag(etag
) && !etag
.weak
)
303 http
->request
->etag
= etag
.str
;
306 debugs(88, 5, "clientReplyContext::processExpired : lastmod " << entry
->lastmod
);
307 http
->storeEntry(entry
);
308 assert(http
->out
.offset
== 0);
309 assert(http
->request
->clientConnectionManager
== http
->getConn());
312 * A refcounted pointer so that FwdState stays around as long as
313 * this clientReplyContext does
315 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
316 FwdState::Start(conn
, http
->storeEntry(), http
->request
, http
->al
);
318 /* Register with storage manager to receive updates when data comes in. */
320 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
321 debugs(88, DBG_CRITICAL
, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
324 /* start counting the length from 0 */
325 StoreIOBuffer
localTempBuffer(HTTP_REQBUF_SZ
, 0, tempbuf
);
326 storeClientCopy(sc
, entry
, localTempBuffer
, HandleIMSReply
, this);
331 clientReplyContext::sendClientUpstreamResponse()
333 StoreIOBuffer tempresult
;
334 removeStoreReference(&old_sc
, &old_entry
);
335 /* here the data to send is the data we just received */
336 tempBuffer
.offset
= 0;
338 /* sendMoreData tracks the offset as well.
339 * Force it back to zero */
341 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
342 /* TODO: provide sendMoreData with the ready parsed reply */
343 tempresult
.length
= reqsize
;
344 tempresult
.data
= tempbuf
;
345 sendMoreData(tempresult
);
349 clientReplyContext::HandleIMSReply(void *data
, StoreIOBuffer result
)
351 clientReplyContext
*context
= (clientReplyContext
*)data
;
352 context
->handleIMSReply(result
);
356 clientReplyContext::sendClientOldEntry()
358 /* Get the old request back */
360 /* here the data to send is in the next nodes buffers already */
361 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
362 /* sendMoreData tracks the offset as well.
363 * Force it back to zero */
365 StoreIOBuffer
tempresult (reqsize
, reqofs
, next()->readBuffer
.data
);
366 sendMoreData(tempresult
);
369 /* This is the workhorse of the HandleIMSReply callback.
371 * It is called when we've got data back from the origin following our
372 * IMS request to revalidate a stale entry.
375 clientReplyContext::handleIMSReply(StoreIOBuffer result
)
380 debugs(88, 3, "handleIMSReply: " << http
->storeEntry()->url() << ", " << (long unsigned) result
.length
<< " bytes" );
382 if (http
->storeEntry() == NULL
)
385 if (result
.flags
.error
&& !EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
))
388 /* update size of the request */
389 reqsize
= result
.length
+ reqofs
;
391 const Http::StatusCode status
= http
->storeEntry()->getReply()->sline
.status();
393 // request to origin was aborted
394 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
395 debugs(88, 3, "handleIMSReply: request to origin aborted '" << http
->storeEntry()->url() << "', sending old entry to client" );
396 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
397 sendClientOldEntry();
400 HttpReply
*old_rep
= (HttpReply
*) old_entry
->getReply();
402 // origin replied 304
403 if (status
== Http::scNotModified
) {
404 http
->logType
= LOG_TCP_REFRESH_UNMODIFIED
;
405 http
->request
->flags
.staleIfHit
= false; // old_entry is no longer stale
407 // update headers on existing entry
408 old_rep
->updateOnNotModified(http
->storeEntry()->getReply());
409 old_entry
->timestampsSet();
411 // if client sent IMS
413 if (http
->request
->flags
.ims
&& !old_entry
->modifiedSince(http
->request
)) {
414 // forward the 304 from origin
415 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and forwarding 304 to client");
416 sendClientUpstreamResponse();
418 // send existing entry, it's still valid
419 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and sending " <<
420 old_rep
->sline
.status() << " to client");
421 sendClientOldEntry();
425 // origin replied with a non-error code
426 else if (status
> Http::scNone
&& status
< Http::scInternalServerError
) {
427 // forward response from origin
428 http
->logType
= LOG_TCP_REFRESH_MODIFIED
;
429 debugs(88, 3, "handleIMSReply: origin replied " << status
<< ", replacing existing entry and forwarding to client");
430 sendClientUpstreamResponse();
433 // origin replied with an error
434 else if (http
->request
->flags
.failOnValidationError
) {
435 http
->logType
= LOG_TCP_REFRESH_FAIL_ERR
;
436 debugs(88, 3, "handleIMSReply: origin replied with error " << status
<<
437 ", forwarding to client due to fail_on_validation_err");
438 sendClientUpstreamResponse();
440 // ignore and let client have old entry
441 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
442 debugs(88, 3, "handleIMSReply: origin replied with error " <<
443 status
<< ", sending old entry (" << old_rep
->sline
.status() << ") to client");
444 sendClientOldEntry();
448 SQUIDCEXTERN CSR clientGetMoreData
;
449 SQUIDCEXTERN CSD clientReplyDetach
;
452 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
453 * have been parsed. Normally this should be a single call, but
454 * it might take more than one. As soon as we have the headers,
455 * we hand off to clientSendMoreData, processExpired, or
459 clientReplyContext::CacheHit(void *data
, StoreIOBuffer result
)
461 clientReplyContext
*context
= (clientReplyContext
*)data
;
462 context
->cacheHit(result
);
466 * Process a possible cache HIT.
469 clientReplyContext::cacheHit(StoreIOBuffer result
)
471 /** Ignore if the HIT object is being deleted. */
473 debugs(88, 3, "HIT object being deleted. Ignore the HIT.");
477 StoreEntry
*e
= http
->storeEntry();
479 HttpRequest
*r
= http
->request
;
481 debugs(88, 3, "clientCacheHit: " << http
->uri
<< ", " << result
.length
<< " bytes");
483 if (http
->storeEntry() == NULL
) {
484 debugs(88, 3, "clientCacheHit: request aborted");
486 } else if (result
.flags
.error
) {
487 /* swap in failure */
488 debugs(88, 3, "clientCacheHit: swapin failure for " << http
->uri
);
489 http
->logType
= LOG_TCP_SWAPFAIL_MISS
;
490 removeClientStoreReference(&sc
, http
);
495 if (result
.length
== 0) {
496 debugs(88, 5, "store IO buffer has no content. MISS");
497 /* the store couldn't get enough data from the file for us to id the
500 /* treat as a miss */
501 http
->logType
= LOG_TCP_MISS
;
506 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
507 /* update size of the request */
508 reqsize
= result
.length
+ reqofs
;
511 * Got the headers, now grok them
513 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
515 if (http
->request
->storeId().cmp(e
->mem_obj
->storeId()) != 0) {
516 debugs(33, DBG_IMPORTANT
, "clientProcessHit: URL mismatch, '" << e
->mem_obj
->storeId() << "' != '" << http
->request
->storeId() << "'");
517 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
522 switch (varyEvaluateMatch(e
, r
)) {
525 /* No variance detected. Continue as normal */
529 /* This is the correct entity for this request. Continue */
530 debugs(88, 2, "clientProcessHit: Vary MATCH!");
534 /* This is not the correct entity for this request. We need
535 * to requery the cache.
537 removeClientStoreReference(&sc
, http
);
539 /* Note: varyEvalyateMatch updates the request with vary information
540 * so we only get here once. (it also takes care of cancelling loops)
542 debugs(88, 2, "clientProcessHit: Vary detected!");
543 clientGetMoreData(ourNode
, http
);
547 /* varyEvaluateMatch found a object loop. Process as miss */
548 debugs(88, DBG_IMPORTANT
, "clientProcessHit: Vary object loop!");
549 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
554 if (r
->method
== Http::METHOD_PURGE
) {
555 debugs(88, 5, "PURGE gets a HIT");
556 removeClientStoreReference(&sc
, http
);
562 if (e
->checkNegativeHit() && !r
->flags
.noCacheHack()) {
563 debugs(88, 5, "negative-HIT");
564 http
->logType
= LOG_TCP_NEGATIVE_HIT
;
565 sendMoreData(result
);
566 } else if (blockedHit()) {
567 debugs(88, 5, "send_hit forces a MISS");
568 http
->logType
= LOG_TCP_MISS
;
571 } else if (!http
->flags
.internal
&& refreshCheckHTTP(e
, r
)) {
572 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
574 * We hold a stale copy; it needs to be validated
577 * The 'needValidation' flag is used to prevent forwarding
578 * loops between siblings. If our copy of the object is stale,
579 * then we should probably only use parents for the validation
580 * request. Otherwise two siblings could generate a loop if
581 * both have a stale version of the object.
583 r
->flags
.needValidation
= true;
585 if (e
->lastmod
< 0) {
586 debugs(88, 3, "validate HIT object? NO. Missing Last-Modified header. Do MISS.");
588 * Previous reply didn't have a Last-Modified header,
589 * we cannot revalidate it.
591 http
->logType
= LOG_TCP_MISS
;
593 } else if (r
->flags
.noCache
) {
594 debugs(88, 3, "validate HIT object? NO. Client sent CC:no-cache. Do CLIENT_REFRESH_MISS");
596 * This did not match a refresh pattern that overrides no-cache
597 * we should honour the client no-cache header.
599 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
601 } else if (r
->url
.getScheme() == AnyP::PROTO_HTTP
) {
602 debugs(88, 3, "validate HIT object? YES.");
604 * Object needs to be revalidated
605 * XXX This could apply to FTP as well, if Last-Modified is known.
609 debugs(88, 3, "validate HIT object? NO. Client protocol non-HTTP. Do MISS.");
611 * We don't know how to re-validate other protocols. Handle
612 * them as if the object has expired.
614 http
->logType
= LOG_TCP_MISS
;
617 } else if (r
->conditional()) {
618 debugs(88, 5, "conditional HIT");
619 processConditional(result
);
622 * plain ol' cache hit
624 debugs(88, 5, "plain old HIT");
627 if (e
->store_status
!= STORE_OK
)
628 http
->logType
= LOG_TCP_MISS
;
631 if (e
->mem_status
== IN_MEMORY
)
632 http
->logType
= LOG_TCP_MEM_HIT
;
633 else if (Config
.onoff
.offline
)
634 http
->logType
= LOG_TCP_OFFLINE_HIT
;
636 sendMoreData(result
);
641 * Prepare to fetch the object as it's a cache miss of some kind.
644 clientReplyContext::processMiss()
646 char *url
= http
->uri
;
647 HttpRequest
*r
= http
->request
;
648 ErrorState
*err
= NULL
;
649 debugs(88, 4, r
->method
<< ' ' << url
);
652 * We might have a left-over StoreEntry from a failed cache hit
655 if (http
->storeEntry()) {
656 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
657 debugs(88, DBG_CRITICAL
, "clientProcessMiss: miss on a special object (" << url
<< ").");
658 debugs(88, DBG_CRITICAL
, "\tlog_type = " << http
->logType
.c_str());
659 http
->storeEntry()->dump(1);
662 removeClientStoreReference(&sc
, http
);
665 /** Check if its a PURGE request to be actioned. */
666 if (r
->method
== Http::METHOD_PURGE
) {
671 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
672 if (r
->method
== Http::METHOD_OTHER
) {
676 /** Check if 'only-if-cached' flag is set. Action if so. */
677 if (http
->onlyIfCached()) {
678 processOnlyIfCachedMiss();
683 if (r
->flags
.loopDetected
) {
684 http
->al
->http
.code
= Http::scForbidden
;
685 err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
686 createStoreEntry(r
->method
, RequestFlags());
687 errorAppendEntry(http
->storeEntry(), err
);
688 triggerInitialStoreRead();
691 assert(http
->out
.offset
== 0);
692 createStoreEntry(r
->method
, r
->flags
);
693 triggerInitialStoreRead();
695 if (http
->redirect
.status
) {
696 HttpReply
*rep
= new HttpReply
;
697 http
->logType
= LOG_TCP_REDIRECT
;
698 http
->storeEntry()->releaseRequest();
699 rep
->redirect(http
->redirect
.status
, http
->redirect
.location
);
700 http
->storeEntry()->replaceHttpReply(rep
);
701 http
->storeEntry()->complete();
705 assert(r
->clientConnectionManager
== http
->getConn());
707 /** Start forwarding to get the new object from network */
708 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
709 FwdState::Start(conn
, http
->storeEntry(), r
, http
->al
);
714 * client issued a request with an only-if-cached cache-control directive;
715 * we did not find a cached object that can be returned without
716 * contacting other servers;
717 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
720 clientReplyContext::processOnlyIfCachedMiss()
722 debugs(88, 4, http
->request
->method
<< ' ' << http
->uri
);
723 http
->al
->http
.code
= Http::scGatewayTimeout
;
724 ErrorState
*err
= clientBuildError(ERR_ONLY_IF_CACHED_MISS
, Http::scGatewayTimeout
, NULL
,
725 http
->getConn()->clientConnection
->remote
, http
->request
);
726 removeClientStoreReference(&sc
, http
);
730 /// process conditional request from client
732 clientReplyContext::processConditional(StoreIOBuffer
&result
)
734 StoreEntry
*const e
= http
->storeEntry();
736 if (e
->getReply()->sline
.status() != Http::scOkay
) {
737 debugs(88, 4, "clientReplyContext::processConditional: Reply code " <<
738 e
->getReply()->sline
.status() << " != 200");
739 http
->logType
= LOG_TCP_MISS
;
744 HttpRequest
&r
= *http
->request
;
746 if (r
.header
.has(Http::HdrType::IF_MATCH
) && !e
->hasIfMatchEtag(r
)) {
747 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
748 sendPreconditionFailedError();
752 bool matchedIfNoneMatch
= false;
753 if (r
.header
.has(Http::HdrType::IF_NONE_MATCH
)) {
754 if (!e
->hasIfNoneMatchEtag(r
)) {
755 // RFC 2616: ignore IMS if If-None-Match did not match
759 r
.header
.delById(Http::HdrType::IF_MODIFIED_SINCE
);
760 http
->logType
= LOG_TCP_MISS
;
761 sendMoreData(result
);
766 // RFC 2616: if If-None-Match matched and there is no IMS,
767 // reply with 304 Not Modified or 412 Precondition Failed
768 sendNotModifiedOrPreconditionFailedError();
772 // otherwise check IMS below to decide if we reply with 304 or 412
773 matchedIfNoneMatch
= true;
777 // handle If-Modified-Since requests from the client
778 if (e
->modifiedSince(&r
)) {
779 http
->logType
= LOG_TCP_IMS_HIT
;
780 sendMoreData(result
);
784 if (matchedIfNoneMatch
) {
785 // If-None-Match matched, reply with 304 Not Modified or
786 // 412 Precondition Failed
787 sendNotModifiedOrPreconditionFailedError();
791 // otherwise reply with 304 Not Modified
796 /// whether squid.conf send_hit prevents us from serving this hit
798 clientReplyContext::blockedHit() const
800 if (!Config
.accessList
.sendHit
)
801 return false; // hits are not blocked by default
803 if (http
->flags
.internal
)
804 return false; // internal content "hits" cannot be blocked
806 if (const HttpReply
*rep
= http
->storeEntry()->getReply()) {
807 std::unique_ptr
<ACLFilledChecklist
> chl(clientAclChecklistCreate(Config
.accessList
.sendHit
, http
));
808 chl
->reply
= const_cast<HttpReply
*>(rep
); // ACLChecklist API bug
809 HTTPMSGLOCK(chl
->reply
);
810 return chl
->fastCheck() != ACCESS_ALLOWED
; // when in doubt, block
813 // This does not happen, I hope, because we are called from CacheHit, which
814 // is called via a storeClientCopy() callback, and store should initialize
815 // the reply before calling that callback.
816 debugs(88, 3, "Missing reply!");
821 clientReplyContext::purgeRequestFindObjectToPurge()
823 /* Try to find a base entry */
824 http
->flags
.purging
= true;
827 // TODO: can we use purgeAllCached() here instead of doing the
828 // getPublicByRequestMethod() dance?
829 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_GET
);
832 // Purges all entries with a given url
833 // TODO: move to SideAgent parent, when we have one
835 * We probably cannot purge Vary-affected responses because their MD5
836 * keys depend on vary headers.
839 purgeEntriesByUrl(HttpRequest
* req
, const char *url
)
842 bool get_or_head_sent
= false;
845 for (HttpRequestMethod
m(Http::METHOD_NONE
); m
!= Http::METHOD_ENUM_END
; ++m
) {
846 if (m
.respMaybeCacheable()) {
847 if (StoreEntry
*entry
= storeGetPublic(url
, m
)) {
848 debugs(88, 5, "purging " << *entry
<< ' ' << m
<< ' ' << url
);
850 neighborsHtcpClear(entry
, url
, req
, m
, HTCP_CLR_INVALIDATION
);
851 if (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
) {
852 get_or_head_sent
= true;
861 if (!get_or_head_sent
) {
862 neighborsHtcpClear(NULL
, url
, req
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_INVALIDATION
);
868 clientReplyContext::purgeAllCached()
870 // XXX: performance regression, c_str() reallocates
871 SBuf
url(http
->request
->effectiveRequestUri());
872 purgeEntriesByUrl(http
->request
, url
.c_str());
876 clientReplyContext::created(StoreEntry
*newEntry
)
878 if (lookingforstore
== 1)
879 purgeFoundGet(newEntry
);
880 else if (lookingforstore
== 2)
881 purgeFoundHead(newEntry
);
882 else if (lookingforstore
== 3)
883 purgeDoPurgeGet(newEntry
);
884 else if (lookingforstore
== 4)
885 purgeDoPurgeHead(newEntry
);
886 else if (lookingforstore
== 5)
887 identifyFoundObject(newEntry
);
891 clientReplyContext::purgeFoundGet(StoreEntry
*newEntry
)
893 if (newEntry
->isNull()) {
895 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
897 purgeFoundObject (newEntry
);
901 clientReplyContext::purgeFoundHead(StoreEntry
*newEntry
)
903 if (newEntry
->isNull())
906 purgeFoundObject (newEntry
);
910 clientReplyContext::purgeFoundObject(StoreEntry
*entry
)
912 assert (entry
&& !entry
->isNull());
914 if (EBIT_TEST(entry
->flags
, ENTRY_SPECIAL
)) {
915 http
->logType
= LOG_TCP_DENIED
;
916 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
,
917 http
->getConn()->clientConnection
->remote
, http
->request
);
919 return; // XXX: leaking unused entry if some store does not keep it
922 StoreIOBuffer localTempBuffer
;
923 /* Swap in the metadata */
924 http
->storeEntry(entry
);
926 http
->storeEntry()->lock("clientReplyContext::purgeFoundObject");
927 http
->storeEntry()->createMemObject(storeId(), http
->log_uri
,
928 http
->request
->method
);
930 sc
= storeClientListAdd(http
->storeEntry(), this);
932 http
->logType
= LOG_TCP_HIT
;
936 localTempBuffer
.offset
= http
->out
.offset
;
938 localTempBuffer
.length
= next()->readBuffer
.length
;
940 localTempBuffer
.data
= next()->readBuffer
.data
;
942 storeClientCopy(sc
, http
->storeEntry(),
943 localTempBuffer
, CacheHit
, this);
947 clientReplyContext::purgeRequest()
949 debugs(88, 3, "Config2.onoff.enable_purge = " <<
950 Config2
.onoff
.enable_purge
);
952 if (!Config2
.onoff
.enable_purge
) {
953 http
->logType
= LOG_TCP_DENIED
;
954 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
959 /* Release both IP cache */
960 ipcacheInvalidate(http
->request
->url
.host());
962 if (!http
->flags
.purging
)
963 purgeRequestFindObjectToPurge();
969 clientReplyContext::purgeDoMissPurge()
971 http
->logType
= LOG_TCP_MISS
;
973 StoreEntry::getPublicByRequestMethod(this,http
->request
, Http::METHOD_GET
);
977 clientReplyContext::purgeDoPurgeGet(StoreEntry
*newEntry
)
980 /* Move to new() when that is created */
981 purgeStatus
= Http::scNotFound
;
983 if (!newEntry
->isNull()) {
984 /* Release the cached URI */
985 debugs(88, 4, "clientPurgeRequest: GET '" << newEntry
->url() << "'" );
987 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
990 purgeStatus
= Http::scOkay
;
994 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
998 clientReplyContext::purgeDoPurgeHead(StoreEntry
*newEntry
)
1000 if (newEntry
&& !newEntry
->isNull()) {
1001 debugs(88, 4, "HEAD " << newEntry
->url());
1003 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1005 newEntry
->release();
1006 purgeStatus
= Http::scOkay
;
1009 /* And for Vary, release the base URI if none of the headers was included in the request */
1011 if (http
->request
->vary_headers
1012 && !strstr(http
->request
->vary_headers
, "=")) {
1013 // XXX: performance regression, c_str() reallocates
1014 SBuf
tmp(http
->request
->effectiveRequestUri());
1015 StoreEntry
*entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_GET
);
1018 debugs(88, 4, "Vary GET " << entry
->url());
1020 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1023 purgeStatus
= Http::scOkay
;
1026 entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_HEAD
);
1029 debugs(88, 4, "Vary HEAD " << entry
->url());
1031 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1034 purgeStatus
= Http::scOkay
;
1039 * Make a new entry to hold the reply to be written
1042 /* FIXME: This doesn't need to go through the store. Simply
1043 * push down the client chain
1045 createStoreEntry(http
->request
->method
, RequestFlags());
1047 triggerInitialStoreRead();
1049 HttpReply
*rep
= new HttpReply
;
1050 rep
->setHeaders(purgeStatus
, NULL
, NULL
, 0, 0, -1);
1051 http
->storeEntry()->replaceHttpReply(rep
);
1052 http
->storeEntry()->complete();
1056 clientReplyContext::traceReply(clientStreamNode
* node
)
1058 clientStreamNode
*nextNode
= (clientStreamNode
*)node
->node
.next
->data
;
1059 StoreIOBuffer localTempBuffer
;
1060 createStoreEntry(http
->request
->method
, RequestFlags());
1061 localTempBuffer
.offset
= nextNode
->readBuffer
.offset
+ headers_sz
;
1062 localTempBuffer
.length
= nextNode
->readBuffer
.length
;
1063 localTempBuffer
.data
= nextNode
->readBuffer
.data
;
1064 storeClientCopy(sc
, http
->storeEntry(),
1065 localTempBuffer
, SendMoreData
, this);
1066 http
->storeEntry()->releaseRequest();
1067 http
->storeEntry()->buffer();
1068 HttpReply
*rep
= new HttpReply
;
1069 rep
->setHeaders(Http::scOkay
, NULL
, "text/plain", http
->request
->prefixLen(), 0, squid_curtime
);
1070 http
->storeEntry()->replaceHttpReply(rep
);
1071 http
->request
->swapOut(http
->storeEntry());
1072 http
->storeEntry()->complete();
1075 #define SENDING_BODY 0
1076 #define SENDING_HDRSONLY 1
1078 clientReplyContext::checkTransferDone()
1080 StoreEntry
*entry
= http
->storeEntry();
1086 * For now, 'done_copying' is used for special cases like
1087 * Range and HEAD requests.
1089 if (http
->flags
.done_copying
)
1092 if (http
->request
->flags
.chunkedReply
&& !flags
.complete
) {
1093 // last-chunk was not sent
1098 * Handle STORE_OK objects.
1099 * objectLen(entry) will be set proprely.
1100 * RC: Does objectLen(entry) include the Headers?
1103 if (entry
->store_status
== STORE_OK
) {
1104 return storeOKTransferDone();
1106 return storeNotOKTransferDone();
1111 clientReplyContext::storeOKTransferDone() const
1113 assert(http
->storeEntry()->objectLen() >= 0);
1114 assert(http
->storeEntry()->objectLen() >= headers_sz
);
1115 if (http
->out
.offset
>= http
->storeEntry()->objectLen() - headers_sz
) {
1116 debugs(88,3,HERE
<< "storeOKTransferDone " <<
1117 " out.offset=" << http
->out
.offset
<<
1118 " objectLen()=" << http
->storeEntry()->objectLen() <<
1119 " headers_sz=" << headers_sz
);
1127 clientReplyContext::storeNotOKTransferDone() const
1130 * Now, handle STORE_PENDING objects
1132 MemObject
*mem
= http
->storeEntry()->mem_obj
;
1133 assert(mem
!= NULL
);
1134 assert(http
->request
!= NULL
);
1135 /* mem->reply was wrong because it uses the UPSTREAM header length!!! */
1136 HttpReply
const *curReply
= mem
->getReply();
1138 if (headers_sz
== 0)
1139 /* haven't found end of headers yet */
1143 * Figure out how much data we are supposed to send.
1144 * If we are sending a body and we don't have a content-length,
1145 * then we must wait for the object to become STORE_OK.
1147 if (curReply
->content_length
< 0)
1150 uint64_t expectedLength
= curReply
->content_length
+ http
->out
.headers_sz
;
1152 if (http
->out
.size
< expectedLength
)
1155 debugs(88,3,HERE
<< "storeNotOKTransferDone " <<
1156 " out.size=" << http
->out
.size
<<
1157 " expectedLength=" << expectedLength
);
1162 /* A write has completed, what is the next status based on the
1163 * canonical request data?
1164 * 1 something is wrong
1165 * 0 nothing is wrong.
1169 clientHttpRequestStatus(int fd
, ClientHttpRequest
const *http
)
1171 #if SIZEOF_INT64_T == 4
1172 if (http
->out
.size
> 0x7FFF0000) {
1173 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
<< " to prevent out.size counter overflow");
1174 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1175 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes");
1176 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1180 if (http
->out
.offset
> 0x7FFF0000) {
1181 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
< " to prevent out.offset counter overflow");
1182 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1183 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes, offset " << http
->out
.offset
);
1184 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1193 * *http is a valid structure.
1194 * fd is either -1, or an open fd.
1196 * TODO: enumify this
1198 * This function is used by any http request sink, to determine the status
1201 clientStream_status_t
1202 clientReplyStatus(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1204 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1206 assert (context
->http
== http
);
1207 return context
->replyStatus();
1210 clientStream_status_t
1211 clientReplyContext::replyStatus()
1214 /* Here because lower nodes don't need it */
1216 if (http
->storeEntry() == NULL
) {
1217 debugs(88, 5, "clientReplyStatus: no storeEntry");
1218 return STREAM_FAILED
; /* yuck, but what can we do? */
1221 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
1222 /* TODO: Could upstream read errors (result.flags.error) be
1223 * lost, and result in undersize requests being considered
1224 * complete. Should we tcp reset such connections ?
1226 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
1227 return STREAM_FAILED
;
1230 if ((done
= checkTransferDone()) != 0 || flags
.complete
) {
1231 debugs(88, 5, "clientReplyStatus: transfer is DONE: " << done
<< flags
.complete
);
1232 /* Ok we're finished, but how? */
1234 const int64_t expectedBodySize
=
1235 http
->storeEntry()->getReply()->bodySize(http
->request
->method
);
1236 if (!http
->request
->flags
.proxyKeepalive
&& expectedBodySize
< 0) {
1237 debugs(88, 5, "clientReplyStatus: closing, content_length < 0");
1238 return STREAM_FAILED
;
1241 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_BAD_LENGTH
)) {
1242 debugs(88, 5, "clientReplyStatus: truncated response body");
1243 return STREAM_UNPLANNED_COMPLETE
;
1247 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
1248 return STREAM_FAILED
;
1251 if (expectedBodySize
>= 0 && !http
->gotEnough()) {
1252 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
1253 return STREAM_UNPLANNED_COMPLETE
;
1256 debugs(88, 5, "clientReplyStatus: stream complete; keepalive=" <<
1257 http
->request
->flags
.proxyKeepalive
);
1258 return STREAM_COMPLETE
;
1261 // XXX: Should this be checked earlier? We could return above w/o checking.
1262 if (reply
->receivedBodyTooLarge(*http
->request
, http
->out
.offset
- 4096)) {
1263 /* 4096 is a margin for the HTTP headers included in out.offset */
1264 debugs(88, 5, "clientReplyStatus: client reply body is too large");
1265 return STREAM_FAILED
;
1271 /* Responses with no body will not have a content-type header,
1272 * which breaks the rep_mime_type acl, which
1273 * coincidentally, is the most common acl for reply access lists.
1274 * A better long term fix for this is to allow acl matchs on the various
1275 * status codes, and then supply a default ruleset that puts these
1276 * codes before any user defines access entries. That way the user
1277 * can choose to block these responses where appropriate, but won't get
1278 * mysterious breakages.
1281 clientReplyContext::alwaysAllowResponse(Http::StatusCode sline
) const
1287 case Http::scContinue
:
1289 case Http::scSwitchingProtocols
:
1291 case Http::scProcessing
:
1293 case Http::scNoContent
:
1295 case Http::scNotModified
:
1307 * Generate the reply headers sent to client.
1309 * Filters out unwanted entries and hop-by-hop from original reply header
1310 * then adds extra entries if we have more info than origin server
1311 * then adds Squid specific entries
1314 clientReplyContext::buildReplyHeader()
1316 HttpHeader
*hdr
= &reply
->header
;
1317 const bool is_hit
= http
->logType
.isTcpHit();
1318 HttpRequest
*request
= http
->request
;
1319 #if DONT_FILTER_THESE
1320 /* but you might want to if you run Squid as an HTTP accelerator */
1321 /* hdr->delById(HDR_ACCEPT_RANGES); */
1322 hdr
->delById(HDR_ETAG
);
1326 hdr
->delById(Http::HdrType::SET_COOKIE
);
1327 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
1329 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
1330 // remove the Proxy-Authenticate header
1331 if ( !request
->peer_login
|| (strcmp(request
->peer_login
,"PASS") != 0 && strcmp(request
->peer_login
,"PASSTHRU") != 0))
1332 reply
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1334 reply
->header
.removeHopByHopEntries();
1336 // if (request->range)
1337 // clientBuildRangeHeader(http, reply);
1340 * Add a estimated Age header on cache hits.
1344 * Remove any existing Age header sent by upstream caches
1345 * (note that the existing header is passed along unmodified
1348 hdr
->delById(Http::HdrType::AGE
);
1350 * This adds the calculated object age. Note that the details of the
1351 * age calculation is performed by adjusting the timestamp in
1352 * StoreEntry::timestampsSet(), not here.
1354 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
1355 hdr
->delById(Http::HdrType::DATE
);
1356 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1357 } else if (http
->getConn() && http
->getConn()->port
->actAsOrigin
) {
1358 // Swap the Date: header to current time if we are simulating an origin
1359 HttpHeaderEntry
*h
= hdr
->findEntry(Http::HdrType::DATE
);
1361 hdr
->putExt("X-Origin-Date", h
->value
.termedBuf());
1362 hdr
->delById(Http::HdrType::DATE
);
1363 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1364 h
= hdr
->findEntry(Http::HdrType::EXPIRES
);
1365 if (h
&& http
->storeEntry()->expires
>= 0) {
1366 hdr
->putExt("X-Origin-Expires", h
->value
.termedBuf());
1367 hdr
->delById(Http::HdrType::EXPIRES
);
1368 hdr
->putTime(Http::HdrType::EXPIRES
, squid_curtime
+ http
->storeEntry()->expires
- http
->storeEntry()->timestamp
);
1370 if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1371 // put X-Cache-Age: instead of Age:
1373 snprintf(age
, sizeof(age
), "%" PRId64
, static_cast<int64_t>(squid_curtime
- http
->storeEntry()->timestamp
));
1374 hdr
->putExt("X-Cache-Age", age
);
1376 } else if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1377 hdr
->putInt(Http::HdrType::AGE
,
1378 squid_curtime
- http
->storeEntry()->timestamp
);
1379 /* Signal old objects. NB: rfc 2616 is not clear,
1380 * by implication, on whether we should do this to all
1381 * responses, or only cache hits.
1382 * 14.46 states it ONLY applys for heuristically caclulated
1383 * freshness values, 13.2.4 doesn't specify the same limitation.
1384 * We interpret RFC 2616 under the combination.
1386 /* TODO: if maxage or s-maxage is present, don't do this */
1388 if (squid_curtime
- http
->storeEntry()->timestamp
>= 86400) {
1390 snprintf (tbuf
, sizeof(tbuf
), "%s %s %s",
1392 "This cache hit is still fresh and more than 1 day old");
1393 hdr
->putStr(Http::HdrType::WARNING
, tbuf
);
1398 /* RFC 2616: Section 14.18
1400 * Add a Date: header if missing.
1401 * We have access to a clock therefore are required to amend any shortcoming in servers.
1403 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1405 if ( !hdr
->has(Http::HdrType::DATE
) ) {
1406 if (!http
->storeEntry())
1407 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1408 else if (http
->storeEntry()->timestamp
> 0)
1409 hdr
->putTime(Http::HdrType::DATE
, http
->storeEntry()->timestamp
);
1411 debugs(88,DBG_IMPORTANT
,"BUG 3279: HTTP reply without Date:");
1412 /* dump something useful about the problem */
1413 http
->storeEntry()->dump(DBG_IMPORTANT
);
1417 // add Warnings required by RFC 2616 if serving a stale hit
1418 if (http
->request
->flags
.staleIfHit
&& http
->logType
.isTcpHit()) {
1419 hdr
->putWarning(110, "Response is stale");
1420 if (http
->request
->flags
.needValidation
)
1421 hdr
->putWarning(111, "Revalidation failed");
1424 /* Filter unproxyable authentication types */
1425 if (http
->logType
.oldType
!= LOG_TCP_DENIED
&&
1426 hdr
->has(Http::HdrType::WWW_AUTHENTICATE
)) {
1427 HttpHeaderPos pos
= HttpHeaderInitPos
;
1430 int connection_auth_blocked
= 0;
1431 while ((e
= hdr
->getEntry(&pos
))) {
1432 if (e
->id
== Http::HdrType::WWW_AUTHENTICATE
) {
1433 const char *value
= e
->value
.rawBuf();
1435 if ((strncasecmp(value
, "NTLM", 4) == 0 &&
1436 (value
[4] == '\0' || value
[4] == ' '))
1438 (strncasecmp(value
, "Negotiate", 9) == 0 &&
1439 (value
[9] == '\0' || value
[9] == ' '))
1441 (strncasecmp(value
, "Kerberos", 8) == 0 &&
1442 (value
[8] == '\0' || value
[8] == ' '))) {
1443 if (request
->flags
.connectionAuthDisabled
) {
1444 hdr
->delAt(pos
, connection_auth_blocked
);
1447 request
->flags
.mustKeepalive
= true;
1448 if (!request
->flags
.accelerated
&& !request
->flags
.intercepted
) {
1449 httpHeaderPutStrf(hdr
, Http::HdrType::PROXY_SUPPORT
, "Session-Based-Authentication");
1451 We send "Connection: Proxy-Support" header to mark
1452 Proxy-Support as a hop-by-hop header for intermediaries that do not
1453 understand the semantics of this header. The RFC should have included
1454 this recommendation.
1456 httpHeaderPutStrf(hdr
, Http::HdrType::CONNECTION
, "Proxy-support");
1463 if (connection_auth_blocked
)
1468 /* Handle authentication headers */
1469 if (http
->logType
.oldType
== LOG_TCP_DENIED
&&
1470 ( reply
->sline
.status() == Http::scProxyAuthenticationRequired
||
1471 reply
->sline
.status() == Http::scUnauthorized
)
1473 /* Add authentication header */
1474 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1475 * depends on authenticate behaviour: all schemes to date send no extra
1476 * data on 407/401 responses, and do not check the accel state on 401/407
1479 authenticateFixHeader(reply
, request
->auth_user_request
, request
, 0, 1);
1480 } else if (request
->auth_user_request
!= NULL
)
1481 authenticateFixHeader(reply
, request
->auth_user_request
, request
, http
->flags
.accel
, 0);
1484 /* Append X-Cache */
1485 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE
, "%s from %s",
1486 is_hit
? "HIT" : "MISS", getMyHostname());
1488 #if USE_CACHE_DIGESTS
1489 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1490 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE_LOOKUP
, "%s from %s:%d",
1491 lookup_type
? lookup_type
: "NONE",
1492 getMyHostname(), getMyPort());
1496 const bool maySendChunkedReply
= !request
->multipartRangeRequest() &&
1497 reply
->sline
.protocol
== AnyP::PROTO_HTTP
&& // response is HTTP
1498 (request
->http_ver
>= Http::ProtocolVersion(1,1));
1500 /* Check whether we should send keep-alive */
1501 if (!Config
.onoff
.error_pconns
&& reply
->sline
.status() >= 400 && !request
->flags
.mustKeepalive
) {
1502 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
1503 request
->flags
.proxyKeepalive
= false;
1504 } else if (!Config
.onoff
.client_pconns
&& !request
->flags
.mustKeepalive
) {
1505 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
1506 request
->flags
.proxyKeepalive
= false;
1507 } else if (request
->flags
.proxyKeepalive
&& shutting_down
) {
1508 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
1509 request
->flags
.proxyKeepalive
= false;
1510 } else if (request
->flags
.connectionAuth
&& !reply
->keep_alive
) {
1511 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
1512 request
->flags
.proxyKeepalive
= false;
1513 } else if (reply
->bodySize(request
->method
) < 0 && !maySendChunkedReply
) {
1514 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
1515 request
->flags
.proxyKeepalive
= false;
1516 } else if (fdUsageHigh()&& !request
->flags
.mustKeepalive
) {
1517 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
1518 request
->flags
.proxyKeepalive
= false;
1519 } else if (request
->flags
.sslBumped
&& !reply
->persistent()) {
1520 // We do not really have to close, but we pretend we are a tunnel.
1521 debugs(88, 3, "clientBuildReplyHeader: bumped reply forces close");
1522 request
->flags
.proxyKeepalive
= false;
1523 } else if (request
->pinnedConnection() && !reply
->persistent()) {
1524 // The peer wants to close the pinned connection
1525 debugs(88, 3, "pinned reply forces close");
1526 request
->flags
.proxyKeepalive
= false;
1527 } else if (http
->getConn()) {
1528 ConnStateData
* conn
= http
->getConn();
1529 if (!Comm::IsConnOpen(conn
->port
->listenConn
)) {
1530 // The listening port closed because of a reconfigure
1531 debugs(88, 3, "listening port closed");
1532 request
->flags
.proxyKeepalive
= false;
1536 // Decide if we send chunked reply
1537 if (maySendChunkedReply
&&
1538 request
->flags
.proxyKeepalive
&&
1539 reply
->bodySize(request
->method
) < 0) {
1540 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
1541 request
->flags
.chunkedReply
= true;
1542 hdr
->putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
1546 if (Config
.onoff
.via
) {
1547 LOCAL_ARRAY(char, bbuf
, MAX_URL
+ 32);
1549 hdr
->getList(Http::HdrType::VIA
, &strVia
);
1550 snprintf(bbuf
, MAX_URL
+ 32, "%d.%d %s",
1551 reply
->sline
.version
.major
,
1552 reply
->sline
.version
.minor
,
1554 strListAdd(&strVia
, bbuf
, ',');
1555 hdr
->delById(Http::HdrType::VIA
);
1556 hdr
->putStr(Http::HdrType::VIA
, strVia
.termedBuf());
1558 /* Signal keep-alive or close explicitly */
1559 hdr
->putStr(Http::HdrType::CONNECTION
, request
->flags
.proxyKeepalive
? "keep-alive" : "close");
1561 #if ADD_X_REQUEST_URI
1563 * Knowing the URI of the request is useful when debugging persistent
1564 * connections in a client; we cannot guarantee the order of http headers,
1565 * but X-Request-URI is likely to be the very last header to ease use from a
1566 * debugger [hdr->entries.count-1].
1568 hdr
->putStr(Http::HdrType::X_REQUEST_URI
,
1569 http
->memOjbect()->url
? http
->memObject()->url
: http
->uri
);
1573 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1574 if ( hdr
->has(Http::HdrType::SURROGATE_CONTROL
) ) {
1575 if (!request
->header
.has(Http::HdrType::SURROGATE_CAPABILITY
)) {
1576 hdr
->delById(Http::HdrType::SURROGATE_CONTROL
);
1578 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1581 httpHdrMangleList(hdr
, request
, ROR_REPLY
);
1585 clientReplyContext::cloneReply()
1587 assert(reply
== NULL
);
1589 reply
= http
->storeEntry()->getReply()->clone();
1592 if (reply
->sline
.protocol
== AnyP::PROTO_HTTP
) {
1593 /* RFC 2616 requires us to advertise our version (but only on real HTTP traffic) */
1594 reply
->sline
.version
= Http::ProtocolVersion();
1597 /* do header conversions */
1601 /// Safely disposes of an entry pointing to a cache hit that we do not want.
1602 /// We cannot just ignore the entry because it may be locking or otherwise
1603 /// holding an associated cache resource of some sort.
1605 clientReplyContext::forgetHit()
1607 StoreEntry
*e
= http
->storeEntry();
1608 assert(e
); // or we are not dealing with a hit
1609 // We probably have not locked the entry earlier, unfortunately. We lock it
1610 // now so that we can unlock two lines later (and trigger cleanup).
1611 // Ideally, ClientHttpRequest::storeEntry() should lock/unlock, but it is
1612 // used so inconsistently that simply adding locking there leads to bugs.
1613 e
->lock("clientReplyContext::forgetHit");
1614 http
->storeEntry(NULL
);
1615 e
->unlock("clientReplyContext::forgetHit"); // may delete e
1619 clientReplyContext::identifyStoreObject()
1621 HttpRequest
*r
= http
->request
;
1623 if (r
->flags
.cachable
|| r
->flags
.internal
) {
1624 lookingforstore
= 5;
1625 StoreEntry::getPublicByRequest (this, r
);
1627 identifyFoundObject (NullStoreEntry::getInstance());
1632 * Check state of the current StoreEntry object.
1633 * to see if we can determine the final status of the request.
1636 clientReplyContext::identifyFoundObject(StoreEntry
*newEntry
)
1638 StoreEntry
*e
= newEntry
;
1639 HttpRequest
*r
= http
->request
;
1641 /** \li If the entry received isNull() then we ignore it. */
1643 http
->storeEntry(NULL
);
1645 http
->storeEntry(e
);
1648 e
= http
->storeEntry();
1650 /* Release IP-cache entries on reload */
1651 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
1652 * 'invalidate' the cached IP entries for this request ???
1654 if (r
->flags
.noCache
|| r
->flags
.noCacheHack())
1655 ipcacheInvalidateNegative(r
->url
.host());
1657 #if USE_CACHE_DIGESTS
1658 lookup_type
= http
->storeEntry() ? "HIT" : "MISS";
1661 if (NULL
== http
->storeEntry()) {
1662 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
1663 debugs(85, 3, "StoreEntry is NULL - MISS");
1664 http
->logType
= LOG_TCP_MISS
;
1669 if (Config
.onoff
.offline
) {
1670 /** \li If we are running in offline mode set to HIT */
1671 debugs(85, 3, "offline HIT " << *e
);
1672 http
->logType
= LOG_TCP_HIT
;
1677 if (http
->redirect
.status
) {
1678 /** \li If redirection status is True force this to be a MISS */
1679 debugs(85, 3, "REDIRECT status forced StoreEntry to NULL (no body on 3XX responses) " << *e
);
1681 http
->logType
= LOG_TCP_REDIRECT
;
1686 if (!e
->validToSend()) {
1687 debugs(85, 3, "!storeEntryValidToSend MISS " << *e
);
1689 http
->logType
= LOG_TCP_MISS
;
1694 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1695 /* \li Special entries are always hits, no matter what the client says */
1696 debugs(85, 3, "ENTRY_SPECIAL HIT " << *e
);
1697 http
->logType
= LOG_TCP_HIT
;
1702 if (r
->flags
.noCache
) {
1703 debugs(85, 3, "no-cache REFRESH MISS " << *e
);
1705 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
1710 debugs(85, 3, "default HIT " << *e
);
1711 http
->logType
= LOG_TCP_HIT
;
1716 * Request more data from the store for the client Stream
1717 * This is *the* entry point to this module.
1720 * - This is the head of the list.
1721 * - There is at least one more node.
1722 * - Data context is not null
1725 clientGetMoreData(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1727 /* Test preconditions */
1728 assert(aNode
!= NULL
);
1729 assert(cbdataReferenceValid(aNode
));
1730 assert(aNode
->node
.prev
== NULL
);
1731 assert(aNode
->node
.next
!= NULL
);
1732 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1734 assert(context
->http
== http
);
1736 clientStreamNode
*next
= ( clientStreamNode
*)aNode
->node
.next
->data
;
1738 if (!context
->ourNode
)
1739 context
->ourNode
= aNode
;
1741 /* no cbdatareference, this is only used once, and safely */
1742 if (context
->flags
.storelogiccomplete
) {
1743 StoreIOBuffer tempBuffer
;
1744 tempBuffer
.offset
= next
->readBuffer
.offset
+ context
->headers_sz
;
1745 tempBuffer
.length
= next
->readBuffer
.length
;
1746 tempBuffer
.data
= next
->readBuffer
.data
;
1748 storeClientCopy(context
->sc
, http
->storeEntry(),
1749 tempBuffer
, clientReplyContext::SendMoreData
, context
);
1753 if (context
->http
->request
->method
== Http::METHOD_PURGE
) {
1754 context
->purgeRequest();
1758 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
1760 if (context
->http
->request
->method
== Http::METHOD_TRACE
) {
1761 if (context
->http
->request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0) {
1762 context
->traceReply(aNode
);
1766 /* continue forwarding, not finished yet. */
1767 http
->logType
= LOG_TCP_MISS
;
1769 context
->doGetMoreData();
1771 context
->identifyStoreObject();
1775 clientReplyContext::doGetMoreData()
1777 /* We still have to do store logic processing - vary, cache hit etc */
1778 if (http
->storeEntry() != NULL
) {
1779 /* someone found the object in the cache for us */
1780 StoreIOBuffer localTempBuffer
;
1782 http
->storeEntry()->lock("clientReplyContext::doGetMoreData");
1784 MemObject
*mem_obj
= http
->storeEntry()->makeMemObject();
1785 if (!mem_obj
->hasUris()) {
1787 * This if-block exists because we don't want to clobber
1788 * a preexiting mem_obj->method value if the mem_obj
1789 * already exists. For example, when a HEAD request
1790 * is a cache hit for a GET response, we want to keep
1791 * the method as GET.
1793 mem_obj
->setUris(storeId(), http
->log_uri
, http
->request
->method
);
1795 * Here we can see if the object was
1796 * created using URL or alternative StoreID from helper.
1798 debugs(88, 3, "storeId: " << http
->storeEntry()->mem_obj
->storeId());
1801 sc
= storeClientListAdd(http
->storeEntry(), this);
1803 sc
->setDelayId(DelayId::DelayClient(http
));
1806 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
1808 /* guarantee nothing has been sent yet! */
1809 assert(http
->out
.size
== 0);
1810 assert(http
->out
.offset
== 0);
1812 if (Ip::Qos::TheConfig
.isHitTosActive()) {
1813 Ip::Qos::doTosLocalHit(http
->getConn()->clientConnection
);
1816 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
1817 Ip::Qos::doNfmarkLocalHit(http
->getConn()->clientConnection
);
1820 localTempBuffer
.offset
= reqofs
;
1821 localTempBuffer
.length
= getNextNode()->readBuffer
.length
;
1822 localTempBuffer
.data
= getNextNode()->readBuffer
.data
;
1823 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, CacheHit
, this);
1825 /* MISS CASE, http->logType is already set! */
1830 /** The next node has removed itself from the stream. */
1832 clientReplyDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1834 /** detach from the stream */
1835 clientStreamDetach(node
, http
);
1839 * Accepts chunk of a http message in buf, parses prefix, filters headers and
1840 * such, writes processed message to the message recipient
1843 clientReplyContext::SendMoreData(void *data
, StoreIOBuffer result
)
1845 clientReplyContext
*context
= static_cast<clientReplyContext
*>(data
);
1846 context
->sendMoreData (result
);
1850 clientReplyContext::makeThisHead()
1852 /* At least, I think thats what this does */
1853 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1854 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1858 clientReplyContext::errorInStream(StoreIOBuffer
const &result
, size_t const &sizeToProcess
)const
1860 return /* aborted request */
1861 (http
->storeEntry() && EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) ||
1862 /* Upstream read error */ (result
.flags
.error
) ||
1863 /* Upstream EOF */ (sizeToProcess
== 0);
1867 clientReplyContext::sendStreamError(StoreIOBuffer
const &result
)
1869 /** call clientWriteComplete so the client socket gets closed
1871 * We call into the stream, because we don't know that there is a
1874 debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.");
1875 StoreIOBuffer localTempBuffer
;
1877 http
->request
->flags
.streamError
= true;
1878 localTempBuffer
.flags
.error
= result
.flags
.error
;
1879 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1884 clientReplyContext::pushStreamData(StoreIOBuffer
const &result
, char *source
)
1886 StoreIOBuffer localTempBuffer
;
1888 if (result
.length
== 0) {
1889 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
1893 assert(result
.offset
- headers_sz
== next()->readBuffer
.offset
);
1894 localTempBuffer
.offset
= result
.offset
- headers_sz
;
1895 localTempBuffer
.length
= result
.length
;
1897 if (localTempBuffer
.length
)
1898 localTempBuffer
.data
= source
;
1900 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1905 clientReplyContext::next() const
1907 assert ( (clientStreamNode
*)http
->client_stream
.head
->next
->data
== getNextNode());
1908 return getNextNode();
1912 clientReplyContext::sendBodyTooLargeError()
1914 Ip::Address tmp_noaddr
;
1915 tmp_noaddr
.setNoAddr(); // TODO: make a global const
1916 http
->logType
= LOG_TCP_DENIED_REPLY
;
1917 ErrorState
*err
= clientBuildError(ERR_TOO_BIG
, Http::scForbidden
, NULL
,
1918 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
1920 removeClientStoreReference(&(sc
), http
);
1921 HTTPMSGUNLOCK(reply
);
1926 /// send 412 (Precondition Failed) to client
1928 clientReplyContext::sendPreconditionFailedError()
1930 http
->logType
= LOG_TCP_HIT
;
1931 ErrorState
*const err
=
1932 clientBuildError(ERR_PRECONDITION_FAILED
, Http::scPreconditionFailed
,
1933 NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
1934 removeClientStoreReference(&sc
, http
);
1935 HTTPMSGUNLOCK(reply
);
1939 /// send 304 (Not Modified) to client
1941 clientReplyContext::sendNotModified()
1943 StoreEntry
*e
= http
->storeEntry();
1944 const time_t timestamp
= e
->timestamp
;
1945 HttpReply
*const temprep
= e
->getReply()->make304();
1946 http
->logType
= LOG_TCP_IMS_HIT
;
1947 removeClientStoreReference(&sc
, http
);
1948 createStoreEntry(http
->request
->method
, RequestFlags());
1949 e
= http
->storeEntry();
1950 // Copy timestamp from the original entry so the 304
1951 // reply has a meaningful Age: header.
1953 e
->timestamp
= timestamp
;
1954 e
->replaceHttpReply(temprep
);
1957 * TODO: why put this in the store and then serialise it and
1958 * then parse it again. Simply mark the request complete in
1959 * our context and write the reply struct to the client side.
1961 triggerInitialStoreRead();
1964 /// send 304 (Not Modified) or 412 (Precondition Failed) to client
1965 /// depending on request method
1967 clientReplyContext::sendNotModifiedOrPreconditionFailedError()
1969 if (http
->request
->method
== Http::METHOD_GET
||
1970 http
->request
->method
== Http::METHOD_HEAD
)
1973 sendPreconditionFailedError();
1977 clientReplyContext::processReplyAccess ()
1979 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
1982 /** Don't block our own responses or HTTP status messages */
1983 if (http
->logType
.oldType
== LOG_TCP_DENIED
||
1984 http
->logType
.oldType
== LOG_TCP_DENIED_REPLY
||
1985 alwaysAllowResponse(reply
->sline
.status())) {
1986 headers_sz
= reply
->hdr_sz
;
1987 processReplyAccessResult(ACCESS_ALLOWED
);
1991 /** Check for reply to big error */
1992 if (reply
->expectedBodyTooLarge(*http
->request
)) {
1993 sendBodyTooLargeError();
1997 headers_sz
= reply
->hdr_sz
;
1999 /** check for absent access controls (permit by default) */
2000 if (!Config
.accessList
.reply
) {
2001 processReplyAccessResult(ACCESS_ALLOWED
);
2005 /** Process http_reply_access lists */
2006 ACLFilledChecklist
*replyChecklist
=
2007 clientAclChecklistCreate(Config
.accessList
.reply
, http
);
2008 replyChecklist
->reply
= reply
;
2009 HTTPMSGLOCK(replyChecklist
->reply
);
2010 replyChecklist
->nonBlockingCheck(ProcessReplyAccessResult
, this);
2014 clientReplyContext::ProcessReplyAccessResult(allow_t rv
, void *voidMe
)
2016 clientReplyContext
*me
= static_cast<clientReplyContext
*>(voidMe
);
2017 me
->processReplyAccessResult(rv
);
2021 clientReplyContext::processReplyAccessResult(const allow_t
&accessAllowed
)
2023 debugs(88, 2, "The reply for " << http
->request
->method
2024 << ' ' << http
->uri
<< " is " << accessAllowed
<< ", because it matched "
2025 << (AclMatchedName
? AclMatchedName
: "NO ACL's"));
2027 if (accessAllowed
!= ACCESS_ALLOWED
) {
2030 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, 1);
2032 http
->logType
= LOG_TCP_DENIED_REPLY
;
2034 if (page_id
== ERR_NONE
)
2035 page_id
= ERR_ACCESS_DENIED
;
2037 Ip::Address tmp_noaddr
;
2038 tmp_noaddr
.setNoAddr();
2039 err
= clientBuildError(page_id
, Http::scForbidden
, NULL
,
2040 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
2043 removeClientStoreReference(&sc
, http
);
2045 HTTPMSGUNLOCK(reply
);
2052 /* Ok, the reply is allowed, */
2053 http
->loggingEntry(http
->storeEntry());
2055 ssize_t body_size
= reqofs
- reply
->hdr_sz
;
2056 if (body_size
< 0) {
2057 reqofs
= reply
->hdr_sz
;
2061 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
2062 (int) body_size
<< " bytes after " << reply
->hdr_sz
<<
2063 " bytes of headers");
2067 if (http
->flags
.accel
&& reply
->sline
.status() != Http::scForbidden
&&
2068 !alwaysAllowResponse(reply
->sline
.status()) &&
2069 esiEnableProcessing(reply
)) {
2070 debugs(88, 2, "Enabling ESI processing for " << http
->uri
);
2071 clientStreamInsertHead(&http
->client_stream
, esiStreamRead
,
2072 esiProcessStream
, esiStreamDetach
, esiStreamStatus
, NULL
);
2077 if (http
->request
->method
== Http::METHOD_HEAD
) {
2078 /* do not forward body for HEAD replies */
2080 http
->flags
.done_copying
= true;
2084 assert (!flags
.headersSent
);
2085 flags
.headersSent
= true;
2087 StoreIOBuffer localTempBuffer
;
2088 char *buf
= next()->readBuffer
.data
;
2089 char *body_buf
= buf
+ reply
->hdr_sz
;
2091 //Server side may disable ranges under some circumstances.
2093 if ((!http
->request
->range
))
2094 next()->readBuffer
.offset
= 0;
2096 body_buf
-= next()->readBuffer
.offset
;
2098 if (next()->readBuffer
.offset
!= 0) {
2099 if (next()->readBuffer
.offset
> body_size
) {
2100 /* Can't use any of the body we received. send nothing */
2101 localTempBuffer
.length
= 0;
2102 localTempBuffer
.data
= NULL
;
2104 localTempBuffer
.length
= body_size
- next()->readBuffer
.offset
;
2105 localTempBuffer
.data
= body_buf
+ next()->readBuffer
.offset
;
2108 localTempBuffer
.length
= body_size
;
2109 localTempBuffer
.data
= body_buf
;
2112 /* TODO??: move the data in the buffer back by the request header size */
2113 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
,
2114 http
, reply
, localTempBuffer
);
2120 clientReplyContext::sendMoreData (StoreIOBuffer result
)
2125 StoreEntry
*entry
= http
->storeEntry();
2127 ConnStateData
* conn
= http
->getConn();
2129 // too late, our conn is closing
2130 // TODO: should we also quit?
2132 debugs(33,3, "not sending more data to a closed connection" );
2135 if (!conn
->isOpen()) {
2136 debugs(33,3, "not sending more data to closing connection " << conn
->clientConnection
);
2139 if (conn
->pinning
.zeroReply
) {
2140 debugs(33,3, "not sending more data after a pinned zero reply " << conn
->clientConnection
);
2144 char *buf
= next()->readBuffer
.data
;
2146 if (buf
!= result
.data
) {
2147 /* we've got to copy some data */
2148 assert(result
.length
<= next()->readBuffer
.length
);
2149 memcpy(buf
, result
.data
, result
.length
);
2152 if (reqofs
==0 && !http
->logType
.isTcpHit() && Comm::IsConnOpen(conn
->clientConnection
)) {
2153 if (Ip::Qos::TheConfig
.isHitTosActive()) {
2154 Ip::Qos::doTosLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2156 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
2157 Ip::Qos::doNfmarkLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2161 /* We've got the final data to start pushing... */
2162 flags
.storelogiccomplete
= 1;
2164 reqofs
+= result
.length
;
2166 assert(reqofs
<= HTTP_REQBUF_SZ
|| flags
.headersSent
);
2168 assert(http
->request
!= NULL
);
2170 /* ESI TODO: remove this assert once everything is stable */
2171 assert(http
->client_stream
.head
->data
2172 && cbdataReferenceValid(http
->client_stream
.head
->data
));
2176 debugs(88, 5, "clientReplyContext::sendMoreData: " << http
->uri
<< ", " <<
2177 reqofs
<< " bytes (" << result
.length
<<
2179 debugs(88, 5, "clientReplyContext::sendMoreData:"
2180 << conn
->clientConnection
<<
2181 " '" << entry
->url() << "'" <<
2182 " out.offset=" << http
->out
.offset
);
2184 /* update size of the request */
2187 if (errorInStream(result
, reqofs
)) {
2188 sendStreamError(result
);
2192 if (flags
.headersSent
) {
2193 pushStreamData (result
, buf
);
2201 sc
->setDelayId(DelayId::DelayClient(http
,reply
));
2204 /* handle headers */
2206 if (Config
.onoff
.log_mime_hdrs
) {
2209 if ((k
= headersEnd(buf
, reqofs
))) {
2210 safe_free(http
->al
->headers
.reply
);
2211 http
->al
->headers
.reply
= (char *)xcalloc(k
+ 1, 1);
2212 xstrncpy(http
->al
->headers
.reply
, buf
, k
);
2216 holdingBuffer
= result
;
2217 processReplyAccess();
2221 /* Using this breaks the client layering just a little!
2224 clientReplyContext::createStoreEntry(const HttpRequestMethod
& m
, RequestFlags reqFlags
)
2226 assert(http
!= NULL
);
2228 * For erroneous requests, we might not have a h->request,
2229 * so make a fake one.
2232 if (http
->request
== NULL
) {
2233 http
->request
= new HttpRequest(m
, AnyP::PROTO_NONE
, null_string
);
2234 HTTPMSGLOCK(http
->request
);
2237 StoreEntry
*e
= storeCreateEntry(storeId(), http
->log_uri
, reqFlags
, m
);
2239 // Make entry collapsable ASAP, to increase collapsing chances for others,
2240 // TODO: every must-revalidate and similar request MUST reach the origin,
2241 // but do we have to prohibit others from collapsing on that request?
2242 if (Config
.onoff
.collapsed_forwarding
&& reqFlags
.cachable
&&
2243 !reqFlags
.needValidation
&&
2244 (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
)) {
2245 // make the entry available for future requests now
2246 Store::Root().allowCollapsing(e
, reqFlags
, m
);
2249 sc
= storeClientListAdd(e
, this);
2252 sc
->setDelayId(DelayId::DelayClient(http
));
2259 /* I don't think this is actually needed! -- adrian */
2260 /* http->reqbuf = http->norm_reqbuf; */
2261 // assert(http->reqbuf == http->norm_reqbuf);
2262 /* The next line is illegal because we don't know if the client stream
2263 * buffers have been set up
2265 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2266 // SendMoreData, this);
2267 /* So, we mark the store logic as complete */
2268 flags
.storelogiccomplete
= 1;
2270 /* and get the caller to request a read, from whereever they are */
2271 /* NOTE: after ANY data flows down the pipe, even one step,
2272 * this function CAN NOT be used to manage errors
2274 http
->storeEntry(e
);
2278 clientBuildError(err_type page_id
, Http::StatusCode status
, char const *url
,
2279 Ip::Address
&src_addr
, HttpRequest
* request
)
2281 ErrorState
*err
= new ErrorState(page_id
, status
, request
);
2282 err
->src_addr
= src_addr
;
2285 err
->url
= xstrdup(url
);