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