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