2 * DEBUG: section 88 Client-side Reply Routines
3 * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c)
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 #include "acl/FilledChecklist.h"
34 #include "acl/Gadgets.h"
35 #include "anyp/PortCfg.h"
36 #include "client_side_reply.h"
37 #include "errorpage.h"
41 #include "format/Token.h"
45 #include "HttpHeaderTools.h"
46 #include "HttpReply.h"
47 #include "HttpRequest.h"
48 #include "ip/QosConfig.h"
50 #include "log/access_log.h"
51 #include "MemObject.h"
52 #include "mime_header.h"
53 #include "neighbors.h"
55 #include "RequestFlags.h"
56 #include "SquidConfig.h"
57 #include "SquidTime.h"
63 #include "auth/UserRequest.h"
66 #include "DelayPools.h"
74 CBDATA_CLASS_INIT(clientReplyContext
);
77 extern "C" CSS clientReplyStatus
;
78 ErrorState
*clientBuildError(err_type
, Http::StatusCode
, char const *, Ip::Address
&, HttpRequest
*);
82 clientReplyContext::~clientReplyContext()
85 /* This may trigger a callback back into SendMoreData as the cbdata
88 removeClientStoreReference(&sc
, http
);
89 /* old_entry might still be set if we didn't yet get the reply
90 * code in HandleIMSReply() */
91 removeStoreReference(&old_sc
, &old_entry
);
92 safe_free(tempBuffer
.data
);
93 cbdataReferenceDone(http
);
97 clientReplyContext::clientReplyContext(ClientHttpRequest
*clientContext
) : http (cbdataReference(clientContext
)), old_entry (NULL
), old_sc(NULL
), deleting(false)
100 /** Create an error in the store awaiting the client side to read it.
102 * This may be better placed in the clientStream logic, but it has not been
103 * relocated there yet
106 clientReplyContext::setReplyToError(
107 err_type err
, Http::StatusCode status
, const HttpRequestMethod
& method
, char const *uri
,
108 Ip::Address
&addr
, HttpRequest
* failedrequest
, const char *unparsedrequest
,
110 Auth::UserRequest::Pointer auth_user_request
116 ErrorState
*errstate
= clientBuildError(err
, status
, uri
, addr
, failedrequest
);
119 errstate
->request_hdrs
= xstrdup(unparsedrequest
);
122 errstate
->auth_user_request
= auth_user_request
;
124 setReplyToError(method
, errstate
);
127 void clientReplyContext::setReplyToError(const HttpRequestMethod
& method
, ErrorState
*errstate
)
129 if (errstate
->httpStatus
== Http::scNotImplemented
&& http
->request
)
130 /* prevent confusion over whether we default to persistent or not */
131 http
->request
->flags
.proxyKeepalive
= false;
133 http
->al
->http
.code
= errstate
->httpStatus
;
136 http
->request
->ignoreRange("responding with a Squid-generated error");
138 createStoreEntry(method
, RequestFlags());
139 assert(errstate
->callback_data
== NULL
);
140 errorAppendEntry(http
->storeEntry(), errstate
);
141 /* Now the caller reads to get this */
145 clientReplyContext::setReplyToReply(HttpReply
*futureReply
)
148 http
->al
->http
.code
= futureReply
->sline
.status();
150 HttpRequestMethod method
;
151 if (http
->request
) { // nil on responses to unparsable requests
152 http
->request
->ignoreRange("responding with a Squid-generated reply");
153 method
= http
->request
->method
;
156 createStoreEntry(method
, RequestFlags());
158 http
->storeEntry()->storeErrorResponse(futureReply
);
159 /* Now the caller reads to get futureReply */
162 // Assumes that the entry contains an error response without Content-Range.
163 // To use with regular entries, make HTTP Range header removal conditional.
164 void clientReplyContext::setReplyToStoreEntry(StoreEntry
*entry
, const char *reason
)
166 entry
->lock("clientReplyContext::setReplyToStoreEntry"); // removeClientStoreReference() unlocks
167 sc
= storeClientListAdd(entry
, this);
169 sc
->setDelayId(DelayId::DelayClient(http
));
174 http
->request
->ignoreRange(reason
);
175 flags
.storelogiccomplete
= 1;
176 http
->storeEntry(entry
);
180 clientReplyContext::removeStoreReference(store_client
** scp
,
184 store_client
*sc_tmp
= *scp
;
186 if ((e
= *ep
) != NULL
) {
188 storeUnregister(sc_tmp
, e
, this);
190 e
->unlock("clientReplyContext::removeStoreReference");
195 clientReplyContext::removeClientStoreReference(store_client
**scp
, ClientHttpRequest
*aHttpRequest
)
197 StoreEntry
*reference
= aHttpRequest
->storeEntry();
198 removeStoreReference(scp
, &reference
);
199 aHttpRequest
->storeEntry(reference
);
203 clientReplyContext::saveState()
205 assert(old_sc
== NULL
);
206 debugs(88, 3, "clientReplyContext::saveState: saving store context");
207 old_entry
= http
->storeEntry();
209 old_reqsize
= reqsize
;
210 tempBuffer
.offset
= reqofs
;
211 /* Prevent accessing the now saved entries */
212 http
->storeEntry(NULL
);
219 clientReplyContext::restoreState()
221 assert(old_sc
!= NULL
);
222 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
223 removeClientStoreReference(&sc
, http
);
224 http
->storeEntry(old_entry
);
226 reqsize
= old_reqsize
;
227 reqofs
= tempBuffer
.offset
;
228 /* Prevent accessed the old saved entries */
232 tempBuffer
.offset
= 0;
236 clientReplyContext::startError(ErrorState
* err
)
238 createStoreEntry(http
->request
->method
, RequestFlags());
239 triggerInitialStoreRead();
240 errorAppendEntry(http
->storeEntry(), err
);
244 clientReplyContext::getNextNode() const
246 return (clientStreamNode
*)ourNode
->node
.next
->data
;
249 /* This function is wrong - the client parameters don't include the
253 clientReplyContext::triggerInitialStoreRead()
255 /* when confident, 0 becomes reqofs, and then this factors into
259 StoreIOBuffer
localTempBuffer (next()->readBuffer
.length
, 0, next()->readBuffer
.data
);
260 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, SendMoreData
, this);
263 /* there is an expired entry in the store.
264 * setup a temporary buffer area and perform an IMS to the origin
267 clientReplyContext::processExpired()
269 const char *url
= storeId();
270 StoreEntry
*entry
= NULL
;
271 debugs(88, 3, "clientReplyContext::processExpired: '" << http
->uri
<< "'");
272 assert(http
->storeEntry()->lastmod
>= 0);
274 * check if we are allowed to contact other servers
275 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
276 * a stale entry *if* it matches client requirements
279 if (http
->onlyIfCached()) {
280 processOnlyIfCachedMiss();
284 http
->request
->flags
.refresh
= true;
285 #if STORE_CLIENT_LIST_DEBUG
286 /* Prevent a race with the store client memory free routines
288 assert(storeClientIsThisAClient(sc
, this));
290 /* Prepare to make a new temporary request */
292 entry
= storeCreateEntry(url
,
293 http
->log_uri
, http
->request
->flags
, http
->request
->method
);
294 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
295 sc
= storeClientListAdd(entry
, this);
297 /* delay_id is already set on original store client */
298 sc
->setDelayId(DelayId::DelayClient(http
));
301 http
->request
->lastmod
= old_entry
->lastmod
;
303 if (!http
->request
->header
.has(HDR_IF_NONE_MATCH
)) {
304 ETag etag
= {NULL
, -1}; // TODO: make that a default ETag constructor
305 if (old_entry
->hasEtag(etag
) && !etag
.weak
)
306 http
->request
->etag
= etag
.str
;
309 debugs(88, 5, "clientReplyContext::processExpired : lastmod " << entry
->lastmod
);
310 http
->storeEntry(entry
);
311 assert(http
->out
.offset
== 0);
312 assert(http
->request
->clientConnectionManager
== http
->getConn());
315 * A refcounted pointer so that FwdState stays around as long as
316 * this clientReplyContext does
318 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
319 FwdState::Start(conn
, http
->storeEntry(), http
->request
, http
->al
);
321 /* Register with storage manager to receive updates when data comes in. */
323 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
324 debugs(88, DBG_CRITICAL
, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
327 /* start counting the length from 0 */
328 StoreIOBuffer
localTempBuffer(HTTP_REQBUF_SZ
, 0, tempbuf
);
329 storeClientCopy(sc
, entry
, localTempBuffer
, HandleIMSReply
, this);
334 clientReplyContext::sendClientUpstreamResponse()
336 StoreIOBuffer tempresult
;
337 removeStoreReference(&old_sc
, &old_entry
);
338 /* here the data to send is the data we just received */
339 tempBuffer
.offset
= 0;
341 /* sendMoreData tracks the offset as well.
342 * Force it back to zero */
344 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
345 /* TODO: provide sendMoreData with the ready parsed reply */
346 tempresult
.length
= reqsize
;
347 tempresult
.data
= tempbuf
;
348 sendMoreData(tempresult
);
352 clientReplyContext::HandleIMSReply(void *data
, StoreIOBuffer result
)
354 clientReplyContext
*context
= (clientReplyContext
*)data
;
355 context
->handleIMSReply(result
);
359 clientReplyContext::sendClientOldEntry()
361 /* Get the old request back */
363 /* here the data to send is in the next nodes buffers already */
364 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
365 /* sendMoreData tracks the offset as well.
366 * Force it back to zero */
368 StoreIOBuffer
tempresult (reqsize
, reqofs
, next()->readBuffer
.data
);
369 sendMoreData(tempresult
);
372 /* This is the workhorse of the HandleIMSReply callback.
374 * It is called when we've got data back from the origin following our
375 * IMS request to revalidate a stale entry.
378 clientReplyContext::handleIMSReply(StoreIOBuffer result
)
383 debugs(88, 3, "handleIMSReply: " << http
->storeEntry()->url() << ", " << (long unsigned) result
.length
<< " bytes" );
385 if (http
->storeEntry() == NULL
)
388 if (result
.flags
.error
&& !EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
))
391 /* update size of the request */
392 reqsize
= result
.length
+ reqofs
;
394 const Http::StatusCode status
= http
->storeEntry()->getReply()->sline
.status();
396 // request to origin was aborted
397 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
398 debugs(88, 3, "handleIMSReply: request to origin aborted '" << http
->storeEntry()->url() << "', sending old entry to client" );
399 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
400 sendClientOldEntry();
403 HttpReply
*old_rep
= (HttpReply
*) old_entry
->getReply();
405 // origin replied 304
406 if (status
== Http::scNotModified
) {
407 http
->logType
= LOG_TCP_REFRESH_UNMODIFIED
;
408 http
->request
->flags
.staleIfHit
= false; // old_entry is no longer stale
410 // update headers on existing entry
411 old_rep
->updateOnNotModified(http
->storeEntry()->getReply());
412 old_entry
->timestampsSet();
414 // if client sent IMS
416 if (http
->request
->flags
.ims
&& !old_entry
->modifiedSince(http
->request
)) {
417 // forward the 304 from origin
418 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and forwarding 304 to client");
419 sendClientUpstreamResponse();
421 // send existing entry, it's still valid
422 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and sending " <<
423 old_rep
->sline
.status() << " to client");
424 sendClientOldEntry();
428 // origin replied with a non-error code
429 else if (status
> Http::scNone
&& status
< Http::scInternalServerError
) {
430 // forward response from origin
431 http
->logType
= LOG_TCP_REFRESH_MODIFIED
;
432 debugs(88, 3, "handleIMSReply: origin replied " << status
<< ", replacing existing entry and forwarding to client");
433 sendClientUpstreamResponse();
436 // origin replied with an error
437 else if (http
->request
->flags
.failOnValidationError
) {
438 http
->logType
= LOG_TCP_REFRESH_FAIL_ERR
;
439 debugs(88, 3, "handleIMSReply: origin replied with error " << status
<<
440 ", forwarding to client due to fail_on_validation_err");
441 sendClientUpstreamResponse();
443 // ignore and let client have old entry
444 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
445 debugs(88, 3, "handleIMSReply: origin replied with error " <<
446 status
<< ", sending old entry (" << old_rep
->sline
.status() << ") to client");
447 sendClientOldEntry();
451 SQUIDCEXTERN CSR clientGetMoreData
;
452 SQUIDCEXTERN CSD clientReplyDetach
;
455 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
456 * have been parsed. Normally this should be a single call, but
457 * it might take more than one. As soon as we have the headers,
458 * we hand off to clientSendMoreData, processExpired, or
462 clientReplyContext::CacheHit(void *data
, StoreIOBuffer result
)
464 clientReplyContext
*context
= (clientReplyContext
*)data
;
465 context
->cacheHit(result
);
469 * Process a possible cache HIT.
472 clientReplyContext::cacheHit(StoreIOBuffer result
)
474 /** Ignore if the HIT object is being deleted. */
476 debugs(88, 3, "HIT object being deleted. Ignore the HIT.");
480 StoreEntry
*e
= http
->storeEntry();
482 HttpRequest
*r
= http
->request
;
484 debugs(88, 3, "clientCacheHit: " << http
->uri
<< ", " << result
.length
<< " bytes");
486 if (http
->storeEntry() == NULL
) {
487 debugs(88, 3, "clientCacheHit: request aborted");
489 } else if (result
.flags
.error
) {
490 /* swap in failure */
491 debugs(88, 3, "clientCacheHit: swapin failure for " << http
->uri
);
492 http
->logType
= LOG_TCP_SWAPFAIL_MISS
;
493 removeClientStoreReference(&sc
, http
);
498 if (result
.length
== 0) {
499 debugs(88, 5, "store IO buffer has no content. MISS");
500 /* the store couldn't get enough data from the file for us to id the
503 /* treat as a miss */
504 http
->logType
= LOG_TCP_MISS
;
509 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
510 /* update size of the request */
511 reqsize
= result
.length
+ reqofs
;
514 * Got the headers, now grok them
516 assert(http
->logType
== LOG_TCP_HIT
);
518 if (strcmp(e
->mem_obj
->storeId(), http
->request
->storeId()) != 0) {
519 debugs(33, DBG_IMPORTANT
, "clientProcessHit: URL mismatch, '" << e
->mem_obj
->storeId() << "' != '" << http
->request
->storeId() << "'");
520 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
525 switch (varyEvaluateMatch(e
, r
)) {
528 /* No variance detected. Continue as normal */
532 /* This is the correct entity for this request. Continue */
533 debugs(88, 2, "clientProcessHit: Vary MATCH!");
537 /* This is not the correct entity for this request. We need
538 * to requery the cache.
540 removeClientStoreReference(&sc
, http
);
542 /* Note: varyEvalyateMatch updates the request with vary information
543 * so we only get here once. (it also takes care of cancelling loops)
545 debugs(88, 2, "clientProcessHit: Vary detected!");
546 clientGetMoreData(ourNode
, http
);
550 /* varyEvaluateMatch found a object loop. Process as miss */
551 debugs(88, DBG_IMPORTANT
, "clientProcessHit: Vary object loop!");
552 http
->logType
= LOG_TCP_MISS
; // we lack a more precise LOG_*_MISS code
557 if (r
->method
== Http::METHOD_PURGE
) {
558 debugs(88, 5, "PURGE gets a HIT");
559 removeClientStoreReference(&sc
, http
);
565 if (e
->checkNegativeHit() && !r
->flags
.noCacheHack()) {
566 debugs(88, 5, "negative-HIT");
567 http
->logType
= LOG_TCP_NEGATIVE_HIT
;
568 sendMoreData(result
);
569 } else if (blockedHit()) {
570 debugs(88, 5, "send_hit forces a MISS");
571 http
->logType
= LOG_TCP_MISS
;
574 } else if (!http
->flags
.internal
&& refreshCheckHTTP(e
, r
)) {
575 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
577 * We hold a stale copy; it needs to be validated
580 * The 'needValidation' flag is used to prevent forwarding
581 * loops between siblings. If our copy of the object is stale,
582 * then we should probably only use parents for the validation
583 * request. Otherwise two siblings could generate a loop if
584 * both have a stale version of the object.
586 r
->flags
.needValidation
= true;
588 if (e
->lastmod
< 0) {
589 debugs(88, 3, "validate HIT object? NO. Missing Last-Modified header. Do MISS.");
591 * Previous reply didn't have a Last-Modified header,
592 * we cannot revalidate it.
594 http
->logType
= LOG_TCP_MISS
;
596 } else if (r
->flags
.noCache
) {
597 debugs(88, 3, "validate HIT object? NO. Client sent CC:no-cache. Do CLIENT_REFRESH_MISS");
599 * This did not match a refresh pattern that overrides no-cache
600 * we should honour the client no-cache header.
602 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
604 } else if (r
->url
.getScheme() == AnyP::PROTO_HTTP
) {
605 debugs(88, 3, "validate HIT object? YES.");
607 * Object needs to be revalidated
608 * XXX This could apply to FTP as well, if Last-Modified is known.
612 debugs(88, 3, "validate HIT object? NO. Client protocol non-HTTP. Do MISS.");
614 * We don't know how to re-validate other protocols. Handle
615 * them as if the object has expired.
617 http
->logType
= LOG_TCP_MISS
;
620 } else if (r
->conditional()) {
621 debugs(88, 5, "conditional HIT");
622 processConditional(result
);
625 * plain ol' cache hit
627 debugs(88, 5, "plain old HIT");
630 if (e
->store_status
!= STORE_OK
)
631 http
->logType
= LOG_TCP_MISS
;
634 if (e
->mem_status
== IN_MEMORY
)
635 http
->logType
= LOG_TCP_MEM_HIT
;
636 else if (Config
.onoff
.offline
)
637 http
->logType
= LOG_TCP_OFFLINE_HIT
;
639 sendMoreData(result
);
644 * Prepare to fetch the object as it's a cache miss of some kind.
647 clientReplyContext::processMiss()
649 char *url
= http
->uri
;
650 HttpRequest
*r
= http
->request
;
651 ErrorState
*err
= NULL
;
652 debugs(88, 4, r
->method
<< ' ' << url
);
655 * We might have a left-over StoreEntry from a failed cache hit
658 if (http
->storeEntry()) {
659 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
660 debugs(88, DBG_CRITICAL
, "clientProcessMiss: miss on a special object (" << url
<< ").");
661 debugs(88, DBG_CRITICAL
, "\tlog_type = " << LogTags_str
[http
->logType
]);
662 http
->storeEntry()->dump(1);
665 removeClientStoreReference(&sc
, http
);
668 /** Check if its a PURGE request to be actioned. */
669 if (r
->method
== Http::METHOD_PURGE
) {
674 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
675 if (r
->method
== Http::METHOD_OTHER
) {
679 /** Check if 'only-if-cached' flag is set. Action if so. */
680 if (http
->onlyIfCached()) {
681 processOnlyIfCachedMiss();
686 if (r
->flags
.loopDetected
) {
687 http
->al
->http
.code
= Http::scForbidden
;
688 err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
689 createStoreEntry(r
->method
, RequestFlags());
690 errorAppendEntry(http
->storeEntry(), err
);
691 triggerInitialStoreRead();
694 assert(http
->out
.offset
== 0);
695 createStoreEntry(r
->method
, r
->flags
);
696 triggerInitialStoreRead();
698 if (http
->redirect
.status
) {
699 HttpReply
*rep
= new HttpReply
;
700 http
->logType
= LOG_TCP_REDIRECT
;
701 http
->storeEntry()->releaseRequest();
702 rep
->redirect(http
->redirect
.status
, http
->redirect
.location
);
703 http
->storeEntry()->replaceHttpReply(rep
);
704 http
->storeEntry()->complete();
708 assert(r
->clientConnectionManager
== http
->getConn());
710 /** Start forwarding to get the new object from network */
711 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
712 FwdState::Start(conn
, http
->storeEntry(), r
, http
->al
);
717 * client issued a request with an only-if-cached cache-control directive;
718 * we did not find a cached object that can be returned without
719 * contacting other servers;
720 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
723 clientReplyContext::processOnlyIfCachedMiss()
725 debugs(88, 4, http
->request
->method
<< ' ' << http
->uri
);
726 http
->al
->http
.code
= Http::scGatewayTimeout
;
727 ErrorState
*err
= clientBuildError(ERR_ONLY_IF_CACHED_MISS
, Http::scGatewayTimeout
, NULL
,
728 http
->getConn()->clientConnection
->remote
, http
->request
);
729 removeClientStoreReference(&sc
, http
);
733 /// process conditional request from client
735 clientReplyContext::processConditional(StoreIOBuffer
&result
)
737 StoreEntry
*const e
= http
->storeEntry();
739 if (e
->getReply()->sline
.status() != Http::scOkay
) {
740 debugs(88, 4, "clientReplyContext::processConditional: Reply code " <<
741 e
->getReply()->sline
.status() << " != 200");
742 http
->logType
= LOG_TCP_MISS
;
747 HttpRequest
&r
= *http
->request
;
749 if (r
.header
.has(HDR_IF_MATCH
) && !e
->hasIfMatchEtag(r
)) {
750 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
751 sendPreconditionFailedError();
755 bool matchedIfNoneMatch
= false;
756 if (r
.header
.has(HDR_IF_NONE_MATCH
)) {
757 if (!e
->hasIfNoneMatchEtag(r
)) {
758 // RFC 2616: ignore IMS if If-None-Match did not match
762 r
.header
.delById(HDR_IF_MODIFIED_SINCE
);
763 http
->logType
= LOG_TCP_MISS
;
764 sendMoreData(result
);
769 // RFC 2616: if If-None-Match matched and there is no IMS,
770 // reply with 304 Not Modified or 412 Precondition Failed
771 sendNotModifiedOrPreconditionFailedError();
775 // otherwise check IMS below to decide if we reply with 304 or 412
776 matchedIfNoneMatch
= true;
780 // handle If-Modified-Since requests from the client
781 if (e
->modifiedSince(&r
)) {
782 http
->logType
= LOG_TCP_IMS_HIT
;
783 sendMoreData(result
);
787 if (matchedIfNoneMatch
) {
788 // If-None-Match matched, reply with 304 Not Modified or
789 // 412 Precondition Failed
790 sendNotModifiedOrPreconditionFailedError();
794 // otherwise reply with 304 Not Modified
799 /// whether squid.conf send_hit prevents us from serving this hit
801 clientReplyContext::blockedHit() const
803 if (!Config
.accessList
.sendHit
)
804 return false; // hits are not blocked by default
806 if (http
->flags
.internal
)
807 return false; // internal content "hits" cannot be blocked
809 if (const HttpReply
*rep
= http
->storeEntry()->getReply()) {
810 std::auto_ptr
<ACLFilledChecklist
> chl(clientAclChecklistCreate(Config
.accessList
.sendHit
, http
));
811 chl
->reply
= const_cast<HttpReply
*>(rep
); // ACLChecklist API bug
812 HTTPMSGLOCK(chl
->reply
);
813 return chl
->fastCheck() != ACCESS_ALLOWED
; // when in doubt, block
816 // This does not happen, I hope, because we are called from CacheHit, which
817 // is called via a storeClientCopy() callback, and store should initialize
818 // the reply before calling that callback.
819 debugs(88, 3, "Missing reply!");
824 clientReplyContext::purgeRequestFindObjectToPurge()
826 /* Try to find a base entry */
827 http
->flags
.purging
= true;
830 // TODO: can we use purgeAllCached() here instead of doing the
831 // getPublicByRequestMethod() dance?
832 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_GET
);
835 // Purges all entries with a given url
836 // TODO: move to SideAgent parent, when we have one
838 * We probably cannot purge Vary-affected responses because their MD5
839 * keys depend on vary headers.
842 purgeEntriesByUrl(HttpRequest
* req
, const char *url
)
845 bool get_or_head_sent
= false;
848 for (HttpRequestMethod
m(Http::METHOD_NONE
); m
!= Http::METHOD_ENUM_END
; ++m
) {
849 if (m
.respMaybeCacheable()) {
850 if (StoreEntry
*entry
= storeGetPublic(url
, m
)) {
851 debugs(88, 5, "purging " << *entry
<< ' ' << m
<< ' ' << url
);
853 neighborsHtcpClear(entry
, url
, req
, m
, HTCP_CLR_INVALIDATION
);
854 if (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
) {
855 get_or_head_sent
= true;
864 if (!get_or_head_sent
) {
865 neighborsHtcpClear(NULL
, url
, req
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_INVALIDATION
);
871 clientReplyContext::purgeAllCached()
873 const char *url
= urlCanonical(http
->request
);
874 purgeEntriesByUrl(http
->request
, url
);
878 clientReplyContext::created(StoreEntry
*newEntry
)
880 if (lookingforstore
== 1)
881 purgeFoundGet(newEntry
);
882 else if (lookingforstore
== 2)
883 purgeFoundHead(newEntry
);
884 else if (lookingforstore
== 3)
885 purgeDoPurgeGet(newEntry
);
886 else if (lookingforstore
== 4)
887 purgeDoPurgeHead(newEntry
);
888 else if (lookingforstore
== 5)
889 identifyFoundObject(newEntry
);
893 clientReplyContext::purgeFoundGet(StoreEntry
*newEntry
)
895 if (newEntry
->isNull()) {
897 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
899 purgeFoundObject (newEntry
);
903 clientReplyContext::purgeFoundHead(StoreEntry
*newEntry
)
905 if (newEntry
->isNull())
908 purgeFoundObject (newEntry
);
912 clientReplyContext::purgeFoundObject(StoreEntry
*entry
)
914 assert (entry
&& !entry
->isNull());
916 if (EBIT_TEST(entry
->flags
, ENTRY_SPECIAL
)) {
917 http
->logType
= LOG_TCP_DENIED
;
918 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
,
919 http
->getConn()->clientConnection
->remote
, http
->request
);
921 return; // XXX: leaking unused entry if some store does not keep it
924 StoreIOBuffer localTempBuffer
;
925 /* Swap in the metadata */
926 http
->storeEntry(entry
);
928 http
->storeEntry()->lock("clientReplyContext::purgeFoundObject");
929 http
->storeEntry()->createMemObject(storeId(), http
->log_uri
,
930 http
->request
->method
);
932 sc
= storeClientListAdd(http
->storeEntry(), this);
934 http
->logType
= LOG_TCP_HIT
;
938 localTempBuffer
.offset
= http
->out
.offset
;
940 localTempBuffer
.length
= next()->readBuffer
.length
;
942 localTempBuffer
.data
= next()->readBuffer
.data
;
944 storeClientCopy(sc
, http
->storeEntry(),
945 localTempBuffer
, CacheHit
, this);
949 clientReplyContext::purgeRequest()
951 debugs(88, 3, "Config2.onoff.enable_purge = " <<
952 Config2
.onoff
.enable_purge
);
954 if (!Config2
.onoff
.enable_purge
) {
955 http
->logType
= LOG_TCP_DENIED
;
956 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, Http::scForbidden
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
961 /* Release both IP cache */
962 ipcacheInvalidate(http
->request
->GetHost());
964 if (!http
->flags
.purging
)
965 purgeRequestFindObjectToPurge();
971 clientReplyContext::purgeDoMissPurge()
973 http
->logType
= LOG_TCP_MISS
;
975 StoreEntry::getPublicByRequestMethod(this,http
->request
, Http::METHOD_GET
);
979 clientReplyContext::purgeDoPurgeGet(StoreEntry
*newEntry
)
982 /* Move to new() when that is created */
983 purgeStatus
= Http::scNotFound
;
985 if (!newEntry
->isNull()) {
986 /* Release the cached URI */
987 debugs(88, 4, "clientPurgeRequest: GET '" << newEntry
->url() << "'" );
989 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
992 purgeStatus
= Http::scOkay
;
996 StoreEntry::getPublicByRequestMethod(this, http
->request
, Http::METHOD_HEAD
);
1000 clientReplyContext::purgeDoPurgeHead(StoreEntry
*newEntry
)
1002 if (newEntry
&& !newEntry
->isNull()) {
1003 debugs(88, 4, "clientPurgeRequest: HEAD '" << newEntry
->url() << "'" );
1005 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_HEAD
), HTCP_CLR_PURGE
);
1007 newEntry
->release();
1008 purgeStatus
= Http::scOkay
;
1011 /* And for Vary, release the base URI if none of the headers was included in the request */
1013 if (http
->request
->vary_headers
1014 && !strstr(http
->request
->vary_headers
, "=")) {
1015 StoreEntry
*entry
= storeGetPublic(urlCanonical(http
->request
), Http::METHOD_GET
);
1018 debugs(88, 4, "clientPurgeRequest: Vary GET '" << entry
->url() << "'" );
1020 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(Http::METHOD_GET
), HTCP_CLR_PURGE
);
1023 purgeStatus
= Http::scOkay
;
1026 entry
= storeGetPublic(urlCanonical(http
->request
), Http::METHOD_HEAD
);
1029 debugs(88, 4, "clientPurgeRequest: 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 int64_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
;
1242 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
1243 return STREAM_FAILED
;
1246 if (expectedBodySize
>= 0 && !http
->gotEnough()) {
1247 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
1248 return STREAM_UNPLANNED_COMPLETE
;
1251 debugs(88, 5, "clientReplyStatus: stream complete; keepalive=" <<
1252 http
->request
->flags
.proxyKeepalive
);
1253 return STREAM_COMPLETE
;
1256 // XXX: Should this be checked earlier? We could return above w/o checking.
1257 if (reply
->receivedBodyTooLarge(*http
->request
, http
->out
.offset
- 4096)) {
1258 /* 4096 is a margin for the HTTP headers included in out.offset */
1259 debugs(88, 5, "clientReplyStatus: client reply body is too large");
1260 return STREAM_FAILED
;
1266 /* Responses with no body will not have a content-type header,
1267 * which breaks the rep_mime_type acl, which
1268 * coincidentally, is the most common acl for reply access lists.
1269 * A better long term fix for this is to allow acl matchs on the various
1270 * status codes, and then supply a default ruleset that puts these
1271 * codes before any user defines access entries. That way the user
1272 * can choose to block these responses where appropriate, but won't get
1273 * mysterious breakages.
1276 clientReplyContext::alwaysAllowResponse(Http::StatusCode sline
) const
1282 case Http::scContinue
:
1284 case Http::scSwitchingProtocols
:
1286 case Http::scProcessing
:
1288 case Http::scNoContent
:
1290 case Http::scNotModified
:
1302 * Generate the reply headers sent to client.
1304 * Filters out unwanted entries and hop-by-hop from original reply header
1305 * then adds extra entries if we have more info than origin server
1306 * then adds Squid specific entries
1309 clientReplyContext::buildReplyHeader()
1311 HttpHeader
*hdr
= &reply
->header
;
1312 int is_hit
= logTypeIsATcpHit(http
->logType
);
1313 HttpRequest
*request
= http
->request
;
1314 #if DONT_FILTER_THESE
1315 /* but you might want to if you run Squid as an HTTP accelerator */
1316 /* hdr->delById(HDR_ACCEPT_RANGES); */
1317 hdr
->delById(HDR_ETAG
);
1321 hdr
->delById(HDR_SET_COOKIE
);
1322 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
1324 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
1325 // remove the Proxy-Authenticate header
1326 if ( !request
->peer_login
|| (strcmp(request
->peer_login
,"PASS") != 0 && strcmp(request
->peer_login
,"PASSTHRU") != 0))
1327 reply
->header
.delById(HDR_PROXY_AUTHENTICATE
);
1329 reply
->header
.removeHopByHopEntries();
1331 // if (request->range)
1332 // clientBuildRangeHeader(http, reply);
1335 * Add a estimated Age header on cache hits.
1339 * Remove any existing Age header sent by upstream caches
1340 * (note that the existing header is passed along unmodified
1343 hdr
->delById(HDR_AGE
);
1345 * This adds the calculated object age. Note that the details of the
1346 * age calculation is performed by adjusting the timestamp in
1347 * StoreEntry::timestampsSet(), not here.
1349 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
1350 hdr
->delById(HDR_DATE
);
1351 hdr
->insertTime(HDR_DATE
, squid_curtime
);
1352 } else if (http
->getConn() && http
->getConn()->port
->actAsOrigin
) {
1353 // Swap the Date: header to current time if we are simulating an origin
1354 HttpHeaderEntry
*h
= hdr
->findEntry(HDR_DATE
);
1356 hdr
->putExt("X-Origin-Date", h
->value
.termedBuf());
1357 hdr
->delById(HDR_DATE
);
1358 hdr
->insertTime(HDR_DATE
, squid_curtime
);
1359 h
= hdr
->findEntry(HDR_EXPIRES
);
1360 if (h
&& http
->storeEntry()->expires
>= 0) {
1361 hdr
->putExt("X-Origin-Expires", h
->value
.termedBuf());
1362 hdr
->delById(HDR_EXPIRES
);
1363 hdr
->insertTime(HDR_EXPIRES
, squid_curtime
+ http
->storeEntry()->expires
- http
->storeEntry()->timestamp
);
1365 if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1366 // put X-Cache-Age: instead of Age:
1368 snprintf(age
, sizeof(age
), "%" PRId64
, static_cast<int64_t>(squid_curtime
- http
->storeEntry()->timestamp
));
1369 hdr
->putExt("X-Cache-Age", age
);
1371 } else if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1372 hdr
->putInt(HDR_AGE
,
1373 squid_curtime
- http
->storeEntry()->timestamp
);
1374 /* Signal old objects. NB: rfc 2616 is not clear,
1375 * by implication, on whether we should do this to all
1376 * responses, or only cache hits.
1377 * 14.46 states it ONLY applys for heuristically caclulated
1378 * freshness values, 13.2.4 doesn't specify the same limitation.
1379 * We interpret RFC 2616 under the combination.
1381 /* TODO: if maxage or s-maxage is present, don't do this */
1383 if (squid_curtime
- http
->storeEntry()->timestamp
>= 86400) {
1385 snprintf (tbuf
, sizeof(tbuf
), "%s %s %s",
1387 "This cache hit is still fresh and more than 1 day old");
1388 hdr
->putStr(HDR_WARNING
, tbuf
);
1393 /* RFC 2616: Section 14.18
1395 * Add a Date: header if missing.
1396 * We have access to a clock therefore are required to amend any shortcoming in servers.
1398 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1400 if ( !hdr
->has(HDR_DATE
) ) {
1401 if (!http
->storeEntry())
1402 hdr
->insertTime(HDR_DATE
, squid_curtime
);
1403 else if (http
->storeEntry()->timestamp
> 0)
1404 hdr
->insertTime(HDR_DATE
, http
->storeEntry()->timestamp
);
1406 debugs(88,DBG_IMPORTANT
,"BUG 3279: HTTP reply without Date:");
1407 /* dump something useful about the problem */
1408 http
->storeEntry()->dump(DBG_IMPORTANT
);
1412 // add Warnings required by RFC 2616 if serving a stale hit
1413 if (http
->request
->flags
.staleIfHit
&& logTypeIsATcpHit(http
->logType
)) {
1414 hdr
->putWarning(110, "Response is stale");
1415 if (http
->request
->flags
.needValidation
)
1416 hdr
->putWarning(111, "Revalidation failed");
1419 /* Filter unproxyable authentication types */
1420 if (http
->logType
!= LOG_TCP_DENIED
&&
1421 hdr
->has(HDR_WWW_AUTHENTICATE
)) {
1422 HttpHeaderPos pos
= HttpHeaderInitPos
;
1425 int connection_auth_blocked
= 0;
1426 while ((e
= hdr
->getEntry(&pos
))) {
1427 if (e
->id
== HDR_WWW_AUTHENTICATE
) {
1428 const char *value
= e
->value
.rawBuf();
1430 if ((strncasecmp(value
, "NTLM", 4) == 0 &&
1431 (value
[4] == '\0' || value
[4] == ' '))
1433 (strncasecmp(value
, "Negotiate", 9) == 0 &&
1434 (value
[9] == '\0' || value
[9] == ' '))
1436 (strncasecmp(value
, "Kerberos", 8) == 0 &&
1437 (value
[8] == '\0' || value
[8] == ' '))) {
1438 if (request
->flags
.connectionAuthDisabled
) {
1439 hdr
->delAt(pos
, connection_auth_blocked
);
1442 request
->flags
.mustKeepalive
= true;
1443 if (!request
->flags
.accelerated
&& !request
->flags
.intercepted
) {
1444 httpHeaderPutStrf(hdr
, HDR_PROXY_SUPPORT
, "Session-Based-Authentication");
1446 We send "Connection: Proxy-Support" header to mark
1447 Proxy-Support as a hop-by-hop header for intermediaries that do not
1448 understand the semantics of this header. The RFC should have included
1449 this recommendation.
1451 httpHeaderPutStrf(hdr
, HDR_CONNECTION
, "Proxy-support");
1458 if (connection_auth_blocked
)
1463 /* Handle authentication headers */
1464 if (http
->logType
== LOG_TCP_DENIED
&&
1465 ( reply
->sline
.status() == Http::scProxyAuthenticationRequired
||
1466 reply
->sline
.status() == Http::scUnauthorized
)
1468 /* Add authentication header */
1469 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1470 * depends on authenticate behaviour: all schemes to date send no extra
1471 * data on 407/401 responses, and do not check the accel state on 401/407
1474 authenticateFixHeader(reply
, request
->auth_user_request
, request
, 0, 1);
1475 } else if (request
->auth_user_request
!= NULL
)
1476 authenticateFixHeader(reply
, request
->auth_user_request
, request
, http
->flags
.accel
, 0);
1479 /* Append X-Cache */
1480 httpHeaderPutStrf(hdr
, HDR_X_CACHE
, "%s from %s",
1481 is_hit
? "HIT" : "MISS", getMyHostname());
1483 #if USE_CACHE_DIGESTS
1484 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1485 httpHeaderPutStrf(hdr
, HDR_X_CACHE_LOOKUP
, "%s from %s:%d",
1486 lookup_type
? lookup_type
: "NONE",
1487 getMyHostname(), getMyPort());
1491 const bool maySendChunkedReply
= !request
->multipartRangeRequest() &&
1492 reply
->sline
.protocol
== AnyP::PROTO_HTTP
&& // response is HTTP
1493 (request
->http_ver
>= Http::ProtocolVersion(1, 1));
1495 /* Check whether we should send keep-alive */
1496 if (!Config
.onoff
.error_pconns
&& reply
->sline
.status() >= 400 && !request
->flags
.mustKeepalive
) {
1497 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
1498 request
->flags
.proxyKeepalive
= false;
1499 } else if (!Config
.onoff
.client_pconns
&& !request
->flags
.mustKeepalive
) {
1500 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
1501 request
->flags
.proxyKeepalive
= false;
1502 } else if (request
->flags
.proxyKeepalive
&& shutting_down
) {
1503 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
1504 request
->flags
.proxyKeepalive
= false;
1505 } else if (request
->flags
.connectionAuth
&& !reply
->keep_alive
) {
1506 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
1507 request
->flags
.proxyKeepalive
= false;
1508 } else if (reply
->bodySize(request
->method
) < 0 && !maySendChunkedReply
) {
1509 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
1510 request
->flags
.proxyKeepalive
= false;
1511 } else if (fdUsageHigh()&& !request
->flags
.mustKeepalive
) {
1512 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
1513 request
->flags
.proxyKeepalive
= false;
1514 } else if (request
->flags
.sslBumped
&& !reply
->persistent()) {
1515 // We do not really have to close, but we pretend we are a tunnel.
1516 debugs(88, 3, "clientBuildReplyHeader: bumped reply forces close");
1517 request
->flags
.proxyKeepalive
= false;
1518 } else if (request
->pinnedConnection() && !reply
->persistent()) {
1519 // The peer wants to close the pinned connection
1520 debugs(88, 3, "pinned reply forces close");
1521 request
->flags
.proxyKeepalive
= false;
1524 // Decide if we send chunked reply
1525 if (maySendChunkedReply
&&
1526 request
->flags
.proxyKeepalive
&&
1527 reply
->bodySize(request
->method
) < 0) {
1528 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
1529 request
->flags
.chunkedReply
= true;
1530 hdr
->putStr(HDR_TRANSFER_ENCODING
, "chunked");
1534 if (Config
.onoff
.via
) {
1535 LOCAL_ARRAY(char, bbuf
, MAX_URL
+ 32);
1537 hdr
->getList(HDR_VIA
, &strVia
);
1538 snprintf(bbuf
, MAX_URL
+ 32, "%d.%d %s",
1539 reply
->sline
.version
.major
,
1540 reply
->sline
.version
.minor
,
1542 strListAdd(&strVia
, bbuf
, ',');
1543 hdr
->delById(HDR_VIA
);
1544 hdr
->putStr(HDR_VIA
, strVia
.termedBuf());
1546 /* Signal keep-alive or close explicitly */
1547 hdr
->putStr(HDR_CONNECTION
, request
->flags
.proxyKeepalive
? "keep-alive" : "close");
1549 #if ADD_X_REQUEST_URI
1551 * Knowing the URI of the request is useful when debugging persistent
1552 * connections in a client; we cannot guarantee the order of http headers,
1553 * but X-Request-URI is likely to be the very last header to ease use from a
1554 * debugger [hdr->entries.count-1].
1556 hdr
->putStr(HDR_X_REQUEST_URI
,
1557 http
->memOjbect()->url
? http
->memObject()->url
: http
->uri
);
1561 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1562 if ( hdr
->has(HDR_SURROGATE_CONTROL
) ) {
1563 if (!request
->header
.has(HDR_SURROGATE_CAPABILITY
)) {
1564 hdr
->delById(HDR_SURROGATE_CONTROL
);
1566 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1569 httpHdrMangleList(hdr
, request
, ROR_REPLY
);
1573 clientReplyContext::cloneReply()
1575 assert(reply
== NULL
);
1577 reply
= http
->storeEntry()->getReply()->clone();
1580 if (reply
->sline
.protocol
== AnyP::PROTO_HTTP
) {
1581 /* RFC 2616 requires us to advertise our 1.1 version (but only on real HTTP traffic) */
1582 reply
->sline
.version
= Http::ProtocolVersion(1,1);
1585 /* do header conversions */
1589 /// Safely disposes of an entry pointing to a cache hit that we do not want.
1590 /// We cannot just ignore the entry because it may be locking or otherwise
1591 /// holding an associated cache resource of some sort.
1593 clientReplyContext::forgetHit()
1595 StoreEntry
*e
= http
->storeEntry();
1596 assert(e
); // or we are not dealing with a hit
1597 // We probably have not locked the entry earlier, unfortunately. We lock it
1598 // now so that we can unlock two lines later (and trigger cleanup).
1599 // Ideally, ClientHttpRequest::storeEntry() should lock/unlock, but it is
1600 // used so inconsistently that simply adding locking there leads to bugs.
1601 e
->lock("clientReplyContext::forgetHit");
1602 http
->storeEntry(NULL
);
1603 e
->unlock("clientReplyContext::forgetHit"); // may delete e
1607 clientReplyContext::identifyStoreObject()
1609 HttpRequest
*r
= http
->request
;
1611 if (r
->flags
.cachable
|| r
->flags
.internal
) {
1612 lookingforstore
= 5;
1613 StoreEntry::getPublicByRequest (this, r
);
1615 identifyFoundObject (NullStoreEntry::getInstance());
1620 * Check state of the current StoreEntry object.
1621 * to see if we can determine the final status of the request.
1624 clientReplyContext::identifyFoundObject(StoreEntry
*newEntry
)
1626 StoreEntry
*e
= newEntry
;
1627 HttpRequest
*r
= http
->request
;
1629 /** \li If the entry received isNull() then we ignore it. */
1631 http
->storeEntry(NULL
);
1633 http
->storeEntry(e
);
1636 e
= http
->storeEntry();
1638 /* Release IP-cache entries on reload */
1639 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
1640 * 'invalidate' the cached IP entries for this request ???
1642 if (r
->flags
.noCache
|| r
->flags
.noCacheHack())
1643 ipcacheInvalidateNegative(r
->GetHost());
1645 #if USE_CACHE_DIGESTS
1646 lookup_type
= http
->storeEntry() ? "HIT" : "MISS";
1649 if (NULL
== http
->storeEntry()) {
1650 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
1651 debugs(85, 3, "StoreEntry is NULL - MISS");
1652 http
->logType
= LOG_TCP_MISS
;
1657 if (Config
.onoff
.offline
) {
1658 /** \li If we are running in offline mode set to HIT */
1659 debugs(85, 3, "offline HIT " << *e
);
1660 http
->logType
= LOG_TCP_HIT
;
1665 if (http
->redirect
.status
) {
1666 /** \li If redirection status is True force this to be a MISS */
1667 debugs(85, 3, "REDIRECT status forced StoreEntry to NULL (no body on 3XX responses) " << *e
);
1669 http
->logType
= LOG_TCP_REDIRECT
;
1674 if (!e
->validToSend()) {
1675 debugs(85, 3, "!storeEntryValidToSend MISS " << *e
);
1677 http
->logType
= LOG_TCP_MISS
;
1682 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1683 /* \li Special entries are always hits, no matter what the client says */
1684 debugs(85, 3, "ENTRY_SPECIAL HIT " << *e
);
1685 http
->logType
= LOG_TCP_HIT
;
1690 if (r
->flags
.noCache
) {
1691 debugs(85, 3, "no-cache REFRESH MISS " << *e
);
1693 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
1698 debugs(85, 3, "default HIT " << *e
);
1699 http
->logType
= LOG_TCP_HIT
;
1704 * Request more data from the store for the client Stream
1705 * This is *the* entry point to this module.
1708 * - This is the head of the list.
1709 * - There is at least one more node.
1710 * - Data context is not null
1713 clientGetMoreData(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1715 /* Test preconditions */
1716 assert(aNode
!= NULL
);
1717 assert(cbdataReferenceValid(aNode
));
1718 assert(aNode
->node
.prev
== NULL
);
1719 assert(aNode
->node
.next
!= NULL
);
1720 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1722 assert(context
->http
== http
);
1724 clientStreamNode
*next
= ( clientStreamNode
*)aNode
->node
.next
->data
;
1726 if (!context
->ourNode
)
1727 context
->ourNode
= aNode
;
1729 /* no cbdatareference, this is only used once, and safely */
1730 if (context
->flags
.storelogiccomplete
) {
1731 StoreIOBuffer tempBuffer
;
1732 tempBuffer
.offset
= next
->readBuffer
.offset
+ context
->headers_sz
;
1733 tempBuffer
.length
= next
->readBuffer
.length
;
1734 tempBuffer
.data
= next
->readBuffer
.data
;
1736 storeClientCopy(context
->sc
, http
->storeEntry(),
1737 tempBuffer
, clientReplyContext::SendMoreData
, context
);
1741 if (context
->http
->request
->method
== Http::METHOD_PURGE
) {
1742 context
->purgeRequest();
1746 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
1748 if (context
->http
->request
->method
== Http::METHOD_TRACE
) {
1749 if (context
->http
->request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0) {
1750 context
->traceReply(aNode
);
1754 /* continue forwarding, not finished yet. */
1755 http
->logType
= LOG_TCP_MISS
;
1757 context
->doGetMoreData();
1759 context
->identifyStoreObject();
1763 clientReplyContext::doGetMoreData()
1765 /* We still have to do store logic processing - vary, cache hit etc */
1766 if (http
->storeEntry() != NULL
) {
1767 /* someone found the object in the cache for us */
1768 StoreIOBuffer localTempBuffer
;
1770 http
->storeEntry()->lock("clientReplyContext::doGetMoreData");
1772 MemObject
*mem_obj
= http
->storeEntry()->makeMemObject();
1773 if (!mem_obj
->hasUris()) {
1775 * This if-block exists because we don't want to clobber
1776 * a preexiting mem_obj->method value if the mem_obj
1777 * already exists. For example, when a HEAD request
1778 * is a cache hit for a GET response, we want to keep
1779 * the method as GET.
1781 mem_obj
->setUris(storeId(), http
->log_uri
, http
->request
->method
);
1783 * Here we can see if the object was
1784 * created using URL or alternative StoreID from helper.
1786 debugs(88, 3, "storeId: " << http
->storeEntry()->mem_obj
->storeId());
1789 sc
= storeClientListAdd(http
->storeEntry(), this);
1791 sc
->setDelayId(DelayId::DelayClient(http
));
1794 assert(http
->logType
== LOG_TCP_HIT
);
1796 /* guarantee nothing has been sent yet! */
1797 assert(http
->out
.size
== 0);
1798 assert(http
->out
.offset
== 0);
1800 if (Ip::Qos::TheConfig
.isHitTosActive()) {
1801 Ip::Qos::doTosLocalHit(http
->getConn()->clientConnection
);
1804 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
1805 Ip::Qos::doNfmarkLocalHit(http
->getConn()->clientConnection
);
1808 localTempBuffer
.offset
= reqofs
;
1809 localTempBuffer
.length
= getNextNode()->readBuffer
.length
;
1810 localTempBuffer
.data
= getNextNode()->readBuffer
.data
;
1811 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, CacheHit
, this);
1813 /* MISS CASE, http->logType is already set! */
1818 /** The next node has removed itself from the stream. */
1820 clientReplyDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1822 /** detach from the stream */
1823 clientStreamDetach(node
, http
);
1827 * Accepts chunk of a http message in buf, parses prefix, filters headers and
1828 * such, writes processed message to the message recipient
1831 clientReplyContext::SendMoreData(void *data
, StoreIOBuffer result
)
1833 clientReplyContext
*context
= static_cast<clientReplyContext
*>(data
);
1834 context
->sendMoreData (result
);
1838 clientReplyContext::makeThisHead()
1840 /* At least, I think thats what this does */
1841 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1842 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1846 clientReplyContext::errorInStream(StoreIOBuffer
const &result
, size_t const &sizeToProcess
)const
1848 return /* aborted request */
1849 (http
->storeEntry() && EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) ||
1850 /* Upstream read error */ (result
.flags
.error
) ||
1851 /* Upstream EOF */ (sizeToProcess
== 0);
1855 clientReplyContext::sendStreamError(StoreIOBuffer
const &result
)
1857 /** call clientWriteComplete so the client socket gets closed
1859 * We call into the stream, because we don't know that there is a
1862 debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.");
1863 StoreIOBuffer localTempBuffer
;
1865 http
->request
->flags
.streamError
= true;
1866 localTempBuffer
.flags
.error
= result
.flags
.error
;
1867 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1872 clientReplyContext::pushStreamData(StoreIOBuffer
const &result
, char *source
)
1874 StoreIOBuffer localTempBuffer
;
1876 if (result
.length
== 0) {
1877 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
1881 assert(result
.offset
- headers_sz
== next()->readBuffer
.offset
);
1882 localTempBuffer
.offset
= result
.offset
- headers_sz
;
1883 localTempBuffer
.length
= result
.length
;
1885 if (localTempBuffer
.length
)
1886 localTempBuffer
.data
= source
;
1888 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1893 clientReplyContext::next() const
1895 assert ( (clientStreamNode
*)http
->client_stream
.head
->next
->data
== getNextNode());
1896 return getNextNode();
1900 clientReplyContext::sendBodyTooLargeError()
1902 Ip::Address tmp_noaddr
;
1903 tmp_noaddr
.setNoAddr(); // TODO: make a global const
1904 http
->logType
= LOG_TCP_DENIED_REPLY
;
1905 ErrorState
*err
= clientBuildError(ERR_TOO_BIG
, Http::scForbidden
, NULL
,
1906 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
1908 removeClientStoreReference(&(sc
), http
);
1909 HTTPMSGUNLOCK(reply
);
1914 /// send 412 (Precondition Failed) to client
1916 clientReplyContext::sendPreconditionFailedError()
1918 http
->logType
= LOG_TCP_HIT
;
1919 ErrorState
*const err
=
1920 clientBuildError(ERR_PRECONDITION_FAILED
, Http::scPreconditionFailed
,
1921 NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
1922 removeClientStoreReference(&sc
, http
);
1923 HTTPMSGUNLOCK(reply
);
1927 /// send 304 (Not Modified) to client
1929 clientReplyContext::sendNotModified()
1931 StoreEntry
*e
= http
->storeEntry();
1932 const time_t timestamp
= e
->timestamp
;
1933 HttpReply
*const temprep
= e
->getReply()->make304();
1934 http
->logType
= LOG_TCP_IMS_HIT
;
1935 removeClientStoreReference(&sc
, http
);
1936 createStoreEntry(http
->request
->method
, RequestFlags());
1937 e
= http
->storeEntry();
1938 // Copy timestamp from the original entry so the 304
1939 // reply has a meaningful Age: header.
1941 e
->timestamp
= timestamp
;
1942 e
->replaceHttpReply(temprep
);
1945 * TODO: why put this in the store and then serialise it and
1946 * then parse it again. Simply mark the request complete in
1947 * our context and write the reply struct to the client side.
1949 triggerInitialStoreRead();
1952 /// send 304 (Not Modified) or 412 (Precondition Failed) to client
1953 /// depending on request method
1955 clientReplyContext::sendNotModifiedOrPreconditionFailedError()
1957 if (http
->request
->method
== Http::METHOD_GET
||
1958 http
->request
->method
== Http::METHOD_HEAD
)
1961 sendPreconditionFailedError();
1965 clientReplyContext::processReplyAccess ()
1967 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
1970 /** Don't block our own responses or HTTP status messages */
1971 if (http
->logType
== LOG_TCP_DENIED
||
1972 http
->logType
== LOG_TCP_DENIED_REPLY
||
1973 alwaysAllowResponse(reply
->sline
.status())) {
1974 headers_sz
= reply
->hdr_sz
;
1975 processReplyAccessResult(ACCESS_ALLOWED
);
1979 /** Check for reply to big error */
1980 if (reply
->expectedBodyTooLarge(*http
->request
)) {
1981 sendBodyTooLargeError();
1985 headers_sz
= reply
->hdr_sz
;
1987 /** check for absent access controls (permit by default) */
1988 if (!Config
.accessList
.reply
) {
1989 processReplyAccessResult(ACCESS_ALLOWED
);
1993 /** Process http_reply_access lists */
1994 ACLFilledChecklist
*replyChecklist
=
1995 clientAclChecklistCreate(Config
.accessList
.reply
, http
);
1996 replyChecklist
->reply
= reply
;
1997 HTTPMSGLOCK(replyChecklist
->reply
);
1998 replyChecklist
->nonBlockingCheck(ProcessReplyAccessResult
, this);
2002 clientReplyContext::ProcessReplyAccessResult(allow_t rv
, void *voidMe
)
2004 clientReplyContext
*me
= static_cast<clientReplyContext
*>(voidMe
);
2005 me
->processReplyAccessResult(rv
);
2009 clientReplyContext::processReplyAccessResult(const allow_t
&accessAllowed
)
2011 debugs(88, 2, "The reply for " << http
->request
->method
2012 << ' ' << http
->uri
<< " is " << accessAllowed
<< ", because it matched "
2013 << (AclMatchedName
? AclMatchedName
: "NO ACL's"));
2015 if (accessAllowed
!= ACCESS_ALLOWED
) {
2018 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, 1);
2020 http
->logType
= LOG_TCP_DENIED_REPLY
;
2022 if (page_id
== ERR_NONE
)
2023 page_id
= ERR_ACCESS_DENIED
;
2025 Ip::Address tmp_noaddr
;
2026 tmp_noaddr
.setNoAddr();
2027 err
= clientBuildError(page_id
, Http::scForbidden
, NULL
,
2028 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
2031 removeClientStoreReference(&sc
, http
);
2033 HTTPMSGUNLOCK(reply
);
2040 /* Ok, the reply is allowed, */
2041 http
->loggingEntry(http
->storeEntry());
2043 ssize_t body_size
= reqofs
- reply
->hdr_sz
;
2044 if (body_size
< 0) {
2045 reqofs
= reply
->hdr_sz
;
2049 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
2050 (int) body_size
<< " bytes after " << reply
->hdr_sz
<<
2051 " bytes of headers");
2055 if (http
->flags
.accel
&& reply
->sline
.status() != Http::scForbidden
&&
2056 !alwaysAllowResponse(reply
->sline
.status()) &&
2057 esiEnableProcessing(reply
)) {
2058 debugs(88, 2, "Enabling ESI processing for " << http
->uri
);
2059 clientStreamInsertHead(&http
->client_stream
, esiStreamRead
,
2060 esiProcessStream
, esiStreamDetach
, esiStreamStatus
, NULL
);
2065 if (http
->request
->method
== Http::METHOD_HEAD
) {
2066 /* do not forward body for HEAD replies */
2068 http
->flags
.done_copying
= true;
2072 assert (!flags
.headersSent
);
2073 flags
.headersSent
= true;
2075 StoreIOBuffer localTempBuffer
;
2076 char *buf
= next()->readBuffer
.data
;
2077 char *body_buf
= buf
+ reply
->hdr_sz
;
2079 //Server side may disable ranges under some circumstances.
2081 if ((!http
->request
->range
))
2082 next()->readBuffer
.offset
= 0;
2084 body_buf
-= next()->readBuffer
.offset
;
2086 if (next()->readBuffer
.offset
!= 0) {
2087 if (next()->readBuffer
.offset
> body_size
) {
2088 /* Can't use any of the body we received. send nothing */
2089 localTempBuffer
.length
= 0;
2090 localTempBuffer
.data
= NULL
;
2092 localTempBuffer
.length
= body_size
- next()->readBuffer
.offset
;
2093 localTempBuffer
.data
= body_buf
+ next()->readBuffer
.offset
;
2096 localTempBuffer
.length
= body_size
;
2097 localTempBuffer
.data
= body_buf
;
2100 /* TODO??: move the data in the buffer back by the request header size */
2101 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
,
2102 http
, reply
, localTempBuffer
);
2108 clientReplyContext::sendMoreData (StoreIOBuffer result
)
2113 StoreEntry
*entry
= http
->storeEntry();
2115 ConnStateData
* conn
= http
->getConn();
2117 // too late, our conn is closing
2118 // TODO: should we also quit?
2120 debugs(33,3, "not sending more data to a closed connection" );
2123 if (!conn
->isOpen()) {
2124 debugs(33,3, "not sending more data to closing connection " << conn
->clientConnection
);
2127 if (conn
->pinning
.zeroReply
) {
2128 debugs(33,3, "not sending more data after a pinned zero reply " << conn
->clientConnection
);
2132 char *buf
= next()->readBuffer
.data
;
2134 if (buf
!= result
.data
) {
2135 /* we've got to copy some data */
2136 assert(result
.length
<= next()->readBuffer
.length
);
2137 memcpy(buf
, result
.data
, result
.length
);
2140 if (reqofs
==0 && !logTypeIsATcpHit(http
->logType
) && Comm::IsConnOpen(conn
->clientConnection
)) {
2141 if (Ip::Qos::TheConfig
.isHitTosActive()) {
2142 Ip::Qos::doTosLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2144 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
2145 Ip::Qos::doNfmarkLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2149 /* We've got the final data to start pushing... */
2150 flags
.storelogiccomplete
= 1;
2152 reqofs
+= result
.length
;
2154 assert(reqofs
<= HTTP_REQBUF_SZ
|| flags
.headersSent
);
2156 assert(http
->request
!= NULL
);
2158 /* ESI TODO: remove this assert once everything is stable */
2159 assert(http
->client_stream
.head
->data
2160 && cbdataReferenceValid(http
->client_stream
.head
->data
));
2164 debugs(88, 5, "clientReplyContext::sendMoreData: " << http
->uri
<< ", " <<
2165 reqofs
<< " bytes (" << result
.length
<<
2167 debugs(88, 5, "clientReplyContext::sendMoreData:"
2168 << conn
->clientConnection
<<
2169 " '" << entry
->url() << "'" <<
2170 " out.offset=" << http
->out
.offset
);
2172 /* update size of the request */
2175 if (errorInStream(result
, reqofs
)) {
2176 sendStreamError(result
);
2180 if (flags
.headersSent
) {
2181 pushStreamData (result
, buf
);
2187 /* handle headers */
2189 if (Config
.onoff
.log_mime_hdrs
) {
2192 if ((k
= headersEnd(buf
, reqofs
))) {
2193 safe_free(http
->al
->headers
.reply
);
2194 http
->al
->headers
.reply
= (char *)xcalloc(k
+ 1, 1);
2195 xstrncpy(http
->al
->headers
.reply
, buf
, k
);
2199 holdingBuffer
= result
;
2200 processReplyAccess();
2204 /* Using this breaks the client layering just a little!
2207 clientReplyContext::createStoreEntry(const HttpRequestMethod
& m
, RequestFlags reqFlags
)
2209 assert(http
!= NULL
);
2211 * For erroneous requests, we might not have a h->request,
2212 * so make a fake one.
2215 if (http
->request
== NULL
) {
2216 http
->request
= new HttpRequest(m
, AnyP::PROTO_NONE
, null_string
);
2217 HTTPMSGLOCK(http
->request
);
2220 StoreEntry
*e
= storeCreateEntry(storeId(), http
->log_uri
, reqFlags
, m
);
2222 // Make entry collapsable ASAP, to increase collapsing chances for others,
2223 // TODO: every must-revalidate and similar request MUST reach the origin,
2224 // but do we have to prohibit others from collapsing on that request?
2225 if (Config
.onoff
.collapsed_forwarding
&& reqFlags
.cachable
&&
2226 !reqFlags
.needValidation
&&
2227 (m
== Http::METHOD_GET
|| m
== Http::METHOD_HEAD
)) {
2228 // make the entry available for future requests now
2229 Store::Root().allowCollapsing(e
, reqFlags
, m
);
2232 sc
= storeClientListAdd(e
, this);
2235 sc
->setDelayId(DelayId::DelayClient(http
));
2242 /* I don't think this is actually needed! -- adrian */
2243 /* http->reqbuf = http->norm_reqbuf; */
2244 // assert(http->reqbuf == http->norm_reqbuf);
2245 /* The next line is illegal because we don't know if the client stream
2246 * buffers have been set up
2248 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2249 // SendMoreData, this);
2250 /* So, we mark the store logic as complete */
2251 flags
.storelogiccomplete
= 1;
2253 /* and get the caller to request a read, from whereever they are */
2254 /* NOTE: after ANY data flows down the pipe, even one step,
2255 * this function CAN NOT be used to manage errors
2257 http
->storeEntry(e
);
2261 clientBuildError(err_type page_id
, Http::StatusCode status
, char const *url
,
2262 Ip::Address
&src_addr
, HttpRequest
* request
)
2264 ErrorState
*err
= new ErrorState(page_id
, status
, request
);
2265 err
->src_addr
= src_addr
;
2268 err
->url
= xstrdup(url
);