2 * Copyright (C) 1996-2017 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 88 Client-side Reply Routines */
12 #include "acl/FilledChecklist.h"
13 #include "acl/Gadgets.h"
14 #include "anyp/PortCfg.h"
15 #include "client_side_reply.h"
16 #include "errorpage.h"
20 #include "format/Token.h"
23 #include "http/Stream.h"
24 #include "HttpHeaderTools.h"
25 #include "HttpReply.h"
26 #include "HttpRequest.h"
27 #include "ip/QosConfig.h"
29 #include "log/access_log.h"
30 #include "MemObject.h"
31 #include "mime_header.h"
32 #include "neighbors.h"
34 #include "RequestFlags.h"
35 #include "SquidConfig.h"
36 #include "SquidTime.h"
42 #include "auth/UserRequest.h"
45 #include "DelayPools.h"
53 CBDATA_CLASS_INIT(clientReplyContext
);
56 extern "C" CSS clientReplyStatus
;
57 ErrorState
*clientBuildError(err_type
, Http::StatusCode
, char const *, Ip::Address
&, HttpRequest
*);
61 clientReplyContext::~clientReplyContext()
64 /* This may trigger a callback back into SendMoreData as the cbdata
67 removeClientStoreReference(&sc
, http
);
68 /* old_entry might still be set if we didn't yet get the reply
69 * code in HandleIMSReply() */
70 removeStoreReference(&old_sc
, &old_entry
);
71 safe_free(tempBuffer
.data
);
72 cbdataReferenceDone(http
);
76 clientReplyContext::clientReplyContext(ClientHttpRequest
*clientContext
) :
77 purgeStatus(Http::scNone
),
79 http(cbdataReference(clientContext
)),
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 const time_t lastmod
= http
->storeEntry()->lastModified();
270 assert(lastmod
>= 0);
272 * check if we are allowed to contact other servers
273 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
274 * a stale entry *if* it matches client requirements
277 if (http
->onlyIfCached()) {
278 processOnlyIfCachedMiss();
282 http
->logType
= LOG_TCP_REFRESH
;
283 http
->request
->flags
.refresh
= true;
284 #if STORE_CLIENT_LIST_DEBUG
285 /* Prevent a race with the store client memory free routines
287 assert(storeClientIsThisAClient(sc
, this));
289 /* Prepare to make a new temporary request */
292 // TODO: support collapsed revalidation for Vary-controlled entries
293 const bool collapsingAllowed
= Config
.onoff
.collapsed_forwarding
&&
294 !Store::Root().smpAware() &&
295 http
->request
->vary_headers
.isEmpty();
297 StoreEntry
*entry
= nullptr;
298 if (collapsingAllowed
) {
299 if ((entry
= storeGetPublicByRequest(http
->request
, ksRevalidation
)))
300 entry
->lock("clientReplyContext::processExpired#alreadyRevalidating");
304 debugs(88, 5, "collapsed on existing revalidation entry: " << *entry
);
305 collapsedRevalidation
= crSlave
;
307 entry
= storeCreateEntry(url
,
308 http
->log_uri
, http
->request
->flags
, http
->request
->method
);
309 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
311 if (collapsingAllowed
) {
312 debugs(88, 5, "allow other revalidation requests to collapse on " << *entry
);
313 Store::Root().allowCollapsing(entry
, http
->request
->flags
,
314 http
->request
->method
);
315 collapsedRevalidation
= crInitiator
;
317 collapsedRevalidation
= crNone
;
321 sc
= storeClientListAdd(entry
, this);
323 /* delay_id is already set on original store client */
324 sc
->setDelayId(DelayId::DelayClient(http
));
327 http
->request
->lastmod
= lastmod
;
329 if (!http
->request
->header
.has(Http::HdrType::IF_NONE_MATCH
)) {
330 ETag etag
= {NULL
, -1}; // TODO: make that a default ETag constructor
331 if (old_entry
->hasEtag(etag
) && !etag
.weak
)
332 http
->request
->etag
= etag
.str
;
335 debugs(88, 5, "lastmod " << entry
->lastModified());
336 http
->storeEntry(entry
);
337 assert(http
->out
.offset
== 0);
338 assert(http
->request
->clientConnectionManager
== http
->getConn());
340 if (collapsedRevalidation
!= crSlave
) {
342 * A refcounted pointer so that FwdState stays around as long as
343 * this clientReplyContext does
345 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
346 FwdState::Start(conn
, http
->storeEntry(), http
->request
, http
->al
);
348 /* Register with storage manager to receive updates when data comes in. */
350 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
351 debugs(88, DBG_CRITICAL
, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
354 /* start counting the length from 0 */
355 StoreIOBuffer
localTempBuffer(HTTP_REQBUF_SZ
, 0, tempbuf
);
356 storeClientCopy(sc
, entry
, localTempBuffer
, HandleIMSReply
, this);
361 clientReplyContext::sendClientUpstreamResponse()
363 StoreIOBuffer tempresult
;
364 removeStoreReference(&old_sc
, &old_entry
);
365 /* here the data to send is the data we just received */
366 tempBuffer
.offset
= 0;
368 /* sendMoreData tracks the offset as well.
369 * Force it back to zero */
371 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
372 /* TODO: provide sendMoreData with the ready parsed reply */
373 tempresult
.length
= reqsize
;
374 tempresult
.data
= tempbuf
;
375 sendMoreData(tempresult
);
379 clientReplyContext::HandleIMSReply(void *data
, StoreIOBuffer result
)
381 clientReplyContext
*context
= (clientReplyContext
*)data
;
382 context
->handleIMSReply(result
);
386 clientReplyContext::sendClientOldEntry()
388 /* Get the old request back */
390 /* here the data to send is in the next nodes buffers already */
391 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
392 /* sendMoreData tracks the offset as well.
393 * Force it back to zero */
395 StoreIOBuffer
tempresult (reqsize
, reqofs
, next()->readBuffer
.data
);
396 sendMoreData(tempresult
);
399 /* This is the workhorse of the HandleIMSReply callback.
401 * It is called when we've got data back from the origin following our
402 * IMS request to revalidate a stale entry.
405 clientReplyContext::handleIMSReply(StoreIOBuffer result
)
410 debugs(88, 3, http
->storeEntry()->url() << ", " << (long unsigned) result
.length
<< " bytes");
412 if (http
->storeEntry() == NULL
)
415 if (result
.flags
.error
&& !EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
))
418 if (collapsedRevalidation
== crSlave
&& !http
->storeEntry()->mayStartHitting()) {
419 debugs(88, 3, "CF slave hit private non-shareable " << *http
->storeEntry() << ". MISS");
420 // restore context to meet processMiss() expectations
422 http
->logType
= LOG_TCP_MISS
;
427 /* update size of the request */
428 reqsize
= result
.length
+ reqofs
;
430 const Http::StatusCode status
= http
->storeEntry()->getReply()->sline
.status();
432 // request to origin was aborted
433 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
434 debugs(88, 3, "request to origin aborted '" << http
->storeEntry()->url() << "', sending old entry to client");
435 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
436 sendClientOldEntry();
439 const HttpReply
*old_rep
= old_entry
->getReply();
441 // origin replied 304
442 if (status
== Http::scNotModified
) {
443 http
->logType
= LOG_TCP_REFRESH_UNMODIFIED
;
444 http
->request
->flags
.staleIfHit
= false; // old_entry is no longer stale
446 // update headers on existing entry
447 Store::Root().updateOnNotModified(old_entry
, *http
->storeEntry());
449 // if client sent IMS
451 if (http
->request
->flags
.ims
&& !old_entry
->modifiedSince(http
->request
->ims
, http
->request
->imslen
)) {
452 // forward the 304 from origin
453 debugs(88, 3, "origin replied 304, revalidating existing entry and forwarding 304 to client");
454 sendClientUpstreamResponse();
456 // send existing entry, it's still valid
457 debugs(88, 3, "origin replied 304, revalidating existing entry and sending " <<
458 old_rep
->sline
.status() << " to client");
459 sendClientOldEntry();
463 // origin replied with a non-error code
464 else if (status
> Http::scNone
&& status
< Http::scInternalServerError
) {
465 const HttpReply
*new_rep
= http
->storeEntry()->getReply();
466 // RFC 7234 section 4: a cache MUST use the most recent response
467 // (as determined by the Date header field)
468 if (new_rep
->olderThan(old_rep
)) {
469 http
->logType
.err
.ignored
= true;
470 debugs(88, 3, "origin replied " << status
<<
471 " but with an older date header, sending old entry (" <<
472 old_rep
->sline
.status() << ") to client");
473 sendClientOldEntry();
475 http
->logType
= LOG_TCP_REFRESH_MODIFIED
;
476 debugs(88, 3, "origin replied " << status
<<
477 ", replacing existing entry and forwarding to client");
479 if (collapsedRevalidation
)
480 http
->storeEntry()->clearPublicKeyScope();
482 sendClientUpstreamResponse();
486 // origin replied with an error
487 else if (http
->request
->flags
.failOnValidationError
) {
488 http
->logType
= LOG_TCP_REFRESH_FAIL_ERR
;
489 debugs(88, 3, "origin replied with error " << status
<<
490 ", forwarding to client due to fail_on_validation_err");
491 sendClientUpstreamResponse();
493 // ignore and let client have old entry
494 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
495 debugs(88, 3, "origin replied with error " <<
496 status
<< ", sending old entry (" << old_rep
->sline
.status() << ") to client");
497 sendClientOldEntry();
501 SQUIDCEXTERN CSR clientGetMoreData
;
502 SQUIDCEXTERN CSD clientReplyDetach
;
505 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
506 * have been parsed. Normally this should be a single call, but
507 * it might take more than one. As soon as we have the headers,
508 * we hand off to clientSendMoreData, processExpired, or
512 clientReplyContext::CacheHit(void *data
, StoreIOBuffer result
)
514 clientReplyContext
*context
= (clientReplyContext
*)data
;
515 context
->cacheHit(result
);
519 * Process a possible cache HIT.
522 clientReplyContext::cacheHit(StoreIOBuffer result
)
524 /** Ignore if the HIT object is being deleted. */
526 debugs(88, 3, "HIT object being deleted. Ignore the HIT.");
530 StoreEntry
*e
= http
->storeEntry();
532 HttpRequest
*r
= http
->request
;
534 debugs(88, 3, "clientCacheHit: " << http
->uri
<< ", " << result
.length
<< " bytes");
536 if (http
->storeEntry() == NULL
) {
537 debugs(88, 3, "clientCacheHit: request aborted");
539 } else if (result
.flags
.error
) {
540 /* swap in failure */
541 debugs(88, 3, "clientCacheHit: swapin failure for " << http
->uri
);
542 http
->logType
= LOG_TCP_SWAPFAIL_MISS
;
543 removeClientStoreReference(&sc
, http
);
548 // The previously identified hit suddenly became unsharable!
549 // This is common for collapsed forwarding slaves but might also
550 // happen to regular hits because we are called asynchronously.
551 if (!e
->mayStartHitting()) {
552 debugs(88, 3, "unsharable " << *e
<< ". MISS");
553 http
->logType
= LOG_TCP_MISS
;
558 if (result
.length
== 0) {
559 debugs(88, 5, "store IO buffer has no content. MISS");
560 /* the store couldn't get enough data from the file for us to id the
563 /* treat as a miss */
564 http
->logType
= LOG_TCP_MISS
;
569 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
570 /* update size of the request */
571 reqsize
= result
.length
+ reqofs
;
574 * Got the headers, now grok them
576 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
578 if (http
->request
->storeId().cmp(e
->mem_obj
->storeId()) != 0) {
579 debugs(33, DBG_IMPORTANT
, "clientProcessHit: URL mismatch, '" << e
->mem_obj
->storeId() << "' != '" << http
->request
->storeId() << "'");
580 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
585 switch (varyEvaluateMatch(e
, r
)) {
588 /* No variance detected. Continue as normal */
592 /* This is the correct entity for this request. Continue */
593 debugs(88, 2, "clientProcessHit: Vary MATCH!");
597 /* This is not the correct entity for this request. We need
598 * to requery the cache.
600 removeClientStoreReference(&sc
, http
);
602 /* Note: varyEvalyateMatch updates the request with vary information
603 * so we only get here once. (it also takes care of cancelling loops)
605 debugs(88, 2, "clientProcessHit: Vary detected!");
606 clientGetMoreData(ourNode
, http
);
610 /* varyEvaluateMatch found a object loop. Process as miss */
611 debugs(88, DBG_IMPORTANT
, "clientProcessHit: Vary object loop!");
612 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
617 if (r
->method
== Http::METHOD_PURGE
) {
618 debugs(88, 5, "PURGE gets a HIT");
619 removeClientStoreReference(&sc
, http
);
625 if (e
->checkNegativeHit() && !r
->flags
.noCacheHack()) {
626 debugs(88, 5, "negative-HIT");
627 http
->logType
= LOG_TCP_NEGATIVE_HIT
;
628 sendMoreData(result
);
630 } else if (blockedHit()) {
631 debugs(88, 5, "send_hit forces a MISS");
632 http
->logType
= LOG_TCP_MISS
;
635 } else if (!http
->flags
.internal
&& refreshCheckHTTP(e
, r
)) {
636 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
638 * We hold a stale copy; it needs to be validated
641 * The 'needValidation' flag is used to prevent forwarding
642 * loops between siblings. If our copy of the object is stale,
643 * then we should probably only use parents for the validation
644 * request. Otherwise two siblings could generate a loop if
645 * both have a stale version of the object.
647 r
->flags
.needValidation
= true;
649 if (e
->lastModified() < 0) {
650 debugs(88, 3, "validate HIT object? NO. Can't calculate entry modification time. Do MISS.");
652 * We cannot revalidate entries without knowing their
654 * XXX: BUG 1890 objects without Date do not get one added.
656 http
->logType
= LOG_TCP_MISS
;
658 } else if (r
->flags
.noCache
) {
659 debugs(88, 3, "validate HIT object? NO. Client sent CC:no-cache. Do CLIENT_REFRESH_MISS");
661 * This did not match a refresh pattern that overrides no-cache
662 * we should honour the client no-cache header.
664 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
666 } else if (r
->url
.getScheme() == AnyP::PROTO_HTTP
) {
667 debugs(88, 3, "validate HIT object? YES.");
669 * Object needs to be revalidated
670 * XXX This could apply to FTP as well, if Last-Modified is known.
674 debugs(88, 3, "validate HIT object? NO. Client protocol non-HTTP. Do MISS.");
676 * We don't know how to re-validate other protocols. Handle
677 * them as if the object has expired.
679 http
->logType
= LOG_TCP_MISS
;
683 } else if (r
->conditional()) {
684 debugs(88, 5, "conditional HIT");
685 if (processConditional(result
))
690 * plain ol' cache hit
692 debugs(88, 5, "plain old HIT");
695 if (e
->store_status
!= STORE_OK
)
696 http
->logType
= LOG_TCP_MISS
;
699 if (e
->mem_status
== IN_MEMORY
)
700 http
->logType
= LOG_TCP_MEM_HIT
;
701 else if (Config
.onoff
.offline
)
702 http
->logType
= LOG_TCP_OFFLINE_HIT
;
704 sendMoreData(result
);
708 * Prepare to fetch the object as it's a cache miss of some kind.
711 clientReplyContext::processMiss()
713 char *url
= http
->uri
;
714 HttpRequest
*r
= http
->request
;
715 ErrorState
*err
= NULL
;
716 debugs(88, 4, r
->method
<< ' ' << url
);
719 * We might have a left-over StoreEntry from a failed cache hit
722 if (http
->storeEntry()) {
723 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
724 debugs(88, DBG_CRITICAL
, "clientProcessMiss: miss on a special object (" << url
<< ").");
725 debugs(88, DBG_CRITICAL
, "\tlog_type = " << http
->logType
.c_str());
726 http
->storeEntry()->dump(1);
729 removeClientStoreReference(&sc
, http
);
732 /** Check if its a PURGE request to be actioned. */
733 if (r
->method
== Http::METHOD_PURGE
) {
738 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
739 if (r
->method
== Http::METHOD_OTHER
) {
743 /** Check if 'only-if-cached' flag is set. Action if so. */
744 if (http
->onlyIfCached()) {
745 processOnlyIfCachedMiss();
750 if (r
->flags
.loopDetected
) {
751 http
->al
->http
.code
= Http::scForbidden
;
752 err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
753 createStoreEntry(r
->method
, RequestFlags());
754 errorAppendEntry(http
->storeEntry(), err
);
755 triggerInitialStoreRead();
758 assert(http
->out
.offset
== 0);
759 createStoreEntry(r
->method
, r
->flags
);
760 triggerInitialStoreRead();
762 if (http
->redirect
.status
) {
763 HttpReply
*rep
= new HttpReply
;
764 http
->logType
= LOG_TCP_REDIRECT
;
765 http
->storeEntry()->releaseRequest();
766 rep
->redirect(http
->redirect
.status
, http
->redirect
.location
);
767 http
->storeEntry()->replaceHttpReply(rep
);
768 http
->storeEntry()->complete();
772 assert(r
->clientConnectionManager
== http
->getConn());
774 /** Start forwarding to get the new object from network */
775 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
776 FwdState::Start(conn
, http
->storeEntry(), r
, http
->al
);
781 * client issued a request with an only-if-cached cache-control directive;
782 * we did not find a cached object that can be returned without
783 * contacting other servers;
784 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
787 clientReplyContext::processOnlyIfCachedMiss()
789 debugs(88, 4, http
->request
->method
<< ' ' << http
->uri
);
790 http
->al
->http
.code
= Http::scGatewayTimeout
;
791 ErrorState
*err
= clientBuildError(ERR_ONLY_IF_CACHED_MISS
, Http::scGatewayTimeout
, NULL
,
792 http
->getConn()->clientConnection
->remote
, http
->request
);
793 removeClientStoreReference(&sc
, http
);
797 /// process conditional request from client
799 clientReplyContext::processConditional(StoreIOBuffer
&result
)
801 StoreEntry
*const e
= http
->storeEntry();
803 if (e
->getReply()->sline
.status() != Http::scOkay
) {
804 debugs(88, 4, "Reply code " << e
->getReply()->sline
.status() << " != 200");
805 http
->logType
= LOG_TCP_MISS
;
810 HttpRequest
&r
= *http
->request
;
812 if (r
.header
.has(Http::HdrType::IF_MATCH
) && !e
->hasIfMatchEtag(r
)) {
813 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
814 sendPreconditionFailedError();
818 if (r
.header
.has(Http::HdrType::IF_NONE_MATCH
)) {
819 // RFC 7232: If-None-Match recipient MUST ignore IMS
823 r
.header
.delById(Http::HdrType::IF_MODIFIED_SINCE
);
825 if (e
->hasIfNoneMatchEtag(r
)) {
826 sendNotModifiedOrPreconditionFailedError();
830 // None-Match is true (no ETag matched); treat as an unconditional hit
835 // handle If-Modified-Since requests from the client
836 if (e
->modifiedSince(r
.ims
, r
.imslen
)) {
837 // Modified-Since is true; treat as an unconditional hit
841 // otherwise reply with 304 Not Modified
850 /// whether squid.conf send_hit prevents us from serving this hit
852 clientReplyContext::blockedHit() const
854 if (!Config
.accessList
.sendHit
)
855 return false; // hits are not blocked by default
857 if (http
->flags
.internal
)
858 return false; // internal content "hits" cannot be blocked
860 if (const HttpReply
*rep
= http
->storeEntry()->getReply()) {
861 std::unique_ptr
<ACLFilledChecklist
> chl(clientAclChecklistCreate(Config
.accessList
.sendHit
, http
));
862 chl
->reply
= const_cast<HttpReply
*>(rep
); // ACLChecklist API bug
863 HTTPMSGLOCK(chl
->reply
);
864 return chl
->fastCheck() != ACCESS_ALLOWED
; // when in doubt, block
867 // This does not happen, I hope, because we are called from CacheHit, which
868 // is called via a storeClientCopy() callback, and store should initialize
869 // the reply before calling that callback.
870 debugs(88, 3, "Missing reply!");
875 clientReplyContext::purgeRequestFindObjectToPurge()
877 /* Try to find a base entry */
878 http
->flags
.purging
= true;
881 // TODO: can we use purgeAllCached() here instead of doing the
882 // getPublicByRequestMethod() dance?
883 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_GET
);
886 // Purges all entries with a given url
887 // TODO: move to SideAgent parent, when we have one
889 * We probably cannot purge Vary-affected responses because their MD5
890 * keys depend on vary headers.
893 purgeEntriesByUrl(HttpRequest
* req
, const char *url
)
896 bool get_or_head_sent
= false;
899 for (HttpRequestMethod
m(Http::METHOD_NONE
); m
!= Http::METHOD_ENUM_END
; ++m
) {
900 if (m
.respMaybeCacheable()) {
901 if (StoreEntry
*entry
= storeGetPublic(url
, m
)) {
902 debugs(88, 5, "purging " << *entry
<< ' ' << m
<< ' ' << url
);
904 neighborsHtcpClear(entry
, url
, req
, m
, HTCP_CLR_INVALIDATION
);
905 if (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
) {
906 get_or_head_sent
= true;
915 if (!get_or_head_sent
) {
916 neighborsHtcpClear(NULL
, url
, req
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_INVALIDATION
);
922 clientReplyContext::purgeAllCached()
924 // XXX: performance regression, c_str() reallocates
925 SBuf
url(http
->request
->effectiveRequestUri());
926 purgeEntriesByUrl(http
->request
, url
.c_str());
930 clientReplyContext::created(StoreEntry
*newEntry
)
932 if (lookingforstore
== 1)
933 purgeFoundGet(newEntry
);
934 else if (lookingforstore
== 2)
935 purgeFoundHead(newEntry
);
936 else if (lookingforstore
== 3)
937 purgeDoPurgeGet(newEntry
);
938 else if (lookingforstore
== 4)
939 purgeDoPurgeHead(newEntry
);
940 else if (lookingforstore
== 5)
941 identifyFoundObject(newEntry
);
945 clientReplyContext::purgeFoundGet(StoreEntry
*newEntry
)
947 if (newEntry
->isNull()) {
949 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
951 purgeFoundObject (newEntry
);
955 clientReplyContext::purgeFoundHead(StoreEntry
*newEntry
)
957 if (newEntry
->isNull())
960 purgeFoundObject (newEntry
);
964 clientReplyContext::purgeFoundObject(StoreEntry
*entry
)
966 assert (entry
&& !entry
->isNull());
968 if (EBIT_TEST(entry
->flags
, ENTRY_SPECIAL
)) {
969 http
->logType
= LOG_TCP_DENIED
;
970 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
,
971 http
->getConn()->clientConnection
->remote
, http
->request
);
973 return; // XXX: leaking unused entry if some store does not keep it
976 StoreIOBuffer localTempBuffer
;
977 /* Swap in the metadata */
978 http
->storeEntry(entry
);
980 http
->storeEntry()->lock("clientReplyContext::purgeFoundObject");
981 http
->storeEntry()->createMemObject(storeId(), http
->log_uri
,
982 http
->request
->method
);
984 sc
= storeClientListAdd(http
->storeEntry(), this);
986 http
->logType
= LOG_TCP_HIT
;
990 localTempBuffer
.offset
= http
->out
.offset
;
992 localTempBuffer
.length
= next()->readBuffer
.length
;
994 localTempBuffer
.data
= next()->readBuffer
.data
;
996 storeClientCopy(sc
, http
->storeEntry(),
997 localTempBuffer
, CacheHit
, this);
1001 clientReplyContext::purgeRequest()
1003 debugs(88, 3, "Config2.onoff.enable_purge = " <<
1004 Config2
.onoff
.enable_purge
);
1006 if (!Config2
.onoff
.enable_purge
) {
1007 http
->logType
= LOG_TCP_DENIED
;
1008 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
1013 /* Release both IP cache */
1014 ipcacheInvalidate(http
->request
->url
.host());
1016 if (!http
->flags
.purging
)
1017 purgeRequestFindObjectToPurge();
1023 clientReplyContext::purgeDoMissPurge()
1025 http
->logType
= LOG_TCP_MISS
;
1026 lookingforstore
= 3;
1027 StoreEntry::getPublicByRequestMethod(this,http
->request
, Http::METHOD_GET
);
1031 clientReplyContext::purgeDoPurgeGet(StoreEntry
*newEntry
)
1034 /* Move to new() when that is created */
1035 purgeStatus
= Http::scNotFound
;
1037 if (!newEntry
->isNull()) {
1038 /* Release the cached URI */
1039 debugs(88, 4, "clientPurgeRequest: GET '" << newEntry
->url() << "'" );
1041 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1043 newEntry
->release();
1044 purgeStatus
= Http::scOkay
;
1047 lookingforstore
= 4;
1048 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
1052 clientReplyContext::purgeDoPurgeHead(StoreEntry
*newEntry
)
1054 if (newEntry
&& !newEntry
->isNull()) {
1055 debugs(88, 4, "HEAD " << newEntry
->url());
1057 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1059 newEntry
->release();
1060 purgeStatus
= Http::scOkay
;
1063 /* And for Vary, release the base URI if none of the headers was included in the request */
1064 if (!http
->request
->vary_headers
.isEmpty()
1065 && http
->request
->vary_headers
.find('=') != SBuf::npos
) {
1066 // XXX: performance regression, c_str() reallocates
1067 SBuf
tmp(http
->request
->effectiveRequestUri());
1068 StoreEntry
*entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_GET
);
1071 debugs(88, 4, "Vary GET " << entry
->url());
1073 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1076 purgeStatus
= Http::scOkay
;
1079 entry
= storeGetPublic(tmp
.c_str(), Http::METHOD_HEAD
);
1082 debugs(88, 4, "Vary HEAD " << entry
->url());
1084 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1087 purgeStatus
= Http::scOkay
;
1092 * Make a new entry to hold the reply to be written
1095 /* FIXME: This doesn't need to go through the store. Simply
1096 * push down the client chain
1098 createStoreEntry(http
->request
->method
, RequestFlags());
1100 triggerInitialStoreRead();
1102 HttpReply
*rep
= new HttpReply
;
1103 rep
->setHeaders(purgeStatus
, NULL
, NULL
, 0, 0, -1);
1104 http
->storeEntry()->replaceHttpReply(rep
);
1105 http
->storeEntry()->complete();
1109 clientReplyContext::traceReply(clientStreamNode
* node
)
1111 clientStreamNode
*nextNode
= (clientStreamNode
*)node
->node
.next
->data
;
1112 StoreIOBuffer localTempBuffer
;
1113 createStoreEntry(http
->request
->method
, RequestFlags());
1114 localTempBuffer
.offset
= nextNode
->readBuffer
.offset
+ headers_sz
;
1115 localTempBuffer
.length
= nextNode
->readBuffer
.length
;
1116 localTempBuffer
.data
= nextNode
->readBuffer
.data
;
1117 storeClientCopy(sc
, http
->storeEntry(),
1118 localTempBuffer
, SendMoreData
, this);
1119 http
->storeEntry()->releaseRequest();
1120 http
->storeEntry()->buffer();
1121 HttpReply
*rep
= new HttpReply
;
1122 rep
->setHeaders(Http::scOkay
, NULL
, "text/plain", http
->request
->prefixLen(), 0, squid_curtime
);
1123 http
->storeEntry()->replaceHttpReply(rep
);
1124 http
->request
->swapOut(http
->storeEntry());
1125 http
->storeEntry()->complete();
1128 #define SENDING_BODY 0
1129 #define SENDING_HDRSONLY 1
1131 clientReplyContext::checkTransferDone()
1133 StoreEntry
*entry
= http
->storeEntry();
1139 * For now, 'done_copying' is used for special cases like
1140 * Range and HEAD requests.
1142 if (http
->flags
.done_copying
)
1145 if (http
->request
->flags
.chunkedReply
&& !flags
.complete
) {
1146 // last-chunk was not sent
1151 * Handle STORE_OK objects.
1152 * objectLen(entry) will be set proprely.
1153 * RC: Does objectLen(entry) include the Headers?
1156 if (entry
->store_status
== STORE_OK
) {
1157 return storeOKTransferDone();
1159 return storeNotOKTransferDone();
1164 clientReplyContext::storeOKTransferDone() const
1166 assert(http
->storeEntry()->objectLen() >= 0);
1167 assert(http
->storeEntry()->objectLen() >= headers_sz
);
1168 if (http
->out
.offset
>= http
->storeEntry()->objectLen() - headers_sz
) {
1169 debugs(88,3,HERE
<< "storeOKTransferDone " <<
1170 " out.offset=" << http
->out
.offset
<<
1171 " objectLen()=" << http
->storeEntry()->objectLen() <<
1172 " headers_sz=" << headers_sz
);
1180 clientReplyContext::storeNotOKTransferDone() const
1183 * Now, handle STORE_PENDING objects
1185 MemObject
*mem
= http
->storeEntry()->mem_obj
;
1186 assert(mem
!= NULL
);
1187 assert(http
->request
!= NULL
);
1189 /* mem->reply was wrong because it uses the UPSTREAM header length!!! */
1190 if (headers_sz
== 0)
1191 /* haven't found end of headers yet */
1194 const HttpReplyPointer
curReply(mem
->getReply());
1197 * Figure out how much data we are supposed to send.
1198 * If we are sending a body and we don't have a content-length,
1199 * then we must wait for the object to become STORE_OK.
1201 if (curReply
->content_length
< 0)
1204 uint64_t expectedLength
= curReply
->content_length
+ http
->out
.headers_sz
;
1206 if (http
->out
.size
< expectedLength
)
1209 debugs(88,3,HERE
<< "storeNotOKTransferDone " <<
1210 " out.size=" << http
->out
.size
<<
1211 " expectedLength=" << expectedLength
);
1216 /* A write has completed, what is the next status based on the
1217 * canonical request data?
1218 * 1 something is wrong
1219 * 0 nothing is wrong.
1223 clientHttpRequestStatus(int fd
, ClientHttpRequest
const *http
)
1225 #if SIZEOF_INT64_T == 4
1226 if (http
->out
.size
> 0x7FFF0000) {
1227 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
<< " to prevent out.size counter overflow");
1228 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1229 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes");
1230 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1234 if (http
->out
.offset
> 0x7FFF0000) {
1235 debugs(88, DBG_IMPORTANT
, "WARNING: closing FD " << fd
< " to prevent out.offset counter overflow");
1236 debugs(88, DBG_IMPORTANT
, "\tclient " << http
->getConn()->peer
);
1237 debugs(88, DBG_IMPORTANT
, "\treceived " << http
->out
.size
<< " bytes, offset " << http
->out
.offset
);
1238 debugs(88, DBG_IMPORTANT
, "\tURI " << http
->log_uri
);
1247 * *http is a valid structure.
1248 * fd is either -1, or an open fd.
1250 * TODO: enumify this
1252 * This function is used by any http request sink, to determine the status
1255 clientStream_status_t
1256 clientReplyStatus(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1258 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1260 assert (context
->http
== http
);
1261 return context
->replyStatus();
1264 clientStream_status_t
1265 clientReplyContext::replyStatus()
1268 /* Here because lower nodes don't need it */
1270 if (http
->storeEntry() == NULL
) {
1271 debugs(88, 5, "clientReplyStatus: no storeEntry");
1272 return STREAM_FAILED
; /* yuck, but what can we do? */
1275 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
1276 /* TODO: Could upstream read errors (result.flags.error) be
1277 * lost, and result in undersize requests being considered
1278 * complete. Should we tcp reset such connections ?
1280 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
1281 return STREAM_FAILED
;
1284 if ((done
= checkTransferDone()) != 0 || flags
.complete
) {
1285 debugs(88, 5, "clientReplyStatus: transfer is DONE: " << done
<< flags
.complete
);
1286 /* Ok we're finished, but how? */
1288 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_BAD_LENGTH
)) {
1289 debugs(88, 5, "clientReplyStatus: truncated response body");
1290 return STREAM_UNPLANNED_COMPLETE
;
1294 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
1295 return STREAM_FAILED
;
1298 const int64_t expectedBodySize
=
1299 http
->storeEntry()->getReply()->bodySize(http
->request
->method
);
1300 if (expectedBodySize
>= 0 && !http
->gotEnough()) {
1301 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
1302 return STREAM_UNPLANNED_COMPLETE
;
1305 debugs(88, 5, "clientReplyStatus: stream complete; keepalive=" <<
1306 http
->request
->flags
.proxyKeepalive
);
1307 return STREAM_COMPLETE
;
1310 // XXX: Should this be checked earlier? We could return above w/o checking.
1311 if (reply
->receivedBodyTooLarge(*http
->request
, http
->out
.offset
- 4096)) {
1312 /* 4096 is a margin for the HTTP headers included in out.offset */
1313 debugs(88, 5, "clientReplyStatus: client reply body is too large");
1314 return STREAM_FAILED
;
1320 /* Responses with no body will not have a content-type header,
1321 * which breaks the rep_mime_type acl, which
1322 * coincidentally, is the most common acl for reply access lists.
1323 * A better long term fix for this is to allow acl matchs on the various
1324 * status codes, and then supply a default ruleset that puts these
1325 * codes before any user defines access entries. That way the user
1326 * can choose to block these responses where appropriate, but won't get
1327 * mysterious breakages.
1330 clientReplyContext::alwaysAllowResponse(Http::StatusCode sline
) const
1336 case Http::scContinue
:
1338 case Http::scSwitchingProtocols
:
1340 case Http::scProcessing
:
1342 case Http::scNoContent
:
1344 case Http::scNotModified
:
1356 * Generate the reply headers sent to client.
1358 * Filters out unwanted entries and hop-by-hop from original reply header
1359 * then adds extra entries if we have more info than origin server
1360 * then adds Squid specific entries
1363 clientReplyContext::buildReplyHeader()
1365 HttpHeader
*hdr
= &reply
->header
;
1366 const bool is_hit
= http
->logType
.isTcpHit();
1367 HttpRequest
*request
= http
->request
;
1368 #if DONT_FILTER_THESE
1369 /* but you might want to if you run Squid as an HTTP accelerator */
1370 /* hdr->delById(HDR_ACCEPT_RANGES); */
1371 hdr
->delById(HDR_ETAG
);
1374 if (is_hit
|| collapsedRevalidation
== crSlave
)
1375 hdr
->delById(Http::HdrType::SET_COOKIE
);
1376 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
1378 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
1379 // remove the Proxy-Authenticate header
1380 if ( !request
->peer_login
|| (strcmp(request
->peer_login
,"PASS") != 0 && strcmp(request
->peer_login
,"PASSTHRU") != 0)) {
1382 // but allow adaptation services to authenticate clients
1383 // via request satisfaction
1384 if (!http
->requestSatisfactionMode())
1386 reply
->header
.delById(Http::HdrType::PROXY_AUTHENTICATE
);
1389 reply
->header
.removeHopByHopEntries();
1391 // if (request->range)
1392 // clientBuildRangeHeader(http, reply);
1395 * Add a estimated Age header on cache hits.
1399 * Remove any existing Age header sent by upstream caches
1400 * (note that the existing header is passed along unmodified
1403 hdr
->delById(Http::HdrType::AGE
);
1405 * This adds the calculated object age. Note that the details of the
1406 * age calculation is performed by adjusting the timestamp in
1407 * StoreEntry::timestampsSet(), not here.
1409 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
1410 hdr
->delById(Http::HdrType::DATE
);
1411 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1412 } else if (http
->getConn() && http
->getConn()->port
->actAsOrigin
) {
1413 // Swap the Date: header to current time if we are simulating an origin
1414 HttpHeaderEntry
*h
= hdr
->findEntry(Http::HdrType::DATE
);
1416 hdr
->putExt("X-Origin-Date", h
->value
.termedBuf());
1417 hdr
->delById(Http::HdrType::DATE
);
1418 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1419 h
= hdr
->findEntry(Http::HdrType::EXPIRES
);
1420 if (h
&& http
->storeEntry()->expires
>= 0) {
1421 hdr
->putExt("X-Origin-Expires", h
->value
.termedBuf());
1422 hdr
->delById(Http::HdrType::EXPIRES
);
1423 hdr
->putTime(Http::HdrType::EXPIRES
, squid_curtime
+ http
->storeEntry()->expires
- http
->storeEntry()->timestamp
);
1425 if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1426 // put X-Cache-Age: instead of Age:
1428 snprintf(age
, sizeof(age
), "%" PRId64
, static_cast<int64_t>(squid_curtime
- http
->storeEntry()->timestamp
));
1429 hdr
->putExt("X-Cache-Age", age
);
1431 } else if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1432 hdr
->putInt(Http::HdrType::AGE
,
1433 squid_curtime
- http
->storeEntry()->timestamp
);
1434 /* Signal old objects. NB: rfc 2616 is not clear,
1435 * by implication, on whether we should do this to all
1436 * responses, or only cache hits.
1437 * 14.46 states it ONLY applys for heuristically caclulated
1438 * freshness values, 13.2.4 doesn't specify the same limitation.
1439 * We interpret RFC 2616 under the combination.
1441 /* TODO: if maxage or s-maxage is present, don't do this */
1443 if (squid_curtime
- http
->storeEntry()->timestamp
>= 86400) {
1445 snprintf (tbuf
, sizeof(tbuf
), "%s %s %s",
1447 "This cache hit is still fresh and more than 1 day old");
1448 hdr
->putStr(Http::HdrType::WARNING
, tbuf
);
1453 /* RFC 2616: Section 14.18
1455 * Add a Date: header if missing.
1456 * We have access to a clock therefore are required to amend any shortcoming in servers.
1458 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1460 if ( !hdr
->has(Http::HdrType::DATE
) ) {
1461 if (!http
->storeEntry())
1462 hdr
->putTime(Http::HdrType::DATE
, squid_curtime
);
1463 else if (http
->storeEntry()->timestamp
> 0)
1464 hdr
->putTime(Http::HdrType::DATE
, http
->storeEntry()->timestamp
);
1466 debugs(88,DBG_IMPORTANT
,"BUG 3279: HTTP reply without Date:");
1467 /* dump something useful about the problem */
1468 http
->storeEntry()->dump(DBG_IMPORTANT
);
1472 // add Warnings required by RFC 2616 if serving a stale hit
1473 if (http
->request
->flags
.staleIfHit
&& http
->logType
.isTcpHit()) {
1474 hdr
->putWarning(110, "Response is stale");
1475 if (http
->request
->flags
.needValidation
)
1476 hdr
->putWarning(111, "Revalidation failed");
1479 /* Filter unproxyable authentication types */
1480 if (http
->logType
.oldType
!= LOG_TCP_DENIED
&&
1481 hdr
->has(Http::HdrType::WWW_AUTHENTICATE
)) {
1482 HttpHeaderPos pos
= HttpHeaderInitPos
;
1485 int connection_auth_blocked
= 0;
1486 while ((e
= hdr
->getEntry(&pos
))) {
1487 if (e
->id
== Http::HdrType::WWW_AUTHENTICATE
) {
1488 const char *value
= e
->value
.rawBuf();
1490 if ((strncasecmp(value
, "NTLM", 4) == 0 &&
1491 (value
[4] == '\0' || value
[4] == ' '))
1493 (strncasecmp(value
, "Negotiate", 9) == 0 &&
1494 (value
[9] == '\0' || value
[9] == ' '))
1496 (strncasecmp(value
, "Kerberos", 8) == 0 &&
1497 (value
[8] == '\0' || value
[8] == ' '))) {
1498 if (request
->flags
.connectionAuthDisabled
) {
1499 hdr
->delAt(pos
, connection_auth_blocked
);
1502 request
->flags
.mustKeepalive
= true;
1503 if (!request
->flags
.accelerated
&& !request
->flags
.intercepted
) {
1504 httpHeaderPutStrf(hdr
, Http::HdrType::PROXY_SUPPORT
, "Session-Based-Authentication");
1506 We send "Connection: Proxy-Support" header to mark
1507 Proxy-Support as a hop-by-hop header for intermediaries that do not
1508 understand the semantics of this header. The RFC should have included
1509 this recommendation.
1511 httpHeaderPutStrf(hdr
, Http::HdrType::CONNECTION
, "Proxy-support");
1518 if (connection_auth_blocked
)
1523 /* Handle authentication headers */
1524 if (http
->logType
.oldType
== LOG_TCP_DENIED
&&
1525 ( reply
->sline
.status() == Http::scProxyAuthenticationRequired
||
1526 reply
->sline
.status() == Http::scUnauthorized
)
1528 /* Add authentication header */
1529 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1530 * depends on authenticate behaviour: all schemes to date send no extra
1531 * data on 407/401 responses, and do not check the accel state on 401/407
1534 Auth::UserRequest::AddReplyAuthHeader(reply
, request
->auth_user_request
, request
, 0, 1);
1535 } else if (request
->auth_user_request
!= NULL
)
1536 Auth::UserRequest::AddReplyAuthHeader(reply
, request
->auth_user_request
, request
, http
->flags
.accel
, 0);
1539 /* Append X-Cache */
1540 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE
, "%s from %s",
1541 is_hit
? "HIT" : "MISS", getMyHostname());
1543 #if USE_CACHE_DIGESTS
1544 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1545 httpHeaderPutStrf(hdr
, Http::HdrType::X_CACHE_LOOKUP
, "%s from %s:%d",
1546 lookup_type
? lookup_type
: "NONE",
1547 getMyHostname(), getMyPort());
1551 const bool maySendChunkedReply
= !request
->multipartRangeRequest() &&
1552 reply
->sline
.protocol
== AnyP::PROTO_HTTP
&& // response is HTTP
1553 (request
->http_ver
>= Http::ProtocolVersion(1,1));
1555 /* Check whether we should send keep-alive */
1556 if (!Config
.onoff
.error_pconns
&& reply
->sline
.status() >= 400 && !request
->flags
.mustKeepalive
) {
1557 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
1558 request
->flags
.proxyKeepalive
= false;
1559 } else if (!Config
.onoff
.client_pconns
&& !request
->flags
.mustKeepalive
) {
1560 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
1561 request
->flags
.proxyKeepalive
= false;
1562 } else if (request
->flags
.proxyKeepalive
&& shutting_down
) {
1563 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
1564 request
->flags
.proxyKeepalive
= false;
1565 } else if (request
->flags
.connectionAuth
&& !reply
->keep_alive
) {
1566 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
1567 request
->flags
.proxyKeepalive
= false;
1568 } else if (reply
->bodySize(request
->method
) < 0 && !maySendChunkedReply
) {
1569 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
1570 request
->flags
.proxyKeepalive
= false;
1571 } else if (fdUsageHigh()&& !request
->flags
.mustKeepalive
) {
1572 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
1573 request
->flags
.proxyKeepalive
= false;
1574 } else if (request
->flags
.sslBumped
&& !reply
->persistent()) {
1575 // We do not really have to close, but we pretend we are a tunnel.
1576 debugs(88, 3, "clientBuildReplyHeader: bumped reply forces close");
1577 request
->flags
.proxyKeepalive
= false;
1578 } else if (request
->pinnedConnection() && !reply
->persistent()) {
1579 // The peer wants to close the pinned connection
1580 debugs(88, 3, "pinned reply forces close");
1581 request
->flags
.proxyKeepalive
= false;
1582 } else if (http
->getConn()) {
1583 ConnStateData
* conn
= http
->getConn();
1584 if (!Comm::IsConnOpen(conn
->port
->listenConn
)) {
1585 // The listening port closed because of a reconfigure
1586 debugs(88, 3, "listening port closed");
1587 request
->flags
.proxyKeepalive
= false;
1591 // Decide if we send chunked reply
1592 if (maySendChunkedReply
&& reply
->bodySize(request
->method
) < 0) {
1593 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
1594 request
->flags
.chunkedReply
= true;
1595 hdr
->putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
1598 hdr
->addVia(reply
->sline
.version
);
1600 /* Signal keep-alive or close explicitly */
1601 hdr
->putStr(Http::HdrType::CONNECTION
, request
->flags
.proxyKeepalive
? "keep-alive" : "close");
1603 #if ADD_X_REQUEST_URI
1605 * Knowing the URI of the request is useful when debugging persistent
1606 * connections in a client; we cannot guarantee the order of http headers,
1607 * but X-Request-URI is likely to be the very last header to ease use from a
1608 * debugger [hdr->entries.count-1].
1610 hdr
->putStr(Http::HdrType::X_REQUEST_URI
,
1611 http
->memOjbect()->url
? http
->memObject()->url
: http
->uri
);
1615 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1616 if ( hdr
->has(Http::HdrType::SURROGATE_CONTROL
) ) {
1617 if (!request
->header
.has(Http::HdrType::SURROGATE_CAPABILITY
)) {
1618 hdr
->delById(Http::HdrType::SURROGATE_CONTROL
);
1620 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1623 httpHdrMangleList(hdr
, request
, http
->al
, ROR_REPLY
);
1627 clientReplyContext::cloneReply()
1629 assert(reply
== NULL
);
1631 reply
= http
->storeEntry()->getReply()->clone();
1634 if (reply
->sline
.protocol
== AnyP::PROTO_HTTP
) {
1635 /* RFC 2616 requires us to advertise our version (but only on real HTTP traffic) */
1636 reply
->sline
.version
= Http::ProtocolVersion();
1639 /* do header conversions */
1643 /// Safely disposes of an entry pointing to a cache hit that we do not want.
1644 /// We cannot just ignore the entry because it may be locking or otherwise
1645 /// holding an associated cache resource of some sort.
1647 clientReplyContext::forgetHit()
1649 StoreEntry
*e
= http
->storeEntry();
1650 assert(e
); // or we are not dealing with a hit
1651 // We probably have not locked the entry earlier, unfortunately. We lock it
1652 // now so that we can unlock two lines later (and trigger cleanup).
1653 // Ideally, ClientHttpRequest::storeEntry() should lock/unlock, but it is
1654 // used so inconsistently that simply adding locking there leads to bugs.
1655 e
->lock("clientReplyContext::forgetHit");
1656 http
->storeEntry(NULL
);
1657 e
->unlock("clientReplyContext::forgetHit"); // may delete e
1661 clientReplyContext::identifyStoreObject()
1663 HttpRequest
*r
= http
->request
;
1665 // client sent CC:no-cache or some other condition has been
1666 // encountered which prevents delivering a public/cached object.
1667 if (!r
->flags
.noCache
|| r
->flags
.internal
) {
1668 lookingforstore
= 5;
1669 StoreEntry::getPublicByRequest (this, r
);
1671 identifyFoundObject (NullStoreEntry::getInstance());
1676 * Check state of the current StoreEntry object.
1677 * to see if we can determine the final status of the request.
1680 clientReplyContext::identifyFoundObject(StoreEntry
*newEntry
)
1682 StoreEntry
*e
= newEntry
;
1683 HttpRequest
*r
= http
->request
;
1685 /** \li If the entry received isNull() then we ignore it. */
1687 http
->storeEntry(NULL
);
1689 http
->storeEntry(e
);
1692 e
= http
->storeEntry();
1694 /* Release IP-cache entries on reload */
1695 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
1696 * 'invalidate' the cached IP entries for this request ???
1698 if (r
->flags
.noCache
|| r
->flags
.noCacheHack())
1699 ipcacheInvalidateNegative(r
->url
.host());
1701 #if USE_CACHE_DIGESTS
1702 lookup_type
= http
->storeEntry() ? "HIT" : "MISS";
1705 if (NULL
== http
->storeEntry()) {
1706 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
1707 debugs(85, 3, "StoreEntry is NULL - MISS");
1708 http
->logType
= LOG_TCP_MISS
;
1713 if (Config
.onoff
.offline
) {
1714 /** \li If we are running in offline mode set to HIT */
1715 debugs(85, 3, "offline HIT " << *e
);
1716 http
->logType
= LOG_TCP_HIT
;
1721 if (http
->redirect
.status
) {
1722 /** \li If redirection status is True force this to be a MISS */
1723 debugs(85, 3, "REDIRECT status forced StoreEntry to NULL (no body on 3XX responses) " << *e
);
1725 http
->logType
= LOG_TCP_REDIRECT
;
1730 if (!e
->validToSend()) {
1731 debugs(85, 3, "!storeEntryValidToSend MISS " << *e
);
1733 http
->logType
= LOG_TCP_MISS
;
1738 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1739 /* \li Special entries are always hits, no matter what the client says */
1740 debugs(85, 3, "ENTRY_SPECIAL HIT " << *e
);
1741 http
->logType
= LOG_TCP_HIT
;
1746 if (r
->flags
.noCache
) {
1747 debugs(85, 3, "no-cache REFRESH MISS " << *e
);
1749 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
1754 debugs(85, 3, "default HIT " << *e
);
1755 http
->logType
= LOG_TCP_HIT
;
1760 * Request more data from the store for the client Stream
1761 * This is *the* entry point to this module.
1764 * - This is the head of the list.
1765 * - There is at least one more node.
1766 * - Data context is not null
1769 clientGetMoreData(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1771 /* Test preconditions */
1772 assert(aNode
!= NULL
);
1773 assert(cbdataReferenceValid(aNode
));
1774 assert(aNode
->node
.prev
== NULL
);
1775 assert(aNode
->node
.next
!= NULL
);
1776 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1778 assert(context
->http
== http
);
1780 clientStreamNode
*next
= ( clientStreamNode
*)aNode
->node
.next
->data
;
1782 if (!context
->ourNode
)
1783 context
->ourNode
= aNode
;
1785 /* no cbdatareference, this is only used once, and safely */
1786 if (context
->flags
.storelogiccomplete
) {
1787 StoreIOBuffer tempBuffer
;
1788 tempBuffer
.offset
= next
->readBuffer
.offset
+ context
->headers_sz
;
1789 tempBuffer
.length
= next
->readBuffer
.length
;
1790 tempBuffer
.data
= next
->readBuffer
.data
;
1792 storeClientCopy(context
->sc
, http
->storeEntry(),
1793 tempBuffer
, clientReplyContext::SendMoreData
, context
);
1797 if (context
->http
->request
->method
== Http::METHOD_PURGE
) {
1798 context
->purgeRequest();
1802 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
1804 if (context
->http
->request
->method
== Http::METHOD_TRACE
) {
1805 if (context
->http
->request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0) {
1806 context
->traceReply(aNode
);
1810 /* continue forwarding, not finished yet. */
1811 http
->logType
= LOG_TCP_MISS
;
1813 context
->doGetMoreData();
1815 context
->identifyStoreObject();
1819 clientReplyContext::doGetMoreData()
1821 /* We still have to do store logic processing - vary, cache hit etc */
1822 if (http
->storeEntry() != NULL
) {
1823 /* someone found the object in the cache for us */
1824 StoreIOBuffer localTempBuffer
;
1826 http
->storeEntry()->lock("clientReplyContext::doGetMoreData");
1828 MemObject
*mem_obj
= http
->storeEntry()->makeMemObject();
1829 if (!mem_obj
->hasUris()) {
1831 * This if-block exists because we don't want to clobber
1832 * a preexiting mem_obj->method value if the mem_obj
1833 * already exists. For example, when a HEAD request
1834 * is a cache hit for a GET response, we want to keep
1835 * the method as GET.
1837 mem_obj
->setUris(storeId(), http
->log_uri
, http
->request
->method
);
1839 * Here we can see if the object was
1840 * created using URL or alternative StoreID from helper.
1842 debugs(88, 3, "storeId: " << http
->storeEntry()->mem_obj
->storeId());
1845 sc
= storeClientListAdd(http
->storeEntry(), this);
1847 sc
->setDelayId(DelayId::DelayClient(http
));
1850 assert(http
->logType
.oldType
== LOG_TCP_HIT
);
1852 /* guarantee nothing has been sent yet! */
1853 assert(http
->out
.size
== 0);
1854 assert(http
->out
.offset
== 0);
1856 if (Ip::Qos::TheConfig
.isHitTosActive()) {
1857 Ip::Qos::doTosLocalHit(http
->getConn()->clientConnection
);
1860 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
1861 Ip::Qos::doNfmarkLocalHit(http
->getConn()->clientConnection
);
1864 localTempBuffer
.offset
= reqofs
;
1865 localTempBuffer
.length
= getNextNode()->readBuffer
.length
;
1866 localTempBuffer
.data
= getNextNode()->readBuffer
.data
;
1867 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, CacheHit
, this);
1869 /* MISS CASE, http->logType is already set! */
1874 /** The next node has removed itself from the stream. */
1876 clientReplyDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1878 /** detach from the stream */
1879 clientStreamDetach(node
, http
);
1883 * Accepts chunk of a http message in buf, parses prefix, filters headers and
1884 * such, writes processed message to the message recipient
1887 clientReplyContext::SendMoreData(void *data
, StoreIOBuffer result
)
1889 clientReplyContext
*context
= static_cast<clientReplyContext
*>(data
);
1890 context
->sendMoreData (result
);
1894 clientReplyContext::makeThisHead()
1896 /* At least, I think thats what this does */
1897 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1898 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1902 clientReplyContext::errorInStream(StoreIOBuffer
const &result
, size_t const &sizeToProcess
)const
1904 return /* aborted request */
1905 (http
->storeEntry() && EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) ||
1906 /* Upstream read error */ (result
.flags
.error
) ||
1907 /* Upstream EOF */ (sizeToProcess
== 0);
1911 clientReplyContext::sendStreamError(StoreIOBuffer
const &result
)
1913 /** call clientWriteComplete so the client socket gets closed
1915 * We call into the stream, because we don't know that there is a
1918 debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.");
1919 StoreIOBuffer localTempBuffer
;
1921 http
->request
->flags
.streamError
= true;
1922 localTempBuffer
.flags
.error
= result
.flags
.error
;
1923 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1928 clientReplyContext::pushStreamData(StoreIOBuffer
const &result
, char *source
)
1930 StoreIOBuffer localTempBuffer
;
1932 if (result
.length
== 0) {
1933 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
1937 assert(result
.offset
- headers_sz
== next()->readBuffer
.offset
);
1938 localTempBuffer
.offset
= result
.offset
- headers_sz
;
1939 localTempBuffer
.length
= result
.length
;
1941 if (localTempBuffer
.length
)
1942 localTempBuffer
.data
= source
;
1944 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1949 clientReplyContext::next() const
1951 assert ( (clientStreamNode
*)http
->client_stream
.head
->next
->data
== getNextNode());
1952 return getNextNode();
1956 clientReplyContext::sendBodyTooLargeError()
1958 Ip::Address tmp_noaddr
;
1959 tmp_noaddr
.setNoAddr(); // TODO: make a global const
1960 http
->logType
= LOG_TCP_DENIED_REPLY
;
1961 ErrorState
*err
= clientBuildError(ERR_TOO_BIG
, Http::scForbidden
, NULL
,
1962 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
1964 removeClientStoreReference(&(sc
), http
);
1965 HTTPMSGUNLOCK(reply
);
1970 /// send 412 (Precondition Failed) to client
1972 clientReplyContext::sendPreconditionFailedError()
1974 http
->logType
= LOG_TCP_HIT
;
1975 ErrorState
*const err
=
1976 clientBuildError(ERR_PRECONDITION_FAILED
, Http::scPreconditionFailed
,
1977 NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
1978 removeClientStoreReference(&sc
, http
);
1979 HTTPMSGUNLOCK(reply
);
1983 /// send 304 (Not Modified) to client
1985 clientReplyContext::sendNotModified()
1987 StoreEntry
*e
= http
->storeEntry();
1988 const time_t timestamp
= e
->timestamp
;
1989 HttpReply
*const temprep
= e
->getReply()->make304();
1990 // log as TCP_INM_HIT if code 304 generated for
1991 // If-None-Match request
1992 if (!http
->request
->flags
.ims
)
1993 http
->logType
= LOG_TCP_INM_HIT
;
1995 http
->logType
= LOG_TCP_IMS_HIT
;
1996 removeClientStoreReference(&sc
, http
);
1997 createStoreEntry(http
->request
->method
, RequestFlags());
1998 e
= http
->storeEntry();
1999 // Copy timestamp from the original entry so the 304
2000 // reply has a meaningful Age: header.
2002 e
->timestamp
= timestamp
;
2003 e
->replaceHttpReply(temprep
);
2006 * TODO: why put this in the store and then serialise it and
2007 * then parse it again. Simply mark the request complete in
2008 * our context and write the reply struct to the client side.
2010 triggerInitialStoreRead();
2013 /// send 304 (Not Modified) or 412 (Precondition Failed) to client
2014 /// depending on request method
2016 clientReplyContext::sendNotModifiedOrPreconditionFailedError()
2018 if (http
->request
->method
== Http::METHOD_GET
||
2019 http
->request
->method
== Http::METHOD_HEAD
)
2022 sendPreconditionFailedError();
2026 clientReplyContext::processReplyAccess ()
2028 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
2031 /** Don't block our own responses or HTTP status messages */
2032 if (http
->logType
.oldType
== LOG_TCP_DENIED
||
2033 http
->logType
.oldType
== LOG_TCP_DENIED_REPLY
||
2034 alwaysAllowResponse(reply
->sline
.status())) {
2035 headers_sz
= reply
->hdr_sz
;
2036 processReplyAccessResult(ACCESS_ALLOWED
);
2040 /** Check for reply to big error */
2041 if (reply
->expectedBodyTooLarge(*http
->request
)) {
2042 sendBodyTooLargeError();
2046 headers_sz
= reply
->hdr_sz
;
2048 /** check for absent access controls (permit by default) */
2049 if (!Config
.accessList
.reply
) {
2050 processReplyAccessResult(ACCESS_ALLOWED
);
2054 /** Process http_reply_access lists */
2055 ACLFilledChecklist
*replyChecklist
=
2056 clientAclChecklistCreate(Config
.accessList
.reply
, http
);
2057 replyChecklist
->reply
= reply
;
2058 HTTPMSGLOCK(replyChecklist
->reply
);
2059 replyChecklist
->nonBlockingCheck(ProcessReplyAccessResult
, this);
2063 clientReplyContext::ProcessReplyAccessResult(allow_t rv
, void *voidMe
)
2065 clientReplyContext
*me
= static_cast<clientReplyContext
*>(voidMe
);
2066 me
->processReplyAccessResult(rv
);
2070 clientReplyContext::processReplyAccessResult(const allow_t
&accessAllowed
)
2072 debugs(88, 2, "The reply for " << http
->request
->method
2073 << ' ' << http
->uri
<< " is " << accessAllowed
<< ", because it matched "
2074 << (AclMatchedName
? AclMatchedName
: "NO ACL's"));
2076 if (accessAllowed
!= ACCESS_ALLOWED
) {
2079 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, 1);
2081 http
->logType
= LOG_TCP_DENIED_REPLY
;
2083 if (page_id
== ERR_NONE
)
2084 page_id
= ERR_ACCESS_DENIED
;
2086 Ip::Address tmp_noaddr
;
2087 tmp_noaddr
.setNoAddr();
2088 err
= clientBuildError(page_id
, Http::scForbidden
, NULL
,
2089 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
2092 removeClientStoreReference(&sc
, http
);
2094 HTTPMSGUNLOCK(reply
);
2101 /* Ok, the reply is allowed, */
2102 http
->loggingEntry(http
->storeEntry());
2104 ssize_t body_size
= reqofs
- reply
->hdr_sz
;
2105 if (body_size
< 0) {
2106 reqofs
= reply
->hdr_sz
;
2110 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
2111 (int) body_size
<< " bytes after " << reply
->hdr_sz
<<
2112 " bytes of headers");
2116 if (http
->flags
.accel
&& reply
->sline
.status() != Http::scForbidden
&&
2117 !alwaysAllowResponse(reply
->sline
.status()) &&
2118 esiEnableProcessing(reply
)) {
2119 debugs(88, 2, "Enabling ESI processing for " << http
->uri
);
2120 clientStreamInsertHead(&http
->client_stream
, esiStreamRead
,
2121 esiProcessStream
, esiStreamDetach
, esiStreamStatus
, NULL
);
2126 if (http
->request
->method
== Http::METHOD_HEAD
) {
2127 /* do not forward body for HEAD replies */
2129 http
->flags
.done_copying
= true;
2133 assert (!flags
.headersSent
);
2134 flags
.headersSent
= true;
2136 StoreIOBuffer localTempBuffer
;
2137 char *buf
= next()->readBuffer
.data
;
2138 char *body_buf
= buf
+ reply
->hdr_sz
;
2140 //Server side may disable ranges under some circumstances.
2142 if ((!http
->request
->range
))
2143 next()->readBuffer
.offset
= 0;
2145 body_buf
-= next()->readBuffer
.offset
;
2147 if (next()->readBuffer
.offset
!= 0) {
2148 if (next()->readBuffer
.offset
> body_size
) {
2149 /* Can't use any of the body we received. send nothing */
2150 localTempBuffer
.length
= 0;
2151 localTempBuffer
.data
= NULL
;
2153 localTempBuffer
.length
= body_size
- next()->readBuffer
.offset
;
2154 localTempBuffer
.data
= body_buf
+ next()->readBuffer
.offset
;
2157 localTempBuffer
.length
= body_size
;
2158 localTempBuffer
.data
= body_buf
;
2161 /* TODO??: move the data in the buffer back by the request header size */
2162 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
,
2163 http
, reply
, localTempBuffer
);
2169 clientReplyContext::sendMoreData (StoreIOBuffer result
)
2174 StoreEntry
*entry
= http
->storeEntry();
2176 if (ConnStateData
* conn
= http
->getConn()) {
2177 if (!conn
->isOpen()) {
2178 debugs(33,3, "not sending more data to closing connection " << conn
->clientConnection
);
2181 if (conn
->pinning
.zeroReply
) {
2182 debugs(33,3, "not sending more data after a pinned zero reply " << conn
->clientConnection
);
2186 if (reqofs
==0 && !http
->logType
.isTcpHit()) {
2187 if (Ip::Qos::TheConfig
.isHitTosActive()) {
2188 Ip::Qos::doTosLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2190 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
2191 Ip::Qos::doNfmarkLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2195 debugs(88, 5, conn
->clientConnection
<<
2196 " '" << entry
->url() << "'" <<
2197 " out.offset=" << http
->out
.offset
);
2200 char *buf
= next()->readBuffer
.data
;
2202 if (buf
!= result
.data
) {
2203 /* we've got to copy some data */
2204 assert(result
.length
<= next()->readBuffer
.length
);
2205 memcpy(buf
, result
.data
, result
.length
);
2208 /* We've got the final data to start pushing... */
2209 flags
.storelogiccomplete
= 1;
2211 reqofs
+= result
.length
;
2213 assert(reqofs
<= HTTP_REQBUF_SZ
|| flags
.headersSent
);
2215 assert(http
->request
!= NULL
);
2217 /* ESI TODO: remove this assert once everything is stable */
2218 assert(http
->client_stream
.head
->data
2219 && cbdataReferenceValid(http
->client_stream
.head
->data
));
2223 debugs(88, 5, "clientReplyContext::sendMoreData: " << http
->uri
<< ", " <<
2224 reqofs
<< " bytes (" << result
.length
<<
2227 /* update size of the request */
2230 if (errorInStream(result
, reqofs
)) {
2231 sendStreamError(result
);
2235 if (flags
.headersSent
) {
2236 pushStreamData (result
, buf
);
2244 sc
->setDelayId(DelayId::DelayClient(http
,reply
));
2247 /* handle headers */
2249 if (Config
.onoff
.log_mime_hdrs
) {
2252 if ((k
= headersEnd(buf
, reqofs
))) {
2253 safe_free(http
->al
->headers
.reply
);
2254 http
->al
->headers
.reply
= (char *)xcalloc(k
+ 1, 1);
2255 xstrncpy(http
->al
->headers
.reply
, buf
, k
);
2259 holdingBuffer
= result
;
2260 processReplyAccess();
2264 /* Using this breaks the client layering just a little!
2267 clientReplyContext::createStoreEntry(const HttpRequestMethod
& m
, RequestFlags reqFlags
)
2269 assert(http
!= NULL
);
2271 * For erroneous requests, we might not have a h->request,
2272 * so make a fake one.
2275 if (http
->request
== NULL
) {
2276 http
->request
= new HttpRequest(m
, AnyP::PROTO_NONE
, "http", null_string
);
2277 HTTPMSGLOCK(http
->request
);
2280 StoreEntry
*e
= storeCreateEntry(storeId(), http
->log_uri
, reqFlags
, m
);
2282 // Make entry collapsable ASAP, to increase collapsing chances for others,
2283 // TODO: every must-revalidate and similar request MUST reach the origin,
2284 // but do we have to prohibit others from collapsing on that request?
2285 if (Config
.onoff
.collapsed_forwarding
&& reqFlags
.cachable
&&
2286 !reqFlags
.needValidation
&&
2287 (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
)) {
2288 // make the entry available for future requests now
2289 Store::Root().allowCollapsing(e
, reqFlags
, m
);
2292 sc
= storeClientListAdd(e
, this);
2295 sc
->setDelayId(DelayId::DelayClient(http
));
2302 /* I don't think this is actually needed! -- adrian */
2303 /* http->reqbuf = http->norm_reqbuf; */
2304 // assert(http->reqbuf == http->norm_reqbuf);
2305 /* The next line is illegal because we don't know if the client stream
2306 * buffers have been set up
2308 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2309 // SendMoreData, this);
2310 /* So, we mark the store logic as complete */
2311 flags
.storelogiccomplete
= 1;
2313 /* and get the caller to request a read, from whereever they are */
2314 /* NOTE: after ANY data flows down the pipe, even one step,
2315 * this function CAN NOT be used to manage errors
2317 http
->storeEntry(e
);
2321 clientBuildError(err_type page_id
, Http::StatusCode status
, char const *url
,
2322 Ip::Address
&src_addr
, HttpRequest
* request
)
2324 ErrorState
*err
= new ErrorState(page_id
, status
, request
);
2325 err
->src_addr
= src_addr
;
2328 err
->url
= xstrdup(url
);