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