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