]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_reply.cc
SourceLayout: shuffle StatusCode.h to http/StatusCode.h
[thirdparty/squid.git] / src / client_side_reply.cc
CommitLineData
edce4d98 1/*
edce4d98 2 * DEBUG: section 88 Client-side Reply Routines
3 * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c)
4 *
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
7 *
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.
16 *
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.
26ac0430 21 *
edce4d98 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.
26ac0430 26 *
edce4d98 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.
30 *
31 */
f7f3304a 32#include "squid.h"
b7ac5457
AJ
33#include "acl/FilledChecklist.h"
34#include "acl/Gadgets.h"
65d448bc 35#include "anyp/PortCfg.h"
0655fa4d 36#include "client_side_reply.h"
582c2af2 37#include "client_side.h"
c8be6d7b 38#include "clientStream.h"
582c2af2 39#include "dlink.h"
b7ac5457 40#include "errorpage.h"
c4ad1349 41#include "fd.h"
7172612f 42#include "fde.h"
31971e6a 43#include "format/Token.h"
582c2af2
FC
44#include "forward.h"
45#include "globals.h"
46#include "globals.h"
a5bac1d2 47#include "HttpHeaderTools.h"
b7ac5457
AJ
48#include "HttpReply.h"
49#include "HttpRequest.h"
50#include "ip/QosConfig.h"
714e68b7 51#include "ipcache.h"
1c7ae5ff 52#include "log/access_log.h"
b7ac5457 53#include "MemObject.h"
b6149797 54#include "mime_header.h"
f0ba2534 55#include "neighbors.h"
c6f15d40 56#include "refresh.h"
f206b652 57#include "RequestFlags.h"
4d5904f7 58#include "SquidConfig.h"
985c86bc 59#include "SquidTime.h"
b7ac5457 60#include "Store.h"
582c2af2 61#include "StoreClient.h"
28204b3b 62#include "StrList.h"
4e540555 63#include "tools.h"
b1bd952a 64#include "URL.h"
582c2af2
FC
65#if USE_AUTH
66#include "auth/UserRequest.h"
67#endif
68#if USE_DELAY_POOLS
69#include "DelayPools.h"
70#endif
71#if USE_SQUID_ESI
72#include "esi/Esi.h"
73#endif
e6ccf245 74
0655fa4d 75CBDATA_CLASS_INIT(clientReplyContext);
edce4d98 76
edce4d98 77/* Local functions */
e6ccf245 78extern "C" CSS clientReplyStatus;
955394ce 79ErrorState *clientBuildError(err_type, Http::StatusCode, char const *, Ip::Address &, HttpRequest *);
edce4d98 80
edce4d98 81/* privates */
edce4d98 82
0655fa4d 83clientReplyContext::~clientReplyContext()
edce4d98 84{
50c09fc4 85 deleting = true;
86 /* This may trigger a callback back into SendMoreData as the cbdata
87 * is still valid
88 */
86a2f789 89 removeClientStoreReference(&sc, http);
edce4d98 90 /* old_entry might still be set if we didn't yet get the reply
0655fa4d 91 * code in HandleIMSReply() */
92 removeStoreReference(&old_sc, &old_entry);
93 safe_free(tempBuffer.data);
94 cbdataReferenceDone(http);
2b7d324b 95 HTTPMSGUNLOCK(reply);
edce4d98 96}
97
59a1efb2 98clientReplyContext::clientReplyContext(ClientHttpRequest *clientContext) : http (cbdataReference(clientContext)), old_entry (NULL), old_sc(NULL), deleting(false)
0655fa4d 99{}
edce4d98 100
a5c8d64d
AJ
101/** Create an error in the store awaiting the client side to read it.
102 *
103 * This may be better placed in the clientStream logic, but it has not been
0655fa4d 104 * relocated there yet
105 */
edce4d98 106void
0655fa4d 107clientReplyContext::setReplyToError(
955394ce 108 err_type err, Http::StatusCode status, const HttpRequestMethod& method, char const *uri,
b7ac5457 109 Ip::Address &addr, HttpRequest * failedrequest, const char *unparsedrequest,
2f1431ea 110#if USE_AUTH
c7baff40 111 Auth::UserRequest::Pointer auth_user_request
2f1431ea 112#else
9d2b8284 113 void*
2f1431ea 114#endif
74174c03 115)
edce4d98 116{
a33a428a 117 ErrorState *errstate = clientBuildError(err, status, uri, addr, failedrequest);
62e76326 118
edce4d98 119 if (unparsedrequest)
62e76326 120 errstate->request_hdrs = xstrdup(unparsedrequest);
edce4d98 121
8eb0a7ee
CT
122#if USE_AUTH
123 errstate->auth_user_request = auth_user_request;
124#endif
125 setReplyToError(method, errstate);
126}
127
128void clientReplyContext::setReplyToError(const HttpRequestMethod& method, ErrorState *errstate)
129{
955394ce 130 if (errstate->httpStatus == Http::scNotImplemented && http->request)
62e76326 131 /* prevent confusion over whether we default to persistent or not */
e857372a 132 http->request->flags.proxyKeepalive = false;
62e76326 133
41ebd397 134 http->al->http.code = errstate->httpStatus;
edce4d98 135
f206b652 136 createStoreEntry(method, RequestFlags());
edce4d98 137 assert(errstate->callback_data == NULL);
86a2f789 138 errorAppendEntry(http->storeEntry(), errstate);
edce4d98 139 /* Now the caller reads to get this */
140}
141
061bbdec
CT
142void clientReplyContext::setReplyToStoreEntry(StoreEntry *entry)
143{
cb9060be 144 entry->lock(); // removeClientStoreReference() unlocks
061bbdec
CT
145 sc = storeClientListAdd(entry, this);
146#if USE_DELAY_POOLS
147 sc->setDelayId(DelayId::DelayClient(http));
148#endif
149 reqofs = 0;
150 reqsize = 0;
151 flags.storelogiccomplete = 1;
152 http->storeEntry(entry);
153}
154
edce4d98 155void
0655fa4d 156clientReplyContext::removeStoreReference(store_client ** scp,
157 StoreEntry ** ep)
edce4d98 158{
159 StoreEntry *e;
e4ae841b 160 store_client *sc_tmp = *scp;
62e76326 161
edce4d98 162 if ((e = *ep) != NULL) {
62e76326 163 *ep = NULL;
e4ae841b 164 storeUnregister(sc_tmp, e, this);
62e76326 165 *scp = NULL;
97b5e68f 166 e->unlock();
edce4d98 167 }
168}
169
86a2f789 170void
8bcf08e0 171clientReplyContext::removeClientStoreReference(store_client **scp, ClientHttpRequest *aHttpRequest)
86a2f789 172{
8bcf08e0 173 StoreEntry *reference = aHttpRequest->storeEntry();
86a2f789 174 removeStoreReference(scp, &reference);
8bcf08e0 175 aHttpRequest->storeEntry(reference);
86a2f789 176}
177
e6ccf245 178void *
a695955b 179clientReplyContext::operator new (size_t byteCount)
e6ccf245 180{
181 /* derived classes with different sizes must implement their own new */
182 assert (byteCount == sizeof (clientReplyContext));
0655fa4d 183 CBDATA_INIT_TYPE(clientReplyContext);
e6ccf245 184 return cbdataAlloc(clientReplyContext);
185}
186
187void
188clientReplyContext::operator delete (void *address)
189{
a50bfe93 190 clientReplyContext * tmp = (clientReplyContext *)address;
191 cbdataFree (tmp);
e6ccf245 192}
193
edce4d98 194void
0655fa4d 195clientReplyContext::saveState()
edce4d98 196{
e6ccf245 197 assert(old_sc == NULL);
bf8fe701 198 debugs(88, 3, "clientReplyContext::saveState: saving store context");
86a2f789 199 old_entry = http->storeEntry();
e6ccf245 200 old_sc = sc;
201 old_reqsize = reqsize;
202 tempBuffer.offset = reqofs;
edce4d98 203 /* Prevent accessing the now saved entries */
86a2f789 204 http->storeEntry(NULL);
e6ccf245 205 sc = NULL;
206 reqsize = 0;
207 reqofs = 0;
edce4d98 208}
209
210void
0655fa4d 211clientReplyContext::restoreState()
edce4d98 212{
e6ccf245 213 assert(old_sc != NULL);
bf8fe701 214 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
86a2f789 215 removeClientStoreReference(&sc, http);
216 http->storeEntry(old_entry);
e6ccf245 217 sc = old_sc;
218 reqsize = old_reqsize;
219 reqofs = tempBuffer.offset;
edce4d98 220 /* Prevent accessed the old saved entries */
0655fa4d 221 old_entry = NULL;
e6ccf245 222 old_sc = NULL;
223 old_reqsize = 0;
224 tempBuffer.offset = 0;
c8be6d7b 225}
226
227void
0655fa4d 228clientReplyContext::startError(ErrorState * err)
c8be6d7b 229{
f206b652 230 createStoreEntry(http->request->method, RequestFlags());
0655fa4d 231 triggerInitialStoreRead();
86a2f789 232 errorAppendEntry(http->storeEntry(), err);
edce4d98 233}
234
e6ccf245 235clientStreamNode *
528b2c61 236clientReplyContext::getNextNode() const
e6ccf245 237{
62e76326 238 return (clientStreamNode *)ourNode->node.next->data;
e6ccf245 239}
240
62e76326 241/* This function is wrong - the client parameters don't include the
528b2c61 242 * header offset
243 */
c8be6d7b 244void
0655fa4d 245clientReplyContext::triggerInitialStoreRead()
c8be6d7b 246{
0655fa4d 247 /* when confident, 0 becomes reqofs, and then this factors into
26ac0430 248 * startSendProcess
528b2c61 249 */
0655fa4d 250 assert(reqofs == 0);
8bcf08e0
FC
251 StoreIOBuffer localTempBuffer (next()->readBuffer.length, 0, next()->readBuffer.data);
252 storeClientCopy(sc, http->storeEntry(), localTempBuffer, SendMoreData, this);
c8be6d7b 253}
edce4d98 254
255/* there is an expired entry in the store.
256 * setup a temporary buffer area and perform an IMS to the origin
257 */
0655fa4d 258void
259clientReplyContext::processExpired()
edce4d98 260{
a8a0b1c2 261 const char *url = storeId();
edce4d98 262 StoreEntry *entry = NULL;
bf8fe701 263 debugs(88, 3, "clientReplyContext::processExpired: '" << http->uri << "'");
86a2f789 264 assert(http->storeEntry()->lastmod >= 0);
edce4d98 265 /*
266 * check if we are allowed to contact other servers
26ac0430 267 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
edce4d98 268 * a stale entry *if* it matches client requirements
269 */
62e76326 270
0655fa4d 271 if (http->onlyIfCached()) {
272 processOnlyIfCachedMiss();
62e76326 273 return;
edce4d98 274 }
62e76326 275
e857372a 276 http->request->flags.refresh = true;
edce4d98 277#if STORE_CLIENT_LIST_DEBUG
c8be6d7b 278 /* Prevent a race with the store client memory free routines
edce4d98 279 */
0655fa4d 280 assert(storeClientIsThisAClient(sc, this));
edce4d98 281#endif
282 /* Prepare to make a new temporary request */
0655fa4d 283 saveState();
edce4d98 284 entry = storeCreateEntry(url,
62e76326 285 http->log_uri, http->request->flags, http->request->method);
34266cde 286 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
0655fa4d 287 sc = storeClientListAdd(entry, this);
9a0a18de 288#if USE_DELAY_POOLS
edce4d98 289 /* delay_id is already set on original store client */
0655fa4d 290 sc->setDelayId(DelayId::DelayClient(http));
edce4d98 291#endif
62e76326 292
0655fa4d 293 http->request->lastmod = old_entry->lastmod;
4a7a3d56 294 debugs(88, 5, "clientReplyContext::processExpired : lastmod " << entry->lastmod );
86a2f789 295 http->storeEntry(entry);
c8be6d7b 296 assert(http->out.offset == 0);
9174ba3d 297 assert(http->request->clientConnectionManager == http->getConn());
655daa06 298
b2d22df6 299 /*
300 * A refcounted pointer so that FwdState stays around as long as
301 * this clientReplyContext does
302 */
73c36fd9 303 Comm::ConnectionPointer conn = http->getConn() != NULL ? http->getConn()->clientConnection : NULL;
4bf68cfa 304 FwdState::Start(conn, http->storeEntry(), http->request, http->al);
62e76326 305
edce4d98 306 /* Register with storage manager to receive updates when data comes in. */
62e76326 307
edce4d98 308 if (EBIT_TEST(entry->flags, ENTRY_ABORTED))
fa84c01d 309 debugs(88, DBG_CRITICAL, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
62e76326 310
c8be6d7b 311 {
62e76326 312 /* start counting the length from 0 */
8bcf08e0
FC
313 StoreIOBuffer localTempBuffer(HTTP_REQBUF_SZ, 0, tempbuf);
314 storeClientCopy(sc, entry, localTempBuffer, HandleIMSReply, this);
edce4d98 315 }
316}
317
528b2c61 318void
319clientReplyContext::sendClientUpstreamResponse()
320{
321 StoreIOBuffer tempresult;
0655fa4d 322 removeStoreReference(&old_sc, &old_entry);
2324cda2 323 /* here the data to send is the data we just received */
528b2c61 324 tempBuffer.offset = 0;
325 old_reqsize = 0;
0655fa4d 326 /* sendMoreData tracks the offset as well.
528b2c61 327 * Force it back to zero */
328 reqofs = 0;
86a2f789 329 assert(!EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED));
0655fa4d 330 /* TODO: provide sendMoreData with the ready parsed reply */
528b2c61 331 tempresult.length = reqsize;
332 tempresult.data = tempbuf;
0655fa4d 333 sendMoreData(tempresult);
528b2c61 334}
335
edce4d98 336void
0655fa4d 337clientReplyContext::HandleIMSReply(void *data, StoreIOBuffer result)
edce4d98 338{
e6ccf245 339 clientReplyContext *context = (clientReplyContext *)data;
0655fa4d 340 context->handleIMSReply(result);
341}
62e76326 342
0655fa4d 343void
344clientReplyContext::sendClientOldEntry()
345{
346 /* Get the old request back */
347 restoreState();
348 /* here the data to send is in the next nodes buffers already */
86a2f789 349 assert(!EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED));
0655fa4d 350 /* sendMoreData tracks the offset as well.
351 * Force it back to zero */
352 reqofs = 0;
353 StoreIOBuffer tempresult (reqsize, reqofs, next()->readBuffer.data);
354 sendMoreData(tempresult);
355}
62e76326 356
1d7ab0f4 357/* This is the workhorse of the HandleIMSReply callback.
358 *
359 * It is called when we've got data back from the origin following our
360 * IMS request to revalidate a stale entry.
361 */
0655fa4d 362void
1d7ab0f4 363clientReplyContext::handleIMSReply(StoreIOBuffer result)
0655fa4d 364{
1d7ab0f4 365 if (deleting)
366 return;
62e76326 367
bf8fe701 368 debugs(88, 3, "handleIMSReply: " << http->storeEntry()->url() << ", " << (long unsigned) result.length << " bytes" );
62e76326 369
1d7ab0f4 370 if (http->storeEntry() == NULL)
371 return;
07947ad8 372
1d7ab0f4 373 if (result.flags.error && !EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED))
374 return;
62e76326 375
1d7ab0f4 376 /* update size of the request */
377 reqsize = result.length + reqofs;
62e76326 378
955394ce 379 const Http::StatusCode status = http->storeEntry()->getReply()->sline.status;
62e76326 380
1d7ab0f4 381 // request to origin was aborted
382 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) {
bf8fe701 383 debugs(88, 3, "handleIMSReply: request to origin aborted '" << http->storeEntry()->url() << "', sending old entry to client" );
7948b784 384 http->logType = LOG_TCP_REFRESH_FAIL_OLD;
1d7ab0f4 385 sendClientOldEntry();
0655fa4d 386 }
62e76326 387
b297bcd0 388 HttpReply *old_rep = (HttpReply *) old_entry->getReply();
62e76326 389
b297bcd0 390 // origin replied 304
955394ce 391 if (status == Http::scNotModified) {
26ac0430 392 http->logType = LOG_TCP_REFRESH_UNMODIFIED;
e857372a 393 http->request->flags.staleIfHit = false; // old_entry is no longer stale
045a76ab 394
26ac0430 395 // update headers on existing entry
4802f60d 396 old_rep->updateOnNotModified(http->storeEntry()->getReply());
26ac0430 397 old_entry->timestampsSet();
62e76326 398
26ac0430 399 // if client sent IMS
62e76326 400
45e5102d 401 if (http->request->flags.ims && !old_entry->modifiedSince(http->request)) {
26ac0430
AJ
402 // forward the 304 from origin
403 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and forwarding 304 to client");
404 sendClientUpstreamResponse();
405 } else {
406 // send existing entry, it's still valid
407 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and sending " <<
4802f60d 408 old_rep->sline.status << " to client");
26ac0430
AJ
409 sendClientOldEntry();
410 }
b297bcd0 411 }
62e76326 412
b297bcd0 413 // origin replied with a non-error code
955394ce 414 else if (status > Http::scNone && status < Http::scInternalServerError) {
26ac0430
AJ
415 // forward response from origin
416 http->logType = LOG_TCP_REFRESH_MODIFIED;
417 debugs(88, 3, "handleIMSReply: origin replied " << status << ", replacing existing entry and forwarding to client");
418 sendClientUpstreamResponse();
b297bcd0 419 }
62e76326 420
b297bcd0 421 // origin replied with an error
450fe1cb 422 else if (http->request->flags.failOnValidationError) {
7948b784
AR
423 http->logType = LOG_TCP_REFRESH_FAIL_ERR;
424 debugs(88, 3, "handleIMSReply: origin replied with error " << status <<
425 ", forwarding to client due to fail_on_validation_err");
426 sendClientUpstreamResponse();
427 } else {
26ac0430 428 // ignore and let client have old entry
7948b784 429 http->logType = LOG_TCP_REFRESH_FAIL_OLD;
26ac0430
AJ
430 debugs(88, 3, "handleIMSReply: origin replied with error " <<
431 status << ", sending old entry (" << old_rep->sline.status << ") to client");
432 sendClientOldEntry();
1d7ab0f4 433 }
edce4d98 434}
435
82afb125
FC
436SQUIDCEXTERN CSR clientGetMoreData;
437SQUIDCEXTERN CSD clientReplyDetach;
edce4d98 438
7d5f62a4
AJ
439/**
440 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
edce4d98 441 * have been parsed. Normally this should be a single call, but
442 * it might take more than one. As soon as we have the headers,
0655fa4d 443 * we hand off to clientSendMoreData, processExpired, or
444 * processMiss.
edce4d98 445 */
446void
0655fa4d 447clientReplyContext::CacheHit(void *data, StoreIOBuffer result)
edce4d98 448{
e6ccf245 449 clientReplyContext *context = (clientReplyContext *)data;
7d5f62a4 450 context->cacheHit(result);
0655fa4d 451}
452
7d5f62a4
AJ
453/**
454 * Process a possible cache HIT.
455 */
0655fa4d 456void
457clientReplyContext::cacheHit(StoreIOBuffer result)
458{
7d5f62a4 459 /** Ignore if the HIT object is being deleted. */
045a76ab 460 if (deleting)
461 return;
462
86a2f789 463 StoreEntry *e = http->storeEntry();
045a76ab 464
190154cf 465 HttpRequest *r = http->request;
045a76ab 466
4a7a3d56 467 debugs(88, 3, "clientCacheHit: " << http->uri << ", " << result.length << " bytes");
62e76326 468
86a2f789 469 if (http->storeEntry() == NULL) {
bf8fe701 470 debugs(88, 3, "clientCacheHit: request aborted");
62e76326 471 return;
c8be6d7b 472 } else if (result.flags.error) {
62e76326 473 /* swap in failure */
bf8fe701 474 debugs(88, 3, "clientCacheHit: swapin failure for " << http->uri);
62e76326 475 http->logType = LOG_TCP_SWAPFAIL_MISS;
86a2f789 476 removeClientStoreReference(&sc, http);
0655fa4d 477 processMiss();
62e76326 478 return;
edce4d98 479 }
62e76326 480
d3b3ab85 481 if (result.length == 0) {
62e76326 482 /* the store couldn't get enough data from the file for us to id the
483 * object
484 */
485 /* treat as a miss */
486 http->logType = LOG_TCP_MISS;
0655fa4d 487 processMiss();
62e76326 488 return;
d3b3ab85 489 }
62e76326 490
edce4d98 491 assert(!EBIT_TEST(e->flags, ENTRY_ABORTED));
492 /* update size of the request */
0655fa4d 493 reqsize = result.length + reqofs;
62e76326 494
edce4d98 495 /*
496 * Got the headers, now grok them
497 */
29b8d8d6 498 assert(http->logType == LOG_TCP_HIT);
62e76326 499
a8a0b1c2
EC
500 if (strcmp(e->mem_obj->url, http->request->storeId()) != 0) {
501 debugs(33, DBG_IMPORTANT, "clientProcessHit: URL mismatch, '" << e->mem_obj->url << "' != '" << http->request->storeId() << "'");
cdd4e1c1 502 processMiss();
503 return;
504 }
505
edce4d98 506 switch (varyEvaluateMatch(e, r)) {
62e76326 507
edce4d98 508 case VARY_NONE:
62e76326 509 /* No variance detected. Continue as normal */
510 break;
511
edce4d98 512 case VARY_MATCH:
62e76326 513 /* This is the correct entity for this request. Continue */
bf8fe701 514 debugs(88, 2, "clientProcessHit: Vary MATCH!");
62e76326 515 break;
516
edce4d98 517 case VARY_OTHER:
62e76326 518 /* This is not the correct entity for this request. We need
519 * to requery the cache.
520 */
86a2f789 521 removeClientStoreReference(&sc, http);
62e76326 522 e = NULL;
523 /* Note: varyEvalyateMatch updates the request with vary information
524 * so we only get here once. (it also takes care of cancelling loops)
525 */
26ac0430 526 debugs(88, 2, "clientProcessHit: Vary detected!");
0655fa4d 527 clientGetMoreData(ourNode, http);
62e76326 528 return;
529
edce4d98 530 case VARY_CANCEL:
62e76326 531 /* varyEvaluateMatch found a object loop. Process as miss */
e0236918 532 debugs(88, DBG_IMPORTANT, "clientProcessHit: Vary object loop!");
0655fa4d 533 processMiss();
62e76326 534 return;
edce4d98 535 }
62e76326 536
c2a7cefd 537 if (r->method == Http::METHOD_PURGE) {
86a2f789 538 removeClientStoreReference(&sc, http);
62e76326 539 e = NULL;
0655fa4d 540 purgeRequest();
62e76326 541 return;
edce4d98 542 }
62e76326 543
45e5102d 544 if (e->checkNegativeHit()
450fe1cb 545 && !r->flags.noCacheHack()
36e6655b 546 ) {
62e76326 547 http->logType = LOG_TCP_NEGATIVE_HIT;
0655fa4d 548 sendMoreData(result);
bcfba8bd 549 } else if (!http->flags.internal && refreshCheckHTTP(e, r)) {
bf8fe701 550 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
62e76326 551 /*
552 * We hold a stale copy; it needs to be validated
553 */
554 /*
450fe1cb 555 * The 'needValidation' flag is used to prevent forwarding
62e76326 556 * loops between siblings. If our copy of the object is stale,
557 * then we should probably only use parents for the validation
558 * request. Otherwise two siblings could generate a loop if
559 * both have a stale version of the object.
560 */
e857372a 561 r->flags.needValidation = true;
62e76326 562
563 if (e->lastmod < 0) {
86310427 564 debugs(88, 3, "validate HIT object? NO. Missing Last-Modified header. Do MISS.");
62e76326 565 /*
566 * Previous reply didn't have a Last-Modified header,
567 * we cannot revalidate it.
568 */
569 http->logType = LOG_TCP_MISS;
0655fa4d 570 processMiss();
450fe1cb 571 } else if (r->flags.noCache) {
86310427 572 debugs(88, 3, "validate HIT object? NO. Client sent CC:no-cache. Do CLIENT_REFRESH_MISS");
62e76326 573 /*
574 * This did not match a refresh pattern that overrides no-cache
575 * we should honour the client no-cache header.
576 */
577 http->logType = LOG_TCP_CLIENT_REFRESH_MISS;
0655fa4d 578 processMiss();
0c3d3f65 579 } else if (r->protocol == AnyP::PROTO_HTTP) {
86310427 580 debugs(88, 3, "validate HIT object? YES.");
62e76326 581 /*
582 * Object needs to be revalidated
583 * XXX This could apply to FTP as well, if Last-Modified is known.
584 */
0655fa4d 585 processExpired();
62e76326 586 } else {
86310427 587 debugs(88, 3, "validate HIT object? NO. Client protocol non-HTTP. Do MISS.");
62e76326 588 /*
589 * We don't know how to re-validate other protocols. Handle
590 * them as if the object has expired.
591 */
592 http->logType = LOG_TCP_MISS;
0655fa4d 593 processMiss();
62e76326 594 }
79c8035e
AR
595 } else if (r->conditional())
596 processConditional(result);
597 else {
62e76326 598 /*
599 * plain ol' cache hit
600 */
601
9a0a18de 602#if USE_DELAY_POOLS
ffdf45f2 603 if (e->store_status != STORE_OK)
849b826a 604 http->logType = LOG_TCP_MISS;
5bf4d170 605 else
606#endif
26ac0430
AJ
607 if (e->mem_status == IN_MEMORY)
608 http->logType = LOG_TCP_MEM_HIT;
609 else if (Config.onoff.offline)
610 http->logType = LOG_TCP_OFFLINE_HIT;
62e76326 611
0655fa4d 612 sendMoreData(result);
edce4d98 613 }
614}
615
7d5f62a4 616/**
edce4d98 617 * Prepare to fetch the object as it's a cache miss of some kind.
618 */
619void
0655fa4d 620clientReplyContext::processMiss()
edce4d98 621{
edce4d98 622 char *url = http->uri;
190154cf 623 HttpRequest *r = http->request;
edce4d98 624 ErrorState *err = NULL;
60745f24 625 debugs(88, 4, "clientProcessMiss: '" << RequestMethodStr(r->method) << " " << url << "'");
7d5f62a4
AJ
626
627 /**
edce4d98 628 * We might have a left-over StoreEntry from a failed cache hit
629 * or IMS request.
630 */
86a2f789 631 if (http->storeEntry()) {
632 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_SPECIAL)) {
fa84c01d 633 debugs(88, DBG_CRITICAL, "clientProcessMiss: miss on a special object (" << url << ").");
02c8dde5 634 debugs(88, DBG_CRITICAL, "\tlog_type = " << LogTags_str[http->logType]);
3900307b 635 http->storeEntry()->dump(1);
62e76326 636 }
637
86a2f789 638 removeClientStoreReference(&sc, http);
edce4d98 639 }
62e76326 640
7d5f62a4 641 /** Check if its a PURGE request to be actioned. */
c2a7cefd 642 if (r->method == Http::METHOD_PURGE) {
0655fa4d 643 purgeRequest();
62e76326 644 return;
edce4d98 645 }
914b89a2 646
7d5f62a4 647 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
c2a7cefd 648 if (r->method == Http::METHOD_OTHER) {
26ac0430 649 purgeAllCached();
60745f24 650 }
62e76326 651
7d5f62a4 652 /** Check if 'only-if-cached' flag is set. Action if so. */
0655fa4d 653 if (http->onlyIfCached()) {
654 processOnlyIfCachedMiss();
62e76326 655 return;
edce4d98 656 }
62e76326 657
42829656 658 /// Deny loops
450fe1cb 659 if (r->flags.loopDetected) {
955394ce
AJ
660 http->al->http.code = Http::scForbidden;
661 err = clientBuildError(ERR_ACCESS_DENIED, Http::scForbidden, NULL, http->getConn()->clientConnection->remote, http->request);
f206b652 662 createStoreEntry(r->method, RequestFlags());
86a2f789 663 errorAppendEntry(http->storeEntry(), err);
0655fa4d 664 triggerInitialStoreRead();
62e76326 665 return;
edce4d98 666 } else {
26ac0430 667 assert(http->out.offset == 0);
0655fa4d 668 createStoreEntry(r->method, r->flags);
669 triggerInitialStoreRead();
62e76326 670
671 if (http->redirect.status) {
06a5ae20 672 HttpReply *rep = new HttpReply;
62e76326 673 http->logType = LOG_TCP_REDIRECT;
d88e3c49 674 http->storeEntry()->releaseRequest();
06a5ae20 675 rep->redirect(http->redirect.status, http->redirect.location);
db237875 676 http->storeEntry()->replaceHttpReply(rep);
86a2f789 677 http->storeEntry()->complete();
62e76326 678 return;
679 }
680
7d5f62a4 681 /** Check for internal requests. Update Protocol info if so. */
62e76326 682 if (http->flags.internal)
0c3d3f65 683 r->protocol = AnyP::PROTO_INTERNAL;
62e76326 684
9174ba3d 685 assert(r->clientConnectionManager == http->getConn());
655daa06 686
7d5f62a4 687 /** Start forwarding to get the new object from network */
73c36fd9 688 Comm::ConnectionPointer conn = http->getConn() != NULL ? http->getConn()->clientConnection : NULL;
4bf68cfa 689 FwdState::Start(conn, http->storeEntry(), r, http->al);
edce4d98 690 }
691}
692
7d5f62a4 693/**
edce4d98 694 * client issued a request with an only-if-cached cache-control directive;
695 * we did not find a cached object that can be returned without
696 * contacting other servers;
697 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
698 */
0655fa4d 699void
700clientReplyContext::processOnlyIfCachedMiss()
edce4d98 701{
bf8fe701 702 debugs(88, 4, "clientProcessOnlyIfCachedMiss: '" <<
60745f24 703 RequestMethodStr(http->request->method) << " " << http->uri << "'");
955394ce
AJ
704 http->al->http.code = Http::scGateway_Timeout;
705 ErrorState *err = clientBuildError(ERR_ONLY_IF_CACHED_MISS, Http::scGateway_Timeout, NULL,
73c36fd9 706 http->getConn()->clientConnection->remote, http->request);
86a2f789 707 removeClientStoreReference(&sc, http);
0655fa4d 708 startError(err);
edce4d98 709}
710
79c8035e
AR
711/// process conditional request from client
712void
713clientReplyContext::processConditional(StoreIOBuffer &result)
714{
a2bd457d 715 StoreEntry *const e = http->storeEntry();
79c8035e 716
955394ce 717 if (e->getReply()->sline.status != Http::scOkay) {
79c8035e
AR
718 debugs(88, 4, "clientReplyContext::processConditional: Reply code " <<
719 e->getReply()->sline.status << " != 200");
720 http->logType = LOG_TCP_MISS;
721 processMiss();
722 return;
723 }
724
725 HttpRequest &r = *http->request;
726
727 if (r.header.has(HDR_IF_MATCH) && !e->hasIfMatchEtag(r)) {
728 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
729 sendPreconditionFailedError();
730 return;
731 }
732
733 bool matchedIfNoneMatch = false;
734 if (r.header.has(HDR_IF_NONE_MATCH)) {
735 if (!e->hasIfNoneMatchEtag(r)) {
736 // RFC 2616: ignore IMS if If-None-Match did not match
e857372a 737 r.flags.ims = false;
79c8035e
AR
738 r.ims = -1;
739 r.imslen = 0;
740 r.header.delById(HDR_IF_MODIFIED_SINCE);
741 http->logType = LOG_TCP_MISS;
742 sendMoreData(result);
743 return;
744 }
745
45e5102d 746 if (!r.flags.ims) {
79c8035e 747 // RFC 2616: if If-None-Match matched and there is no IMS,
a2bd457d
AJ
748 // reply with 304 Not Modified or 412 Precondition Failed
749 sendNotModifiedOrPreconditionFailedError();
79c8035e
AR
750 return;
751 }
752
a2bd457d 753 // otherwise check IMS below to decide if we reply with 304 or 412
79c8035e
AR
754 matchedIfNoneMatch = true;
755 }
756
45e5102d 757 if (r.flags.ims) {
79c8035e
AR
758 // handle If-Modified-Since requests from the client
759 if (e->modifiedSince(&r)) {
760 http->logType = LOG_TCP_IMS_HIT;
761 sendMoreData(result);
762 return;
763 }
764
765 if (matchedIfNoneMatch) {
a2bd457d
AJ
766 // If-None-Match matched, reply with 304 Not Modified or
767 // 412 Precondition Failed
768 sendNotModifiedOrPreconditionFailedError();
79c8035e
AR
769 return;
770 }
771
772 // otherwise reply with 304 Not Modified
a2bd457d 773 sendNotModified();
79c8035e
AR
774 }
775}
776
edce4d98 777void
e6ccf245 778clientReplyContext::purgeRequestFindObjectToPurge()
26ac0430 779{
e6ccf245 780 /* Try to find a base entry */
be4d35dc 781 http->flags.purging = true;
e6ccf245 782 lookingforstore = 1;
26ac0430
AJ
783
784 // TODO: can we use purgeAllCached() here instead of doing the
785 // getPublicByRequestMethod() dance?
c2a7cefd 786 StoreEntry::getPublicByRequestMethod(this, http->request, Http::METHOD_GET);
e6ccf245 787}
788
c1520b67
AJ
789// Purges all entries with a given url
790// TODO: move to SideAgent parent, when we have one
60745f24 791/*
792 * We probably cannot purge Vary-affected responses because their MD5
793 * keys depend on vary headers.
794 */
c1520b67 795void
90bd689c 796purgeEntriesByUrl(HttpRequest * req, const char *url)
c1520b67 797{
8dceeee3
BR
798#if USE_HTCP
799 bool get_or_head_sent = false;
800#endif
26ac0430 801
c2a7cefd
AJ
802 for (HttpRequestMethod m(Http::METHOD_NONE); m != Http::METHOD_ENUM_END; ++m) {
803 if (m.respMaybeCacheable()) {
c1520b67
AJ
804 if (StoreEntry *entry = storeGetPublic(url, m)) {
805 debugs(88, 5, "purging " << RequestMethodStr(m) << ' ' << url);
90bd689c 806#if USE_HTCP
8dceeee3 807 neighborsHtcpClear(entry, url, req, m, HTCP_CLR_INVALIDATION);
c2a7cefd 808 if (m == Http::METHOD_GET || m == Http::METHOD_HEAD) {
8dceeee3
BR
809 get_or_head_sent = true;
810 }
90bd689c 811#endif
8dceeee3 812 entry->release();
c1520b67
AJ
813 }
814 }
815 }
8dceeee3
BR
816
817#if USE_HTCP
818 if (!get_or_head_sent) {
c2a7cefd 819 neighborsHtcpClear(NULL, url, req, HttpRequestMethod(Http::METHOD_GET), HTCP_CLR_INVALIDATION);
8dceeee3
BR
820 }
821#endif
c1520b67
AJ
822}
823
26ac0430 824void
60745f24 825clientReplyContext::purgeAllCached()
826{
26ac0430 827 const char *url = urlCanonical(http->request);
90bd689c 828 purgeEntriesByUrl(http->request, url);
35ececa5 829}
60745f24 830
e6ccf245 831void
3b13a8fd 832clientReplyContext::created(StoreEntry *newEntry)
e6ccf245 833{
834 if (lookingforstore == 1)
62e76326 835 purgeFoundGet(newEntry);
e6ccf245 836 else if (lookingforstore == 2)
62e76326 837 purgeFoundHead(newEntry);
e6ccf245 838 else if (lookingforstore == 3)
62e76326 839 purgeDoPurgeGet(newEntry);
e6ccf245 840 else if (lookingforstore == 4)
62e76326 841 purgeDoPurgeHead(newEntry);
e6ccf245 842 else if (lookingforstore == 5)
62e76326 843 identifyFoundObject(newEntry);
e6ccf245 844}
845
846void
3b13a8fd 847clientReplyContext::purgeFoundGet(StoreEntry *newEntry)
e6ccf245 848{
849 if (newEntry->isNull()) {
62e76326 850 lookingforstore = 2;
c2a7cefd 851 StoreEntry::getPublicByRequestMethod(this, http->request, Http::METHOD_HEAD);
e6ccf245 852 } else
62e76326 853 purgeFoundObject (newEntry);
e6ccf245 854}
855
856void
3b13a8fd 857clientReplyContext::purgeFoundHead(StoreEntry *newEntry)
e6ccf245 858{
859 if (newEntry->isNull())
62e76326 860 purgeDoMissPurge();
e6ccf245 861 else
62e76326 862 purgeFoundObject (newEntry);
e6ccf245 863}
62e76326 864
e6ccf245 865void
3b13a8fd 866clientReplyContext::purgeFoundObject(StoreEntry *entry)
e6ccf245 867{
868 assert (entry && !entry->isNull());
e4b9a2f0 869
870 if (EBIT_TEST(entry->flags, ENTRY_SPECIAL)) {
871 http->logType = LOG_TCP_DENIED;
955394ce 872 ErrorState *err = clientBuildError(ERR_ACCESS_DENIED, Http::scForbidden, NULL,
73c36fd9 873 http->getConn()->clientConnection->remote, http->request);
e4b9a2f0 874 startError(err);
875 return;
876 }
877
8bcf08e0 878 StoreIOBuffer localTempBuffer;
62e76326 879 /* Swap in the metadata */
86a2f789 880 http->storeEntry(entry);
34266cde 881
3d0ac046 882 http->storeEntry()->lock();
a8a0b1c2 883 http->storeEntry()->createMemObject(storeId(), http->log_uri);
34266cde 884
86a2f789 885 http->storeEntry()->mem_obj->method = http->request->method;
34266cde 886
86a2f789 887 sc = storeClientListAdd(http->storeEntry(), this);
34266cde 888
62e76326 889 http->logType = LOG_TCP_HIT;
34266cde 890
62e76326 891 reqofs = 0;
34266cde 892
8bcf08e0 893 localTempBuffer.offset = http->out.offset;
34266cde 894
8bcf08e0 895 localTempBuffer.length = next()->readBuffer.length;
34266cde 896
8bcf08e0 897 localTempBuffer.data = next()->readBuffer.data;
34266cde 898
86a2f789 899 storeClientCopy(sc, http->storeEntry(),
8bcf08e0 900 localTempBuffer, CacheHit, this);
e6ccf245 901}
902
903void
904clientReplyContext::purgeRequest()
edce4d98 905{
bf8fe701 906 debugs(88, 3, "Config2.onoff.enable_purge = " <<
907 Config2.onoff.enable_purge);
62e76326 908
edce4d98 909 if (!Config2.onoff.enable_purge) {
62e76326 910 http->logType = LOG_TCP_DENIED;
955394ce 911 ErrorState *err = clientBuildError(ERR_ACCESS_DENIED, Http::scForbidden, NULL, http->getConn()->clientConnection->remote, http->request);
0655fa4d 912 startError(err);
62e76326 913 return;
edce4d98 914 }
62e76326 915
edce4d98 916 /* Release both IP cache */
cc192b50 917 ipcacheInvalidate(http->request->GetHost());
edce4d98 918
e6ccf245 919 if (!http->flags.purging)
62e76326 920 purgeRequestFindObjectToPurge();
e6ccf245 921 else
62e76326 922 purgeDoMissPurge();
e6ccf245 923}
924
925void
926clientReplyContext::purgeDoMissPurge()
927{
29b8d8d6 928 http->logType = LOG_TCP_MISS;
e6ccf245 929 lookingforstore = 3;
c2a7cefd 930 StoreEntry::getPublicByRequestMethod(this,http->request, Http::METHOD_GET);
e6ccf245 931}
932
933void
3b13a8fd 934clientReplyContext::purgeDoPurgeGet(StoreEntry *newEntry)
e6ccf245 935{
936 assert (newEntry);
937 /* Move to new() when that is created */
955394ce 938 purgeStatus = Http::scNotFound;
e6ccf245 939
940 if (!newEntry->isNull()) {
62e76326 941 /* Release the cached URI */
bf8fe701 942 debugs(88, 4, "clientPurgeRequest: GET '" << newEntry->url() << "'" );
8dceeee3 943#if USE_HTCP
c2a7cefd 944 neighborsHtcpClear(newEntry, NULL, http->request, HttpRequestMethod(Http::METHOD_GET), HTCP_CLR_PURGE);
8dceeee3 945#endif
5f33b71d 946 newEntry->release();
955394ce 947 purgeStatus = Http::scOkay;
edce4d98 948 }
62e76326 949
e6ccf245 950 lookingforstore = 4;
c2a7cefd 951 StoreEntry::getPublicByRequestMethod(this, http->request, Http::METHOD_HEAD);
e6ccf245 952}
953
954void
3b13a8fd 955clientReplyContext::purgeDoPurgeHead(StoreEntry *newEntry)
e6ccf245 956{
4fc0ac76 957 if (newEntry && !newEntry->isNull()) {
bf8fe701 958 debugs(88, 4, "clientPurgeRequest: HEAD '" << newEntry->url() << "'" );
8dceeee3 959#if USE_HTCP
c2a7cefd 960 neighborsHtcpClear(newEntry, NULL, http->request, HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_PURGE);
8dceeee3 961#endif
5f33b71d 962 newEntry->release();
955394ce 963 purgeStatus = Http::scOkay;
edce4d98 964 }
62e76326 965
edce4d98 966 /* And for Vary, release the base URI if none of the headers was included in the request */
62e76326 967
edce4d98 968 if (http->request->vary_headers
62e76326 969 && !strstr(http->request->vary_headers, "=")) {
c2a7cefd 970 StoreEntry *entry = storeGetPublic(urlCanonical(http->request), Http::METHOD_GET);
62e76326 971
972 if (entry) {
bf8fe701 973 debugs(88, 4, "clientPurgeRequest: Vary GET '" << entry->url() << "'" );
8dceeee3 974#if USE_HTCP
c2a7cefd 975 neighborsHtcpClear(entry, NULL, http->request, HttpRequestMethod(Http::METHOD_GET), HTCP_CLR_PURGE);
8dceeee3 976#endif
5f33b71d 977 entry->release();
955394ce 978 purgeStatus = Http::scOkay;
62e76326 979 }
980
c2a7cefd 981 entry = storeGetPublic(urlCanonical(http->request), Http::METHOD_HEAD);
62e76326 982
983 if (entry) {
bf8fe701 984 debugs(88, 4, "clientPurgeRequest: Vary HEAD '" << entry->url() << "'" );
8dceeee3 985#if USE_HTCP
c2a7cefd 986 neighborsHtcpClear(entry, NULL, http->request, HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_PURGE);
8dceeee3 987#endif
5f33b71d 988 entry->release();
955394ce 989 purgeStatus = Http::scOkay;
62e76326 990 }
edce4d98 991 }
62e76326 992
edce4d98 993 /*
994 * Make a new entry to hold the reply to be written
995 * to the client.
996 */
528b2c61 997 /* FIXME: This doesn't need to go through the store. Simply
998 * push down the client chain
999 */
f206b652 1000 createStoreEntry(http->request->method, RequestFlags());
62e76326 1001
0655fa4d 1002 triggerInitialStoreRead();
62e76326 1003
7dc5f514 1004 HttpReply *rep = new HttpReply;
11992b6f 1005 rep->setHeaders(purgeStatus, NULL, NULL, 0, 0, -1);
7dc5f514 1006 http->storeEntry()->replaceHttpReply(rep);
86a2f789 1007 http->storeEntry()->complete();
edce4d98 1008}
1009
1010void
0655fa4d 1011clientReplyContext::traceReply(clientStreamNode * node)
edce4d98 1012{
076df709 1013 clientStreamNode *nextNode = (clientStreamNode *)node->node.next->data;
8bcf08e0 1014 StoreIOBuffer localTempBuffer;
f206b652 1015 createStoreEntry(http->request->method, RequestFlags());
076df709
FC
1016 localTempBuffer.offset = nextNode->readBuffer.offset + headers_sz;
1017 localTempBuffer.length = nextNode->readBuffer.length;
1018 localTempBuffer.data = nextNode->readBuffer.data;
86a2f789 1019 storeClientCopy(sc, http->storeEntry(),
8bcf08e0 1020 localTempBuffer, SendMoreData, this);
d88e3c49 1021 http->storeEntry()->releaseRequest();
3900307b 1022 http->storeEntry()->buffer();
7dc5f514 1023 HttpReply *rep = new HttpReply;
955394ce 1024 rep->setHeaders(Http::scOkay, NULL, "text/plain", http->request->prefixLen(), 0, squid_curtime);
db237875 1025 http->storeEntry()->replaceHttpReply(rep);
5cafad19 1026 http->request->swapOut(http->storeEntry());
86a2f789 1027 http->storeEntry()->complete();
edce4d98 1028}
1029
1030#define SENDING_BODY 0
1031#define SENDING_HDRSONLY 1
1032int
0655fa4d 1033clientReplyContext::checkTransferDone()
edce4d98 1034{
86a2f789 1035 StoreEntry *entry = http->storeEntry();
62e76326 1036
edce4d98 1037 if (entry == NULL)
62e76326 1038 return 0;
1039
1040 /*
edce4d98 1041 * For now, 'done_copying' is used for special cases like
1042 * Range and HEAD requests.
1043 */
0655fa4d 1044 if (http->flags.done_copying)
62e76326 1045 return 1;
1046
450fe1cb 1047 if (http->request->flags.chunkedReply && !flags.complete) {
4ad60609
AR
1048 // last-chunk was not sent
1049 return 0;
1050 }
1051
edce4d98 1052 /*
1053 * Handle STORE_OK objects.
1054 * objectLen(entry) will be set proprely.
26ac0430 1055 * RC: Does objectLen(entry) include the Headers?
0e3be1ea 1056 * RC: Yes.
edce4d98 1057 */
1058 if (entry->store_status == STORE_OK) {
0655fa4d 1059 return storeOKTransferDone();
e39b9382 1060 } else {
0655fa4d 1061 return storeNotOKTransferDone();
edce4d98 1062 }
e39b9382 1063}
1064
1065int
1066clientReplyContext::storeOKTransferDone() const
1067{
aa1a691e
AR
1068 assert(http->storeEntry()->objectLen() >= 0);
1069 assert(http->storeEntry()->objectLen() >= headers_sz);
47f6e231 1070 if (http->out.offset >= http->storeEntry()->objectLen() - headers_sz) {
26ac0430
AJ
1071 debugs(88,3,HERE << "storeOKTransferDone " <<
1072 " out.offset=" << http->out.offset <<
1073 " objectLen()=" << http->storeEntry()->objectLen() <<
1074 " headers_sz=" << headers_sz);
62e76326 1075 return 1;
47f6e231 1076 }
62e76326 1077
e39b9382 1078 return 0;
1079}
1080
1081int
1082clientReplyContext::storeNotOKTransferDone() const
1083{
edce4d98 1084 /*
1085 * Now, handle STORE_PENDING objects
1086 */
86a2f789 1087 MemObject *mem = http->storeEntry()->mem_obj;
edce4d98 1088 assert(mem != NULL);
1089 assert(http->request != NULL);
0e3be1ea 1090 /* mem->reply was wrong because it uses the UPSTREAM header length!!! */
8bcf08e0 1091 HttpReply const *curReply = mem->getReply();
62e76326 1092
e39b9382 1093 if (headers_sz == 0)
62e76326 1094 /* haven't found end of headers yet */
1095 return 0;
e39b9382 1096
edce4d98 1097 /*
1098 * Figure out how much data we are supposed to send.
1099 * If we are sending a body and we don't have a content-length,
1100 * then we must wait for the object to become STORE_OK.
1101 */
8bcf08e0 1102 if (curReply->content_length < 0)
62e76326 1103 return 0;
e39b9382 1104
8bcf08e0 1105 int64_t expectedLength = curReply->content_length + http->out.headers_sz;
62e76326 1106
e39b9382 1107 if (http->out.size < expectedLength)
62e76326 1108 return 0;
47f6e231 1109 else {
26ac0430
AJ
1110 debugs(88,3,HERE << "storeNotOKTransferDone " <<
1111 " out.size=" << http->out.size <<
1112 " expectedLength=" << expectedLength);
62e76326 1113 return 1;
47f6e231 1114 }
edce4d98 1115}
1116
edce4d98 1117/* A write has completed, what is the next status based on the
1118 * canonical request data?
1119 * 1 something is wrong
1120 * 0 nothing is wrong.
1121 *
1122 */
1123int
59a1efb2 1124clientHttpRequestStatus(int fd, ClientHttpRequest const *http)
edce4d98 1125{
062f7f4e
FC
1126#if SIZEOF_INT64_T == 4
1127 if (http->out.size > 0x7FFF0000) {
e0236918
FC
1128 debugs(88, DBG_IMPORTANT, "WARNING: closing FD " << fd << " to prevent out.size counter overflow");
1129 debugs(88, DBG_IMPORTANT, "\tclient " << http->getConn()->peer);
1130 debugs(88, DBG_IMPORTANT, "\treceived " << http->out.size << " bytes");
1131 debugs(88, DBG_IMPORTANT, "\tURI " << http->log_uri);
062f7f4e
FC
1132 return 1;
1133 }
1134
1135 if (http->out.offset > 0x7FFF0000) {
e0236918
FC
1136 debugs(88, DBG_IMPORTANT, "WARNING: closing FD " << fd < " to prevent out.offset counter overflow");
1137 debugs(88, DBG_IMPORTANT, "\tclient " << http->getConn()->peer);
1138 debugs(88, DBG_IMPORTANT, "\treceived " << http->out.size << " bytes, offset " << http->out.offset);
1139 debugs(88, DBG_IMPORTANT, "\tURI " << http->log_uri);
062f7f4e
FC
1140 return 1;
1141 }
1142
1143#endif
edce4d98 1144 return 0;
1145}
1146
62e76326 1147/* Preconditions:
edce4d98 1148 * *http is a valid structure.
1149 * fd is either -1, or an open fd.
1150 *
1151 * TODO: enumify this
1152 *
1153 * This function is used by any http request sink, to determine the status
1154 * of the object.
1155 */
1156clientStream_status_t
59a1efb2 1157clientReplyStatus(clientStreamNode * aNode, ClientHttpRequest * http)
edce4d98 1158{
0655fa4d 1159 clientReplyContext *context = dynamic_cast<clientReplyContext *>(aNode->data.getRaw());
1160 assert (context);
1161 assert (context->http == http);
1162 return context->replyStatus();
1163}
1164
1165clientStream_status_t
1166clientReplyContext::replyStatus()
1167{
edce4d98 1168 int done;
1169 /* Here because lower nodes don't need it */
62e76326 1170
3daaed1a 1171 if (http->storeEntry() == NULL) {
1172 debugs(88, 5, "clientReplyStatus: no storeEntry");
62e76326 1173 return STREAM_FAILED; /* yuck, but what can we do? */
3daaed1a 1174 }
62e76326 1175
3daaed1a 1176 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) {
62e76326 1177 /* TODO: Could upstream read errors (result.flags.error) be
1178 * lost, and result in undersize requests being considered
1179 * complete. Should we tcp reset such connections ?
1180 */
3daaed1a 1181 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
62e76326 1182 return STREAM_FAILED;
3daaed1a 1183 }
62e76326 1184
0655fa4d 1185 if ((done = checkTransferDone()) != 0 || flags.complete) {
bf8fe701 1186 debugs(88, 5, "clientReplyStatus: transfer is DONE");
62e76326 1187 /* Ok we're finished, but how? */
1188
4ad60609
AR
1189 const int64_t expectedBodySize =
1190 http->storeEntry()->getReply()->bodySize(http->request->method);
450fe1cb 1191 if (!http->request->flags.proxyKeepalive && expectedBodySize < 0) {
bf8fe701 1192 debugs(88, 5, "clientReplyStatus: closing, content_length < 0");
62e76326 1193 return STREAM_FAILED;
1194 }
1195
1196 if (!done) {
bf8fe701 1197 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
62e76326 1198 return STREAM_FAILED;
1199 }
1200
4ad60609 1201 if (expectedBodySize >= 0 && !http->gotEnough()) {
bf8fe701 1202 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
62e76326 1203 return STREAM_UNPLANNED_COMPLETE;
1204 }
1205
450fe1cb 1206 if (http->request->flags.proxyKeepalive) {
bf8fe701 1207 debugs(88, 5, "clientReplyStatus: stream complete and can keepalive");
62e76326 1208 return STREAM_COMPLETE;
1209 }
1210
bf8fe701 1211 debugs(88, 5, "clientReplyStatus: stream was not expected to complete!");
62e76326 1212 return STREAM_UNPLANNED_COMPLETE;
edce4d98 1213 }
62e76326 1214
16611143 1215 // XXX: Should this be checked earlier? We could return above w/o checking.
1216 if (reply->receivedBodyTooLarge(*http->request, http->out.offset - 4096)) {
b51aec66 1217 /* 4096 is a margin for the HTTP headers included in out.offset */
bf8fe701 1218 debugs(88, 5, "clientReplyStatus: client reply body is too large");
62e76326 1219 return STREAM_FAILED;
0e3be1ea 1220 }
62e76326 1221
edce4d98 1222 return STREAM_NONE;
1223}
1224
62e76326 1225/* Responses with no body will not have a content-type header,
edce4d98 1226 * which breaks the rep_mime_type acl, which
1227 * coincidentally, is the most common acl for reply access lists.
1228 * A better long term fix for this is to allow acl matchs on the various
26ac0430
AJ
1229 * status codes, and then supply a default ruleset that puts these
1230 * codes before any user defines access entries. That way the user
edce4d98 1231 * can choose to block these responses where appropriate, but won't get
1232 * mysterious breakages.
1233 */
0655fa4d 1234bool
955394ce 1235clientReplyContext::alwaysAllowResponse(Http::StatusCode sline) const
edce4d98 1236{
4ef4b952 1237 bool result;
1238
edce4d98 1239 switch (sline) {
62e76326 1240
955394ce 1241 case Http::scContinue:
62e76326 1242
955394ce 1243 case Http::scSwitchingProtocols:
62e76326 1244
955394ce 1245 case Http::scProcessing:
62e76326 1246
955394ce 1247 case Http::scNoContent:
62e76326 1248
955394ce 1249 case Http::scNotModified:
4ef4b952 1250 result = true;
62e76326 1251 break;
1252
edce4d98 1253 default:
4ef4b952 1254 result = false;
edce4d98 1255 }
4ef4b952 1256
1257 return result;
edce4d98 1258}
1259
a5c8d64d
AJ
1260/**
1261 * Generate the reply headers sent to client.
1262 *
1263 * Filters out unwanted entries and hop-by-hop from original reply header
1264 * then adds extra entries if we have more info than origin server
1265 * then adds Squid specific entries
edce4d98 1266 */
0655fa4d 1267void
1268clientReplyContext::buildReplyHeader()
edce4d98 1269{
7dc5f514 1270 HttpHeader *hdr = &reply->header;
c8be6d7b 1271 int is_hit = logTypeIsATcpHit(http->logType);
190154cf 1272 HttpRequest *request = http->request;
edce4d98 1273#if DONT_FILTER_THESE
1274 /* but you might want to if you run Squid as an HTTP accelerator */
a9925b40 1275 /* hdr->delById(HDR_ACCEPT_RANGES); */
1276 hdr->delById(HDR_ETAG);
edce4d98 1277#endif
62e76326 1278
edce4d98 1279 if (is_hit)
a9925b40 1280 hdr->delById(HDR_SET_COOKIE);
f89d4012 1281 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
62e76326 1282
23c6d7e7 1283 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
dcf3665b 1284 // remove the Proxy-Authenticate header
23c6d7e7 1285 if ( !request->peer_login || (strcmp(request->peer_login,"PASS") != 0 && strcmp(request->peer_login,"PASSTHRU") != 0))
26ac0430 1286 reply->header.delById(HDR_PROXY_AUTHENTICATE);
dcf3665b 1287
2cdeea82 1288 reply->header.removeHopByHopEntries();
62e76326 1289
1290 // if (request->range)
7dc5f514 1291 // clientBuildRangeHeader(http, reply);
a5c8d64d 1292
edce4d98 1293 /*
1294 * Add a estimated Age header on cache hits.
1295 */
1296 if (is_hit) {
62e76326 1297 /*
1298 * Remove any existing Age header sent by upstream caches
1299 * (note that the existing header is passed along unmodified
1300 * on cache misses)
1301 */
a9925b40 1302 hdr->delById(HDR_AGE);
62e76326 1303 /*
1304 * This adds the calculated object age. Note that the details of the
1305 * age calculation is performed by adjusting the timestamp in
3900307b 1306 * StoreEntry::timestampsSet(), not here.
62e76326 1307 */
a5c8d64d
AJ
1308#if DEAD_CODE
1309 // XXX: realy useless? or is there a bug now that this is detatched from the below if-sequence ?
1310 // looks like this pre-if was supposed to be the browser workaround...
86a2f789 1311 if (NULL == http->storeEntry())
62e76326 1312 (void) 0;
86a2f789 1313 else if (http->storeEntry()->timestamp < 0)
62e76326 1314 (void) 0;
a5c8d64d 1315#endif
bbe58ab5 1316
1317 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_SPECIAL)) {
a9925b40 1318 hdr->delById(HDR_DATE);
1319 hdr->insertTime(HDR_DATE, squid_curtime);
90fa5816
AJ
1320 } else if (http->getConn() && http->getConn()->port->actAsOrigin) {
1321 // Swap the Date: header to current time if we are simulating an origin
fd49b08b
A
1322 HttpHeaderEntry *h = hdr->findEntry(HDR_DATE);
1323 if (h)
1324 hdr->putExt("X-Origin-Date", h->value.termedBuf());
90fa5816
AJ
1325 hdr->delById(HDR_DATE);
1326 hdr->insertTime(HDR_DATE, squid_curtime);
fd49b08b
A
1327 h = hdr->findEntry(HDR_EXPIRES);
1328 if (h && http->storeEntry()->expires >= 0) {
1329 hdr->putExt("X-Origin-Expires", h->value.termedBuf());
1330 hdr->delById(HDR_EXPIRES);
1331 hdr->insertTime(HDR_EXPIRES, squid_curtime + http->storeEntry()->expires - http->storeEntry()->timestamp);
1332 }
90fa5816
AJ
1333 if (http->storeEntry()->timestamp <= squid_curtime) {
1334 // put X-Cache-Age: instead of Age:
fd49b08b
A
1335 char age[64];
1336 snprintf(age, sizeof(age), "%ld", (long int) squid_curtime - http->storeEntry()->timestamp);
1337 hdr->putExt("X-Cache-Age", age);
1338 }
a81e7089 1339 } else if (http->storeEntry()->timestamp <= squid_curtime) {
a9925b40 1340 hdr->putInt(HDR_AGE,
1341 squid_curtime - http->storeEntry()->timestamp);
62e76326 1342 /* Signal old objects. NB: rfc 2616 is not clear,
1343 * by implication, on whether we should do this to all
1344 * responses, or only cache hits.
1345 * 14.46 states it ONLY applys for heuristically caclulated
1346 * freshness values, 13.2.4 doesn't specify the same limitation.
1347 * We interpret RFC 2616 under the combination.
1348 */
1349 /* TODO: if maxage or s-maxage is present, don't do this */
1350
86a2f789 1351 if (squid_curtime - http->storeEntry()->timestamp >= 86400) {
8bcf08e0
FC
1352 char tbuf[512];
1353 snprintf (tbuf, sizeof(tbuf), "%s %s %s",
62e76326 1354 "113", ThisCache,
1355 "This cache hit is still fresh and more than 1 day old");
8bcf08e0 1356 hdr->putStr(HDR_WARNING, tbuf);
62e76326 1357 }
1358 }
a5c8d64d 1359 }
528b2c61 1360
a5c8d64d
AJ
1361 /* RFC 2616: Section 14.18
1362 *
1363 * Add a Date: header if missing.
1364 * We have access to a clock therefore are required to amend any shortcoming in servers.
1365 *
1366 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1367 */
1368 if ( !hdr->has(HDR_DATE) ) {
f0dedeb5 1369 if (!http->storeEntry())
a5c8d64d 1370 hdr->insertTime(HDR_DATE, squid_curtime);
f0dedeb5
AJ
1371 else if (http->storeEntry()->timestamp > 0)
1372 hdr->insertTime(HDR_DATE, http->storeEntry()->timestamp);
1373 else {
d9d98242 1374 debugs(88,DBG_IMPORTANT,"BUG 3279: HTTP reply without Date:");
e78ae89a
AJ
1375 /* dump something useful about the problem */
1376 http->storeEntry()->dump(DBG_IMPORTANT);
f0dedeb5 1377 }
edce4d98 1378 }
62e76326 1379
bcfba8bd 1380 // add Warnings required by RFC 2616 if serving a stale hit
450fe1cb 1381 if (http->request->flags.staleIfHit && logTypeIsATcpHit(http->logType)) {
bcfba8bd 1382 hdr->putWarning(110, "Response is stale");
450fe1cb 1383 if (http->request->flags.needValidation)
bcfba8bd
AR
1384 hdr->putWarning(111, "Revalidation failed");
1385 }
1386
0bd9aa82 1387 /* Filter unproxyable authentication types */
ddd31ed3 1388 if (http->logType != LOG_TCP_DENIED &&
d67acb4e 1389 hdr->has(HDR_WWW_AUTHENTICATE)) {
62e76326 1390 HttpHeaderPos pos = HttpHeaderInitPos;
1391 HttpHeaderEntry *e;
1392
26ac0430 1393 int connection_auth_blocked = 0;
a9925b40 1394 while ((e = hdr->getEntry(&pos))) {
d67acb4e 1395 if (e->id == HDR_WWW_AUTHENTICATE) {
5b4117d8 1396 const char *value = e->value.rawBuf();
62e76326 1397
1398 if ((strncasecmp(value, "NTLM", 4) == 0 &&
1399 (value[4] == '\0' || value[4] == ' '))
1400 ||
1401 (strncasecmp(value, "Negotiate", 9) == 0 &&
d67acb4e 1402 (value[9] == '\0' || value[9] == ' '))
26ac0430
AJ
1403 ||
1404 (strncasecmp(value, "Kerberos", 8) == 0 &&
1405 (value[8] == '\0' || value[8] == ' '))) {
450fe1cb 1406 if (request->flags.connectionAuthDisabled) {
26ac0430 1407 hdr->delAt(pos, connection_auth_blocked);
d67acb4e
AJ
1408 continue;
1409 }
e857372a 1410 request->flags.mustKeepalive = true;
45e5102d 1411 if (!request->flags.accelerated && !request->flags.intercepted) {
d67acb4e 1412 httpHeaderPutStrf(hdr, HDR_PROXY_SUPPORT, "Session-Based-Authentication");
26ac0430
AJ
1413 /*
1414 We send "[Proxy-]Connection: Proxy-Support" header to mark
1415 Proxy-Support as a hop-by-hop header for intermediaries that do not
1416 understand the semantics of this header. The RFC should have included
1417 this recommendation.
1418 */
d67acb4e
AJ
1419 httpHeaderPutStrf(hdr, HDR_CONNECTION, "Proxy-support");
1420 }
1421 break;
26ac0430 1422 }
62e76326 1423 }
1424 }
d67acb4e
AJ
1425
1426 if (connection_auth_blocked)
ba9fb01d 1427 hdr->refreshMask();
0bd9aa82 1428 }
62e76326 1429
2f1431ea 1430#if USE_AUTH
edce4d98 1431 /* Handle authentication headers */
26ac0430 1432 if (http->logType == LOG_TCP_DENIED &&
955394ce
AJ
1433 ( reply->sline.status == Http::scProxyAuthenticationRequired ||
1434 reply->sline.status == Http::scUnauthorized)
26ac0430
AJ
1435 ) {
1436 /* Add authentication header */
1437 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1438 * depends on authenticate behaviour: all schemes to date send no extra
1439 * data on 407/401 responses, and do not check the accel state on 401/407
1440 * responses
1441 */
1442 authenticateFixHeader(reply, request->auth_user_request, request, 0, 1);
a33a428a
AJ
1443 } else if (request->auth_user_request != NULL)
1444 authenticateFixHeader(reply, request->auth_user_request, request, http->flags.accel, 0);
2f1431ea 1445#endif
62e76326 1446
edce4d98 1447 /* Append X-Cache */
1448 httpHeaderPutStrf(hdr, HDR_X_CACHE, "%s from %s",
62e76326 1449 is_hit ? "HIT" : "MISS", getMyHostname());
1450
edce4d98 1451#if USE_CACHE_DIGESTS
1452 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1453 httpHeaderPutStrf(hdr, HDR_X_CACHE_LOOKUP, "%s from %s:%d",
0655fa4d 1454 lookup_type ? lookup_type : "NONE",
62e76326 1455 getMyHostname(), getMyPort());
1456
edce4d98 1457#endif
62e76326 1458
45e5102d 1459 const bool maySendChunkedReply = !request->multipartRangeRequest() &&
f7701e72 1460 reply->sline.protocol == AnyP::PROTO_HTTP && // response is HTTP
4cb2536f 1461 (request->http_ver >= HttpVersion(1, 1));
4ad60609 1462
f529bb20 1463 /* Check whether we should send keep-alive */
450fe1cb 1464 if (!Config.onoff.error_pconns && reply->sline.status >= 400 && !request->flags.mustKeepalive) {
bf8fe701 1465 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
e857372a 1466 request->flags.proxyKeepalive = false;
450fe1cb 1467 } else if (!Config.onoff.client_pconns && !request->flags.mustKeepalive) {
17b57873 1468 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
e857372a 1469 request->flags.proxyKeepalive = false;
450fe1cb 1470 } else if (request->flags.proxyKeepalive && shutting_down) {
f529bb20 1471 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
e857372a 1472 request->flags.proxyKeepalive = false;
450fe1cb 1473 } else if (request->flags.connectionAuth && !reply->keep_alive) {
26ac0430 1474 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
e857372a 1475 request->flags.proxyKeepalive = false;
4ad60609 1476 } else if (reply->bodySize(request->method) < 0 && !maySendChunkedReply) {
17b57873 1477 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
e857372a 1478 request->flags.proxyKeepalive = false;
450fe1cb 1479 } else if (fdUsageHigh()&& !request->flags.mustKeepalive) {
17b57873 1480 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
e857372a 1481 request->flags.proxyKeepalive = false;
450fe1cb 1482 } else if (request->flags.sslBumped && !reply->persistent()) {
49f1c7f7
AR
1483 // We do not really have to close, but we pretend we are a tunnel.
1484 debugs(88, 3, "clientBuildReplyHeader: bumped reply forces close");
e857372a 1485 request->flags.proxyKeepalive = false;
693cb033
CT
1486 } else if (request->pinnedConnection() && !reply->persistent()) {
1487 // The peer wants to close the pinned connection
1488 debugs(88, 3, "pinned reply forces close");
e857372a 1489 request->flags.proxyKeepalive = false;
17b57873 1490 }
d67acb4e 1491
4ad60609
AR
1492 // Decide if we send chunked reply
1493 if (maySendChunkedReply &&
450fe1cb 1494 request->flags.proxyKeepalive &&
4cb2536f 1495 reply->bodySize(request->method) < 0) {
4ad60609 1496 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
e857372a 1497 request->flags.chunkedReply = true;
4ad60609
AR
1498 hdr->putStr(HDR_TRANSFER_ENCODING, "chunked");
1499 }
f529bb20 1500
4dea3fdd 1501 /* Append VIA */
92caea77 1502 if (Config.onoff.via) {
62e76326 1503 LOCAL_ARRAY(char, bbuf, MAX_URL + 32);
30abd221 1504 String strVia;
26ac0430 1505 hdr->getList(HDR_VIA, &strVia);
88331887 1506 snprintf(bbuf, MAX_URL + 32, "%d.%d %s",
7dc5f514 1507 reply->sline.version.major,
1508 reply->sline.version.minor,
62e76326 1509 ThisCache);
1510 strListAdd(&strVia, bbuf, ',');
a9925b40 1511 hdr->delById(HDR_VIA);
5b4117d8 1512 hdr->putStr(HDR_VIA, strVia.termedBuf());
c8be6d7b 1513 }
95e78500 1514 /* Signal keep-alive or close explicitly */
450fe1cb 1515 hdr->putStr(HDR_CONNECTION, request->flags.proxyKeepalive ? "keep-alive" : "close");
62e76326 1516
edce4d98 1517#if ADD_X_REQUEST_URI
1518 /*
1519 * Knowing the URI of the request is useful when debugging persistent
1520 * connections in a client; we cannot guarantee the order of http headers,
1521 * but X-Request-URI is likely to be the very last header to ease use from a
1522 * debugger [hdr->entries.count-1].
1523 */
a9925b40 1524 hdr->putStr(HDR_X_REQUEST_URI,
1525 http->memOjbect()->url ? http->memObject()->url : http->uri);
62e76326 1526
edce4d98 1527#endif
62e76326 1528
45cca89d
AJ
1529 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1530 if ( hdr->has(HDR_SURROGATE_CONTROL) ) {
1531 if (!request->header.has(HDR_SURROGATE_CAPABILITY)) {
1532 hdr->delById(HDR_SURROGATE_CONTROL);
1533 }
1534 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1535 }
1536
8c01ada0 1537 httpHdrMangleList(hdr, request, ROR_REPLY);
edce4d98 1538}
1539
0655fa4d 1540void
b297bcd0 1541clientReplyContext::cloneReply()
edce4d98 1542{
7dc5f514 1543 assert(reply == NULL);
0655fa4d 1544
b248c2a3
AJ
1545 reply = http->storeEntry()->getReply()->clone();
1546 HTTPMSGLOCK(reply);
7dc5f514 1547
0c3d3f65 1548 if (reply->sline.protocol == AnyP::PROTO_HTTP) {
871c031f
AJ
1549 /* RFC 2616 requires us to advertise our 1.1 version (but only on real HTTP traffic) */
1550 reply->sline.version = HttpVersion(1,1);
e77d7ef0 1551 }
0655fa4d 1552
1553 /* do header conversions */
1554 buildReplyHeader();
edce4d98 1555}
1556
e6ccf245 1557void
1558clientReplyContext::identifyStoreObject()
edce4d98 1559{
190154cf 1560 HttpRequest *r = http->request;
62e76326 1561
45e5102d 1562 if (r->flags.cachable || r->flags.internal) {
62e76326 1563 lookingforstore = 5;
1564 StoreEntry::getPublicByRequest (this, r);
559da936 1565 } else {
62e76326 1566 identifyFoundObject (NullStoreEntry::getInstance());
559da936 1567 }
e6ccf245 1568}
1569
7d5f62a4
AJ
1570/**
1571 * Check state of the current StoreEntry object.
1572 * to see if we can determine the final status of the request.
1573 */
e6ccf245 1574void
1575clientReplyContext::identifyFoundObject(StoreEntry *newEntry)
1576{
1577 StoreEntry *e = newEntry;
190154cf 1578 HttpRequest *r = http->request;
62e76326 1579
d85b8894 1580 /** \li If the entry received isNull() then we ignore it. */
e6ccf245 1581 if (e->isNull()) {
86a2f789 1582 http->storeEntry(NULL);
e6ccf245 1583 } else {
86a2f789 1584 http->storeEntry(e);
e6ccf245 1585 }
62e76326 1586
86a2f789 1587 e = http->storeEntry();
a12a049a 1588
7d5f62a4 1589 /* Release IP-cache entries on reload */
d85b8894 1590 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
7d5f62a4
AJ
1591 * 'invalidate' the cached IP entries for this request ???
1592 */
450fe1cb 1593 if (r->flags.noCache) {
a12a049a 1594
f64091a7 1595#if USE_DNSHELPER
cc192b50 1596 ipcacheInvalidate(r->GetHost());
a12a049a 1597#else
cc192b50 1598 ipcacheInvalidateNegative(r->GetHost());
f64091a7 1599#endif /* USE_DNSHELPER */
a12a049a 1600
450fe1cb 1601 } else if (r->flags.noCacheHack()) {
45e5102d 1602
f64091a7 1603#if USE_DNSHELPER
cc192b50 1604 ipcacheInvalidate(r->GetHost());
a12a049a 1605#else
cc192b50 1606 ipcacheInvalidateNegative(r->GetHost());
f64091a7 1607#endif /* USE_DNSHELPER */
45e5102d 1608
a12a049a 1609 }
45e5102d 1610
edce4d98 1611#if USE_CACHE_DIGESTS
86a2f789 1612 lookup_type = http->storeEntry() ? "HIT" : "MISS";
edce4d98 1613#endif
62e76326 1614
86a2f789 1615 if (NULL == http->storeEntry()) {
d85b8894 1616 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
7d5f62a4 1617 debugs(85, 3, "clientProcessRequest2: StoreEntry is NULL - MISS");
62e76326 1618 http->logType = LOG_TCP_MISS;
1619 doGetMoreData();
1620 return;
edce4d98 1621 }
62e76326 1622
edce4d98 1623 if (Config.onoff.offline) {
d85b8894 1624 /** \li If we are running in offline mode set to HIT */
bf8fe701 1625 debugs(85, 3, "clientProcessRequest2: offline HIT");
62e76326 1626 http->logType = LOG_TCP_HIT;
1627 doGetMoreData();
1628 return;
edce4d98 1629 }
62e76326 1630
edce4d98 1631 if (http->redirect.status) {
d85b8894 1632 /** \li If redirection status is True force this to be a MISS */
16cd3193 1633 debugs(85, 3, HERE << "REDIRECT status forced StoreEntry to NULL (no body on 3XX responses)");
86a2f789 1634 http->storeEntry(NULL);
16cd3193 1635 http->logType = LOG_TCP_REDIRECT;
62e76326 1636 doGetMoreData();
1637 return;
edce4d98 1638 }
62e76326 1639
3900307b 1640 if (!e->validToSend()) {
bf8fe701 1641 debugs(85, 3, "clientProcessRequest2: !storeEntryValidToSend MISS" );
86a2f789 1642 http->storeEntry(NULL);
62e76326 1643 http->logType = LOG_TCP_MISS;
1644 doGetMoreData();
1645 return;
edce4d98 1646 }
62e76326 1647
edce4d98 1648 if (EBIT_TEST(e->flags, ENTRY_SPECIAL)) {
d85b8894 1649 /* \li Special entries are always hits, no matter what the client says */
bf8fe701 1650 debugs(85, 3, "clientProcessRequest2: ENTRY_SPECIAL HIT");
62e76326 1651 http->logType = LOG_TCP_HIT;
1652 doGetMoreData();
1653 return;
edce4d98 1654 }
62e76326 1655
450fe1cb 1656 if (r->flags.noCache) {
bf8fe701 1657 debugs(85, 3, "clientProcessRequest2: no-cache REFRESH MISS");
86a2f789 1658 http->storeEntry(NULL);
62e76326 1659 http->logType = LOG_TCP_CLIENT_REFRESH_MISS;
1660 doGetMoreData();
1661 return;
edce4d98 1662 }
62e76326 1663
bf8fe701 1664 debugs(85, 3, "clientProcessRequest2: default HIT");
e6ccf245 1665 http->logType = LOG_TCP_HIT;
1666 doGetMoreData();
edce4d98 1667}
1668
d85b8894
AJ
1669/**
1670 * Request more data from the store for the client Stream
edce4d98 1671 * This is *the* entry point to this module.
1672 *
1673 * Preconditions:
d85b8894
AJ
1674 * - This is the head of the list.
1675 * - There is at least one more node.
1676 * - Data context is not null
edce4d98 1677 */
1678void
59a1efb2 1679clientGetMoreData(clientStreamNode * aNode, ClientHttpRequest * http)
edce4d98 1680{
edce4d98 1681 /* Test preconditions */
e6ccf245 1682 assert(aNode != NULL);
1683 assert(cbdataReferenceValid(aNode));
e6ccf245 1684 assert(aNode->node.prev == NULL);
1685 assert(aNode->node.next != NULL);
0655fa4d 1686 clientReplyContext *context = dynamic_cast<clientReplyContext *>(aNode->data.getRaw());
1687 assert (context);
edce4d98 1688 assert(context->http == http);
1689
0655fa4d 1690 clientStreamNode *next = ( clientStreamNode *)aNode->node.next->data;
62e76326 1691
edce4d98 1692 if (!context->ourNode)
62e76326 1693 context->ourNode = aNode;
1694
e6ccf245 1695 /* no cbdatareference, this is only used once, and safely */
edce4d98 1696 if (context->flags.storelogiccomplete) {
62e76326 1697 StoreIOBuffer tempBuffer;
1698 tempBuffer.offset = next->readBuffer.offset + context->headers_sz;
1699 tempBuffer.length = next->readBuffer.length;
1700 tempBuffer.data = next->readBuffer.data;
1701
86a2f789 1702 storeClientCopy(context->sc, http->storeEntry(),
0655fa4d 1703 tempBuffer, clientReplyContext::SendMoreData, context);
62e76326 1704 return;
edce4d98 1705 }
62e76326 1706
c2a7cefd 1707 if (context->http->request->method == Http::METHOD_PURGE) {
62e76326 1708 context->purgeRequest();
1709 return;
edce4d98 1710 }
62e76326 1711
e18b8316 1712 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
fc90edc3 1713
c2a7cefd 1714 if (context->http->request->method == Http::METHOD_TRACE) {
34ee6e73 1715 if (context->http->request->header.getInt64(HDR_MAX_FORWARDS) == 0) {
0655fa4d 1716 context->traceReply(aNode);
62e76326 1717 return;
1718 }
1719
1720 /* continue forwarding, not finished yet. */
1721 http->logType = LOG_TCP_MISS;
1722
1723 context->doGetMoreData();
edce4d98 1724 } else
62e76326 1725 context->identifyStoreObject();
e6ccf245 1726}
1727
1728void
1729clientReplyContext::doGetMoreData()
1730{
edce4d98 1731 /* We still have to do store logic processing - vary, cache hit etc */
86a2f789 1732 if (http->storeEntry() != NULL) {
62e76326 1733 /* someone found the object in the cache for us */
8bcf08e0 1734 StoreIOBuffer localTempBuffer;
34266cde 1735
3d0ac046 1736 http->storeEntry()->lock();
62e76326 1737
86a2f789 1738 if (http->storeEntry()->mem_obj == NULL) {
62e76326 1739 /*
1740 * This if-block exists because we don't want to clobber
1741 * a preexiting mem_obj->method value if the mem_obj
1742 * already exists. For example, when a HEAD request
1743 * is a cache hit for a GET response, we want to keep
1744 * the method as GET.
1745 */
a8a0b1c2 1746 http->storeEntry()->createMemObject(storeId(), http->log_uri);
7d5f62a4 1747 http->storeEntry()->mem_obj->method = http->request->method;
a8a0b1c2
EC
1748 /**
1749 * Here we can see if the object was
1750 * created using URL or alternative StoreID from helper.
1751 */
1752 debugs(88, 3, "mem_obj->url: " << http->storeEntry()->mem_obj->url);
62e76326 1753 }
1754
86a2f789 1755 sc = storeClientListAdd(http->storeEntry(), this);
9a0a18de 1756#if USE_DELAY_POOLS
62e76326 1757 sc->setDelayId(DelayId::DelayClient(http));
edce4d98 1758#endif
62e76326 1759
1760 assert(http->logType == LOG_TCP_HIT);
1761 reqofs = 0;
1762 /* guarantee nothing has been sent yet! */
1763 assert(http->out.size == 0);
1764 assert(http->out.offset == 0);
425de4c8
AJ
1765
1766 if (Ip::Qos::TheConfig.isHitTosActive()) {
73c36fd9 1767 Ip::Qos::doTosLocalHit(http->getConn()->clientConnection);
425de4c8
AJ
1768 }
1769
1770 if (Ip::Qos::TheConfig.isHitNfmarkActive()) {
73c36fd9 1771 Ip::Qos::doNfmarkLocalHit(http->getConn()->clientConnection);
b86ab75b 1772 }
425de4c8 1773
8bcf08e0
FC
1774 localTempBuffer.offset = reqofs;
1775 localTempBuffer.length = getNextNode()->readBuffer.length;
1776 localTempBuffer.data = getNextNode()->readBuffer.data;
1777 storeClientCopy(sc, http->storeEntry(), localTempBuffer, CacheHit, this);
edce4d98 1778 } else {
62e76326 1779 /* MISS CASE, http->logType is already set! */
0655fa4d 1780 processMiss();
edce4d98 1781 }
1782}
1783
d85b8894 1784/** The next node has removed itself from the stream. */
edce4d98 1785void
59a1efb2 1786clientReplyDetach(clientStreamNode * node, ClientHttpRequest * http)
edce4d98 1787{
d85b8894 1788 /** detach from the stream */
edce4d98 1789 clientStreamDetach(node, http);
1790}
1791
d85b8894
AJ
1792/**
1793 * Accepts chunk of a http message in buf, parses prefix, filters headers and
edce4d98 1794 * such, writes processed message to the message recipient
1795 */
1796void
0655fa4d 1797clientReplyContext::SendMoreData(void *data, StoreIOBuffer result)
edce4d98 1798{
e6ccf245 1799 clientReplyContext *context = static_cast<clientReplyContext *>(data);
528b2c61 1800 context->sendMoreData (result);
1801}
1802
1803void
1804clientReplyContext::makeThisHead()
1805{
1806 /* At least, I think thats what this does */
1807 dlinkDelete(&http->active, &ClientActiveRequests);
1808 dlinkAdd(http, &http->active, &ClientActiveRequests);
1809}
1810
1811bool
1812clientReplyContext::errorInStream(StoreIOBuffer const &result, size_t const &sizeToProcess)const
1813{
1814 return /* aborted request */
86a2f789 1815 (http->storeEntry() && EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) ||
62e76326 1816 /* Upstream read error */ (result.flags.error) ||
1817 /* Upstream EOF */ (sizeToProcess == 0);
528b2c61 1818}
1819
1820void
1821clientReplyContext::sendStreamError(StoreIOBuffer const &result)
1822{
d85b8894 1823 /** call clientWriteComplete so the client socket gets closed
af6a12ee 1824 *
d85b8894 1825 * We call into the stream, because we don't know that there is a
528b2c61 1826 * client socket!
1827 */
26ac0430 1828 debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.");
8bcf08e0 1829 StoreIOBuffer localTempBuffer;
528b2c61 1830 flags.complete = 1;
e857372a 1831 http->request->flags.streamError = true;
8bcf08e0 1832 localTempBuffer.flags.error = result.flags.error;
528b2c61 1833 clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
8bcf08e0 1834 localTempBuffer);
528b2c61 1835}
1836
1837void
1838clientReplyContext::pushStreamData(StoreIOBuffer const &result, char *source)
1839{
8bcf08e0 1840 StoreIOBuffer localTempBuffer;
62e76326 1841
528b2c61 1842 if (result.length == 0) {
bf8fe701 1843 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
62e76326 1844 flags.complete = 1;
528b2c61 1845 }
62e76326 1846
43ae1d95 1847 assert(result.offset - headers_sz == next()->readBuffer.offset);
8bcf08e0
FC
1848 localTempBuffer.offset = result.offset - headers_sz;
1849 localTempBuffer.length = result.length;
62e76326 1850
8bcf08e0
FC
1851 if (localTempBuffer.length)
1852 localTempBuffer.data = source;
62e76326 1853
528b2c61 1854 clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
8bcf08e0 1855 localTempBuffer);
528b2c61 1856}
1857
1858clientStreamNode *
1859clientReplyContext::next() const
1860{
1861 assert ( (clientStreamNode*)http->client_stream.head->next->data == getNextNode());
1862 return getNextNode();
1863}
1864
b51aec66 1865void
16611143 1866clientReplyContext::sendBodyTooLargeError()
b51aec66 1867{
b7ac5457 1868 Ip::Address tmp_noaddr;
26ac0430 1869 tmp_noaddr.SetNoAddr(); // TODO: make a global const
af0d9bca 1870 http->logType = LOG_TCP_DENIED_REPLY;
955394ce 1871 ErrorState *err = clientBuildError(ERR_TOO_BIG, Http::scForbidden, NULL,
73c36fd9 1872 http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmp_noaddr,
26ac0430 1873 http->request);
16611143 1874 removeClientStoreReference(&(sc), http);
1875 HTTPMSGUNLOCK(reply);
1876 startError(err);
26ac0430 1877
b51aec66 1878}
1879
79c8035e
AR
1880/// send 412 (Precondition Failed) to client
1881void
1882clientReplyContext::sendPreconditionFailedError()
1883{
1884 http->logType = LOG_TCP_HIT;
1885 ErrorState *const err =
955394ce 1886 clientBuildError(ERR_PRECONDITION_FAILED, Http::scPreconditionFailed,
73c36fd9 1887 NULL, http->getConn()->clientConnection->remote, http->request);
79c8035e
AR
1888 removeClientStoreReference(&sc, http);
1889 HTTPMSGUNLOCK(reply);
1890 startError(err);
1891}
1892
a2bd457d
AJ
1893/// send 304 (Not Modified) to client
1894void
1895clientReplyContext::sendNotModified()
1896{
1897 StoreEntry *e = http->storeEntry();
1898 const time_t timestamp = e->timestamp;
1899 HttpReply *const temprep = e->getReply()->make304();
1900 http->logType = LOG_TCP_IMS_HIT;
1901 removeClientStoreReference(&sc, http);
f206b652 1902 createStoreEntry(http->request->method, RequestFlags());
a2bd457d
AJ
1903 e = http->storeEntry();
1904 // Copy timestamp from the original entry so the 304
1905 // reply has a meaningful Age: header.
90fa5816 1906 e->timestampsSet();
a2bd457d
AJ
1907 e->timestamp = timestamp;
1908 e->replaceHttpReply(temprep);
1909 e->complete();
1910 /*
1911 * TODO: why put this in the store and then serialise it and
1912 * then parse it again. Simply mark the request complete in
1913 * our context and write the reply struct to the client side.
1914 */
1915 triggerInitialStoreRead();
1916}
1917
1918/// send 304 (Not Modified) or 412 (Precondition Failed) to client
1919/// depending on request method
1920void
1921clientReplyContext::sendNotModifiedOrPreconditionFailedError()
1922{
c2a7cefd
AJ
1923 if (http->request->method == Http::METHOD_GET ||
1924 http->request->method == Http::METHOD_HEAD)
a2bd457d
AJ
1925 sendNotModified();
1926 else
1927 sendPreconditionFailedError();
1928}
1929
4993f571 1930void
1931clientReplyContext::processReplyAccess ()
1932{
b50e327b 1933 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
7dc5f514 1934 assert(reply);
b50e327b
AJ
1935
1936 /** Don't block our own responses or HTTP status messages */
16611143 1937 if (http->logType == LOG_TCP_DENIED ||
26ac0430
AJ
1938 http->logType == LOG_TCP_DENIED_REPLY ||
1939 alwaysAllowResponse(reply->sline.status)) {
acbf9428 1940 headers_sz = reply->hdr_sz;
2efeb0b7 1941 processReplyAccessResult(ACCESS_ALLOWED);
26ac0430 1942 return;
230a8cc6 1943 }
26ac0430 1944
b50e327b 1945 /** Check for reply to big error */
16611143 1946 if (reply->expectedBodyTooLarge(*http->request)) {
1947 sendBodyTooLargeError();
62e76326 1948 return;
1949 }
1950
7dc5f514 1951 headers_sz = reply->hdr_sz;
230a8cc6 1952
b50e327b 1953 /** check for absent access controls (permit by default) */
230a8cc6 1954 if (!Config.accessList.reply) {
2efeb0b7 1955 processReplyAccessResult(ACCESS_ALLOWED);
26ac0430 1956 return;
230a8cc6 1957 }
1958
b50e327b 1959 /** Process http_reply_access lists */
127dce76
AR
1960 ACLFilledChecklist *replyChecklist =
1961 clientAclChecklistCreate(Config.accessList.reply, http);
b248c2a3
AJ
1962 replyChecklist->reply = reply;
1963 HTTPMSGLOCK(replyChecklist->reply);
0655fa4d 1964 replyChecklist->nonBlockingCheck(ProcessReplyAccessResult, this);
4993f571 1965}
1966
1967void
2efeb0b7 1968clientReplyContext::ProcessReplyAccessResult(allow_t rv, void *voidMe)
4993f571 1969{
1970 clientReplyContext *me = static_cast<clientReplyContext *>(voidMe);
0655fa4d 1971 me->processReplyAccessResult(rv);
4993f571 1972}
1973
1974void
2efeb0b7 1975clientReplyContext::processReplyAccessResult(const allow_t &accessAllowed)
4993f571 1976{
26ac0430 1977 debugs(88, 2, "The reply for " << RequestMethodStr(http->request->method)
2efeb0b7 1978 << " " << http->uri << " is " << accessAllowed << ", because it matched '"
bf8fe701 1979 << (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" );
62e76326 1980
2efeb0b7 1981 if (accessAllowed != ACCESS_ALLOWED) {
62e76326 1982 ErrorState *err;
0185bd6f 1983 err_type page_id;
9ce7856a 1984 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, 1);
0185bd6f 1985
c466369c 1986 http->logType = LOG_TCP_DENIED_REPLY;
1987
0185bd6f 1988 if (page_id == ERR_NONE)
1989 page_id = ERR_ACCESS_DENIED;
1990
b7ac5457 1991 Ip::Address tmp_noaddr;
26ac0430 1992 tmp_noaddr.SetNoAddr();
955394ce 1993 err = clientBuildError(page_id, Http::scForbidden, NULL,
73c36fd9 1994 http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmp_noaddr,
26ac0430 1995 http->request);
0185bd6f 1996
86a2f789 1997 removeClientStoreReference(&sc, http);
0185bd6f 1998
7dc5f514 1999 HTTPMSGUNLOCK(reply);
0185bd6f 2000
3c2c1d31 2001 startError(err);
2002
62e76326 2003 return;
2004 }
2005
0976f8db 2006 /* Ok, the reply is allowed, */
2007 http->loggingEntry(http->storeEntry());
2008
7dc5f514 2009 ssize_t body_size = reqofs - reply->hdr_sz;
b297bcd0 2010 if (body_size < 0) {
26ac0430
AJ
2011 reqofs = reply->hdr_sz;
2012 body_size = 0;
b297bcd0 2013 }
0976f8db 2014
bf8fe701 2015 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
2016 (int) body_size << " bytes after " << reply->hdr_sz <<
2017 " bytes of headers");
0976f8db 2018
f41735ea 2019#if USE_SQUID_ESI
62e76326 2020
955394ce 2021 if (http->flags.accel && reply->sline.status != Http::scForbidden &&
7dc5f514 2022 !alwaysAllowResponse(reply->sline.status) &&
2023 esiEnableProcessing(reply)) {
bf8fe701 2024 debugs(88, 2, "Enabling ESI processing for " << http->uri);
43ae1d95 2025 clientStreamInsertHead(&http->client_stream, esiStreamRead,
2026 esiProcessStream, esiStreamDetach, esiStreamStatus, NULL);
2027 }
2028
5ef38a13 2029#endif
2030
c2a7cefd 2031 if (http->request->method == Http::METHOD_HEAD) {
62e76326 2032 /* do not forward body for HEAD replies */
2033 body_size = 0;
be4d35dc 2034 http->flags.done_copying = true;
62e76326 2035 flags.complete = 1;
2036 }
2037
2038 assert (!flags.headersSent);
2039 flags.headersSent = true;
2040
8bcf08e0 2041 StoreIOBuffer localTempBuffer;
62e76326 2042 char *buf = next()->readBuffer.data;
e85eb4e1 2043 char *body_buf = buf + reply->hdr_sz;
62e76326 2044
49ea0125 2045 //Server side may disable ranges under some circumstances.
2046
2047 if ((!http->request->range))
2048 next()->readBuffer.offset = 0;
2049
e85eb4e1
AJ
2050 body_buf -= next()->readBuffer.offset;
2051
62e76326 2052 if (next()->readBuffer.offset != 0) {
2053 if (next()->readBuffer.offset > body_size) {
2324cda2 2054 /* Can't use any of the body we received. send nothing */
8bcf08e0
FC
2055 localTempBuffer.length = 0;
2056 localTempBuffer.data = NULL;
62e76326 2057 } else {
8bcf08e0
FC
2058 localTempBuffer.length = body_size - next()->readBuffer.offset;
2059 localTempBuffer.data = body_buf + next()->readBuffer.offset;
62e76326 2060 }
2061 } else {
8bcf08e0
FC
2062 localTempBuffer.length = body_size;
2063 localTempBuffer.data = body_buf;
62e76326 2064 }
2065
0655fa4d 2066 /* TODO??: move the data in the buffer back by the request header size */
62e76326 2067 clientStreamCallback((clientStreamNode *)http->client_stream.head->data,
8bcf08e0 2068 http, reply, localTempBuffer);
62e76326 2069
2070 return;
4993f571 2071}
2072
528b2c61 2073void
2074clientReplyContext::sendMoreData (StoreIOBuffer result)
2075{
50c09fc4 2076 if (deleting)
2077 return;
2078
86a2f789 2079 StoreEntry *entry = http->storeEntry();
50c09fc4 2080
1cf238db 2081 ConnStateData * conn = http->getConn();
50c09fc4 2082
ea25a575
TH
2083 // too late, our conn is closing
2084 // TODO: should we also quit?
2085 if (conn == NULL) {
2086 debugs(33,3, "not sending more data to a closed connection" );
2087 return;
2088 }
2089 if (!conn->isOpen()) {
2090 debugs(33,3, "not sending more data to closing connection " << conn->clientConnection);
9af2f95b
AR
2091 return;
2092 }
693cb033
CT
2093 if (conn->pinning.zeroReply) {
2094 debugs(33,3, "not sending more data after a pinned zero reply " << conn->clientConnection);
2095 return;
2096 }
50c09fc4 2097
528b2c61 2098 char *buf = next()->readBuffer.data;
50c09fc4 2099
da33c835 2100 if (buf != result.data) {
62e76326 2101 /* we've got to copy some data */
2102 assert(result.length <= next()->readBuffer.length);
41d00cd3 2103 memcpy(buf, result.data, result.length);
edce4d98 2104 }
62e76326 2105
73c36fd9 2106 if (reqofs==0 && !logTypeIsATcpHit(http->logType) && Comm::IsConnOpen(conn->clientConnection)) {
425de4c8 2107 if (Ip::Qos::TheConfig.isHitTosActive()) {
73c36fd9 2108 Ip::Qos::doTosLocalMiss(conn->clientConnection, http->request->hier.code);
425de4c8
AJ
2109 }
2110 if (Ip::Qos::TheConfig.isHitNfmarkActive()) {
73c36fd9 2111 Ip::Qos::doNfmarkLocalMiss(conn->clientConnection, http->request->hier.code);
452bb8e2 2112 }
7172612f 2113 }
7172612f 2114
ab9c533b
HN
2115 /* We've got the final data to start pushing... */
2116 flags.storelogiccomplete = 1;
2117
4993f571 2118 reqofs += result.length;
2119
2120 assert(reqofs <= HTTP_REQBUF_SZ || flags.headersSent);
62e76326 2121
edce4d98 2122 assert(http->request != NULL);
62e76326 2123
edce4d98 2124 /* ESI TODO: remove this assert once everything is stable */
2125 assert(http->client_stream.head->data
62e76326 2126 && cbdataReferenceValid(http->client_stream.head->data));
528b2c61 2127
2128 makeThisHead();
62e76326 2129
bf8fe701 2130 debugs(88, 5, "clientReplyContext::sendMoreData: " << http->uri << ", " <<
47f6e231 2131 reqofs << " bytes (" << result.length <<
bf8fe701 2132 " new bytes)");
47f6e231 2133 debugs(88, 5, "clientReplyContext::sendMoreData:"
73c36fd9 2134 << conn->clientConnection <<
26ac0430
AJ
2135 " '" << entry->url() << "'" <<
2136 " out.offset=" << http->out.offset);
528b2c61 2137
edce4d98 2138 /* update size of the request */
4993f571 2139 reqsize = reqofs;
62e76326 2140
4993f571 2141 if (errorInStream(result, reqofs)) {
62e76326 2142 sendStreamError(result);
2143 return;
edce4d98 2144 }
528b2c61 2145
2146 if (flags.headersSent) {
62e76326 2147 pushStreamData (result, buf);
2148 return;
edce4d98 2149 }
62e76326 2150
b297bcd0 2151 cloneReply();
21b92762 2152
b297bcd0 2153 /* handle headers */
21b92762 2154
b297bcd0 2155 if (Config.onoff.log_mime_hdrs) {
26ac0430 2156 size_t k;
43ae1d95 2157
26ac0430 2158 if ((k = headersEnd(buf, reqofs))) {
41ebd397
CT
2159 safe_free(http->al->headers.reply);
2160 http->al->headers.reply = (char *)xcalloc(k + 1, 1);
2161 xstrncpy(http->al->headers.reply, buf, k);
26ac0430 2162 }
edce4d98 2163 }
b297bcd0
HN
2164
2165 holdingBuffer = result;
2166 processReplyAccess();
2167 return;
edce4d98 2168}
2169
edce4d98 2170/* Using this breaks the client layering just a little!
2171 */
0655fa4d 2172void
f206b652 2173clientReplyContext::createStoreEntry(const HttpRequestMethod& m, RequestFlags reqFlags)
edce4d98 2174{
0655fa4d 2175 assert(http != NULL);
edce4d98 2176 /*
2177 * For erroneous requests, we might not have a h->request,
2178 * so make a fake one.
2179 */
62e76326 2180
b248c2a3
AJ
2181 if (http->request == NULL) {
2182 http->request = new HttpRequest(m, AnyP::PROTO_NONE, null_string);
2183 HTTPMSGLOCK(http->request);
2184 }
62e76326 2185
a8a0b1c2 2186 StoreEntry *e = storeCreateEntry(storeId(), http->log_uri, reqFlags, m);
62e76326 2187
0655fa4d 2188 sc = storeClientListAdd(e, this);
62e76326 2189
9a0a18de 2190#if USE_DELAY_POOLS
0655fa4d 2191 sc->setDelayId(DelayId::DelayClient(http));
edce4d98 2192#endif
62e76326 2193
0655fa4d 2194 reqofs = 0;
62e76326 2195
0655fa4d 2196 reqsize = 0;
62e76326 2197
edce4d98 2198 /* I don't think this is actually needed! -- adrian */
0655fa4d 2199 /* http->reqbuf = http->norm_reqbuf; */
2200 // assert(http->reqbuf == http->norm_reqbuf);
edce4d98 2201 /* The next line is illegal because we don't know if the client stream
26ac0430 2202 * buffers have been set up
edce4d98 2203 */
0655fa4d 2204 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2205 // SendMoreData, this);
edce4d98 2206 /* So, we mark the store logic as complete */
8bcf08e0 2207 flags.storelogiccomplete = 1;
62e76326 2208
edce4d98 2209 /* and get the caller to request a read, from whereever they are */
62e76326 2210 /* NOTE: after ANY data flows down the pipe, even one step,
26ac0430 2211 * this function CAN NOT be used to manage errors
edce4d98 2212 */
86a2f789 2213 http->storeEntry(e);
edce4d98 2214}
2215
2216ErrorState *
955394ce 2217clientBuildError(err_type page_id, Http::StatusCode status, char const *url,
b7ac5457 2218 Ip::Address &src_addr, HttpRequest * request)
edce4d98 2219{
913524f0 2220 ErrorState *err = new ErrorState(page_id, status, request);
cc192b50 2221 err->src_addr = src_addr;
62e76326 2222
edce4d98 2223 if (url)
62e76326 2224 err->url = xstrdup(url);
2225
edce4d98 2226 return err;
2227}