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