4 * DEBUG: section 88 Client-side Reply Routines
5 * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c)
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
36 /* for ClientActiveRequests global */
39 /* old includes without reasons given. */
41 #include "acl/FilledChecklist.h"
42 #include "acl/Gadgets.h"
44 #include "auth/UserRequest.h"
46 #include "client_side.h"
47 #include "client_side_reply.h"
48 #include "clientStream.h"
50 #include "DelayPools.h"
52 #include "errorpage.h"
58 #include "format/Token.h"
59 #include "HttpReply.h"
60 #include "HttpRequest.h"
61 #include "ip/QosConfig.h"
63 #include "MemObject.h"
64 #include "ProtoPort.h"
65 #include "SquidTime.h"
66 #include "StoreClient.h"
69 CBDATA_CLASS_INIT(clientReplyContext
);
72 extern "C" CSS clientReplyStatus
;
73 extern ErrorState
*clientBuildError(err_type
, http_status
, char const *, Ip::Address
&, HttpRequest
*);
77 clientReplyContext::~clientReplyContext()
80 /* This may trigger a callback back into SendMoreData as the cbdata
83 removeClientStoreReference(&sc
, http
);
84 /* old_entry might still be set if we didn't yet get the reply
85 * code in HandleIMSReply() */
86 removeStoreReference(&old_sc
, &old_entry
);
87 safe_free(tempBuffer
.data
);
88 cbdataReferenceDone(http
);
92 clientReplyContext::clientReplyContext(ClientHttpRequest
*clientContext
) : http (cbdataReference(clientContext
)), old_entry (NULL
), old_sc(NULL
), deleting(false)
95 /** Create an error in the store awaiting the client side to read it.
97 * This may be better placed in the clientStream logic, but it has not been
101 clientReplyContext::setReplyToError(
102 err_type err
, http_status status
, const HttpRequestMethod
& method
, char const *uri
,
103 Ip::Address
&addr
, HttpRequest
* failedrequest
, const char *unparsedrequest
,
105 AuthUserRequest::Pointer auth_user_request
111 ErrorState
*errstate
= clientBuildError(err
, status
, uri
, addr
, failedrequest
);
114 errstate
->request_hdrs
= xstrdup(unparsedrequest
);
116 if (status
== HTTP_NOT_IMPLEMENTED
&& http
->request
)
117 /* prevent confusion over whether we default to persistent or not */
118 http
->request
->flags
.proxy_keepalive
= 0;
120 http
->al
.http
.code
= errstate
->httpStatus
;
122 createStoreEntry(method
, request_flags());
124 errstate
->auth_user_request
= auth_user_request
;
126 assert(errstate
->callback_data
== NULL
);
127 errorAppendEntry(http
->storeEntry(), errstate
);
128 /* Now the caller reads to get this */
131 void clientReplyContext::setReplyToStoreEntry(StoreEntry
*entry
)
133 sc
= storeClientListAdd(entry
, this);
135 sc
->setDelayId(DelayId::DelayClient(http
));
139 flags
.storelogiccomplete
= 1;
140 http
->storeEntry(entry
);
144 clientReplyContext::removeStoreReference(store_client
** scp
,
148 store_client
*sc_tmp
= *scp
;
150 if ((e
= *ep
) != NULL
) {
152 storeUnregister(sc_tmp
, e
, this);
159 clientReplyContext::removeClientStoreReference(store_client
**scp
, ClientHttpRequest
*aHttpRequest
)
161 StoreEntry
*reference
= aHttpRequest
->storeEntry();
162 removeStoreReference(scp
, &reference
);
163 aHttpRequest
->storeEntry(reference
);
167 clientReplyContext::operator new (size_t byteCount
)
169 /* derived classes with different sizes must implement their own new */
170 assert (byteCount
== sizeof (clientReplyContext
));
171 CBDATA_INIT_TYPE(clientReplyContext
);
172 return cbdataAlloc(clientReplyContext
);
176 clientReplyContext::operator delete (void *address
)
178 clientReplyContext
* tmp
= (clientReplyContext
*)address
;
183 clientReplyContext::saveState()
185 assert(old_sc
== NULL
);
186 debugs(88, 3, "clientReplyContext::saveState: saving store context");
187 old_entry
= http
->storeEntry();
189 old_reqsize
= reqsize
;
190 tempBuffer
.offset
= reqofs
;
191 /* Prevent accessing the now saved entries */
192 http
->storeEntry(NULL
);
199 clientReplyContext::restoreState()
201 assert(old_sc
!= NULL
);
202 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
203 removeClientStoreReference(&sc
, http
);
204 http
->storeEntry(old_entry
);
206 reqsize
= old_reqsize
;
207 reqofs
= tempBuffer
.offset
;
208 /* Prevent accessed the old saved entries */
212 tempBuffer
.offset
= 0;
216 clientReplyContext::startError(ErrorState
* err
)
218 createStoreEntry(http
->request
->method
, request_flags());
219 triggerInitialStoreRead();
220 errorAppendEntry(http
->storeEntry(), err
);
224 clientReplyContext::getNextNode() const
226 return (clientStreamNode
*)ourNode
->node
.next
->data
;
229 /* This function is wrong - the client parameters don't include the
233 clientReplyContext::triggerInitialStoreRead()
235 /* when confident, 0 becomes reqofs, and then this factors into
239 StoreIOBuffer
localTempBuffer (next()->readBuffer
.length
, 0, next()->readBuffer
.data
);
240 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, SendMoreData
, this);
243 /* there is an expired entry in the store.
244 * setup a temporary buffer area and perform an IMS to the origin
247 clientReplyContext::processExpired()
249 char *url
= http
->uri
;
250 StoreEntry
*entry
= NULL
;
251 debugs(88, 3, "clientReplyContext::processExpired: '" << http
->uri
<< "'");
252 assert(http
->storeEntry()->lastmod
>= 0);
254 * check if we are allowed to contact other servers
255 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
256 * a stale entry *if* it matches client requirements
259 if (http
->onlyIfCached()) {
260 processOnlyIfCachedMiss();
264 http
->request
->flags
.refresh
= 1;
265 #if STORE_CLIENT_LIST_DEBUG
266 /* Prevent a race with the store client memory free routines
268 assert(storeClientIsThisAClient(sc
, this));
270 /* Prepare to make a new temporary request */
272 entry
= storeCreateEntry(url
,
273 http
->log_uri
, http
->request
->flags
, http
->request
->method
);
274 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
275 sc
= storeClientListAdd(entry
, this);
277 /* delay_id is already set on original store client */
278 sc
->setDelayId(DelayId::DelayClient(http
));
281 http
->request
->lastmod
= old_entry
->lastmod
;
282 debugs(88, 5, "clientReplyContext::processExpired : lastmod " << entry
->lastmod
);
283 http
->storeEntry(entry
);
284 assert(http
->out
.offset
== 0);
285 assert(http
->request
->clientConnectionManager
== http
->getConn());
288 * A refcounted pointer so that FwdState stays around as long as
289 * this clientReplyContext does
291 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
292 FwdState::fwdStart(conn
, http
->storeEntry(), http
->request
);
294 /* Register with storage manager to receive updates when data comes in. */
296 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
297 debugs(88, 0, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
300 /* start counting the length from 0 */
301 StoreIOBuffer
localTempBuffer(HTTP_REQBUF_SZ
, 0, tempbuf
);
302 storeClientCopy(sc
, entry
, localTempBuffer
, HandleIMSReply
, this);
308 clientReplyContext::sendClientUpstreamResponse()
310 StoreIOBuffer tempresult
;
311 removeStoreReference(&old_sc
, &old_entry
);
312 /* here the data to send is the data we just received */
313 tempBuffer
.offset
= 0;
315 /* sendMoreData tracks the offset as well.
316 * Force it back to zero */
318 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
319 /* TODO: provide sendMoreData with the ready parsed reply */
320 tempresult
.length
= reqsize
;
321 tempresult
.data
= tempbuf
;
322 sendMoreData(tempresult
);
326 clientReplyContext::HandleIMSReply(void *data
, StoreIOBuffer result
)
328 clientReplyContext
*context
= (clientReplyContext
*)data
;
329 context
->handleIMSReply(result
);
333 clientReplyContext::sendClientOldEntry()
335 /* Get the old request back */
337 /* here the data to send is in the next nodes buffers already */
338 assert(!EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
));
339 /* sendMoreData tracks the offset as well.
340 * Force it back to zero */
342 StoreIOBuffer
tempresult (reqsize
, reqofs
, next()->readBuffer
.data
);
343 sendMoreData(tempresult
);
346 /* This is the workhorse of the HandleIMSReply callback.
348 * It is called when we've got data back from the origin following our
349 * IMS request to revalidate a stale entry.
352 clientReplyContext::handleIMSReply(StoreIOBuffer result
)
357 debugs(88, 3, "handleIMSReply: " << http
->storeEntry()->url() << ", " << (long unsigned) result
.length
<< " bytes" );
359 if (http
->storeEntry() == NULL
)
362 if (result
.flags
.error
&& !EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
))
365 /* update size of the request */
366 reqsize
= result
.length
+ reqofs
;
368 const http_status status
= http
->storeEntry()->getReply()->sline
.status
;
370 // request to origin was aborted
371 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
372 debugs(88, 3, "handleIMSReply: request to origin aborted '" << http
->storeEntry()->url() << "', sending old entry to client" );
373 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
374 sendClientOldEntry();
377 HttpReply
*old_rep
= (HttpReply
*) old_entry
->getReply();
379 // origin replied 304
380 if (status
== HTTP_NOT_MODIFIED
) {
381 http
->logType
= LOG_TCP_REFRESH_UNMODIFIED
;
383 // update headers on existing entry
384 old_rep
->updateOnNotModified(http
->storeEntry()->getReply());
385 old_entry
->timestampsSet();
387 // if client sent IMS
389 if (http
->request
->flags
.ims
&& !old_entry
->modifiedSince(http
->request
)) {
390 // forward the 304 from origin
391 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and forwarding 304 to client");
392 sendClientUpstreamResponse();
394 // send existing entry, it's still valid
395 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and sending " <<
396 old_rep
->sline
.status
<< " to client");
397 sendClientOldEntry();
401 // origin replied with a non-error code
402 else if (status
> HTTP_STATUS_NONE
&& status
< HTTP_INTERNAL_SERVER_ERROR
) {
403 // forward response from origin
404 http
->logType
= LOG_TCP_REFRESH_MODIFIED
;
405 debugs(88, 3, "handleIMSReply: origin replied " << status
<< ", replacing existing entry and forwarding to client");
406 sendClientUpstreamResponse();
409 // origin replied with an error
410 else if (http
->request
->flags
.fail_on_validation_err
) {
411 http
->logType
= LOG_TCP_REFRESH_FAIL_ERR
;
412 debugs(88, 3, "handleIMSReply: origin replied with error " << status
<<
413 ", forwarding to client due to fail_on_validation_err");
414 sendClientUpstreamResponse();
416 // ignore and let client have old entry
417 http
->logType
= LOG_TCP_REFRESH_FAIL_OLD
;
418 debugs(88, 3, "handleIMSReply: origin replied with error " <<
419 status
<< ", sending old entry (" << old_rep
->sline
.status
<< ") to client");
420 sendClientOldEntry();
424 extern "C" CSR clientGetMoreData
;
425 extern "C" CSD clientReplyDetach
;
428 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
429 * have been parsed. Normally this should be a single call, but
430 * it might take more than one. As soon as we have the headers,
431 * we hand off to clientSendMoreData, processExpired, or
435 clientReplyContext::CacheHit(void *data
, StoreIOBuffer result
)
437 clientReplyContext
*context
= (clientReplyContext
*)data
;
438 context
->cacheHit(result
);
442 * Process a possible cache HIT.
445 clientReplyContext::cacheHit(StoreIOBuffer result
)
447 /** Ignore if the HIT object is being deleted. */
451 StoreEntry
*e
= http
->storeEntry();
453 HttpRequest
*r
= http
->request
;
455 debugs(88, 3, "clientCacheHit: " << http
->uri
<< ", " << result
.length
<< " bytes");
457 if (http
->storeEntry() == NULL
) {
458 debugs(88, 3, "clientCacheHit: request aborted");
460 } else if (result
.flags
.error
) {
461 /* swap in failure */
462 debugs(88, 3, "clientCacheHit: swapin failure for " << http
->uri
);
463 http
->logType
= LOG_TCP_SWAPFAIL_MISS
;
464 removeClientStoreReference(&sc
, http
);
469 if (result
.length
== 0) {
470 /* the store couldn't get enough data from the file for us to id the
473 /* treat as a miss */
474 http
->logType
= LOG_TCP_MISS
;
479 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
480 /* update size of the request */
481 reqsize
= result
.length
+ reqofs
;
484 * Got the headers, now grok them
486 assert(http
->logType
== LOG_TCP_HIT
);
488 if (strcmp(e
->mem_obj
->url
, urlCanonical(r
)) != 0) {
489 debugs(33, 1, "clientProcessHit: URL mismatch, '" << e
->mem_obj
->url
<< "' != '" << urlCanonical(r
) << "'");
494 switch (varyEvaluateMatch(e
, r
)) {
497 /* No variance detected. Continue as normal */
501 /* This is the correct entity for this request. Continue */
502 debugs(88, 2, "clientProcessHit: Vary MATCH!");
506 /* This is not the correct entity for this request. We need
507 * to requery the cache.
509 removeClientStoreReference(&sc
, http
);
511 /* Note: varyEvalyateMatch updates the request with vary information
512 * so we only get here once. (it also takes care of cancelling loops)
514 debugs(88, 2, "clientProcessHit: Vary detected!");
515 clientGetMoreData(ourNode
, http
);
519 /* varyEvaluateMatch found a object loop. Process as miss */
520 debugs(88, 1, "clientProcessHit: Vary object loop!");
525 if (r
->method
== METHOD_PURGE
) {
526 removeClientStoreReference(&sc
, http
);
532 if (e
->checkNegativeHit()
533 #if USE_HTTP_VIOLATIONS
534 && !r
->flags
.nocache_hack
537 http
->logType
= LOG_TCP_NEGATIVE_HIT
;
538 sendMoreData(result
);
539 } else if (!http
->flags
.internal
&& refreshCheckHTTP(e
, r
)) {
540 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
542 * We hold a stale copy; it needs to be validated
545 * The 'need_validation' flag is used to prevent forwarding
546 * loops between siblings. If our copy of the object is stale,
547 * then we should probably only use parents for the validation
548 * request. Otherwise two siblings could generate a loop if
549 * both have a stale version of the object.
551 r
->flags
.need_validation
= 1;
553 if (e
->lastmod
< 0) {
555 * Previous reply didn't have a Last-Modified header,
556 * we cannot revalidate it.
558 http
->logType
= LOG_TCP_MISS
;
560 } else if (r
->flags
.nocache
) {
562 * This did not match a refresh pattern that overrides no-cache
563 * we should honour the client no-cache header.
565 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
567 } else if (r
->protocol
== AnyP::PROTO_HTTP
) {
569 * Object needs to be revalidated
570 * XXX This could apply to FTP as well, if Last-Modified is known.
575 * We don't know how to re-validate other protocols. Handle
576 * them as if the object has expired.
578 http
->logType
= LOG_TCP_MISS
;
581 } else if (r
->conditional())
582 processConditional(result
);
585 * plain ol' cache hit
589 if (e
->store_status
!= STORE_OK
)
590 http
->logType
= LOG_TCP_MISS
;
593 if (e
->mem_status
== IN_MEMORY
)
594 http
->logType
= LOG_TCP_MEM_HIT
;
595 else if (Config
.onoff
.offline
)
596 http
->logType
= LOG_TCP_OFFLINE_HIT
;
598 sendMoreData(result
);
603 * Prepare to fetch the object as it's a cache miss of some kind.
606 clientReplyContext::processMiss()
608 char *url
= http
->uri
;
609 HttpRequest
*r
= http
->request
;
610 ErrorState
*err
= NULL
;
611 debugs(88, 4, "clientProcessMiss: '" << RequestMethodStr(r
->method
) << " " << url
<< "'");
614 * We might have a left-over StoreEntry from a failed cache hit
617 if (http
->storeEntry()) {
618 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
619 debugs(88, 0, "clientProcessMiss: miss on a special object (" << url
<< ").");
620 debugs(88, 0, "\tlog_type = " << Format::log_tags
[http
->logType
]);
621 http
->storeEntry()->dump(1);
624 removeClientStoreReference(&sc
, http
);
627 /** Check if its a PURGE request to be actioned. */
628 if (r
->method
== METHOD_PURGE
) {
633 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
634 if (r
->method
== METHOD_OTHER
) {
638 /** Check if 'only-if-cached' flag is set. Action if so. */
639 if (http
->onlyIfCached()) {
640 processOnlyIfCachedMiss();
644 /// Deny loops for accelerator and interceptor. TODO: deny in all modes?
645 if (r
->flags
.loopdetect
&&
646 (http
->flags
.accel
|| http
->flags
.intercepted
)) {
647 http
->al
.http
.code
= HTTP_FORBIDDEN
;
648 err
= clientBuildError(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
649 createStoreEntry(r
->method
, request_flags());
650 errorAppendEntry(http
->storeEntry(), err
);
651 triggerInitialStoreRead();
654 assert(http
->out
.offset
== 0);
655 createStoreEntry(r
->method
, r
->flags
);
656 triggerInitialStoreRead();
658 if (http
->redirect
.status
) {
659 HttpReply
*rep
= new HttpReply
;
660 #if LOG_TCP_REDIRECTS
662 http
->logType
= LOG_TCP_REDIRECT
;
665 http
->storeEntry()->releaseRequest();
666 rep
->redirect(http
->redirect
.status
, http
->redirect
.location
);
667 http
->storeEntry()->replaceHttpReply(rep
);
668 http
->storeEntry()->complete();
672 /** Check for internal requests. Update Protocol info if so. */
673 if (http
->flags
.internal
)
674 r
->protocol
= AnyP::PROTO_INTERNAL
;
676 assert(r
->clientConnectionManager
== http
->getConn());
678 /** Start forwarding to get the new object from network */
679 Comm::ConnectionPointer conn
= http
->getConn() != NULL
? http
->getConn()->clientConnection
: NULL
;
680 FwdState::fwdStart(conn
, http
->storeEntry(), r
);
685 * client issued a request with an only-if-cached cache-control directive;
686 * we did not find a cached object that can be returned without
687 * contacting other servers;
688 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
691 clientReplyContext::processOnlyIfCachedMiss()
693 debugs(88, 4, "clientProcessOnlyIfCachedMiss: '" <<
694 RequestMethodStr(http
->request
->method
) << " " << http
->uri
<< "'");
695 http
->al
.http
.code
= HTTP_GATEWAY_TIMEOUT
;
696 ErrorState
*err
= clientBuildError(ERR_ONLY_IF_CACHED_MISS
, HTTP_GATEWAY_TIMEOUT
, NULL
,
697 http
->getConn()->clientConnection
->remote
, http
->request
);
698 removeClientStoreReference(&sc
, http
);
702 /// process conditional request from client
704 clientReplyContext::processConditional(StoreIOBuffer
&result
)
706 StoreEntry
*const e
= http
->storeEntry();
708 if (e
->getReply()->sline
.status
!= HTTP_OK
) {
709 debugs(88, 4, "clientReplyContext::processConditional: Reply code " <<
710 e
->getReply()->sline
.status
<< " != 200");
711 http
->logType
= LOG_TCP_MISS
;
716 HttpRequest
&r
= *http
->request
;
718 if (r
.header
.has(HDR_IF_MATCH
) && !e
->hasIfMatchEtag(r
)) {
719 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
720 sendPreconditionFailedError();
724 bool matchedIfNoneMatch
= false;
725 if (r
.header
.has(HDR_IF_NONE_MATCH
)) {
726 if (!e
->hasIfNoneMatchEtag(r
)) {
727 // RFC 2616: ignore IMS if If-None-Match did not match
731 r
.header
.delById(HDR_IF_MODIFIED_SINCE
);
732 http
->logType
= LOG_TCP_MISS
;
733 sendMoreData(result
);
738 // RFC 2616: if If-None-Match matched and there is no IMS,
739 // reply with 304 Not Modified or 412 Precondition Failed
740 sendNotModifiedOrPreconditionFailedError();
744 // otherwise check IMS below to decide if we reply with 304 or 412
745 matchedIfNoneMatch
= true;
749 // handle If-Modified-Since requests from the client
750 if (e
->modifiedSince(&r
)) {
751 http
->logType
= LOG_TCP_IMS_HIT
;
752 sendMoreData(result
);
756 if (matchedIfNoneMatch
) {
757 // If-None-Match matched, reply with 304 Not Modified or
758 // 412 Precondition Failed
759 sendNotModifiedOrPreconditionFailedError();
763 // otherwise reply with 304 Not Modified
769 clientReplyContext::purgeRequestFindObjectToPurge()
771 /* Try to find a base entry */
772 http
->flags
.purging
= 1;
775 // TODO: can we use purgeAllCached() here instead of doing the
776 // getPublicByRequestMethod() dance?
777 StoreEntry::getPublicByRequestMethod(this, http
->request
, METHOD_GET
);
780 // Purges all entries with a given url
781 // TODO: move to SideAgent parent, when we have one
783 * We probably cannot purge Vary-affected responses because their MD5
784 * keys depend on vary headers.
787 purgeEntriesByUrl(HttpRequest
* req
, const char *url
)
790 bool get_or_head_sent
= false;
793 for (HttpRequestMethod
m(METHOD_NONE
); m
!= METHOD_ENUM_END
; ++m
) {
794 if (m
.isCacheble()) {
795 if (StoreEntry
*entry
= storeGetPublic(url
, m
)) {
796 debugs(88, 5, "purging " << RequestMethodStr(m
) << ' ' << url
);
798 neighborsHtcpClear(entry
, url
, req
, m
, HTCP_CLR_INVALIDATION
);
799 if (m
== METHOD_GET
|| m
== METHOD_HEAD
) {
800 get_or_head_sent
= true;
809 if (!get_or_head_sent
) {
810 neighborsHtcpClear(NULL
, url
, req
, HttpRequestMethod(METHOD_GET
), HTCP_CLR_INVALIDATION
);
816 clientReplyContext::purgeAllCached()
818 const char *url
= urlCanonical(http
->request
);
819 purgeEntriesByUrl(http
->request
, url
);
823 clientReplyContext::created(StoreEntry
*newEntry
)
825 if (lookingforstore
== 1)
826 purgeFoundGet(newEntry
);
827 else if (lookingforstore
== 2)
828 purgeFoundHead(newEntry
);
829 else if (lookingforstore
== 3)
830 purgeDoPurgeGet(newEntry
);
831 else if (lookingforstore
== 4)
832 purgeDoPurgeHead(newEntry
);
833 else if (lookingforstore
== 5)
834 identifyFoundObject(newEntry
);
838 clientReplyContext::purgeFoundGet(StoreEntry
*newEntry
)
840 if (newEntry
->isNull()) {
842 StoreEntry::getPublicByRequestMethod(this, http
->request
, METHOD_HEAD
);
844 purgeFoundObject (newEntry
);
848 clientReplyContext::purgeFoundHead(StoreEntry
*newEntry
)
850 if (newEntry
->isNull())
853 purgeFoundObject (newEntry
);
857 clientReplyContext::purgeFoundObject(StoreEntry
*entry
)
859 assert (entry
&& !entry
->isNull());
861 if (EBIT_TEST(entry
->flags
, ENTRY_SPECIAL
)) {
862 http
->logType
= LOG_TCP_DENIED
;
863 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
, NULL
,
864 http
->getConn()->clientConnection
->remote
, http
->request
);
869 StoreIOBuffer localTempBuffer
;
870 /* Swap in the metadata */
871 http
->storeEntry(entry
);
873 http
->storeEntry()->lock();
874 http
->storeEntry()->createMemObject(http
->uri
, http
->log_uri
);
876 http
->storeEntry()->mem_obj
->method
= http
->request
->method
;
878 sc
= storeClientListAdd(http
->storeEntry(), this);
880 http
->logType
= LOG_TCP_HIT
;
884 localTempBuffer
.offset
= http
->out
.offset
;
886 localTempBuffer
.length
= next()->readBuffer
.length
;
888 localTempBuffer
.data
= next()->readBuffer
.data
;
890 storeClientCopy(sc
, http
->storeEntry(),
891 localTempBuffer
, CacheHit
, this);
895 clientReplyContext::purgeRequest()
897 debugs(88, 3, "Config2.onoff.enable_purge = " <<
898 Config2
.onoff
.enable_purge
);
900 if (!Config2
.onoff
.enable_purge
) {
901 http
->logType
= LOG_TCP_DENIED
;
902 ErrorState
*err
= clientBuildError(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
907 /* Release both IP cache */
908 ipcacheInvalidate(http
->request
->GetHost());
910 if (!http
->flags
.purging
)
911 purgeRequestFindObjectToPurge();
917 clientReplyContext::purgeDoMissPurge()
919 http
->logType
= LOG_TCP_MISS
;
921 StoreEntry::getPublicByRequestMethod(this,http
->request
, METHOD_GET
);
925 clientReplyContext::purgeDoPurgeGet(StoreEntry
*newEntry
)
928 /* Move to new() when that is created */
929 purgeStatus
= HTTP_NOT_FOUND
;
931 if (!newEntry
->isNull()) {
932 /* Release the cached URI */
933 debugs(88, 4, "clientPurgeRequest: GET '" << newEntry
->url() << "'" );
935 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(METHOD_GET
), HTCP_CLR_PURGE
);
938 purgeStatus
= HTTP_OK
;
942 StoreEntry::getPublicByRequestMethod(this, http
->request
, METHOD_HEAD
);
946 clientReplyContext::purgeDoPurgeHead(StoreEntry
*newEntry
)
948 if (newEntry
&& !newEntry
->isNull()) {
949 debugs(88, 4, "clientPurgeRequest: HEAD '" << newEntry
->url() << "'" );
951 neighborsHtcpClear(newEntry
, NULL
, http
->request
, HttpRequestMethod(METHOD_HEAD
), HTCP_CLR_PURGE
);
954 purgeStatus
= HTTP_OK
;
957 /* And for Vary, release the base URI if none of the headers was included in the request */
959 if (http
->request
->vary_headers
960 && !strstr(http
->request
->vary_headers
, "=")) {
961 StoreEntry
*entry
= storeGetPublic(urlCanonical(http
->request
), METHOD_GET
);
964 debugs(88, 4, "clientPurgeRequest: Vary GET '" << entry
->url() << "'" );
966 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(METHOD_GET
), HTCP_CLR_PURGE
);
969 purgeStatus
= HTTP_OK
;
972 entry
= storeGetPublic(urlCanonical(http
->request
), METHOD_HEAD
);
975 debugs(88, 4, "clientPurgeRequest: Vary HEAD '" << entry
->url() << "'" );
977 neighborsHtcpClear(entry
, NULL
, http
->request
, HttpRequestMethod(METHOD_HEAD
), HTCP_CLR_PURGE
);
980 purgeStatus
= HTTP_OK
;
985 * Make a new entry to hold the reply to be written
988 /* FIXME: This doesn't need to go through the store. Simply
989 * push down the client chain
991 createStoreEntry(http
->request
->method
, request_flags());
993 triggerInitialStoreRead();
995 HttpReply
*rep
= new HttpReply
;
996 rep
->setHeaders(purgeStatus
, NULL
, NULL
, 0, 0, -1);
997 http
->storeEntry()->replaceHttpReply(rep
);
998 http
->storeEntry()->complete();
1002 clientReplyContext::traceReply(clientStreamNode
* node
)
1004 clientStreamNode
*nextNode
= (clientStreamNode
*)node
->node
.next
->data
;
1005 StoreIOBuffer localTempBuffer
;
1006 createStoreEntry(http
->request
->method
, request_flags());
1007 localTempBuffer
.offset
= nextNode
->readBuffer
.offset
+ headers_sz
;
1008 localTempBuffer
.length
= nextNode
->readBuffer
.length
;
1009 localTempBuffer
.data
= nextNode
->readBuffer
.data
;
1010 storeClientCopy(sc
, http
->storeEntry(),
1011 localTempBuffer
, SendMoreData
, this);
1012 http
->storeEntry()->releaseRequest();
1013 http
->storeEntry()->buffer();
1014 HttpReply
*rep
= new HttpReply
;
1015 rep
->setHeaders(HTTP_OK
, NULL
, "text/plain", http
->request
->prefixLen(), 0, squid_curtime
);
1016 http
->storeEntry()->replaceHttpReply(rep
);
1017 http
->request
->swapOut(http
->storeEntry());
1018 http
->storeEntry()->complete();
1021 #define SENDING_BODY 0
1022 #define SENDING_HDRSONLY 1
1024 clientReplyContext::checkTransferDone()
1026 StoreEntry
*entry
= http
->storeEntry();
1032 * For now, 'done_copying' is used for special cases like
1033 * Range and HEAD requests.
1035 if (http
->flags
.done_copying
)
1038 if (http
->request
->flags
.chunked_reply
&& !flags
.complete
) {
1039 // last-chunk was not sent
1044 * Handle STORE_OK objects.
1045 * objectLen(entry) will be set proprely.
1046 * RC: Does objectLen(entry) include the Headers?
1049 if (entry
->store_status
== STORE_OK
) {
1050 return storeOKTransferDone();
1052 return storeNotOKTransferDone();
1057 clientReplyContext::storeOKTransferDone() const
1059 assert(http
->storeEntry()->objectLen() >= 0);
1060 assert(http
->storeEntry()->objectLen() >= headers_sz
);
1061 if (http
->out
.offset
>= http
->storeEntry()->objectLen() - headers_sz
) {
1062 debugs(88,3,HERE
<< "storeOKTransferDone " <<
1063 " out.offset=" << http
->out
.offset
<<
1064 " objectLen()=" << http
->storeEntry()->objectLen() <<
1065 " headers_sz=" << headers_sz
);
1073 clientReplyContext::storeNotOKTransferDone() const
1076 * Now, handle STORE_PENDING objects
1078 MemObject
*mem
= http
->storeEntry()->mem_obj
;
1079 assert(mem
!= NULL
);
1080 assert(http
->request
!= NULL
);
1081 /* mem->reply was wrong because it uses the UPSTREAM header length!!! */
1082 HttpReply
const *curReply
= mem
->getReply();
1084 if (headers_sz
== 0)
1085 /* haven't found end of headers yet */
1089 * Figure out how much data we are supposed to send.
1090 * If we are sending a body and we don't have a content-length,
1091 * then we must wait for the object to become STORE_OK.
1093 if (curReply
->content_length
< 0)
1096 int64_t expectedLength
= curReply
->content_length
+ http
->out
.headers_sz
;
1098 if (http
->out
.size
< expectedLength
)
1101 debugs(88,3,HERE
<< "storeNotOKTransferDone " <<
1102 " out.size=" << http
->out
.size
<<
1103 " expectedLength=" << expectedLength
);
1109 /* A write has completed, what is the next status based on the
1110 * canonical request data?
1111 * 1 something is wrong
1112 * 0 nothing is wrong.
1116 clientHttpRequestStatus(int fd
, ClientHttpRequest
const *http
)
1118 #if SIZEOF_INT64_T == 4
1119 if (http
->out
.size
> 0x7FFF0000) {
1120 debugs(88, 1, "WARNING: closing FD " << fd
<< " to prevent out.size counter overflow");
1121 debugs(88, 1, "\tclient " << http
->getConn()->peer
);
1122 debugs(88, 1, "\treceived " << http
->out
.size
<< " bytes");
1123 debugs(88, 1, "\tURI " << http
->log_uri
);
1127 if (http
->out
.offset
> 0x7FFF0000) {
1128 debugs(88, 1, "WARNING: closing FD " << fd
< " to prevent out.offset counter overflow");
1129 debugs(88, 1, "\tclient " << http
->getConn()->peer
);
1130 debugs(88, 1, "\treceived " << http
->out
.size
<< " bytes, offset " << http
->out
.offset
);
1131 debugs(88, 1, "\tURI " << http
->log_uri
);
1140 * *http is a valid structure.
1141 * fd is either -1, or an open fd.
1143 * TODO: enumify this
1145 * This function is used by any http request sink, to determine the status
1148 clientStream_status_t
1149 clientReplyStatus(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1151 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1153 assert (context
->http
== http
);
1154 return context
->replyStatus();
1157 clientStream_status_t
1158 clientReplyContext::replyStatus()
1161 /* Here because lower nodes don't need it */
1163 if (http
->storeEntry() == NULL
) {
1164 debugs(88, 5, "clientReplyStatus: no storeEntry");
1165 return STREAM_FAILED
; /* yuck, but what can we do? */
1168 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) {
1169 /* TODO: Could upstream read errors (result.flags.error) be
1170 * lost, and result in undersize requests being considered
1171 * complete. Should we tcp reset such connections ?
1173 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
1174 return STREAM_FAILED
;
1177 if ((done
= checkTransferDone()) != 0 || flags
.complete
) {
1178 debugs(88, 5, "clientReplyStatus: transfer is DONE");
1179 /* Ok we're finished, but how? */
1181 const int64_t expectedBodySize
=
1182 http
->storeEntry()->getReply()->bodySize(http
->request
->method
);
1183 if (!http
->request
->flags
.proxy_keepalive
&& expectedBodySize
< 0) {
1184 debugs(88, 5, "clientReplyStatus: closing, content_length < 0");
1185 return STREAM_FAILED
;
1189 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
1190 return STREAM_FAILED
;
1193 if (expectedBodySize
>= 0 && !http
->gotEnough()) {
1194 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
1195 return STREAM_UNPLANNED_COMPLETE
;
1198 if (http
->request
->flags
.proxy_keepalive
) {
1199 debugs(88, 5, "clientReplyStatus: stream complete and can keepalive");
1200 return STREAM_COMPLETE
;
1203 debugs(88, 5, "clientReplyStatus: stream was not expected to complete!");
1204 return STREAM_UNPLANNED_COMPLETE
;
1207 // XXX: Should this be checked earlier? We could return above w/o checking.
1208 if (reply
->receivedBodyTooLarge(*http
->request
, http
->out
.offset
- 4096)) {
1209 /* 4096 is a margin for the HTTP headers included in out.offset */
1210 debugs(88, 5, "clientReplyStatus: client reply body is too large");
1211 return STREAM_FAILED
;
1217 /* Responses with no body will not have a content-type header,
1218 * which breaks the rep_mime_type acl, which
1219 * coincidentally, is the most common acl for reply access lists.
1220 * A better long term fix for this is to allow acl matchs on the various
1221 * status codes, and then supply a default ruleset that puts these
1222 * codes before any user defines access entries. That way the user
1223 * can choose to block these responses where appropriate, but won't get
1224 * mysterious breakages.
1227 clientReplyContext::alwaysAllowResponse(http_status sline
) const
1235 case HTTP_SWITCHING_PROTOCOLS
:
1237 case HTTP_PROCESSING
:
1239 case HTTP_NO_CONTENT
:
1241 case HTTP_NOT_MODIFIED
:
1253 * Generate the reply headers sent to client.
1255 * Filters out unwanted entries and hop-by-hop from original reply header
1256 * then adds extra entries if we have more info than origin server
1257 * then adds Squid specific entries
1260 clientReplyContext::buildReplyHeader()
1262 HttpHeader
*hdr
= &reply
->header
;
1263 int is_hit
= logTypeIsATcpHit(http
->logType
);
1264 HttpRequest
*request
= http
->request
;
1265 #if DONT_FILTER_THESE
1266 /* but you might want to if you run Squid as an HTTP accelerator */
1267 /* hdr->delById(HDR_ACCEPT_RANGES); */
1268 hdr
->delById(HDR_ETAG
);
1272 hdr
->delById(HDR_SET_COOKIE
);
1273 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
1275 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
1276 // remove the Proxy-Authenticate header
1277 if ( !request
->peer_login
|| (strcmp(request
->peer_login
,"PASS") != 0 && strcmp(request
->peer_login
,"PASSTHRU") != 0))
1278 reply
->header
.delById(HDR_PROXY_AUTHENTICATE
);
1280 reply
->header
.removeHopByHopEntries();
1282 // if (request->range)
1283 // clientBuildRangeHeader(http, reply);
1286 * Add a estimated Age header on cache hits.
1290 * Remove any existing Age header sent by upstream caches
1291 * (note that the existing header is passed along unmodified
1294 hdr
->delById(HDR_AGE
);
1296 * This adds the calculated object age. Note that the details of the
1297 * age calculation is performed by adjusting the timestamp in
1298 * StoreEntry::timestampsSet(), not here.
1301 // XXX: realy useless? or is there a bug now that this is detatched from the below if-sequence ?
1302 // looks like this pre-if was supposed to be the browser workaround...
1303 if (NULL
== http
->storeEntry())
1305 else if (http
->storeEntry()->timestamp
< 0)
1309 if (EBIT_TEST(http
->storeEntry()->flags
, ENTRY_SPECIAL
)) {
1310 hdr
->delById(HDR_DATE
);
1311 hdr
->insertTime(HDR_DATE
, squid_curtime
);
1312 } else if (http
->getConn() && http
->getConn()->port
->actAsOrigin
) {
1313 // Swap the Date: header to current time if we are simulating an origin
1314 HttpHeaderEntry
*h
= hdr
->findEntry(HDR_DATE
);
1316 hdr
->putExt("X-Origin-Date", h
->value
.termedBuf());
1317 hdr
->delById(HDR_DATE
);
1318 hdr
->insertTime(HDR_DATE
, squid_curtime
);
1319 h
= hdr
->findEntry(HDR_EXPIRES
);
1320 if (h
&& http
->storeEntry()->expires
>= 0) {
1321 hdr
->putExt("X-Origin-Expires", h
->value
.termedBuf());
1322 hdr
->delById(HDR_EXPIRES
);
1323 hdr
->insertTime(HDR_EXPIRES
, squid_curtime
+ http
->storeEntry()->expires
- http
->storeEntry()->timestamp
);
1325 if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1326 // put X-Cache-Age: instead of Age:
1328 snprintf(age
, sizeof(age
), "%ld", (long int) squid_curtime
- http
->storeEntry()->timestamp
);
1329 hdr
->putExt("X-Cache-Age", age
);
1331 } else if (http
->storeEntry()->timestamp
<= squid_curtime
) {
1332 hdr
->putInt(HDR_AGE
,
1333 squid_curtime
- http
->storeEntry()->timestamp
);
1334 /* Signal old objects. NB: rfc 2616 is not clear,
1335 * by implication, on whether we should do this to all
1336 * responses, or only cache hits.
1337 * 14.46 states it ONLY applys for heuristically caclulated
1338 * freshness values, 13.2.4 doesn't specify the same limitation.
1339 * We interpret RFC 2616 under the combination.
1341 /* TODO: if maxage or s-maxage is present, don't do this */
1343 if (squid_curtime
- http
->storeEntry()->timestamp
>= 86400) {
1345 snprintf (tbuf
, sizeof(tbuf
), "%s %s %s",
1347 "This cache hit is still fresh and more than 1 day old");
1348 hdr
->putStr(HDR_WARNING
, tbuf
);
1353 /* RFC 2616: Section 14.18
1355 * Add a Date: header if missing.
1356 * We have access to a clock therefore are required to amend any shortcoming in servers.
1358 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1360 if ( !hdr
->has(HDR_DATE
) ) {
1361 if (!http
->storeEntry())
1362 hdr
->insertTime(HDR_DATE
, squid_curtime
);
1363 else if (http
->storeEntry()->timestamp
> 0)
1364 hdr
->insertTime(HDR_DATE
, http
->storeEntry()->timestamp
);
1366 debugs(88,DBG_IMPORTANT
,"WARNING: An error inside Squid has caused an HTTP reply without Date:. Please report this:");
1367 /* dump something useful about the problem */
1368 http
->storeEntry()->dump(DBG_IMPORTANT
);
1372 // add Warnings required by RFC 2616 if serving a stale hit
1373 if (http
->request
->flags
.stale_if_hit
&& logTypeIsATcpHit(http
->logType
)) {
1374 hdr
->putWarning(110, "Response is stale");
1375 if (http
->request
->flags
.need_validation
)
1376 hdr
->putWarning(111, "Revalidation failed");
1379 /* Filter unproxyable authentication types */
1380 if (http
->logType
!= LOG_TCP_DENIED
&&
1381 hdr
->has(HDR_WWW_AUTHENTICATE
)) {
1382 HttpHeaderPos pos
= HttpHeaderInitPos
;
1385 int connection_auth_blocked
= 0;
1386 while ((e
= hdr
->getEntry(&pos
))) {
1387 if (e
->id
== HDR_WWW_AUTHENTICATE
) {
1388 const char *value
= e
->value
.rawBuf();
1390 if ((strncasecmp(value
, "NTLM", 4) == 0 &&
1391 (value
[4] == '\0' || value
[4] == ' '))
1393 (strncasecmp(value
, "Negotiate", 9) == 0 &&
1394 (value
[9] == '\0' || value
[9] == ' '))
1396 (strncasecmp(value
, "Kerberos", 8) == 0 &&
1397 (value
[8] == '\0' || value
[8] == ' '))) {
1398 if (request
->flags
.connection_auth_disabled
) {
1399 hdr
->delAt(pos
, connection_auth_blocked
);
1402 request
->flags
.must_keepalive
= 1;
1403 if (!request
->flags
.accelerated
&& !request
->flags
.intercepted
) {
1404 httpHeaderPutStrf(hdr
, HDR_PROXY_SUPPORT
, "Session-Based-Authentication");
1406 We send "[Proxy-]Connection: Proxy-Support" header to mark
1407 Proxy-Support as a hop-by-hop header for intermediaries that do not
1408 understand the semantics of this header. The RFC should have included
1409 this recommendation.
1411 httpHeaderPutStrf(hdr
, HDR_CONNECTION
, "Proxy-support");
1418 if (connection_auth_blocked
)
1423 /* Handle authentication headers */
1424 if (http
->logType
== LOG_TCP_DENIED
&&
1425 ( reply
->sline
.status
== HTTP_PROXY_AUTHENTICATION_REQUIRED
||
1426 reply
->sline
.status
== HTTP_UNAUTHORIZED
)
1428 /* Add authentication header */
1429 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1430 * depends on authenticate behaviour: all schemes to date send no extra
1431 * data on 407/401 responses, and do not check the accel state on 401/407
1434 authenticateFixHeader(reply
, request
->auth_user_request
, request
, 0, 1);
1435 } else if (request
->auth_user_request
!= NULL
)
1436 authenticateFixHeader(reply
, request
->auth_user_request
, request
, http
->flags
.accel
, 0);
1439 /* Append X-Cache */
1440 httpHeaderPutStrf(hdr
, HDR_X_CACHE
, "%s from %s",
1441 is_hit
? "HIT" : "MISS", getMyHostname());
1443 #if USE_CACHE_DIGESTS
1444 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1445 httpHeaderPutStrf(hdr
, HDR_X_CACHE_LOOKUP
, "%s from %s:%d",
1446 lookup_type
? lookup_type
: "NONE",
1447 getMyHostname(), getMyPort());
1451 const bool maySendChunkedReply
= !request
->multipartRangeRequest() &&
1452 (request
->http_ver
>= HttpVersion(1, 1));
1454 /* Check whether we should send keep-alive */
1455 if (!Config
.onoff
.error_pconns
&& reply
->sline
.status
>= 400 && !request
->flags
.must_keepalive
) {
1456 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
1457 request
->flags
.proxy_keepalive
= 0;
1458 } else if (!Config
.onoff
.client_pconns
&& !request
->flags
.must_keepalive
) {
1459 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
1460 request
->flags
.proxy_keepalive
= 0;
1461 } else if (request
->flags
.proxy_keepalive
&& shutting_down
) {
1462 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
1463 request
->flags
.proxy_keepalive
= 0;
1464 } else if (request
->flags
.connection_auth
&& !reply
->keep_alive
) {
1465 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
1466 request
->flags
.proxy_keepalive
= 0;
1467 } else if (reply
->bodySize(request
->method
) < 0 && !maySendChunkedReply
) {
1468 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
1469 request
->flags
.proxy_keepalive
= 0;
1470 } else if (fdUsageHigh()&& !request
->flags
.must_keepalive
) {
1471 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
1472 request
->flags
.proxy_keepalive
= 0;
1475 // Decide if we send chunked reply
1476 if (maySendChunkedReply
&&
1477 request
->flags
.proxy_keepalive
&&
1478 reply
->bodySize(request
->method
) < 0) {
1479 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
1480 request
->flags
.chunked_reply
= 1;
1481 hdr
->putStr(HDR_TRANSFER_ENCODING
, "chunked");
1485 if (Config
.onoff
.via
) {
1486 LOCAL_ARRAY(char, bbuf
, MAX_URL
+ 32);
1488 hdr
->getList(HDR_VIA
, &strVia
);
1489 snprintf(bbuf
, MAX_URL
+ 32, "%d.%d %s",
1490 reply
->sline
.version
.major
,
1491 reply
->sline
.version
.minor
,
1493 strListAdd(&strVia
, bbuf
, ',');
1494 hdr
->delById(HDR_VIA
);
1495 hdr
->putStr(HDR_VIA
, strVia
.termedBuf());
1497 /* Signal keep-alive or close explicitly */
1498 hdr
->putStr(HDR_CONNECTION
, request
->flags
.proxy_keepalive
? "keep-alive" : "close");
1500 #if ADD_X_REQUEST_URI
1502 * Knowing the URI of the request is useful when debugging persistent
1503 * connections in a client; we cannot guarantee the order of http headers,
1504 * but X-Request-URI is likely to be the very last header to ease use from a
1505 * debugger [hdr->entries.count-1].
1507 hdr
->putStr(HDR_X_REQUEST_URI
,
1508 http
->memOjbect()->url
? http
->memObject()->url
: http
->uri
);
1512 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1513 if ( hdr
->has(HDR_SURROGATE_CONTROL
) ) {
1514 if (!request
->header
.has(HDR_SURROGATE_CAPABILITY
)) {
1515 hdr
->delById(HDR_SURROGATE_CONTROL
);
1517 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1520 httpHdrMangleList(hdr
, request
, ROR_REPLY
);
1525 clientReplyContext::cloneReply()
1527 assert(reply
== NULL
);
1529 HttpReply
*rep
= http
->storeEntry()->getReply()->clone();
1531 reply
= HTTPMSGLOCK(rep
);
1533 if (reply
->sline
.protocol
== AnyP::PROTO_HTTP
) {
1534 /* RFC 2616 requires us to advertise our 1.1 version (but only on real HTTP traffic) */
1535 reply
->sline
.version
= HttpVersion(1,1);
1538 /* do header conversions */
1543 clientReplyContext::identifyStoreObject()
1545 HttpRequest
*r
= http
->request
;
1547 if (r
->flags
.cachable
|| r
->flags
.internal
) {
1548 lookingforstore
= 5;
1549 StoreEntry::getPublicByRequest (this, r
);
1551 identifyFoundObject (NullStoreEntry::getInstance());
1556 * Check state of the current StoreEntry object.
1557 * to see if we can determine the final status of the request.
1560 clientReplyContext::identifyFoundObject(StoreEntry
*newEntry
)
1562 StoreEntry
*e
= newEntry
;
1563 HttpRequest
*r
= http
->request
;
1565 /** \li If the entry received isNull() then we ignore it. */
1567 http
->storeEntry(NULL
);
1569 http
->storeEntry(e
);
1572 e
= http
->storeEntry();
1574 /* Release IP-cache entries on reload */
1575 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
1576 * 'invalidate' the cached IP entries for this request ???
1578 if (r
->flags
.nocache
) {
1582 ipcacheInvalidate(r
->GetHost());
1586 ipcacheInvalidateNegative(r
->GetHost());
1588 #endif /* USE_DNSSERVERS */
1592 #if USE_HTTP_VIOLATIONS
1594 else if (r
->flags
.nocache_hack
) {
1598 ipcacheInvalidate(r
->GetHost());
1602 ipcacheInvalidateNegative(r
->GetHost());
1604 #endif /* USE_DNSSERVERS */
1608 #endif /* USE_HTTP_VIOLATIONS */
1609 #if USE_CACHE_DIGESTS
1611 lookup_type
= http
->storeEntry() ? "HIT" : "MISS";
1615 if (NULL
== http
->storeEntry()) {
1616 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
1617 debugs(85, 3, "clientProcessRequest2: StoreEntry is NULL - MISS");
1618 http
->logType
= LOG_TCP_MISS
;
1623 if (Config
.onoff
.offline
) {
1624 /** \li If we are running in offline mode set to HIT */
1625 debugs(85, 3, "clientProcessRequest2: offline HIT");
1626 http
->logType
= LOG_TCP_HIT
;
1631 if (http
->redirect
.status
) {
1632 /** \li If redirection status is True force this to be a MISS */
1633 debugs(85, 3, "clientProcessRequest2: redirectStatus forced StoreEntry to NULL - MISS");
1634 http
->storeEntry(NULL
);
1635 http
->logType
= LOG_TCP_MISS
;
1640 if (!e
->validToSend()) {
1641 debugs(85, 3, "clientProcessRequest2: !storeEntryValidToSend MISS" );
1642 http
->storeEntry(NULL
);
1643 http
->logType
= LOG_TCP_MISS
;
1648 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1649 /* \li Special entries are always hits, no matter what the client says */
1650 debugs(85, 3, "clientProcessRequest2: ENTRY_SPECIAL HIT");
1651 http
->logType
= LOG_TCP_HIT
;
1656 if (r
->flags
.nocache
) {
1657 debugs(85, 3, "clientProcessRequest2: no-cache REFRESH MISS");
1658 http
->storeEntry(NULL
);
1659 http
->logType
= LOG_TCP_CLIENT_REFRESH_MISS
;
1664 debugs(85, 3, "clientProcessRequest2: default HIT");
1665 http
->logType
= LOG_TCP_HIT
;
1670 * Request more data from the store for the client Stream
1671 * This is *the* entry point to this module.
1674 * - This is the head of the list.
1675 * - There is at least one more node.
1676 * - Data context is not null
1679 clientGetMoreData(clientStreamNode
* aNode
, ClientHttpRequest
* http
)
1681 /* Test preconditions */
1682 assert(aNode
!= NULL
);
1683 assert(cbdataReferenceValid(aNode
));
1684 assert(aNode
->node
.prev
== NULL
);
1685 assert(aNode
->node
.next
!= NULL
);
1686 clientReplyContext
*context
= dynamic_cast<clientReplyContext
*>(aNode
->data
.getRaw());
1688 assert(context
->http
== http
);
1691 clientStreamNode
*next
= ( clientStreamNode
*)aNode
->node
.next
->data
;
1693 if (!context
->ourNode
)
1694 context
->ourNode
= aNode
;
1696 /* no cbdatareference, this is only used once, and safely */
1697 if (context
->flags
.storelogiccomplete
) {
1698 StoreIOBuffer tempBuffer
;
1699 tempBuffer
.offset
= next
->readBuffer
.offset
+ context
->headers_sz
;
1700 tempBuffer
.length
= next
->readBuffer
.length
;
1701 tempBuffer
.data
= next
->readBuffer
.data
;
1703 storeClientCopy(context
->sc
, http
->storeEntry(),
1704 tempBuffer
, clientReplyContext::SendMoreData
, context
);
1708 if (context
->http
->request
->method
== METHOD_PURGE
) {
1709 context
->purgeRequest();
1713 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
1715 if (context
->http
->request
->method
== METHOD_TRACE
) {
1716 if (context
->http
->request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0) {
1717 context
->traceReply(aNode
);
1721 /* continue forwarding, not finished yet. */
1722 http
->logType
= LOG_TCP_MISS
;
1724 context
->doGetMoreData();
1726 context
->identifyStoreObject();
1730 clientReplyContext::doGetMoreData()
1732 /* We still have to do store logic processing - vary, cache hit etc */
1733 if (http
->storeEntry() != NULL
) {
1734 /* someone found the object in the cache for us */
1735 StoreIOBuffer localTempBuffer
;
1737 http
->storeEntry()->lock();
1739 if (http
->storeEntry()->mem_obj
== NULL
) {
1741 * This if-block exists because we don't want to clobber
1742 * a preexiting mem_obj->method value if the mem_obj
1743 * already exists. For example, when a HEAD request
1744 * is a cache hit for a GET response, we want to keep
1745 * the method as GET.
1747 http
->storeEntry()->createMemObject(http
->uri
, http
->log_uri
);
1748 http
->storeEntry()->mem_obj
->method
= http
->request
->method
;
1751 sc
= storeClientListAdd(http
->storeEntry(), this);
1753 sc
->setDelayId(DelayId::DelayClient(http
));
1756 assert(http
->logType
== LOG_TCP_HIT
);
1758 /* guarantee nothing has been sent yet! */
1759 assert(http
->out
.size
== 0);
1760 assert(http
->out
.offset
== 0);
1762 if (Ip::Qos::TheConfig
.isHitTosActive()) {
1763 Ip::Qos::doTosLocalHit(http
->getConn()->clientConnection
);
1766 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
1767 Ip::Qos::doNfmarkLocalHit(http
->getConn()->clientConnection
);
1770 localTempBuffer
.offset
= reqofs
;
1771 localTempBuffer
.length
= getNextNode()->readBuffer
.length
;
1772 localTempBuffer
.data
= getNextNode()->readBuffer
.data
;
1773 storeClientCopy(sc
, http
->storeEntry(), localTempBuffer
, CacheHit
, this);
1775 /* MISS CASE, http->logType is already set! */
1780 /** The next node has removed itself from the stream. */
1782 clientReplyDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1784 /** detach from the stream */
1785 clientStreamDetach(node
, http
);
1789 * Accepts chunk of a http message in buf, parses prefix, filters headers and
1790 * such, writes processed message to the message recipient
1793 clientReplyContext::SendMoreData(void *data
, StoreIOBuffer result
)
1795 clientReplyContext
*context
= static_cast<clientReplyContext
*>(data
);
1796 context
->sendMoreData (result
);
1800 clientReplyContext::makeThisHead()
1802 /* At least, I think thats what this does */
1803 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1804 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1808 clientReplyContext::errorInStream(StoreIOBuffer
const &result
, size_t const &sizeToProcess
)const
1810 return /* aborted request */
1811 (http
->storeEntry() && EBIT_TEST(http
->storeEntry()->flags
, ENTRY_ABORTED
)) ||
1812 /* Upstream read error */ (result
.flags
.error
) ||
1813 /* Upstream EOF */ (sizeToProcess
== 0);
1817 clientReplyContext::sendStreamError(StoreIOBuffer
const &result
)
1819 /** call clientWriteComplete so the client socket gets closed
1821 * We call into the stream, because we don't know that there is a
1824 debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.");
1825 StoreIOBuffer localTempBuffer
;
1827 http
->request
->flags
.stream_error
= 1;
1828 localTempBuffer
.flags
.error
= result
.flags
.error
;
1829 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1834 clientReplyContext::pushStreamData(StoreIOBuffer
const &result
, char *source
)
1836 StoreIOBuffer localTempBuffer
;
1838 if (result
.length
== 0) {
1839 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
1843 assert(result
.offset
- headers_sz
== next()->readBuffer
.offset
);
1844 localTempBuffer
.offset
= result
.offset
- headers_sz
;
1845 localTempBuffer
.length
= result
.length
;
1847 if (localTempBuffer
.length
)
1848 localTempBuffer
.data
= source
;
1850 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
, http
, NULL
,
1855 clientReplyContext::next() const
1857 assert ( (clientStreamNode
*)http
->client_stream
.head
->next
->data
== getNextNode());
1858 return getNextNode();
1862 clientReplyContext::sendBodyTooLargeError()
1864 Ip::Address tmp_noaddr
;
1865 tmp_noaddr
.SetNoAddr(); // TODO: make a global const
1866 http
->logType
= LOG_TCP_DENIED_REPLY
;
1867 ErrorState
*err
= clientBuildError(ERR_TOO_BIG
, HTTP_FORBIDDEN
, NULL
,
1868 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
1870 removeClientStoreReference(&(sc
), http
);
1871 HTTPMSGUNLOCK(reply
);
1876 /// send 412 (Precondition Failed) to client
1878 clientReplyContext::sendPreconditionFailedError()
1880 http
->logType
= LOG_TCP_HIT
;
1881 ErrorState
*const err
=
1882 clientBuildError(ERR_PRECONDITION_FAILED
, HTTP_PRECONDITION_FAILED
,
1883 NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
1884 removeClientStoreReference(&sc
, http
);
1885 HTTPMSGUNLOCK(reply
);
1889 /// send 304 (Not Modified) to client
1891 clientReplyContext::sendNotModified()
1893 StoreEntry
*e
= http
->storeEntry();
1894 const time_t timestamp
= e
->timestamp
;
1895 HttpReply
*const temprep
= e
->getReply()->make304();
1896 http
->logType
= LOG_TCP_IMS_HIT
;
1897 removeClientStoreReference(&sc
, http
);
1898 createStoreEntry(http
->request
->method
, request_flags());
1899 e
= http
->storeEntry();
1900 // Copy timestamp from the original entry so the 304
1901 // reply has a meaningful Age: header.
1903 e
->timestamp
= timestamp
;
1904 e
->replaceHttpReply(temprep
);
1907 * TODO: why put this in the store and then serialise it and
1908 * then parse it again. Simply mark the request complete in
1909 * our context and write the reply struct to the client side.
1911 triggerInitialStoreRead();
1914 /// send 304 (Not Modified) or 412 (Precondition Failed) to client
1915 /// depending on request method
1917 clientReplyContext::sendNotModifiedOrPreconditionFailedError()
1919 if (http
->request
->method
== METHOD_GET
||
1920 http
->request
->method
== METHOD_HEAD
)
1923 sendPreconditionFailedError();
1927 clientReplyContext::processReplyAccess ()
1929 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
1932 /** Don't block our own responses or HTTP status messages */
1933 if (http
->logType
== LOG_TCP_DENIED
||
1934 http
->logType
== LOG_TCP_DENIED_REPLY
||
1935 alwaysAllowResponse(reply
->sline
.status
)) {
1936 headers_sz
= reply
->hdr_sz
;
1937 processReplyAccessResult(ACCESS_ALLOWED
);
1941 /** Check for reply to big error */
1942 if (reply
->expectedBodyTooLarge(*http
->request
)) {
1943 sendBodyTooLargeError();
1947 headers_sz
= reply
->hdr_sz
;
1949 /** check for absent access controls (permit by default) */
1950 if (!Config
.accessList
.reply
) {
1951 processReplyAccessResult(ACCESS_ALLOWED
);
1955 /** Process http_reply_access lists */
1956 ACLFilledChecklist
*replyChecklist
=
1957 clientAclChecklistCreate(Config
.accessList
.reply
, http
);
1958 replyChecklist
->reply
= HTTPMSGLOCK(reply
);
1959 replyChecklist
->nonBlockingCheck(ProcessReplyAccessResult
, this);
1963 clientReplyContext::ProcessReplyAccessResult(allow_t rv
, void *voidMe
)
1965 clientReplyContext
*me
= static_cast<clientReplyContext
*>(voidMe
);
1966 me
->processReplyAccessResult(rv
);
1970 clientReplyContext::processReplyAccessResult(const allow_t
&accessAllowed
)
1972 debugs(88, 2, "The reply for " << RequestMethodStr(http
->request
->method
)
1973 << " " << http
->uri
<< " is " << accessAllowed
<< ", because it matched '"
1974 << (AclMatchedName
? AclMatchedName
: "NO ACL's") << "'" );
1976 if (accessAllowed
!= ACCESS_ALLOWED
) {
1979 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, 1);
1981 http
->logType
= LOG_TCP_DENIED_REPLY
;
1983 if (page_id
== ERR_NONE
)
1984 page_id
= ERR_ACCESS_DENIED
;
1986 Ip::Address tmp_noaddr
;
1987 tmp_noaddr
.SetNoAddr();
1988 err
= clientBuildError(page_id
, HTTP_FORBIDDEN
, NULL
,
1989 http
->getConn() != NULL
? http
->getConn()->clientConnection
->remote
: tmp_noaddr
,
1992 removeClientStoreReference(&sc
, http
);
1994 HTTPMSGUNLOCK(reply
);
2002 /* Ok, the reply is allowed, */
2003 http
->loggingEntry(http
->storeEntry());
2005 ssize_t body_size
= reqofs
- reply
->hdr_sz
;
2006 if (body_size
< 0) {
2007 reqofs
= reply
->hdr_sz
;
2011 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
2012 (int) body_size
<< " bytes after " << reply
->hdr_sz
<<
2013 " bytes of headers");
2017 if (http
->flags
.accel
&& reply
->sline
.status
!= HTTP_FORBIDDEN
&&
2018 !alwaysAllowResponse(reply
->sline
.status
) &&
2019 esiEnableProcessing(reply
)) {
2020 debugs(88, 2, "Enabling ESI processing for " << http
->uri
);
2021 clientStreamInsertHead(&http
->client_stream
, esiStreamRead
,
2022 esiProcessStream
, esiStreamDetach
, esiStreamStatus
, NULL
);
2027 if (http
->request
->method
== METHOD_HEAD
) {
2028 /* do not forward body for HEAD replies */
2030 http
->flags
.done_copying
= 1;
2034 assert (!flags
.headersSent
);
2035 flags
.headersSent
= true;
2037 StoreIOBuffer localTempBuffer
;
2038 char *buf
= next()->readBuffer
.data
;
2039 char *body_buf
= buf
+ reply
->hdr_sz
;
2041 //Server side may disable ranges under some circumstances.
2043 if ((!http
->request
->range
))
2044 next()->readBuffer
.offset
= 0;
2046 body_buf
-= next()->readBuffer
.offset
;
2048 if (next()->readBuffer
.offset
!= 0) {
2049 if (next()->readBuffer
.offset
> body_size
) {
2050 /* Can't use any of the body we received. send nothing */
2051 localTempBuffer
.length
= 0;
2052 localTempBuffer
.data
= NULL
;
2054 localTempBuffer
.length
= body_size
- next()->readBuffer
.offset
;
2055 localTempBuffer
.data
= body_buf
+ next()->readBuffer
.offset
;
2058 localTempBuffer
.length
= body_size
;
2059 localTempBuffer
.data
= body_buf
;
2062 /* TODO??: move the data in the buffer back by the request header size */
2063 clientStreamCallback((clientStreamNode
*)http
->client_stream
.head
->data
,
2064 http
, reply
, localTempBuffer
);
2070 clientReplyContext::sendMoreData (StoreIOBuffer result
)
2075 StoreEntry
*entry
= http
->storeEntry();
2077 ConnStateData
* conn
= http
->getConn();
2079 if (conn
== NULL
|| !conn
->isOpen()) {
2080 // too late, our conn is closing
2081 // TODO: should we also quit?
2082 debugs(33,3, HERE
<< "not sending more data to a closing " << conn
->clientConnection
);
2086 char *buf
= next()->readBuffer
.data
;
2088 if (buf
!= result
.data
) {
2089 /* we've got to copy some data */
2090 assert(result
.length
<= next()->readBuffer
.length
);
2091 memcpy(buf
, result
.data
, result
.length
);
2094 if (reqofs
==0 && !logTypeIsATcpHit(http
->logType
) && Comm::IsConnOpen(conn
->clientConnection
)) {
2095 if (Ip::Qos::TheConfig
.isHitTosActive()) {
2096 Ip::Qos::doTosLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2098 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
2099 Ip::Qos::doNfmarkLocalMiss(conn
->clientConnection
, http
->request
->hier
.code
);
2103 /* We've got the final data to start pushing... */
2104 flags
.storelogiccomplete
= 1;
2106 reqofs
+= result
.length
;
2108 assert(reqofs
<= HTTP_REQBUF_SZ
|| flags
.headersSent
);
2110 assert(http
->request
!= NULL
);
2112 /* ESI TODO: remove this assert once everything is stable */
2113 assert(http
->client_stream
.head
->data
2114 && cbdataReferenceValid(http
->client_stream
.head
->data
));
2118 debugs(88, 5, "clientReplyContext::sendMoreData: " << http
->uri
<< ", " <<
2119 reqofs
<< " bytes (" << result
.length
<<
2121 debugs(88, 5, "clientReplyContext::sendMoreData:"
2122 << conn
->clientConnection
<<
2123 " '" << entry
->url() << "'" <<
2124 " out.offset=" << http
->out
.offset
);
2126 /* update size of the request */
2129 if (errorInStream(result
, reqofs
)) {
2130 sendStreamError(result
);
2134 if (flags
.headersSent
) {
2135 pushStreamData (result
, buf
);
2141 /* handle headers */
2143 if (Config
.onoff
.log_mime_hdrs
) {
2146 if ((k
= headersEnd(buf
, reqofs
))) {
2147 safe_free(http
->al
.headers
.reply
);
2148 http
->al
.headers
.reply
= (char *)xcalloc(k
+ 1, 1);
2149 xstrncpy(http
->al
.headers
.reply
, buf
, k
);
2153 holdingBuffer
= result
;
2154 processReplyAccess();
2160 /* Using this breaks the client layering just a little!
2163 clientReplyContext::createStoreEntry(const HttpRequestMethod
& m
, request_flags reqFlags
)
2165 assert(http
!= NULL
);
2167 * For erroneous requests, we might not have a h->request,
2168 * so make a fake one.
2171 if (http
->request
== NULL
)
2172 http
->request
= HTTPMSGLOCK(new HttpRequest(m
, AnyP::PROTO_NONE
, null_string
));
2174 StoreEntry
*e
= storeCreateEntry(http
->uri
, http
->log_uri
, reqFlags
, m
);
2176 sc
= storeClientListAdd(e
, this);
2179 sc
->setDelayId(DelayId::DelayClient(http
));
2186 /* I don't think this is actually needed! -- adrian */
2187 /* http->reqbuf = http->norm_reqbuf; */
2188 // assert(http->reqbuf == http->norm_reqbuf);
2189 /* The next line is illegal because we don't know if the client stream
2190 * buffers have been set up
2192 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2193 // SendMoreData, this);
2194 /* So, we mark the store logic as complete */
2195 flags
.storelogiccomplete
= 1;
2197 /* and get the caller to request a read, from whereever they are */
2198 /* NOTE: after ANY data flows down the pipe, even one step,
2199 * this function CAN NOT be used to manage errors
2201 http
->storeEntry(e
);
2205 clientBuildError(err_type page_id
, http_status status
, char const *url
,
2206 Ip::Address
&src_addr
, HttpRequest
* request
)
2208 ErrorState
*err
= errorCon(page_id
, status
, request
);
2209 err
->src_addr
= src_addr
;
2212 err
->url
= xstrdup(url
);