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