]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_reply.cc
Fix parsing of malformed quoted squid.conf strings (#2239)
[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,
7976fed3 96 const ConnStateData *conn, HttpRequest *failedrequest, const char *unparsedrequest,
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
edce4d98 106 if (unparsedrequest)
62e76326 107 errstate->request_hdrs = xstrdup(unparsedrequest);
edce4d98 108
8eb0a7ee
CT
109#if USE_AUTH
110 errstate->auth_user_request = auth_user_request;
111#endif
eb026889 112 setReplyToError(failedrequest ? failedrequest->method : HttpRequestMethod(Http::METHOD_NONE), errstate);
8eb0a7ee
CT
113}
114
115void clientReplyContext::setReplyToError(const HttpRequestMethod& method, ErrorState *errstate)
116{
955394ce 117 if (errstate->httpStatus == Http::scNotImplemented && http->request)
62e76326 118 /* prevent confusion over whether we default to persistent or not */
e857372a 119 http->request->flags.proxyKeepalive = false;
62e76326 120
41ebd397 121 http->al->http.code = errstate->httpStatus;
edce4d98 122
f0baf149
AR
123 if (http->request)
124 http->request->ignoreRange("responding with a Squid-generated error");
125
f206b652 126 createStoreEntry(method, RequestFlags());
aee3523a 127 assert(errstate->callback_data == nullptr);
86a2f789 128 errorAppendEntry(http->storeEntry(), errstate);
edce4d98 129 /* Now the caller reads to get this */
130}
131
eacfca83
AR
132void
133clientReplyContext::setReplyToReply(HttpReply *futureReply)
134{
135 Must(futureReply);
136 http->al->http.code = futureReply->sline.status();
137
138 HttpRequestMethod method;
139 if (http->request) { // nil on responses to unparsable requests
140 http->request->ignoreRange("responding with a Squid-generated reply");
141 method = http->request->method;
142 }
143
144 createStoreEntry(method, RequestFlags());
145
146 http->storeEntry()->storeErrorResponse(futureReply);
147 /* Now the caller reads to get futureReply */
148}
149
f0baf149
AR
150// Assumes that the entry contains an error response without Content-Range.
151// To use with regular entries, make HTTP Range header removal conditional.
152void clientReplyContext::setReplyToStoreEntry(StoreEntry *entry, const char *reason)
061bbdec 153{
1bfe9ade 154 entry->lock("clientReplyContext::setReplyToStoreEntry"); // removeClientStoreReference() unlocks
061bbdec
CT
155 sc = storeClientListAdd(entry, this);
156#if USE_DELAY_POOLS
157 sc->setDelayId(DelayId::DelayClient(http));
158#endif
f0baf149
AR
159 if (http->request)
160 http->request->ignoreRange(reason);
061bbdec
CT
161 flags.storelogiccomplete = 1;
162 http->storeEntry(entry);
163}
164
edce4d98 165void
0655fa4d 166clientReplyContext::removeStoreReference(store_client ** scp,
167 StoreEntry ** ep)
edce4d98 168{
169 StoreEntry *e;
e4ae841b 170 store_client *sc_tmp = *scp;
62e76326 171
aee3523a
AR
172 if ((e = *ep) != nullptr) {
173 *ep = nullptr;
e4ae841b 174 storeUnregister(sc_tmp, e, this);
aee3523a 175 *scp = nullptr;
1bfe9ade 176 e->unlock("clientReplyContext::removeStoreReference");
edce4d98 177 }
178}
179
86a2f789 180void
8bcf08e0 181clientReplyContext::removeClientStoreReference(store_client **scp, ClientHttpRequest *aHttpRequest)
86a2f789 182{
8bcf08e0 183 StoreEntry *reference = aHttpRequest->storeEntry();
86a2f789 184 removeStoreReference(scp, &reference);
8bcf08e0 185 aHttpRequest->storeEntry(reference);
86a2f789 186}
187
edce4d98 188void
0655fa4d 189clientReplyContext::saveState()
edce4d98 190{
aee3523a 191 assert(old_sc == nullptr);
bf8fe701 192 debugs(88, 3, "clientReplyContext::saveState: saving store context");
86a2f789 193 old_entry = http->storeEntry();
e6ccf245 194 old_sc = sc;
e7e0f8a4
EB
195 old_lastmod = http->request->lastmod;
196 old_etag = http->request->etag;
edce4d98 197 /* Prevent accessing the now saved entries */
aee3523a
AR
198 http->storeEntry(nullptr);
199 sc = nullptr;
edce4d98 200}
201
202void
0655fa4d 203clientReplyContext::restoreState()
edce4d98 204{
aee3523a 205 assert(old_sc != nullptr);
bf8fe701 206 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
86a2f789 207 removeClientStoreReference(&sc, http);
208 http->storeEntry(old_entry);
e6ccf245 209 sc = old_sc;
e7e0f8a4
EB
210 http->request->lastmod = old_lastmod;
211 http->request->etag = old_etag;
edce4d98 212 /* Prevent accessed the old saved entries */
aee3523a
AR
213 old_entry = nullptr;
214 old_sc = nullptr;
e7e0f8a4
EB
215 old_lastmod = -1;
216 old_etag.clean();
c8be6d7b 217}
218
219void
0655fa4d 220clientReplyContext::startError(ErrorState * err)
c8be6d7b 221{
f206b652 222 createStoreEntry(http->request->method, RequestFlags());
0655fa4d 223 triggerInitialStoreRead();
86a2f789 224 errorAppendEntry(http->storeEntry(), err);
edce4d98 225}
226
e6ccf245 227clientStreamNode *
528b2c61 228clientReplyContext::getNextNode() const
e6ccf245 229{
62e76326 230 return (clientStreamNode *)ourNode->node.next->data;
e6ccf245 231}
232
122a6e3c
AR
233/// Request HTTP response headers from Store, to be sent to the given recipient.
234/// That recipient also gets zero, some, or all HTTP response body bytes (into
235/// next()->readBuffer).
c8be6d7b 236void
122a6e3c 237clientReplyContext::triggerInitialStoreRead(STCB recipient)
c8be6d7b 238{
122a6e3c
AR
239 Assure(recipient != HandleIMSReply);
240 lastStreamBufferedBytes = StoreIOBuffer(); // storeClientCopy(next()->readBuffer) invalidates
8bcf08e0 241 StoreIOBuffer localTempBuffer (next()->readBuffer.length, 0, next()->readBuffer.data);
122a6e3c
AR
242 ::storeClientCopy(sc, http->storeEntry(), localTempBuffer, recipient, this);
243}
244
245/// Request HTTP response body bytes from Store into next()->readBuffer. This
246/// method requests body bytes at readerBuffer.offset and, hence, it should only
247/// be called after we triggerInitialStoreRead() and get the requested HTTP
248/// response headers (using zero offset).
249void
250clientReplyContext::requestMoreBodyFromStore()
251{
252 lastStreamBufferedBytes = StoreIOBuffer(); // storeClientCopy(next()->readBuffer) invalidates
253 ::storeClientCopy(sc, http->storeEntry(), next()->readBuffer, SendMoreData, this);
c8be6d7b 254}
edce4d98 255
256/* there is an expired entry in the store.
257 * setup a temporary buffer area and perform an IMS to the origin
258 */
0655fa4d 259void
260clientReplyContext::processExpired()
edce4d98 261{
a8a0b1c2 262 const char *url = storeId();
bf8fe701 263 debugs(88, 3, "clientReplyContext::processExpired: '" << http->uri << "'");
438b41ba
EB
264 const time_t lastmod = http->storeEntry()->lastModified();
265 assert(lastmod >= 0);
edce4d98 266 /*
267 * check if we are allowed to contact other servers
26ac0430 268 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
edce4d98 269 * a stale entry *if* it matches client requirements
270 */
62e76326 271
0655fa4d 272 if (http->onlyIfCached()) {
273 processOnlyIfCachedMiss();
62e76326 274 return;
edce4d98 275 }
62e76326 276
12f5a662 277 http->updateLoggingTags(LOG_TCP_REFRESH);
e857372a 278 http->request->flags.refresh = true;
edce4d98 279#if STORE_CLIENT_LIST_DEBUG
c8be6d7b 280 /* Prevent a race with the store client memory free routines
edce4d98 281 */
0655fa4d 282 assert(storeClientIsThisAClient(sc, this));
edce4d98 283#endif
284 /* Prepare to make a new temporary request */
0655fa4d 285 saveState();
1a210de4 286
d2a6dcba 287 // TODO: Consider also allowing regular (non-collapsed) revalidation hits.
1a210de4 288 // TODO: support collapsed revalidation for Vary-controlled entries
819be284 289 bool collapsingAllowed = Config.onoff.collapsed_forwarding &&
daed75a9 290 !Store::Controller::SmpAware() &&
819be284 291 http->request->vary_headers.isEmpty();
1a210de4
EB
292
293 StoreEntry *entry = nullptr;
294 if (collapsingAllowed) {
819be284 295 if (const auto e = storeGetPublicByRequest(http->request, ksRevalidation)) {
d2a6dcba 296 if (e->hittingRequiresCollapsing() && startCollapsingOn(*e, true)) {
819be284
EB
297 entry = e;
298 entry->lock("clientReplyContext::processExpired#alreadyRevalidating");
299 } else {
d868b138 300 e->abandon(__func__);
819be284
EB
301 // assume mayInitiateCollapsing() would fail too
302 collapsingAllowed = false;
303 }
304 }
1a210de4
EB
305 }
306
307 if (entry) {
76d61119 308 entry->ensureMemObject(url, http->log_uri, http->request->method);
1a210de4
EB
309 debugs(88, 5, "collapsed on existing revalidation entry: " << *entry);
310 collapsedRevalidation = crSlave;
311 } else {
312 entry = storeCreateEntry(url,
313 http->log_uri, http->request->flags, http->request->method);
314 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
315
819be284
EB
316 if (collapsingAllowed && mayInitiateCollapsing() &&
317 Store::Root().allowCollapsing(entry, http->request->flags, http->request->method)) {
1a210de4 318 debugs(88, 5, "allow other revalidation requests to collapse on " << *entry);
1a210de4
EB
319 collapsedRevalidation = crInitiator;
320 } else {
321 collapsedRevalidation = crNone;
322 }
323 }
324
0655fa4d 325 sc = storeClientListAdd(entry, this);
9a0a18de 326#if USE_DELAY_POOLS
edce4d98 327 /* delay_id is already set on original store client */
0655fa4d 328 sc->setDelayId(DelayId::DelayClient(http));
edce4d98 329#endif
62e76326 330
438b41ba 331 http->request->lastmod = lastmod;
46017fdd 332
789217a2 333 if (!http->request->header.has(Http::HdrType::IF_NONE_MATCH)) {
aee3523a 334 ETag etag = {nullptr, -1}; // TODO: make that a default ETag constructor
46017fdd
CT
335 if (old_entry->hasEtag(etag) && !etag.weak)
336 http->request->etag = etag.str;
337 }
338
438b41ba 339 debugs(88, 5, "lastmod " << entry->lastModified());
86a2f789 340 http->storeEntry(entry);
c8be6d7b 341 assert(http->out.offset == 0);
9174ba3d 342 assert(http->request->clientConnectionManager == http->getConn());
655daa06 343
1a210de4
EB
344 if (collapsedRevalidation != crSlave) {
345 /*
346 * A refcounted pointer so that FwdState stays around as long as
347 * this clientReplyContext does
348 */
aee3523a 349 Comm::ConnectionPointer conn = http->getConn() != nullptr ? http->getConn()->clientConnection : nullptr;
1a210de4
EB
350 FwdState::Start(conn, http->storeEntry(), http->request, http->al);
351 }
edce4d98 352 /* Register with storage manager to receive updates when data comes in. */
62e76326 353
edce4d98 354 if (EBIT_TEST(entry->flags, ENTRY_ABORTED))
fa84c01d 355 debugs(88, DBG_CRITICAL, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
62e76326 356
c8be6d7b 357 {
62e76326 358 /* start counting the length from 0 */
8bcf08e0 359 StoreIOBuffer localTempBuffer(HTTP_REQBUF_SZ, 0, tempbuf);
122a6e3c
AR
360 // keep lastStreamBufferedBytes: tempbuf is not a Client Stream buffer
361 ::storeClientCopy(sc, entry, localTempBuffer, HandleIMSReply, this);
edce4d98 362 }
363}
364
528b2c61 365void
122a6e3c 366clientReplyContext::sendClientUpstreamResponse(const StoreIOBuffer &upstreamResponse)
528b2c61 367{
0655fa4d 368 removeStoreReference(&old_sc, &old_entry);
6c8cbe63
D
369
370 if (collapsedRevalidation)
371 http->storeEntry()->clearPublicKeyScope();
372
2324cda2 373 /* here the data to send is the data we just received */
86a2f789 374 assert(!EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED));
122a6e3c 375 sendMoreData(upstreamResponse);
528b2c61 376}
377
edce4d98 378void
0655fa4d 379clientReplyContext::HandleIMSReply(void *data, StoreIOBuffer result)
edce4d98 380{
e6ccf245 381 clientReplyContext *context = (clientReplyContext *)data;
0655fa4d 382 context->handleIMSReply(result);
383}
62e76326 384
0655fa4d 385void
386clientReplyContext::sendClientOldEntry()
387{
388 /* Get the old request back */
389 restoreState();
84f5cdd6
AR
390
391 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) {
392 debugs(88, 3, "stale entry aborted while we revalidated: " << *http->storeEntry());
393 http->updateLoggingTags(LOG_TCP_MISS);
394 processMiss();
395 return;
396 }
397
0655fa4d 398 /* here the data to send is in the next nodes buffers already */
122a6e3c
AR
399 Assure(matchesStreamBodyBuffer(lastStreamBufferedBytes));
400 Assure(!lastStreamBufferedBytes.offset);
401 sendMoreData(lastStreamBufferedBytes);
0655fa4d 402}
62e76326 403
1d7ab0f4 404/* This is the workhorse of the HandleIMSReply callback.
405 *
406 * It is called when we've got data back from the origin following our
407 * IMS request to revalidate a stale entry.
408 */
0655fa4d 409void
122a6e3c 410clientReplyContext::handleIMSReply(const StoreIOBuffer result)
0655fa4d 411{
1d7ab0f4 412 if (deleting)
413 return;
62e76326 414
aee3523a 415 if (http->storeEntry() == nullptr)
1d7ab0f4 416 return;
07947ad8 417
122a6e3c
AR
418 debugs(88, 3, http->storeEntry()->url() << " got " << result);
419
1d7ab0f4 420 if (result.flags.error && !EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED))
421 return;
62e76326 422
39fe14b2
EB
423 if (collapsedRevalidation == crSlave && !http->storeEntry()->mayStartHitting()) {
424 debugs(88, 3, "CF slave hit private non-shareable " << *http->storeEntry() << ". MISS");
096c9df3
EB
425 // restore context to meet processMiss() expectations
426 restoreState();
12f5a662 427 http->updateLoggingTags(LOG_TCP_MISS);
096c9df3
EB
428 processMiss();
429 return;
430 }
431
1d7ab0f4 432 // request to origin was aborted
433 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) {
eace013e 434 debugs(88, 3, "request to origin aborted '" << http->storeEntry()->url() << "', sending old entry to client");
12f5a662 435 http->updateLoggingTags(LOG_TCP_REFRESH_FAIL_OLD);
1d7ab0f4 436 sendClientOldEntry();
760e650f 437 return;
0655fa4d 438 }
62e76326 439
66d51f4f
AR
440 const auto oldStatus = old_entry->mem().freshestReply().sline.status();
441 const auto &new_rep = http->storeEntry()->mem().freshestReply();
442 const auto status = new_rep.sline.status();
62e76326 443
6c8cbe63
D
444 // XXX: Disregard stale incomplete (i.e. still being written) borrowed (i.e.
445 // not caused by our request) IMS responses. That new_rep may be very old!
446
b297bcd0 447 // origin replied 304
955394ce 448 if (status == Http::scNotModified) {
66d51f4f
AR
449 // TODO: The update may not be instantaneous. Should we wait for its
450 // completion to avoid spawning too much client-disassociated work?
55e1c6e8
EB
451 if (!Store::Root().updateOnNotModified(old_entry, *http->storeEntry())) {
452 old_entry->release(true);
453 restoreState();
454 http->updateLoggingTags(LOG_TCP_MISS);
455 processMiss();
456 return;
457 }
458
459 http->updateLoggingTags(LOG_TCP_REFRESH_UNMODIFIED);
460 http->request->flags.staleIfHit = false; // old_entry is no longer stale
62e76326 461
26ac0430 462 // if client sent IMS
438b41ba 463 if (http->request->flags.ims && !old_entry->modifiedSince(http->request->ims, http->request->imslen)) {
26ac0430 464 // forward the 304 from origin
760e650f 465 debugs(88, 3, "origin replied 304, revalidated existing entry and forwarding 304 to client");
122a6e3c 466 sendClientUpstreamResponse(result);
760e650f 467 return;
26ac0430 468 }
760e650f
AJ
469
470 // send existing entry, it's still valid
471 debugs(88, 3, "origin replied 304, revalidated existing entry and sending " << oldStatus << " to client");
472 sendClientOldEntry();
473 return;
b297bcd0 474 }
62e76326 475
b297bcd0 476 // origin replied with a non-error code
760e650f 477 if (status > Http::scNone && status < Http::scInternalServerError) {
0ac163be
AJ
478 // RFC 9111 section 4:
479 // "When more than one suitable response is stored,
480 // a cache MUST use the most recent one
481 // (as determined by the Date header field)."
66d51f4f 482 if (new_rep.olderThan(&old_entry->mem().freshestReply())) {
12f5a662 483 http->al->cache.code.err.ignored = true;
760e650f 484 debugs(88, 3, "origin replied " << status << " but with an older date header, sending old entry (" << oldStatus << ") to client");
eace013e 485 sendClientOldEntry();
760e650f 486 return;
eace013e 487 }
760e650f 488
12f5a662 489 http->updateLoggingTags(LOG_TCP_REFRESH_MODIFIED);
760e650f 490 debugs(88, 3, "origin replied " << status << ", forwarding to client");
122a6e3c 491 sendClientUpstreamResponse(result);
760e650f 492 return;
b297bcd0 493 }
62e76326 494
b297bcd0 495 // origin replied with an error
760e650f 496 if (http->request->flags.failOnValidationError) {
12f5a662 497 http->updateLoggingTags(LOG_TCP_REFRESH_FAIL_ERR);
760e650f 498 debugs(88, 3, "origin replied with error " << status << ", forwarding to client due to fail_on_validation_err");
122a6e3c 499 sendClientUpstreamResponse(result);
760e650f 500 return;
1d7ab0f4 501 }
760e650f
AJ
502
503 // ignore and let client have old entry
12f5a662 504 http->updateLoggingTags(LOG_TCP_REFRESH_FAIL_OLD);
760e650f
AJ
505 debugs(88, 3, "origin replied with error " << status << ", sending old entry (" << oldStatus << ") to client");
506 sendClientOldEntry();
edce4d98 507}
508
ca919500
FC
509CSR clientGetMoreData;
510CSD clientReplyDetach;
edce4d98 511
122a6e3c 512/// \copydoc clientReplyContext::cacheHit()
edce4d98 513void
0655fa4d 514clientReplyContext::CacheHit(void *data, StoreIOBuffer result)
edce4d98 515{
e6ccf245 516 clientReplyContext *context = (clientReplyContext *)data;
7d5f62a4 517 context->cacheHit(result);
0655fa4d 518}
519
122a6e3c
AR
520/// Processes HTTP response headers received from Store on a suspected cache hit
521/// path. May be called several times (e.g., a Vary marker object hit followed
522/// by the corresponding variant hit).
0655fa4d 523void
122a6e3c 524clientReplyContext::cacheHit(const StoreIOBuffer result)
0655fa4d 525{
7d5f62a4 526 /** Ignore if the HIT object is being deleted. */
1b7514d9
AJ
527 if (deleting) {
528 debugs(88, 3, "HIT object being deleted. Ignore the HIT.");
045a76ab 529 return;
1b7514d9 530 }
045a76ab 531
86a2f789 532 StoreEntry *e = http->storeEntry();
045a76ab 533
190154cf 534 HttpRequest *r = http->request;
045a76ab 535
122a6e3c 536 debugs(88, 3, http->uri << " got " << result);
62e76326 537
aee3523a 538 if (http->storeEntry() == nullptr) {
bf8fe701 539 debugs(88, 3, "clientCacheHit: request aborted");
62e76326 540 return;
c8be6d7b 541 } else if (result.flags.error) {
62e76326 542 /* swap in failure */
bf8fe701 543 debugs(88, 3, "clientCacheHit: swapin failure for " << http->uri);
12f5a662 544 http->updateLoggingTags(LOG_TCP_SWAPFAIL_MISS);
86a2f789 545 removeClientStoreReference(&sc, http);
0655fa4d 546 processMiss();
62e76326 547 return;
edce4d98 548 }
62e76326 549
2f8abb64 550 // The previously identified hit suddenly became unshareable!
096c9df3
EB
551 // This is common for collapsed forwarding slaves but might also
552 // happen to regular hits because we are called asynchronously.
39fe14b2 553 if (!e->mayStartHitting()) {
2f8abb64 554 debugs(88, 3, "unshareable " << *e << ". MISS");
12f5a662 555 http->updateLoggingTags(LOG_TCP_MISS);
096c9df3
EB
556 processMiss();
557 return;
558 }
559
84f5cdd6
AR
560 if (EBIT_TEST(e->flags, ENTRY_ABORTED)) {
561 debugs(88, 3, "refusing aborted " << *e);
562 http->updateLoggingTags(LOG_TCP_MISS);
563 processMiss();
564 return;
565 }
62e76326 566
edce4d98 567 /*
568 * Got the headers, now grok them
569 */
12f5a662 570 assert(http->loggingTags().oldType == LOG_TCP_HIT);
62e76326 571
851feda6 572 if (http->request->storeId().cmp(e->mem_obj->storeId()) != 0) {
c877c0bc 573 debugs(33, DBG_IMPORTANT, "clientProcessHit: URL mismatch, '" << e->mem_obj->storeId() << "' != '" << http->request->storeId() << "'");
12f5a662 574 http->updateLoggingTags(LOG_TCP_MISS); // we lack a more precise LOG_*_MISS code
cdd4e1c1 575 processMiss();
576 return;
577 }
578
122a6e3c
AR
579 noteStreamBufferredBytes(result);
580
edce4d98 581 switch (varyEvaluateMatch(e, r)) {
62e76326 582
edce4d98 583 case VARY_NONE:
62e76326 584 /* No variance detected. Continue as normal */
585 break;
586
edce4d98 587 case VARY_MATCH:
62e76326 588 /* This is the correct entity for this request. Continue */
bf8fe701 589 debugs(88, 2, "clientProcessHit: Vary MATCH!");
62e76326 590 break;
591
edce4d98 592 case VARY_OTHER:
62e76326 593 /* This is not the correct entity for this request. We need
594 * to requery the cache.
595 */
86a2f789 596 removeClientStoreReference(&sc, http);
aee3523a 597 e = nullptr;
62e76326 598 /* Note: varyEvalyateMatch updates the request with vary information
599 * so we only get here once. (it also takes care of cancelling loops)
600 */
26ac0430 601 debugs(88, 2, "clientProcessHit: Vary detected!");
0655fa4d 602 clientGetMoreData(ourNode, http);
62e76326 603 return;
604
edce4d98 605 case VARY_CANCEL:
62e76326 606 /* varyEvaluateMatch found a object loop. Process as miss */
e0236918 607 debugs(88, DBG_IMPORTANT, "clientProcessHit: Vary object loop!");
12f5a662 608 http->updateLoggingTags(LOG_TCP_MISS); // we lack a more precise LOG_*_MISS code
0655fa4d 609 processMiss();
62e76326 610 return;
edce4d98 611 }
62e76326 612
c2a7cefd 613 if (r->method == Http::METHOD_PURGE) {
1b7514d9 614 debugs(88, 5, "PURGE gets a HIT");
86a2f789 615 removeClientStoreReference(&sc, http);
aee3523a 616 e = nullptr;
0655fa4d 617 purgeRequest();
62e76326 618 return;
edce4d98 619 }
62e76326 620
1b7514d9
AJ
621 if (e->checkNegativeHit() && !r->flags.noCacheHack()) {
622 debugs(88, 5, "negative-HIT");
12f5a662 623 http->updateLoggingTags(LOG_TCP_NEGATIVE_HIT);
0655fa4d 624 sendMoreData(result);
ec4011ac 625 return;
70706149
AR
626 } else if (blockedHit()) {
627 debugs(88, 5, "send_hit forces a MISS");
12f5a662 628 http->updateLoggingTags(LOG_TCP_MISS);
70706149
AR
629 processMiss();
630 return;
ee989932 631 } else if (!r->flags.internal && !didCollapse && refreshCheckHTTP(e, r)) {
bf8fe701 632 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
62e76326 633 /*
634 * We hold a stale copy; it needs to be validated
635 */
636 /*
450fe1cb 637 * The 'needValidation' flag is used to prevent forwarding
62e76326 638 * loops between siblings. If our copy of the object is stale,
639 * then we should probably only use parents for the validation
640 * request. Otherwise two siblings could generate a loop if
641 * both have a stale version of the object.
642 */
e857372a 643 r->flags.needValidation = true;
62e76326 644
438b41ba
EB
645 if (e->lastModified() < 0) {
646 debugs(88, 3, "validate HIT object? NO. Can't calculate entry modification time. Do MISS.");
62e76326 647 /*
438b41ba
EB
648 * We cannot revalidate entries without knowing their
649 * modification time.
650 * XXX: BUG 1890 objects without Date do not get one added.
62e76326 651 */
12f5a662 652 http->updateLoggingTags(LOG_TCP_MISS);
0655fa4d 653 processMiss();
450fe1cb 654 } else if (r->flags.noCache) {
86310427 655 debugs(88, 3, "validate HIT object? NO. Client sent CC:no-cache. Do CLIENT_REFRESH_MISS");
62e76326 656 /*
657 * This did not match a refresh pattern that overrides no-cache
658 * we should honour the client no-cache header.
659 */
12f5a662 660 http->updateLoggingTags(LOG_TCP_CLIENT_REFRESH_MISS);
0655fa4d 661 processMiss();
ec4568e3 662 } else if (r->url.getScheme() == AnyP::PROTO_HTTP || r->url.getScheme() == AnyP::PROTO_HTTPS) {
86310427 663 debugs(88, 3, "validate HIT object? YES.");
62e76326 664 /*
665 * Object needs to be revalidated
666 * XXX This could apply to FTP as well, if Last-Modified is known.
667 */
0655fa4d 668 processExpired();
62e76326 669 } else {
86310427 670 debugs(88, 3, "validate HIT object? NO. Client protocol non-HTTP. Do MISS.");
62e76326 671 /*
672 * We don't know how to re-validate other protocols. Handle
673 * them as if the object has expired.
674 */
12f5a662 675 http->updateLoggingTags(LOG_TCP_MISS);
0655fa4d 676 processMiss();
62e76326 677 }
ec4011ac 678 return;
1b7514d9
AJ
679 } else if (r->conditional()) {
680 debugs(88, 5, "conditional HIT");
8b082ed9 681 if (processConditional())
acd68301
GD
682 return;
683 }
684
685 /*
686 * plain ol' cache hit
687 */
688 debugs(88, 5, "plain old HIT");
62e76326 689
9a0a18de 690#if USE_DELAY_POOLS
acd68301 691 if (e->store_status != STORE_OK)
12f5a662 692 http->updateLoggingTags(LOG_TCP_MISS);
acd68301 693 else
5bf4d170 694#endif
acd68301 695 if (e->mem_status == IN_MEMORY)
12f5a662 696 http->updateLoggingTags(LOG_TCP_MEM_HIT);
acd68301 697 else if (Config.onoff.offline)
12f5a662 698 http->updateLoggingTags(LOG_TCP_OFFLINE_HIT);
62e76326 699
acd68301 700 sendMoreData(result);
edce4d98 701}
702
7d5f62a4 703/**
edce4d98 704 * Prepare to fetch the object as it's a cache miss of some kind.
705 */
706void
0655fa4d 707clientReplyContext::processMiss()
edce4d98 708{
edce4d98 709 char *url = http->uri;
190154cf 710 HttpRequest *r = http->request;
aee3523a 711 ErrorState *err = nullptr;
7f06a3d8 712 debugs(88, 4, r->method << ' ' << url);
7d5f62a4
AJ
713
714 /**
edce4d98 715 * We might have a left-over StoreEntry from a failed cache hit
716 * or IMS request.
717 */
86a2f789 718 if (http->storeEntry()) {
719 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_SPECIAL)) {
fa84c01d 720 debugs(88, DBG_CRITICAL, "clientProcessMiss: miss on a special object (" << url << ").");
12f5a662 721 debugs(88, DBG_CRITICAL, "\tlog_type = " << http->loggingTags().c_str());
3900307b 722 http->storeEntry()->dump(1);
62e76326 723 }
724
86a2f789 725 removeClientStoreReference(&sc, http);
edce4d98 726 }
62e76326 727
7d5f62a4 728 /** Check if its a PURGE request to be actioned. */
c2a7cefd 729 if (r->method == Http::METHOD_PURGE) {
0655fa4d 730 purgeRequest();
62e76326 731 return;
edce4d98 732 }
914b89a2 733
7d5f62a4 734 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
c2a7cefd 735 if (r->method == Http::METHOD_OTHER) {
26ac0430 736 purgeAllCached();
60745f24 737 }
62e76326 738
7d5f62a4 739 /** Check if 'only-if-cached' flag is set. Action if so. */
0655fa4d 740 if (http->onlyIfCached()) {
741 processOnlyIfCachedMiss();
62e76326 742 return;
edce4d98 743 }
62e76326 744
42829656 745 /// Deny loops
450fe1cb 746 if (r->flags.loopDetected) {
955394ce 747 http->al->http.code = Http::scForbidden;
7976fed3 748 err = clientBuildError(ERR_ACCESS_DENIED, Http::scForbidden, nullptr, http->getConn(), http->request, http->al);
f206b652 749 createStoreEntry(r->method, RequestFlags());
86a2f789 750 errorAppendEntry(http->storeEntry(), err);
0655fa4d 751 triggerInitialStoreRead();
62e76326 752 return;
edce4d98 753 } else {
26ac0430 754 assert(http->out.offset == 0);
0655fa4d 755 createStoreEntry(r->method, r->flags);
756 triggerInitialStoreRead();
62e76326 757
758 if (http->redirect.status) {
66d51f4f 759 const HttpReplyPointer rep(new HttpReply);
12f5a662 760 http->updateLoggingTags(LOG_TCP_REDIRECT);
d88e3c49 761 http->storeEntry()->releaseRequest();
06a5ae20 762 rep->redirect(http->redirect.status, http->redirect.location);
db237875 763 http->storeEntry()->replaceHttpReply(rep);
86a2f789 764 http->storeEntry()->complete();
62e76326 765 return;
766 }
767
9174ba3d 768 assert(r->clientConnectionManager == http->getConn());
655daa06 769
7976fed3 770 Comm::ConnectionPointer conn = http->getConn() != nullptr ? http->getConn()->clientConnection : nullptr;
7d5f62a4 771 /** Start forwarding to get the new object from network */
4bf68cfa 772 FwdState::Start(conn, http->storeEntry(), r, http->al);
edce4d98 773 }
774}
775
7d5f62a4 776/**
edce4d98 777 * client issued a request with an only-if-cached cache-control directive;
778 * we did not find a cached object that can be returned without
779 * contacting other servers;
780 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
781 */
0655fa4d 782void
783clientReplyContext::processOnlyIfCachedMiss()
edce4d98 784{
7f06a3d8 785 debugs(88, 4, http->request->method << ' ' << http->uri);
f11c8e2f 786 http->al->http.code = Http::scGatewayTimeout;
aee3523a 787 ErrorState *err = clientBuildError(ERR_ONLY_IF_CACHED_MISS, Http::scGatewayTimeout, nullptr,
7976fed3 788 http->getConn(), http->request, http->al);
86a2f789 789 removeClientStoreReference(&sc, http);
0655fa4d 790 startError(err);
edce4d98 791}
792
79c8035e 793/// process conditional request from client
acd68301 794bool
8b082ed9 795clientReplyContext::processConditional()
79c8035e 796{
a2bd457d 797 StoreEntry *const e = http->storeEntry();
79c8035e 798
66d51f4f
AR
799 const auto replyStatusCode = e->mem().baseReply().sline.status();
800 if (replyStatusCode != Http::scOkay) {
801 debugs(88, 4, "miss because " << replyStatusCode << " != 200");
12f5a662 802 http->updateLoggingTags(LOG_TCP_MISS);
79c8035e 803 processMiss();
acd68301 804 return true;
79c8035e
AR
805 }
806
807 HttpRequest &r = *http->request;
808
789217a2 809 if (r.header.has(Http::HdrType::IF_MATCH) && !e->hasIfMatchEtag(r)) {
79c8035e
AR
810 // RFC 2616: reply with 412 Precondition Failed if If-Match did not match
811 sendPreconditionFailedError();
acd68301 812 return true;
79c8035e
AR
813 }
814
789217a2 815 if (r.header.has(Http::HdrType::IF_NONE_MATCH)) {
787ea68c
GD
816 // RFC 7232: If-None-Match recipient MUST ignore IMS
817 r.flags.ims = false;
818 r.ims = -1;
819 r.imslen = 0;
820 r.header.delById(Http::HdrType::IF_MODIFIED_SINCE);
79c8035e 821
787ea68c 822 if (e->hasIfNoneMatchEtag(r)) {
a2bd457d 823 sendNotModifiedOrPreconditionFailedError();
acd68301 824 return true;
79c8035e
AR
825 }
826
787ea68c
GD
827 // None-Match is true (no ETag matched); treat as an unconditional hit
828 return false;
79c8035e
AR
829 }
830
45e5102d 831 if (r.flags.ims) {
79c8035e 832 // handle If-Modified-Since requests from the client
438b41ba 833 if (e->modifiedSince(r.ims, r.imslen)) {
2e2ef19a
SM
834 // Modified-Since is true; treat as an unconditional hit
835 return false;
79c8035e 836
acd68301
GD
837 } else {
838 // otherwise reply with 304 Not Modified
839 sendNotModified();
840 }
841 return true;
79c8035e 842 }
acd68301
GD
843
844 return false;
79c8035e
AR
845}
846
70706149
AR
847/// whether squid.conf send_hit prevents us from serving this hit
848bool
849clientReplyContext::blockedHit() const
850{
851 if (!Config.accessList.sendHit)
852 return false; // hits are not blocked by default
853
101694e4 854 if (http->request->flags.internal)
70706149
AR
855 return false; // internal content "hits" cannot be blocked
856
66d51f4f 857 {
ebe87c09
EB
858 ACLFilledChecklist chl(Config.accessList.sendHit, nullptr);
859 clientAclChecklistFill(chl, http);
860 chl.updateReply(&http->storeEntry()->mem().freshestReply());
861 return !chl.fastCheck().allowed(); // when in doubt, block
70706149 862 }
70706149
AR
863}
864
c1520b67
AJ
865// Purges all entries with a given url
866// TODO: move to SideAgent parent, when we have one
60745f24 867/*
868 * We probably cannot purge Vary-affected responses because their MD5
869 * keys depend on vary headers.
870 */
c1520b67 871void
90bd689c 872purgeEntriesByUrl(HttpRequest * req, const char *url)
c1520b67 873{
c2a7cefd
AJ
874 for (HttpRequestMethod m(Http::METHOD_NONE); m != Http::METHOD_ENUM_END; ++m) {
875 if (m.respMaybeCacheable()) {
4310f8b0
EB
876 const cache_key *key = storeKeyPublic(url, m);
877 debugs(88, 5, m << ' ' << url << ' ' << storeKeyText(key));
90bd689c 878#if USE_HTCP
1ac1d4d3 879 neighborsHtcpClear(nullptr, req, m, HTCP_CLR_INVALIDATION);
8b082ed9
FC
880#else
881 (void)req;
90bd689c 882#endif
4310f8b0 883 Store::Root().evictIfFound(key);
c1520b67
AJ
884 }
885 }
886}
887
26ac0430 888void
60745f24 889clientReplyContext::purgeAllCached()
890{
851feda6
AJ
891 // XXX: performance regression, c_str() reallocates
892 SBuf url(http->request->effectiveRequestUri());
893 purgeEntriesByUrl(http->request, url.c_str());
35ececa5 894}
60745f24 895
d2a6dcba 896LogTags *
7976fed3 897clientReplyContext::loggingTags() const
d2a6dcba
EB
898{
899 // XXX: clientReplyContext code assumes that http cbdata is always valid.
900 // TODO: Either add cbdataReferenceValid(http) checks in all the relevant
901 // places, like this one, or remove cbdata protection of the http member.
12f5a662 902 return &http->al->cache.code;
d2a6dcba
EB
903}
904
e6ccf245 905void
906clientReplyContext::purgeRequest()
edce4d98 907{
bf8fe701 908 debugs(88, 3, "Config2.onoff.enable_purge = " <<
909 Config2.onoff.enable_purge);
62e76326 910
edce4d98 911 if (!Config2.onoff.enable_purge) {
12f5a662 912 http->updateLoggingTags(LOG_TCP_DENIED);
aee3523a 913 ErrorState *err = clientBuildError(ERR_ACCESS_DENIED, Http::scForbidden, nullptr,
7976fed3 914 http->getConn(), http->request, http->al);
0655fa4d 915 startError(err);
62e76326 916 return;
edce4d98 917 }
62e76326 918
edce4d98 919 /* Release both IP cache */
5c51bffb 920 ipcacheInvalidate(http->request->url.host());
edce4d98 921
7976fed3
EB
922 // TODO: can we use purgeAllCached() here instead?
923 purgeDoPurge();
e6ccf245 924}
925
926void
7976fed3
EB
927clientReplyContext::purgeDoPurge()
928{
929 auto firstFound = false;
930 if (const auto entry = storeGetPublicByRequestMethod(http->request, Http::METHOD_GET)) {
931 // special entries are only METHOD_GET entries without variance
932 if (EBIT_TEST(entry->flags, ENTRY_SPECIAL)) {
12f5a662 933 http->updateLoggingTags(LOG_TCP_DENIED);
7976fed3
EB
934 const auto err = clientBuildError(ERR_ACCESS_DENIED, Http::scForbidden, nullptr,
935 http->getConn(), http->request, http->al);
936 startError(err);
d868b138 937 entry->abandon(__func__);
7976fed3
EB
938 return;
939 }
940 firstFound = true;
941 if (!purgeEntry(*entry, Http::METHOD_GET))
942 return;
edce4d98 943 }
62e76326 944
7976fed3 945 detailStoreLookup(storeLookupString(firstFound));
e6ccf245 946
7976fed3
EB
947 if (const auto entry = storeGetPublicByRequestMethod(http->request, Http::METHOD_HEAD)) {
948 if (!purgeEntry(*entry, Http::METHOD_HEAD))
949 return;
edce4d98 950 }
62e76326 951
edce4d98 952 /* And for Vary, release the base URI if none of the headers was included in the request */
90ab8f20
AJ
953 if (!http->request->vary_headers.isEmpty()
954 && http->request->vary_headers.find('=') != SBuf::npos) {
851feda6
AJ
955 // XXX: performance regression, c_str() reallocates
956 SBuf tmp(http->request->effectiveRequestUri());
62e76326 957
7976fed3
EB
958 if (const auto entry = storeGetPublic(tmp.c_str(), Http::METHOD_GET)) {
959 if (!purgeEntry(*entry, Http::METHOD_GET, "Vary "))
960 return;
62e76326 961 }
962
7976fed3
EB
963 if (const auto entry = storeGetPublic(tmp.c_str(), Http::METHOD_HEAD)) {
964 if (!purgeEntry(*entry, Http::METHOD_HEAD, "Vary "))
965 return;
62e76326 966 }
edce4d98 967 }
62e76326 968
7f98aad5
CT
969 if (purgeStatus == Http::scNone)
970 purgeStatus = Http::scNotFound;
971
edce4d98 972 /*
973 * Make a new entry to hold the reply to be written
974 * to the client.
975 */
9837567d 976 /* TODO: This doesn't need to go through the store. Simply
528b2c61 977 * push down the client chain
978 */
f206b652 979 createStoreEntry(http->request->method, RequestFlags());
62e76326 980
0655fa4d 981 triggerInitialStoreRead();
62e76326 982
66d51f4f 983 const HttpReplyPointer rep(new HttpReply);
aee3523a 984 rep->setHeaders(purgeStatus, nullptr, nullptr, 0, 0, -1);
7dc5f514 985 http->storeEntry()->replaceHttpReply(rep);
86a2f789 986 http->storeEntry()->complete();
edce4d98 987}
988
7976fed3
EB
989bool
990clientReplyContext::purgeEntry(StoreEntry &entry, const Http::MethodType methodType, const char *descriptionPrefix)
991{
992 debugs(88, 4, descriptionPrefix << Http::MethodStr(methodType) << " '" << entry.url() << "'" );
993#if USE_HTCP
994 neighborsHtcpClear(&entry, http->request, HttpRequestMethod(methodType), HTCP_CLR_PURGE);
995#endif
996 entry.release(true);
997 purgeStatus = Http::scOkay;
998 return true;
999}
1000
edce4d98 1001void
122a6e3c 1002clientReplyContext::traceReply()
edce4d98 1003{
f206b652 1004 createStoreEntry(http->request->method, RequestFlags());
122a6e3c 1005 triggerInitialStoreRead();
d88e3c49 1006 http->storeEntry()->releaseRequest();
3900307b 1007 http->storeEntry()->buffer();
66d51f4f 1008 const HttpReplyPointer rep(new HttpReply);
aee3523a 1009 rep->setHeaders(Http::scOkay, nullptr, "text/plain", http->request->prefixLen(), 0, squid_curtime);
db237875 1010 http->storeEntry()->replaceHttpReply(rep);
5cafad19 1011 http->request->swapOut(http->storeEntry());
86a2f789 1012 http->storeEntry()->complete();
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