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