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