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