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