]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_reply.cc
Bug #2648: Reserved helpers not shut down after reconfigure/rotate
[thirdparty/squid.git] / src / client_side_reply.cc
CommitLineData
edce4d98 1/*
262a0e14 2 * $Id$
edce4d98 3 *
4 * DEBUG: section 88 Client-side Reply Routines
5 * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c)
6 *
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
9 *
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
26ac0430 23 *
edce4d98 24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
26ac0430 28 *
edce4d98 29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
32 *
33 */
f5bffbd5 34#include "config.h"
edce4d98 35
e1f7507e
AJ
36/* for ClientActiveRequests global */
37#include "dlink.h"
38
39/* old includes without reasons given. */
edce4d98 40#include "squid.h"
0655fa4d 41#include "client_side_reply.h"
aa839030 42#include "errorpage.h"
c8be6d7b 43#include "StoreClient.h"
e6ccf245 44#include "Store.h"
528b2c61 45#include "HttpReply.h"
46#include "HttpRequest.h"
b6b6f466 47#include "forward.h"
c8be6d7b 48#include "clientStream.h"
2d2b0bb7 49#include "auth/UserRequest.h"
f41735ea 50#if USE_SQUID_ESI
f99c2cfe 51#include "esi/Esi.h"
43ae1d95 52#endif
528b2c61 53#include "MemObject.h"
7172612f 54#include "fde.h"
127dce76
AR
55#include "acl/FilledChecklist.h"
56#include "acl/Gadgets.h"
b67e2c8c 57#if DELAY_POOLS
58#include "DelayPools.h"
59#endif
a46d2c0e 60#include "client_side.h"
985c86bc 61#include "SquidTime.h"
e6ccf245 62
0655fa4d 63CBDATA_CLASS_INIT(clientReplyContext);
edce4d98 64
edce4d98 65/* Local functions */
e6ccf245 66extern "C" CSS clientReplyStatus;
ad61a2b4 67extern ErrorState *clientBuildError(err_type, http_status, char const *, IpAddress &, HttpRequest *);
edce4d98 68
edce4d98 69/* privates */
edce4d98 70
0655fa4d 71clientReplyContext::~clientReplyContext()
edce4d98 72{
50c09fc4 73 deleting = true;
74 /* This may trigger a callback back into SendMoreData as the cbdata
75 * is still valid
76 */
86a2f789 77 removeClientStoreReference(&sc, http);
edce4d98 78 /* old_entry might still be set if we didn't yet get the reply
0655fa4d 79 * code in HandleIMSReply() */
80 removeStoreReference(&old_sc, &old_entry);
81 safe_free(tempBuffer.data);
82 cbdataReferenceDone(http);
2b7d324b 83 HTTPMSGUNLOCK(reply);
edce4d98 84}
85
59a1efb2 86clientReplyContext::clientReplyContext(ClientHttpRequest *clientContext) : http (cbdataReference(clientContext)), old_entry (NULL), old_sc(NULL), deleting(false)
0655fa4d 87{}
edce4d98 88
a5c8d64d
AJ
89/** Create an error in the store awaiting the client side to read it.
90 *
91 * This may be better placed in the clientStream logic, but it has not been
0655fa4d 92 * relocated there yet
93 */
edce4d98 94void
0655fa4d 95clientReplyContext::setReplyToError(
60745f24 96 err_type err, http_status status, const HttpRequestMethod& method, char const *uri,
e57c1885 97 IpAddress &addr, HttpRequest * failedrequest, const char *unparsedrequest,
76f142cd 98 AuthUserRequest * auth_user_request)
edce4d98 99{
edce4d98 100 ErrorState *errstate =
62e76326 101 clientBuildError(err, status, uri, addr, failedrequest);
102
edce4d98 103 if (unparsedrequest)
62e76326 104 errstate->request_hdrs = xstrdup(unparsedrequest);
edce4d98 105
0655fa4d 106 if (status == HTTP_NOT_IMPLEMENTED && http->request)
62e76326 107 /* prevent confusion over whether we default to persistent or not */
0655fa4d 108 http->request->flags.proxy_keepalive = 0;
62e76326 109
0655fa4d 110 http->al.http.code = errstate->httpStatus;
edce4d98 111
0655fa4d 112 createStoreEntry(method, request_flags());
62e76326 113
26ac0430 114 if (auth_user_request) {
62e76326 115 errstate->auth_user_request = auth_user_request;
26ac0430 116 AUTHUSERREQUESTLOCK(errstate->auth_user_request, "errstate");
edce4d98 117 }
62e76326 118
edce4d98 119 assert(errstate->callback_data == NULL);
86a2f789 120 errorAppendEntry(http->storeEntry(), errstate);
edce4d98 121 /* Now the caller reads to get this */
122}
123
124void
0655fa4d 125clientReplyContext::removeStoreReference(store_client ** scp,
126 StoreEntry ** ep)
edce4d98 127{
128 StoreEntry *e;
129 store_client *sc = *scp;
62e76326 130
edce4d98 131 if ((e = *ep) != NULL) {
62e76326 132 *ep = NULL;
0655fa4d 133 storeUnregister(sc, e, this);
62e76326 134 *scp = NULL;
97b5e68f 135 e->unlock();
edce4d98 136 }
137}
138
86a2f789 139void
140clientReplyContext::removeClientStoreReference(store_client **scp, ClientHttpRequest *http)
141{
142 StoreEntry *reference = http->storeEntry();
143 removeStoreReference(scp, &reference);
144 http->storeEntry(reference);
145}
146
e6ccf245 147void *
a695955b 148clientReplyContext::operator new (size_t byteCount)
e6ccf245 149{
150 /* derived classes with different sizes must implement their own new */
151 assert (byteCount == sizeof (clientReplyContext));
0655fa4d 152 CBDATA_INIT_TYPE(clientReplyContext);
e6ccf245 153 return cbdataAlloc(clientReplyContext);
154}
155
156void
157clientReplyContext::operator delete (void *address)
158{
a50bfe93 159 clientReplyContext * tmp = (clientReplyContext *)address;
160 cbdataFree (tmp);
e6ccf245 161}
162
edce4d98 163void
0655fa4d 164clientReplyContext::saveState()
edce4d98 165{
e6ccf245 166 assert(old_sc == NULL);
bf8fe701 167 debugs(88, 3, "clientReplyContext::saveState: saving store context");
86a2f789 168 old_entry = http->storeEntry();
e6ccf245 169 old_sc = sc;
170 old_reqsize = reqsize;
171 tempBuffer.offset = reqofs;
edce4d98 172 /* Prevent accessing the now saved entries */
86a2f789 173 http->storeEntry(NULL);
e6ccf245 174 sc = NULL;
175 reqsize = 0;
176 reqofs = 0;
edce4d98 177}
178
179void
0655fa4d 180clientReplyContext::restoreState()
edce4d98 181{
e6ccf245 182 assert(old_sc != NULL);
bf8fe701 183 debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
86a2f789 184 removeClientStoreReference(&sc, http);
185 http->storeEntry(old_entry);
e6ccf245 186 sc = old_sc;
187 reqsize = old_reqsize;
188 reqofs = tempBuffer.offset;
edce4d98 189 /* Prevent accessed the old saved entries */
0655fa4d 190 old_entry = NULL;
e6ccf245 191 old_sc = NULL;
192 old_reqsize = 0;
193 tempBuffer.offset = 0;
c8be6d7b 194}
195
196void
0655fa4d 197clientReplyContext::startError(ErrorState * err)
c8be6d7b 198{
0655fa4d 199 createStoreEntry(http->request->method, request_flags());
200 triggerInitialStoreRead();
86a2f789 201 errorAppendEntry(http->storeEntry(), err);
edce4d98 202}
203
e6ccf245 204clientStreamNode *
528b2c61 205clientReplyContext::getNextNode() const
e6ccf245 206{
62e76326 207 return (clientStreamNode *)ourNode->node.next->data;
e6ccf245 208}
209
62e76326 210/* This function is wrong - the client parameters don't include the
528b2c61 211 * header offset
212 */
c8be6d7b 213void
0655fa4d 214clientReplyContext::triggerInitialStoreRead()
c8be6d7b 215{
0655fa4d 216 /* when confident, 0 becomes reqofs, and then this factors into
26ac0430 217 * startSendProcess
528b2c61 218 */
0655fa4d 219 assert(reqofs == 0);
dd272b8e 220 StoreIOBuffer tempBuffer (next()->readBuffer.length, 0, next()->readBuffer.data);
86a2f789 221 storeClientCopy(sc, http->storeEntry(), tempBuffer, SendMoreData, this);
c8be6d7b 222}
edce4d98 223
224/* there is an expired entry in the store.
225 * setup a temporary buffer area and perform an IMS to the origin
226 */
0655fa4d 227void
228clientReplyContext::processExpired()
edce4d98 229{
edce4d98 230 char *url = http->uri;
231 StoreEntry *entry = NULL;
bf8fe701 232 debugs(88, 3, "clientReplyContext::processExpired: '" << http->uri << "'");
86a2f789 233 assert(http->storeEntry()->lastmod >= 0);
edce4d98 234 /*
235 * check if we are allowed to contact other servers
26ac0430 236 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
edce4d98 237 * a stale entry *if* it matches client requirements
238 */
62e76326 239
0655fa4d 240 if (http->onlyIfCached()) {
241 processOnlyIfCachedMiss();
62e76326 242 return;
edce4d98 243 }
62e76326 244
edce4d98 245 http->request->flags.refresh = 1;
246#if STORE_CLIENT_LIST_DEBUG
c8be6d7b 247 /* Prevent a race with the store client memory free routines
edce4d98 248 */
0655fa4d 249 assert(storeClientIsThisAClient(sc, this));
edce4d98 250#endif
251 /* Prepare to make a new temporary request */
0655fa4d 252 saveState();
edce4d98 253 entry = storeCreateEntry(url,
62e76326 254 http->log_uri, http->request->flags, http->request->method);
34266cde 255 /* NOTE, don't call StoreEntry->lock(), storeCreateEntry() does it */
0655fa4d 256 sc = storeClientListAdd(entry, this);
edce4d98 257#if DELAY_POOLS
258 /* delay_id is already set on original store client */
0655fa4d 259 sc->setDelayId(DelayId::DelayClient(http));
edce4d98 260#endif
62e76326 261
0655fa4d 262 http->request->lastmod = old_entry->lastmod;
4a7a3d56 263 debugs(88, 5, "clientReplyContext::processExpired : lastmod " << entry->lastmod );
86a2f789 264 http->storeEntry(entry);
c8be6d7b 265 assert(http->out.offset == 0);
b2d22df6 266
267 /*
268 * A refcounted pointer so that FwdState stays around as long as
269 * this clientReplyContext does
270 */
94a396a3 271 FwdState::fwdStart(http->getConn() != NULL ? http->getConn()->fd : -1,
be0c6690 272 http->storeEntry(),
273 http->request);
edce4d98 274 /* Register with storage manager to receive updates when data comes in. */
62e76326 275
edce4d98 276 if (EBIT_TEST(entry->flags, ENTRY_ABORTED))
bf8fe701 277 debugs(88, 0, "clientReplyContext::processExpired: Found ENTRY_ABORTED object");
62e76326 278
c8be6d7b 279 {
62e76326 280 /* start counting the length from 0 */
0655fa4d 281 StoreIOBuffer tempBuffer(HTTP_REQBUF_SZ, 0, tempbuf);
282 storeClientCopy(sc, entry, tempBuffer, HandleIMSReply, this);
edce4d98 283 }
284}
285
edce4d98 286
528b2c61 287void
288clientReplyContext::sendClientUpstreamResponse()
289{
290 StoreIOBuffer tempresult;
0655fa4d 291 removeStoreReference(&old_sc, &old_entry);
2324cda2 292 /* here the data to send is the data we just received */
528b2c61 293 tempBuffer.offset = 0;
294 old_reqsize = 0;
0655fa4d 295 /* sendMoreData tracks the offset as well.
528b2c61 296 * Force it back to zero */
297 reqofs = 0;
86a2f789 298 assert(!EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED));
0655fa4d 299 /* TODO: provide sendMoreData with the ready parsed reply */
528b2c61 300 tempresult.length = reqsize;
301 tempresult.data = tempbuf;
0655fa4d 302 sendMoreData(tempresult);
528b2c61 303}
304
edce4d98 305void
0655fa4d 306clientReplyContext::HandleIMSReply(void *data, StoreIOBuffer result)
edce4d98 307{
e6ccf245 308 clientReplyContext *context = (clientReplyContext *)data;
0655fa4d 309 context->handleIMSReply(result);
310}
62e76326 311
0655fa4d 312void
313clientReplyContext::sendClientOldEntry()
314{
315 /* Get the old request back */
316 restoreState();
317 /* here the data to send is in the next nodes buffers already */
86a2f789 318 assert(!EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED));
0655fa4d 319 /* sendMoreData tracks the offset as well.
320 * Force it back to zero */
321 reqofs = 0;
322 StoreIOBuffer tempresult (reqsize, reqofs, next()->readBuffer.data);
323 sendMoreData(tempresult);
324}
62e76326 325
1d7ab0f4 326/* This is the workhorse of the HandleIMSReply callback.
327 *
328 * It is called when we've got data back from the origin following our
329 * IMS request to revalidate a stale entry.
330 */
0655fa4d 331void
1d7ab0f4 332clientReplyContext::handleIMSReply(StoreIOBuffer result)
0655fa4d 333{
1d7ab0f4 334 if (deleting)
335 return;
62e76326 336
bf8fe701 337 debugs(88, 3, "handleIMSReply: " << http->storeEntry()->url() << ", " << (long unsigned) result.length << " bytes" );
62e76326 338
1d7ab0f4 339 if (http->storeEntry() == NULL)
340 return;
07947ad8 341
1d7ab0f4 342 if (result.flags.error && !EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED))
343 return;
62e76326 344
1d7ab0f4 345 /* update size of the request */
346 reqsize = result.length + reqofs;
62e76326 347
1d7ab0f4 348 const http_status status = http->storeEntry()->getReply()->sline.status;
62e76326 349
1d7ab0f4 350 // request to origin was aborted
351 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) {
bf8fe701 352 debugs(88, 3, "handleIMSReply: request to origin aborted '" << http->storeEntry()->url() << "', sending old entry to client" );
1d7ab0f4 353 http->logType = LOG_TCP_REFRESH_FAIL;
354 sendClientOldEntry();
0655fa4d 355 }
62e76326 356
b297bcd0 357 HttpReply *old_rep = (HttpReply *) old_entry->getReply();
62e76326 358
b297bcd0 359 // origin replied 304
62e76326 360
b297bcd0 361 if (status == HTTP_NOT_MODIFIED) {
26ac0430 362 http->logType = LOG_TCP_REFRESH_UNMODIFIED;
045a76ab 363
26ac0430
AJ
364 // update headers on existing entry
365 HttpReply *old_rep = (HttpReply *) old_entry->getReply();
366 old_rep->updateOnNotModified(http->storeEntry()->getReply());
367 old_entry->timestampsSet();
62e76326 368
26ac0430 369 // if client sent IMS
62e76326 370
26ac0430
AJ
371 if (http->request->flags.ims) {
372 // forward the 304 from origin
373 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and forwarding 304 to client");
374 sendClientUpstreamResponse();
375 } else {
376 // send existing entry, it's still valid
377 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and sending " <<
378 old_rep->sline.status << " to client");
379 sendClientOldEntry();
380 }
b297bcd0 381 }
62e76326 382
b297bcd0
HN
383 // origin replied with a non-error code
384 else if (status > HTTP_STATUS_NONE && status < HTTP_INTERNAL_SERVER_ERROR) {
26ac0430
AJ
385 // forward response from origin
386 http->logType = LOG_TCP_REFRESH_MODIFIED;
387 debugs(88, 3, "handleIMSReply: origin replied " << status << ", replacing existing entry and forwarding to client");
388 sendClientUpstreamResponse();
b297bcd0 389 }
62e76326 390
b297bcd0
HN
391 // origin replied with an error
392 else {
26ac0430
AJ
393 // ignore and let client have old entry
394 http->logType = LOG_TCP_REFRESH_FAIL;
395 debugs(88, 3, "handleIMSReply: origin replied with error " <<
396 status << ", sending old entry (" << old_rep->sline.status << ") to client");
397 sendClientOldEntry();
1d7ab0f4 398 }
edce4d98 399}
400
e6ccf245 401extern "C" CSR clientGetMoreData;
402extern "C" CSD clientReplyDetach;
edce4d98 403
7d5f62a4
AJ
404/**
405 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
edce4d98 406 * have been parsed. Normally this should be a single call, but
407 * it might take more than one. As soon as we have the headers,
0655fa4d 408 * we hand off to clientSendMoreData, processExpired, or
409 * processMiss.
edce4d98 410 */
411void
0655fa4d 412clientReplyContext::CacheHit(void *data, StoreIOBuffer result)
edce4d98 413{
e6ccf245 414 clientReplyContext *context = (clientReplyContext *)data;
7d5f62a4 415 context->cacheHit(result);
0655fa4d 416}
417
7d5f62a4
AJ
418/**
419 * Process a possible cache HIT.
420 */
0655fa4d 421void
422clientReplyContext::cacheHit(StoreIOBuffer result)
423{
7d5f62a4 424 /** Ignore if the HIT object is being deleted. */
045a76ab 425 if (deleting)
426 return;
427
86a2f789 428 StoreEntry *e = http->storeEntry();
045a76ab 429
190154cf 430 HttpRequest *r = http->request;
045a76ab 431
4a7a3d56 432 debugs(88, 3, "clientCacheHit: " << http->uri << ", " << result.length << " bytes");
62e76326 433
86a2f789 434 if (http->storeEntry() == NULL) {
bf8fe701 435 debugs(88, 3, "clientCacheHit: request aborted");
62e76326 436 return;
c8be6d7b 437 } else if (result.flags.error) {
62e76326 438 /* swap in failure */
bf8fe701 439 debugs(88, 3, "clientCacheHit: swapin failure for " << http->uri);
62e76326 440 http->logType = LOG_TCP_SWAPFAIL_MISS;
86a2f789 441 removeClientStoreReference(&sc, http);
0655fa4d 442 processMiss();
62e76326 443 return;
edce4d98 444 }
62e76326 445
d3b3ab85 446 if (result.length == 0) {
62e76326 447 /* the store couldn't get enough data from the file for us to id the
448 * object
449 */
450 /* treat as a miss */
451 http->logType = LOG_TCP_MISS;
0655fa4d 452 processMiss();
62e76326 453 return;
d3b3ab85 454 }
62e76326 455
edce4d98 456 assert(!EBIT_TEST(e->flags, ENTRY_ABORTED));
457 /* update size of the request */
0655fa4d 458 reqsize = result.length + reqofs;
62e76326 459
edce4d98 460 /*
461 * Got the headers, now grok them
462 */
29b8d8d6 463 assert(http->logType == LOG_TCP_HIT);
62e76326 464
cdd4e1c1 465 if (strcmp(e->mem_obj->url, urlCanonical(r)) != 0) {
26ac0430 466 debugs(33, 1, "clientProcessHit: URL mismatch, '" << e->mem_obj->url << "' != '" << urlCanonical(r) << "'");
cdd4e1c1 467 processMiss();
468 return;
469 }
470
edce4d98 471 switch (varyEvaluateMatch(e, r)) {
62e76326 472
edce4d98 473 case VARY_NONE:
62e76326 474 /* No variance detected. Continue as normal */
475 break;
476
edce4d98 477 case VARY_MATCH:
62e76326 478 /* This is the correct entity for this request. Continue */
bf8fe701 479 debugs(88, 2, "clientProcessHit: Vary MATCH!");
62e76326 480 break;
481
edce4d98 482 case VARY_OTHER:
62e76326 483 /* This is not the correct entity for this request. We need
484 * to requery the cache.
485 */
86a2f789 486 removeClientStoreReference(&sc, http);
62e76326 487 e = NULL;
488 /* Note: varyEvalyateMatch updates the request with vary information
489 * so we only get here once. (it also takes care of cancelling loops)
490 */
26ac0430 491 debugs(88, 2, "clientProcessHit: Vary detected!");
0655fa4d 492 clientGetMoreData(ourNode, http);
62e76326 493 return;
494
edce4d98 495 case VARY_CANCEL:
62e76326 496 /* varyEvaluateMatch found a object loop. Process as miss */
bf8fe701 497 debugs(88, 1, "clientProcessHit: Vary object loop!");
0655fa4d 498 processMiss();
62e76326 499 return;
edce4d98 500 }
62e76326 501
edce4d98 502 if (r->method == METHOD_PURGE) {
86a2f789 503 removeClientStoreReference(&sc, http);
62e76326 504 e = NULL;
0655fa4d 505 purgeRequest();
62e76326 506 return;
edce4d98 507 }
62e76326 508
3900307b 509 if (e->checkNegativeHit()
36e6655b 510#if HTTP_VIOLATIONS
511 && !r->flags.nocache_hack
512#endif
513 ) {
62e76326 514 http->logType = LOG_TCP_NEGATIVE_HIT;
0655fa4d 515 sendMoreData(result);
f7cf9b8c 516 } else if (!Config.onoff.offline && refreshCheckHTTP(e, r) && !http->flags.internal) {
bf8fe701 517 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
62e76326 518 /*
519 * We hold a stale copy; it needs to be validated
520 */
521 /*
522 * The 'need_validation' flag is used to prevent forwarding
523 * loops between siblings. If our copy of the object is stale,
524 * then we should probably only use parents for the validation
525 * request. Otherwise two siblings could generate a loop if
526 * both have a stale version of the object.
527 */
528 r->flags.need_validation = 1;
529
530 if (e->lastmod < 0) {
531 /*
532 * Previous reply didn't have a Last-Modified header,
533 * we cannot revalidate it.
534 */
535 http->logType = LOG_TCP_MISS;
0655fa4d 536 processMiss();
62e76326 537 } else if (r->flags.nocache) {
538 /*
539 * This did not match a refresh pattern that overrides no-cache
540 * we should honour the client no-cache header.
541 */
542 http->logType = LOG_TCP_CLIENT_REFRESH_MISS;
0655fa4d 543 processMiss();
62e76326 544 } else if (r->protocol == PROTO_HTTP) {
545 /*
546 * Object needs to be revalidated
547 * XXX This could apply to FTP as well, if Last-Modified is known.
548 */
0655fa4d 549 processExpired();
62e76326 550 } else {
551 /*
552 * We don't know how to re-validate other protocols. Handle
553 * them as if the object has expired.
554 */
555 http->logType = LOG_TCP_MISS;
0655fa4d 556 processMiss();
62e76326 557 }
edce4d98 558 } else if (r->flags.ims) {
62e76326 559 /*
560 * Handle If-Modified-Since requests from the client
561 */
562
563 if (e->getReply()->sline.status != HTTP_OK) {
bf8fe701 564 debugs(88, 4, "clientCacheHit: Reply code " <<
565 e->getReply()->sline.status << " != 200");
62e76326 566 http->logType = LOG_TCP_MISS;
0655fa4d 567 processMiss();
568 } else if (e->modifiedSince(http->request)) {
62e76326 569 http->logType = LOG_TCP_IMS_HIT;
0655fa4d 570 sendMoreData(result);
62e76326 571 } else {
0655fa4d 572 time_t const timestamp = e->timestamp;
06a5ae20 573 HttpReply *temprep = e->getReply()->make304();
62e76326 574 http->logType = LOG_TCP_IMS_HIT;
86a2f789 575 removeClientStoreReference(&sc, http);
0655fa4d 576 createStoreEntry(http->request->method,
577 request_flags());
86a2f789 578 e = http->storeEntry();
62e76326 579 /*
580 * Copy timestamp from the original entry so the 304
581 * reply has a meaningful Age: header.
582 */
583 e->timestamp = timestamp;
db237875 584 e->replaceHttpReply(temprep);
62e76326 585 e->complete();
586 /* TODO: why put this in the store and then serialise it and then parse it again.
587 * Simply mark the request complete in our context and
588 * write the reply struct to the client side
589 */
0655fa4d 590 triggerInitialStoreRead();
62e76326 591 }
edce4d98 592 } else {
62e76326 593 /*
594 * plain ol' cache hit
595 */
596
8d5f19a0 597#if DELAY_POOLS
ffdf45f2 598 if (e->store_status != STORE_OK)
849b826a 599 http->logType = LOG_TCP_MISS;
5bf4d170 600 else
601#endif
26ac0430
AJ
602 if (e->mem_status == IN_MEMORY)
603 http->logType = LOG_TCP_MEM_HIT;
604 else if (Config.onoff.offline)
605 http->logType = LOG_TCP_OFFLINE_HIT;
62e76326 606
0655fa4d 607 sendMoreData(result);
edce4d98 608 }
609}
610
7d5f62a4 611/**
edce4d98 612 * Prepare to fetch the object as it's a cache miss of some kind.
613 */
614void
0655fa4d 615clientReplyContext::processMiss()
edce4d98 616{
edce4d98 617 char *url = http->uri;
190154cf 618 HttpRequest *r = http->request;
edce4d98 619 ErrorState *err = NULL;
60745f24 620 debugs(88, 4, "clientProcessMiss: '" << RequestMethodStr(r->method) << " " << url << "'");
7d5f62a4
AJ
621
622 /**
edce4d98 623 * We might have a left-over StoreEntry from a failed cache hit
624 * or IMS request.
625 */
86a2f789 626 if (http->storeEntry()) {
627 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_SPECIAL)) {
bf8fe701 628 debugs(88, 0, "clientProcessMiss: miss on a special object (" << url << ").");
629 debugs(88, 0, "\tlog_type = " << log_tags[http->logType]);
3900307b 630 http->storeEntry()->dump(1);
62e76326 631 }
632
86a2f789 633 removeClientStoreReference(&sc, http);
edce4d98 634 }
62e76326 635
7d5f62a4 636 /** Check if its a PURGE request to be actioned. */
edce4d98 637 if (r->method == METHOD_PURGE) {
0655fa4d 638 purgeRequest();
62e76326 639 return;
edce4d98 640 }
914b89a2 641
7d5f62a4 642 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
914b89a2 643 if (r->method == METHOD_OTHER) {
26ac0430 644 purgeAllCached();
60745f24 645 }
62e76326 646
7d5f62a4 647 /** Check if 'only-if-cached' flag is set. Action if so. */
0655fa4d 648 if (http->onlyIfCached()) {
649 processOnlyIfCachedMiss();
62e76326 650 return;
edce4d98 651 }
62e76326 652
ce5a16c2
AR
653 /// Deny loops for accelerator and interceptor. TODO: deny in all modes?
654 if (r->flags.loopdetect &&
655 (http->flags.accel || http->flags.intercepted)) {
62e76326 656 http->al.http.code = HTTP_FORBIDDEN;
cc192b50 657 err = clientBuildError(ERR_ACCESS_DENIED, HTTP_FORBIDDEN, NULL, http->getConn()->peer, http->request);
0655fa4d 658 createStoreEntry(r->method, request_flags());
86a2f789 659 errorAppendEntry(http->storeEntry(), err);
0655fa4d 660 triggerInitialStoreRead();
62e76326 661 return;
edce4d98 662 } else {
26ac0430 663 assert(http->out.offset == 0);
0655fa4d 664 createStoreEntry(r->method, r->flags);
665 triggerInitialStoreRead();
62e76326 666
667 if (http->redirect.status) {
06a5ae20 668 HttpReply *rep = new HttpReply;
edce4d98 669#if LOG_TCP_REDIRECTS
62e76326 670
671 http->logType = LOG_TCP_REDIRECT;
edce4d98 672#endif
62e76326 673
d88e3c49 674 http->storeEntry()->releaseRequest();
06a5ae20 675 rep->redirect(http->redirect.status, http->redirect.location);
db237875 676 http->storeEntry()->replaceHttpReply(rep);
86a2f789 677 http->storeEntry()->complete();
62e76326 678 return;
679 }
680
7d5f62a4 681 /** Check for internal requests. Update Protocol info if so. */
62e76326 682 if (http->flags.internal)
683 r->protocol = PROTO_INTERNAL;
684
7d5f62a4 685 /** Start forwarding to get the new object from network */
94a396a3 686 FwdState::fwdStart(http->getConn() != NULL ? http->getConn()->fd : -1,
be0c6690 687 http->storeEntry(),
688 r);
edce4d98 689 }
690}
691
7d5f62a4 692/**
edce4d98 693 * client issued a request with an only-if-cached cache-control directive;
694 * we did not find a cached object that can be returned without
695 * contacting other servers;
696 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
697 */
0655fa4d 698void
699clientReplyContext::processOnlyIfCachedMiss()
edce4d98 700{
edce4d98 701 ErrorState *err = NULL;
bf8fe701 702 debugs(88, 4, "clientProcessOnlyIfCachedMiss: '" <<
60745f24 703 RequestMethodStr(http->request->method) << " " << http->uri << "'");
edce4d98 704 http->al.http.code = HTTP_GATEWAY_TIMEOUT;
cc192b50 705 err = clientBuildError(ERR_ONLY_IF_CACHED_MISS, HTTP_GATEWAY_TIMEOUT, NULL, http->getConn()->peer, http->request);
86a2f789 706 removeClientStoreReference(&sc, http);
0655fa4d 707 startError(err);
edce4d98 708}
709
710void
e6ccf245 711clientReplyContext::purgeRequestFindObjectToPurge()
26ac0430 712{
e6ccf245 713 /* Try to find a base entry */
714 http->flags.purging = 1;
715 lookingforstore = 1;
26ac0430
AJ
716
717 // TODO: can we use purgeAllCached() here instead of doing the
718 // getPublicByRequestMethod() dance?
3b13a8fd 719 StoreEntry::getPublicByRequestMethod(this, http->request, METHOD_GET);
e6ccf245 720}
721
c1520b67
AJ
722// Purges all entries with a given url
723// TODO: move to SideAgent parent, when we have one
60745f24 724/*
725 * We probably cannot purge Vary-affected responses because their MD5
726 * keys depend on vary headers.
727 */
c1520b67 728void
90bd689c 729purgeEntriesByUrl(HttpRequest * req, const char *url)
c1520b67 730{
8dceeee3
BR
731#if USE_HTCP
732 bool get_or_head_sent = false;
733#endif
26ac0430 734
c1520b67
AJ
735 for (HttpRequestMethod m(METHOD_NONE); m != METHOD_ENUM_END; ++m) {
736 if (m.isCacheble()) {
737 if (StoreEntry *entry = storeGetPublic(url, m)) {
738 debugs(88, 5, "purging " << RequestMethodStr(m) << ' ' << url);
90bd689c 739#if USE_HTCP
8dceeee3
BR
740 neighborsHtcpClear(entry, url, req, m, HTCP_CLR_INVALIDATION);
741 if (m == METHOD_GET || m == METHOD_HEAD) {
742 get_or_head_sent = true;
743 }
90bd689c 744#endif
8dceeee3 745 entry->release();
c1520b67
AJ
746 }
747 }
748 }
8dceeee3
BR
749
750#if USE_HTCP
751 if (!get_or_head_sent) {
752 neighborsHtcpClear(NULL, url, req, HttpRequestMethod(METHOD_GET), HTCP_CLR_INVALIDATION);
753 }
754#endif
c1520b67
AJ
755}
756
26ac0430 757void
60745f24 758clientReplyContext::purgeAllCached()
759{
26ac0430 760 const char *url = urlCanonical(http->request);
90bd689c 761 purgeEntriesByUrl(http->request, url);
35ececa5 762}
60745f24 763
e6ccf245 764void
3b13a8fd 765clientReplyContext::created(StoreEntry *newEntry)
e6ccf245 766{
767 if (lookingforstore == 1)
62e76326 768 purgeFoundGet(newEntry);
e6ccf245 769 else if (lookingforstore == 2)
62e76326 770 purgeFoundHead(newEntry);
e6ccf245 771 else if (lookingforstore == 3)
62e76326 772 purgeDoPurgeGet(newEntry);
e6ccf245 773 else if (lookingforstore == 4)
62e76326 774 purgeDoPurgeHead(newEntry);
e6ccf245 775 else if (lookingforstore == 5)
62e76326 776 identifyFoundObject(newEntry);
e6ccf245 777}
778
779void
3b13a8fd 780clientReplyContext::purgeFoundGet(StoreEntry *newEntry)
e6ccf245 781{
782 if (newEntry->isNull()) {
62e76326 783 lookingforstore = 2;
784 StoreEntry::getPublicByRequestMethod(this, http->request, METHOD_HEAD);
e6ccf245 785 } else
62e76326 786 purgeFoundObject (newEntry);
e6ccf245 787}
788
789void
3b13a8fd 790clientReplyContext::purgeFoundHead(StoreEntry *newEntry)
e6ccf245 791{
792 if (newEntry->isNull())
62e76326 793 purgeDoMissPurge();
e6ccf245 794 else
62e76326 795 purgeFoundObject (newEntry);
e6ccf245 796}
62e76326 797
e6ccf245 798void
3b13a8fd 799clientReplyContext::purgeFoundObject(StoreEntry *entry)
e6ccf245 800{
801 assert (entry && !entry->isNull());
e4b9a2f0 802
803 if (EBIT_TEST(entry->flags, ENTRY_SPECIAL)) {
804 http->logType = LOG_TCP_DENIED;
cc192b50 805 ErrorState *err = clientBuildError(ERR_ACCESS_DENIED, HTTP_FORBIDDEN, NULL, http->getConn()->peer, http->request);
e4b9a2f0 806 startError(err);
807 return;
808 }
809
62e76326 810 StoreIOBuffer tempBuffer;
811 /* Swap in the metadata */
86a2f789 812 http->storeEntry(entry);
34266cde 813
3d0ac046 814 http->storeEntry()->lock();
3900307b 815 http->storeEntry()->createMemObject(http->uri, http->log_uri);
34266cde 816
86a2f789 817 http->storeEntry()->mem_obj->method = http->request->method;
34266cde 818
86a2f789 819 sc = storeClientListAdd(http->storeEntry(), this);
34266cde 820
62e76326 821 http->logType = LOG_TCP_HIT;
34266cde 822
62e76326 823 reqofs = 0;
34266cde 824
62e76326 825 tempBuffer.offset = http->out.offset;
34266cde 826
0655fa4d 827 tempBuffer.length = next()->readBuffer.length;
34266cde 828
0655fa4d 829 tempBuffer.data = next()->readBuffer.data;
34266cde 830
86a2f789 831 storeClientCopy(sc, http->storeEntry(),
0655fa4d 832 tempBuffer, CacheHit, this);
e6ccf245 833}
834
835void
836clientReplyContext::purgeRequest()
edce4d98 837{
bf8fe701 838 debugs(88, 3, "Config2.onoff.enable_purge = " <<
839 Config2.onoff.enable_purge);
62e76326 840
edce4d98 841 if (!Config2.onoff.enable_purge) {
62e76326 842 http->logType = LOG_TCP_DENIED;
cc192b50 843 ErrorState *err = clientBuildError(ERR_ACCESS_DENIED, HTTP_FORBIDDEN, NULL, http->getConn()->peer, http->request);
0655fa4d 844 startError(err);
62e76326 845 return;
edce4d98 846 }
62e76326 847
edce4d98 848 /* Release both IP cache */
cc192b50 849 ipcacheInvalidate(http->request->GetHost());
edce4d98 850
e6ccf245 851 if (!http->flags.purging)
62e76326 852 purgeRequestFindObjectToPurge();
e6ccf245 853 else
62e76326 854 purgeDoMissPurge();
e6ccf245 855}
856
857void
858clientReplyContext::purgeDoMissPurge()
859{
29b8d8d6 860 http->logType = LOG_TCP_MISS;
e6ccf245 861 lookingforstore = 3;
3b13a8fd 862 StoreEntry::getPublicByRequestMethod(this,http->request, METHOD_GET);
e6ccf245 863}
864
865void
3b13a8fd 866clientReplyContext::purgeDoPurgeGet(StoreEntry *newEntry)
e6ccf245 867{
868 assert (newEntry);
869 /* Move to new() when that is created */
870 purgeStatus = HTTP_NOT_FOUND;
871
872 if (!newEntry->isNull()) {
62e76326 873 /* Release the cached URI */
bf8fe701 874 debugs(88, 4, "clientPurgeRequest: GET '" << newEntry->url() << "'" );
8dceeee3
BR
875#if USE_HTCP
876 neighborsHtcpClear(newEntry, NULL, http->request, HttpRequestMethod(METHOD_GET), HTCP_CLR_PURGE);
877#endif
5f33b71d 878 newEntry->release();
62e76326 879 purgeStatus = HTTP_OK;
edce4d98 880 }
62e76326 881
e6ccf245 882 lookingforstore = 4;
3b13a8fd 883 StoreEntry::getPublicByRequestMethod(this, http->request, METHOD_HEAD);
e6ccf245 884}
885
886void
3b13a8fd 887clientReplyContext::purgeDoPurgeHead(StoreEntry *newEntry)
e6ccf245 888{
4fc0ac76 889 if (newEntry && !newEntry->isNull()) {
bf8fe701 890 debugs(88, 4, "clientPurgeRequest: HEAD '" << newEntry->url() << "'" );
8dceeee3
BR
891#if USE_HTCP
892 neighborsHtcpClear(newEntry, NULL, http->request, HttpRequestMethod(METHOD_HEAD), HTCP_CLR_PURGE);
893#endif
5f33b71d 894 newEntry->release();
62e76326 895 purgeStatus = HTTP_OK;
edce4d98 896 }
62e76326 897
edce4d98 898 /* And for Vary, release the base URI if none of the headers was included in the request */
62e76326 899
edce4d98 900 if (http->request->vary_headers
62e76326 901 && !strstr(http->request->vary_headers, "=")) {
902 StoreEntry *entry = storeGetPublic(urlCanonical(http->request), METHOD_GET);
903
904 if (entry) {
bf8fe701 905 debugs(88, 4, "clientPurgeRequest: Vary GET '" << entry->url() << "'" );
8dceeee3
BR
906#if USE_HTCP
907 neighborsHtcpClear(entry, NULL, http->request, HttpRequestMethod(METHOD_GET), HTCP_CLR_PURGE);
908#endif
5f33b71d 909 entry->release();
62e76326 910 purgeStatus = HTTP_OK;
911 }
912
913 entry = storeGetPublic(urlCanonical(http->request), METHOD_HEAD);
914
915 if (entry) {
bf8fe701 916 debugs(88, 4, "clientPurgeRequest: Vary HEAD '" << entry->url() << "'" );
8dceeee3
BR
917#if USE_HTCP
918 neighborsHtcpClear(entry, NULL, http->request, HttpRequestMethod(METHOD_HEAD), HTCP_CLR_PURGE);
919#endif
5f33b71d 920 entry->release();
62e76326 921 purgeStatus = HTTP_OK;
922 }
edce4d98 923 }
62e76326 924
edce4d98 925 /*
926 * Make a new entry to hold the reply to be written
927 * to the client.
928 */
528b2c61 929 /* FIXME: This doesn't need to go through the store. Simply
930 * push down the client chain
931 */
0655fa4d 932 createStoreEntry(http->request->method, request_flags());
62e76326 933
0655fa4d 934 triggerInitialStoreRead();
62e76326 935
7dc5f514 936 HttpReply *rep = new HttpReply;
62e76326 937
450e0c10 938 HttpVersion version(1,0);
62e76326 939
7dc5f514 940 rep->setHeaders(version, purgeStatus, NULL, NULL, 0, 0, -1);
62e76326 941
7dc5f514 942 http->storeEntry()->replaceHttpReply(rep);
62e76326 943
86a2f789 944 http->storeEntry()->complete();
edce4d98 945}
946
947void
0655fa4d 948clientReplyContext::traceReply(clientStreamNode * node)
edce4d98 949{
e6ccf245 950 clientStreamNode *next = (clientStreamNode *)node->node.next->data;
528b2c61 951 StoreIOBuffer tempBuffer;
0655fa4d 952 assert(http->request->max_forwards == 0);
953 createStoreEntry(http->request->method, request_flags());
954 tempBuffer.offset = next->readBuffer.offset + headers_sz;
c8be6d7b 955 tempBuffer.length = next->readBuffer.length;
956 tempBuffer.data = next->readBuffer.data;
86a2f789 957 storeClientCopy(sc, http->storeEntry(),
0655fa4d 958 tempBuffer, SendMoreData, this);
d88e3c49 959 http->storeEntry()->releaseRequest();
3900307b 960 http->storeEntry()->buffer();
7dc5f514 961 HttpReply *rep = new HttpReply;
450e0c10 962 HttpVersion version(1,0);
06a5ae20 963 rep->setHeaders(version, HTTP_OK, NULL, "text/plain",
5cafad19 964 http->request->prefixLen(), 0, squid_curtime);
db237875 965 http->storeEntry()->replaceHttpReply(rep);
5cafad19 966 http->request->swapOut(http->storeEntry());
86a2f789 967 http->storeEntry()->complete();
edce4d98 968}
969
970#define SENDING_BODY 0
971#define SENDING_HDRSONLY 1
972int
0655fa4d 973clientReplyContext::checkTransferDone()
edce4d98 974{
86a2f789 975 StoreEntry *entry = http->storeEntry();
62e76326 976
edce4d98 977 if (entry == NULL)
62e76326 978 return 0;
979
980 /*
edce4d98 981 * For now, 'done_copying' is used for special cases like
982 * Range and HEAD requests.
983 */
0655fa4d 984 if (http->flags.done_copying)
62e76326 985 return 1;
986
edce4d98 987 /*
988 * Handle STORE_OK objects.
989 * objectLen(entry) will be set proprely.
26ac0430 990 * RC: Does objectLen(entry) include the Headers?
0e3be1ea 991 * RC: Yes.
edce4d98 992 */
993 if (entry->store_status == STORE_OK) {
0655fa4d 994 return storeOKTransferDone();
e39b9382 995 } else {
0655fa4d 996 return storeNotOKTransferDone();
edce4d98 997 }
e39b9382 998}
999
1000int
1001clientReplyContext::storeOKTransferDone() const
1002{
47f6e231 1003 if (http->out.offset >= http->storeEntry()->objectLen() - headers_sz) {
26ac0430
AJ
1004 debugs(88,3,HERE << "storeOKTransferDone " <<
1005 " out.offset=" << http->out.offset <<
1006 " objectLen()=" << http->storeEntry()->objectLen() <<
1007 " headers_sz=" << headers_sz);
62e76326 1008 return 1;
47f6e231 1009 }
62e76326 1010
e39b9382 1011 return 0;
1012}
1013
1014int
1015clientReplyContext::storeNotOKTransferDone() const
1016{
edce4d98 1017 /*
1018 * Now, handle STORE_PENDING objects
1019 */
86a2f789 1020 MemObject *mem = http->storeEntry()->mem_obj;
edce4d98 1021 assert(mem != NULL);
1022 assert(http->request != NULL);
0e3be1ea 1023 /* mem->reply was wrong because it uses the UPSTREAM header length!!! */
0353e724 1024 HttpReply const *reply = mem->getReply();
62e76326 1025
e39b9382 1026 if (headers_sz == 0)
62e76326 1027 /* haven't found end of headers yet */
1028 return 0;
e39b9382 1029
1030 int sending = SENDING_BODY;
62e76326 1031
e39b9382 1032 if (reply->sline.status == HTTP_NO_CONTENT ||
62e76326 1033 reply->sline.status == HTTP_NOT_MODIFIED ||
1034 reply->sline.status < HTTP_OK ||
1035 http->request->method == METHOD_HEAD)
1036 sending = SENDING_HDRSONLY;
1037
edce4d98 1038 /*
1039 * Figure out how much data we are supposed to send.
1040 * If we are sending a body and we don't have a content-length,
1041 * then we must wait for the object to become STORE_OK.
1042 */
0e3be1ea 1043 if (reply->content_length < 0)
62e76326 1044 return 0;
e39b9382 1045
47f6e231 1046 int64_t expectedLength = reply->content_length + http->out.headers_sz;
62e76326 1047
e39b9382 1048 if (http->out.size < expectedLength)
62e76326 1049 return 0;
47f6e231 1050 else {
26ac0430
AJ
1051 debugs(88,3,HERE << "storeNotOKTransferDone " <<
1052 " out.size=" << http->out.size <<
1053 " expectedLength=" << expectedLength);
62e76326 1054 return 1;
47f6e231 1055 }
edce4d98 1056}
1057
1058
edce4d98 1059/* A write has completed, what is the next status based on the
1060 * canonical request data?
1061 * 1 something is wrong
1062 * 0 nothing is wrong.
1063 *
1064 */
1065int
59a1efb2 1066clientHttpRequestStatus(int fd, ClientHttpRequest const *http)
edce4d98 1067{
47f6e231 1068#if SIZEOF_INT64_T == 4
edce4d98 1069 if (http->out.size > 0x7FFF0000) {
47f6e231 1070 debugs(88, 1, "WARNING: closing FD " << fd << " to prevent out.size counter overflow");
cc192b50 1071 debugs(88, 1, "\tclient " << http->getConn()->peer);
47f6e231 1072 debugs(88, 1, "\treceived " << http->out.size << " bytes");
1073 debugs(88, 1, "\tURI " << http->log_uri);
62e76326 1074 return 1;
edce4d98 1075 }
62e76326 1076
edce4d98 1077#endif
47f6e231 1078#if SIZEOF_INT64_T == 4
edce4d98 1079 if (http->out.offset > 0x7FFF0000) {
3ec12e4a 1080 debugs(88, 1, "WARNING: closing FD " << fd < " to prevent out.offset counter overflow");
cc192b50 1081 debugs(88, 1, "\tclient " << http->getConn()->peer);
3ec12e4a 1082 debugs(88, 1, "\treceived " << http->out.size << " bytes, offset " << http->out.offset);
1083 debugs(88, 1, "\tURI " << http->log_uri);
62e76326 1084 return 1;
edce4d98 1085 }
62e76326 1086
edce4d98 1087#endif
1088 return 0;
1089}
1090
62e76326 1091/* Preconditions:
edce4d98 1092 * *http is a valid structure.
1093 * fd is either -1, or an open fd.
1094 *
1095 * TODO: enumify this
1096 *
1097 * This function is used by any http request sink, to determine the status
1098 * of the object.
1099 */
1100clientStream_status_t
59a1efb2 1101clientReplyStatus(clientStreamNode * aNode, ClientHttpRequest * http)
edce4d98 1102{
0655fa4d 1103 clientReplyContext *context = dynamic_cast<clientReplyContext *>(aNode->data.getRaw());
1104 assert (context);
1105 assert (context->http == http);
1106 return context->replyStatus();
1107}
1108
1109clientStream_status_t
1110clientReplyContext::replyStatus()
1111{
edce4d98 1112 int done;
1113 /* Here because lower nodes don't need it */
62e76326 1114
3daaed1a 1115 if (http->storeEntry() == NULL) {
1116 debugs(88, 5, "clientReplyStatus: no storeEntry");
62e76326 1117 return STREAM_FAILED; /* yuck, but what can we do? */
3daaed1a 1118 }
62e76326 1119
3daaed1a 1120 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) {
62e76326 1121 /* TODO: Could upstream read errors (result.flags.error) be
1122 * lost, and result in undersize requests being considered
1123 * complete. Should we tcp reset such connections ?
1124 */
3daaed1a 1125 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
62e76326 1126 return STREAM_FAILED;
3daaed1a 1127 }
62e76326 1128
0655fa4d 1129 if ((done = checkTransferDone()) != 0 || flags.complete) {
bf8fe701 1130 debugs(88, 5, "clientReplyStatus: transfer is DONE");
62e76326 1131 /* Ok we're finished, but how? */
1132
06a5ae20 1133 if (http->storeEntry()->getReply()->bodySize(http->request->method) < 0) {
bf8fe701 1134 debugs(88, 5, "clientReplyStatus: closing, content_length < 0");
62e76326 1135 return STREAM_FAILED;
1136 }
1137
1138 if (!done) {
bf8fe701 1139 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
62e76326 1140 return STREAM_FAILED;
1141 }
1142
0655fa4d 1143 if (!http->gotEnough()) {
bf8fe701 1144 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
62e76326 1145 return STREAM_UNPLANNED_COMPLETE;
1146 }
1147
1148 if (http->request->flags.proxy_keepalive) {
bf8fe701 1149 debugs(88, 5, "clientReplyStatus: stream complete and can keepalive");
62e76326 1150 return STREAM_COMPLETE;
1151 }
1152
bf8fe701 1153 debugs(88, 5, "clientReplyStatus: stream was not expected to complete!");
62e76326 1154 return STREAM_UNPLANNED_COMPLETE;
edce4d98 1155 }
62e76326 1156
16611143 1157 // XXX: Should this be checked earlier? We could return above w/o checking.
1158 if (reply->receivedBodyTooLarge(*http->request, http->out.offset - 4096)) {
b51aec66 1159 /* 4096 is a margin for the HTTP headers included in out.offset */
bf8fe701 1160 debugs(88, 5, "clientReplyStatus: client reply body is too large");
62e76326 1161 return STREAM_FAILED;
0e3be1ea 1162 }
62e76326 1163
edce4d98 1164 return STREAM_NONE;
1165}
1166
62e76326 1167/* Responses with no body will not have a content-type header,
edce4d98 1168 * which breaks the rep_mime_type acl, which
1169 * coincidentally, is the most common acl for reply access lists.
1170 * A better long term fix for this is to allow acl matchs on the various
26ac0430
AJ
1171 * status codes, and then supply a default ruleset that puts these
1172 * codes before any user defines access entries. That way the user
edce4d98 1173 * can choose to block these responses where appropriate, but won't get
1174 * mysterious breakages.
1175 */
0655fa4d 1176bool
1177clientReplyContext::alwaysAllowResponse(http_status sline) const
edce4d98 1178{
4ef4b952 1179 bool result;
1180
edce4d98 1181 switch (sline) {
62e76326 1182
edce4d98 1183 case HTTP_CONTINUE:
62e76326 1184
edce4d98 1185 case HTTP_SWITCHING_PROTOCOLS:
62e76326 1186
edce4d98 1187 case HTTP_PROCESSING:
62e76326 1188
edce4d98 1189 case HTTP_NO_CONTENT:
62e76326 1190
edce4d98 1191 case HTTP_NOT_MODIFIED:
4ef4b952 1192 result = true;
62e76326 1193 break;
1194
edce4d98 1195 default:
4ef4b952 1196 result = false;
edce4d98 1197 }
4ef4b952 1198
1199 return result;
edce4d98 1200}
1201
a5c8d64d
AJ
1202/**
1203 * Generate the reply headers sent to client.
1204 *
1205 * Filters out unwanted entries and hop-by-hop from original reply header
1206 * then adds extra entries if we have more info than origin server
1207 * then adds Squid specific entries
edce4d98 1208 */
0655fa4d 1209void
1210clientReplyContext::buildReplyHeader()
edce4d98 1211{
7dc5f514 1212 HttpHeader *hdr = &reply->header;
c8be6d7b 1213 int is_hit = logTypeIsATcpHit(http->logType);
190154cf 1214 HttpRequest *request = http->request;
edce4d98 1215#if DONT_FILTER_THESE
1216 /* but you might want to if you run Squid as an HTTP accelerator */
a9925b40 1217 /* hdr->delById(HDR_ACCEPT_RANGES); */
1218 hdr->delById(HDR_ETAG);
edce4d98 1219#endif
62e76326 1220
edce4d98 1221 if (is_hit)
a9925b40 1222 hdr->delById(HDR_SET_COOKIE);
62e76326 1223
26ac0430 1224 // if there is not configured a peer proxy with login=PASS option enabled
dcf3665b
AJ
1225 // remove the Proxy-Authenticate header
1226 if ( !(request->peer_login && strcmp(request->peer_login,"PASS") ==0))
26ac0430 1227 reply->header.delById(HDR_PROXY_AUTHENTICATE);
dcf3665b 1228
2cdeea82 1229 reply->header.removeHopByHopEntries();
62e76326 1230
1231 // if (request->range)
7dc5f514 1232 // clientBuildRangeHeader(http, reply);
a5c8d64d 1233
edce4d98 1234 /*
1235 * Add a estimated Age header on cache hits.
1236 */
1237 if (is_hit) {
62e76326 1238 /*
1239 * Remove any existing Age header sent by upstream caches
1240 * (note that the existing header is passed along unmodified
1241 * on cache misses)
1242 */
a9925b40 1243 hdr->delById(HDR_AGE);
62e76326 1244 /*
1245 * This adds the calculated object age. Note that the details of the
1246 * age calculation is performed by adjusting the timestamp in
3900307b 1247 * StoreEntry::timestampsSet(), not here.
62e76326 1248 *
1249 * BROWSER WORKAROUND: IE sometimes hangs when receiving a 0 Age
1250 * header, so don't use it unless there is a age to report. Please
1251 * note that Age is only used to make a conservative estimation of
1252 * the objects age, so a Age: 0 header does not add any useful
1253 * information to the reply in any case.
1254 */
a5c8d64d
AJ
1255#if DEAD_CODE
1256 // XXX: realy useless? or is there a bug now that this is detatched from the below if-sequence ?
1257 // looks like this pre-if was supposed to be the browser workaround...
86a2f789 1258 if (NULL == http->storeEntry())
62e76326 1259 (void) 0;
86a2f789 1260 else if (http->storeEntry()->timestamp < 0)
62e76326 1261 (void) 0;
a5c8d64d 1262#endif
bbe58ab5 1263
1264 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_SPECIAL)) {
a9925b40 1265 hdr->delById(HDR_DATE);
1266 hdr->insertTime(HDR_DATE, squid_curtime);
bbe58ab5 1267 } else if (http->storeEntry()->timestamp < squid_curtime) {
a9925b40 1268 hdr->putInt(HDR_AGE,
1269 squid_curtime - http->storeEntry()->timestamp);
62e76326 1270 /* Signal old objects. NB: rfc 2616 is not clear,
1271 * by implication, on whether we should do this to all
1272 * responses, or only cache hits.
1273 * 14.46 states it ONLY applys for heuristically caclulated
1274 * freshness values, 13.2.4 doesn't specify the same limitation.
1275 * We interpret RFC 2616 under the combination.
1276 */
1277 /* TODO: if maxage or s-maxage is present, don't do this */
1278
86a2f789 1279 if (squid_curtime - http->storeEntry()->timestamp >= 86400) {
62e76326 1280 char tempbuf[512];
1281 snprintf (tempbuf, sizeof(tempbuf), "%s %s %s",
1282 "113", ThisCache,
1283 "This cache hit is still fresh and more than 1 day old");
a9925b40 1284 hdr->putStr(HDR_WARNING, tempbuf);
62e76326 1285 }
1286 }
a5c8d64d 1287 }
528b2c61 1288
a5c8d64d
AJ
1289 /* RFC 2616: Section 14.18
1290 *
1291 * Add a Date: header if missing.
1292 * We have access to a clock therefore are required to amend any shortcoming in servers.
1293 *
1294 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1295 */
1296 if ( !hdr->has(HDR_DATE) ) {
f0dedeb5 1297 if (!http->storeEntry())
a5c8d64d 1298 hdr->insertTime(HDR_DATE, squid_curtime);
f0dedeb5
AJ
1299 else if (http->storeEntry()->timestamp > 0)
1300 hdr->insertTime(HDR_DATE, http->storeEntry()->timestamp);
1301 else {
1302 debugs(88,1,"WARNING: An error inside Squid has caused an HTTP reply without Date:. Please report this");
1303 /* TODO: dump something useful about the problem */
1304 }
edce4d98 1305 }
62e76326 1306
0bd9aa82 1307 /* Filter unproxyable authentication types */
dcf3665b 1308
ddd31ed3 1309 if (http->logType != LOG_TCP_DENIED &&
d67acb4e 1310 hdr->has(HDR_WWW_AUTHENTICATE)) {
62e76326 1311 HttpHeaderPos pos = HttpHeaderInitPos;
1312 HttpHeaderEntry *e;
1313
26ac0430 1314 int connection_auth_blocked = 0;
a9925b40 1315 while ((e = hdr->getEntry(&pos))) {
d67acb4e 1316 if (e->id == HDR_WWW_AUTHENTICATE) {
5b4117d8 1317 const char *value = e->value.rawBuf();
62e76326 1318
1319 if ((strncasecmp(value, "NTLM", 4) == 0 &&
1320 (value[4] == '\0' || value[4] == ' '))
1321 ||
1322 (strncasecmp(value, "Negotiate", 9) == 0 &&
d67acb4e 1323 (value[9] == '\0' || value[9] == ' '))
26ac0430
AJ
1324 ||
1325 (strncasecmp(value, "Kerberos", 8) == 0 &&
1326 (value[8] == '\0' || value[8] == ' '))) {
1327 if (request->flags.connection_auth_disabled) {
1328 hdr->delAt(pos, connection_auth_blocked);
d67acb4e
AJ
1329 continue;
1330 }
26ac0430
AJ
1331 request->flags.must_keepalive = 1;
1332 if (!request->flags.accelerated && !request->flags.intercepted) {
d67acb4e 1333 httpHeaderPutStrf(hdr, HDR_PROXY_SUPPORT, "Session-Based-Authentication");
26ac0430
AJ
1334 /*
1335 We send "[Proxy-]Connection: Proxy-Support" header to mark
1336 Proxy-Support as a hop-by-hop header for intermediaries that do not
1337 understand the semantics of this header. The RFC should have included
1338 this recommendation.
1339 */
d67acb4e
AJ
1340 httpHeaderPutStrf(hdr, HDR_CONNECTION, "Proxy-support");
1341 }
1342 break;
26ac0430 1343 }
62e76326 1344 }
1345 }
d67acb4e
AJ
1346
1347 if (connection_auth_blocked)
ba9fb01d 1348 hdr->refreshMask();
0bd9aa82 1349 }
62e76326 1350
edce4d98 1351 /* Handle authentication headers */
26ac0430
AJ
1352 if (http->logType == LOG_TCP_DENIED &&
1353 ( reply->sline.status == HTTP_PROXY_AUTHENTICATION_REQUIRED ||
1354 reply->sline.status == HTTP_UNAUTHORIZED)
1355 ) {
1356 /* Add authentication header */
1357 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1358 * depends on authenticate behaviour: all schemes to date send no extra
1359 * data on 407/401 responses, and do not check the accel state on 401/407
1360 * responses
1361 */
1362 authenticateFixHeader(reply, request->auth_user_request, request, 0, 1);
1363 } else if (request->auth_user_request)
7dc5f514 1364 authenticateFixHeader(reply, request->auth_user_request, request,
62e76326 1365 http->flags.accel, 0);
1366
edce4d98 1367 /* Append X-Cache */
1368 httpHeaderPutStrf(hdr, HDR_X_CACHE, "%s from %s",
62e76326 1369 is_hit ? "HIT" : "MISS", getMyHostname());
1370
edce4d98 1371#if USE_CACHE_DIGESTS
1372 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1373 httpHeaderPutStrf(hdr, HDR_X_CACHE_LOOKUP, "%s from %s:%d",
0655fa4d 1374 lookup_type ? lookup_type : "NONE",
62e76326 1375 getMyHostname(), getMyPort());
1376
edce4d98 1377#endif
62e76326 1378
f529bb20 1379 /* Check whether we should send keep-alive */
58850d15 1380 if (!Config.onoff.error_pconns && reply->sline.status >= 400 && !request->flags.must_keepalive) {
bf8fe701 1381 debugs(33, 3, "clientBuildReplyHeader: Error, don't keep-alive");
58850d15 1382 request->flags.proxy_keepalive = 0;
af6a12ee 1383 } else if (!Config.onoff.client_pconns && !request->flags.must_keepalive) {
17b57873 1384 debugs(33, 2, "clientBuildReplyHeader: Connection Keep-Alive not requested by admin or client");
f5e45ad8 1385 request->flags.proxy_keepalive = 0;
af6a12ee 1386 } else if (request->flags.proxy_keepalive && shutting_down) {
f529bb20 1387 debugs(88, 3, "clientBuildReplyHeader: Shutting down, don't keep-alive.");
1388 request->flags.proxy_keepalive = 0;
af6a12ee 1389 } else if (request->flags.connection_auth && !reply->keep_alive) {
26ac0430
AJ
1390 debugs(33, 2, "clientBuildReplyHeader: Connection oriented auth but server side non-persistent");
1391 request->flags.proxy_keepalive = 0;
af6a12ee 1392 } else if (reply->bodySize(request->method) < 0) {
17b57873
AJ
1393 debugs(88, 3, "clientBuildReplyHeader: can't keep-alive, unknown body size" );
1394 request->flags.proxy_keepalive = 0;
af6a12ee 1395 } else if (fdUsageHigh()&& !request->flags.must_keepalive) {
17b57873
AJ
1396 debugs(88, 3, "clientBuildReplyHeader: Not many unused FDs, can't keep-alive");
1397 request->flags.proxy_keepalive = 0;
1398 }
d67acb4e 1399
f529bb20 1400
4dea3fdd 1401 /* Append VIA */
92caea77 1402 if (Config.onoff.via) {
62e76326 1403 LOCAL_ARRAY(char, bbuf, MAX_URL + 32);
30abd221 1404 String strVia;
26ac0430 1405 hdr->getList(HDR_VIA, &strVia);
88331887 1406 snprintf(bbuf, MAX_URL + 32, "%d.%d %s",
7dc5f514 1407 reply->sline.version.major,
1408 reply->sline.version.minor,
62e76326 1409 ThisCache);
1410 strListAdd(&strVia, bbuf, ',');
a9925b40 1411 hdr->delById(HDR_VIA);
5b4117d8 1412 hdr->putStr(HDR_VIA, strVia.termedBuf());
c8be6d7b 1413 }
edce4d98 1414 /* Signal keep-alive if needed */
a9925b40 1415 hdr->putStr(http->flags.accel ? HDR_CONNECTION : HDR_PROXY_CONNECTION,
1416 request->flags.proxy_keepalive ? "keep-alive" : "close");
62e76326 1417
edce4d98 1418#if ADD_X_REQUEST_URI
1419 /*
1420 * Knowing the URI of the request is useful when debugging persistent
1421 * connections in a client; we cannot guarantee the order of http headers,
1422 * but X-Request-URI is likely to be the very last header to ease use from a
1423 * debugger [hdr->entries.count-1].
1424 */
a9925b40 1425 hdr->putStr(HDR_X_REQUEST_URI,
1426 http->memOjbect()->url ? http->memObject()->url : http->uri);
62e76326 1427
edce4d98 1428#endif
62e76326 1429
8c01ada0 1430 httpHdrMangleList(hdr, request, ROR_REPLY);
edce4d98 1431}
1432
1433
0655fa4d 1434void
b297bcd0 1435clientReplyContext::cloneReply()
edce4d98 1436{
7dc5f514 1437 assert(reply == NULL);
0655fa4d 1438
b297bcd0 1439 HttpReply *rep = http->storeEntry()->getReply()->clone();
7dc5f514 1440
1441 reply = HTTPMSGLOCK(rep);
1442
0655fa4d 1443 /* enforce 1.0 reply version */
7dc5f514 1444 reply->sline.version = HttpVersion(1,0);
0655fa4d 1445
1446 /* do header conversions */
1447 buildReplyHeader();
edce4d98 1448}
1449
e6ccf245 1450void
1451clientReplyContext::identifyStoreObject()
edce4d98 1452{
190154cf 1453 HttpRequest *r = http->request;
62e76326 1454
e6ccf245 1455 if (r->flags.cachable || r->flags.internal) {
62e76326 1456 lookingforstore = 5;
1457 StoreEntry::getPublicByRequest (this, r);
559da936 1458 } else {
62e76326 1459 identifyFoundObject (NullStoreEntry::getInstance());
559da936 1460 }
e6ccf245 1461}
1462
7d5f62a4
AJ
1463/**
1464 * Check state of the current StoreEntry object.
1465 * to see if we can determine the final status of the request.
1466 */
e6ccf245 1467void
1468clientReplyContext::identifyFoundObject(StoreEntry *newEntry)
1469{
1470 StoreEntry *e = newEntry;
190154cf 1471 HttpRequest *r = http->request;
62e76326 1472
d85b8894 1473 /** \li If the entry received isNull() then we ignore it. */
e6ccf245 1474 if (e->isNull()) {
86a2f789 1475 http->storeEntry(NULL);
e6ccf245 1476 } else {
86a2f789 1477 http->storeEntry(e);
e6ccf245 1478 }
62e76326 1479
86a2f789 1480 e = http->storeEntry();
a12a049a 1481
7d5f62a4 1482 /* Release IP-cache entries on reload */
d85b8894 1483 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
7d5f62a4
AJ
1484 * 'invalidate' the cached IP entries for this request ???
1485 */
a12a049a 1486 if (r->flags.nocache) {
1487
1488#if USE_DNSSERVERS
62e76326 1489
cc192b50 1490 ipcacheInvalidate(r->GetHost());
62e76326 1491
a12a049a 1492#else
1493
cc192b50 1494 ipcacheInvalidateNegative(r->GetHost());
a12a049a 1495
1496#endif /* USE_DNSSERVERS */
1497
1498 }
1499
edce4d98 1500#if HTTP_VIOLATIONS
62e76326 1501
a12a049a 1502 else if (r->flags.nocache_hack) {
1503
1504#if USE_DNSSERVERS
1505
cc192b50 1506 ipcacheInvalidate(r->GetHost());
62e76326 1507
a12a049a 1508#else
1509
cc192b50 1510 ipcacheInvalidateNegative(r->GetHost());
a12a049a 1511
1512#endif /* USE_DNSSERVERS */
1513
1514 }
1515
1516#endif /* HTTP_VIOLATIONS */
edce4d98 1517#if USE_CACHE_DIGESTS
62e76326 1518
86a2f789 1519 lookup_type = http->storeEntry() ? "HIT" : "MISS";
62e76326 1520
edce4d98 1521#endif
62e76326 1522
86a2f789 1523 if (NULL == http->storeEntry()) {
d85b8894 1524 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
7d5f62a4 1525 debugs(85, 3, "clientProcessRequest2: StoreEntry is NULL - MISS");
62e76326 1526 http->logType = LOG_TCP_MISS;
1527 doGetMoreData();
1528 return;
edce4d98 1529 }
62e76326 1530
edce4d98 1531 if (Config.onoff.offline) {
d85b8894 1532 /** \li If we are running in offline mode set to HIT */
bf8fe701 1533 debugs(85, 3, "clientProcessRequest2: offline HIT");
62e76326 1534 http->logType = LOG_TCP_HIT;
1535 doGetMoreData();
1536 return;
edce4d98 1537 }
62e76326 1538
edce4d98 1539 if (http->redirect.status) {
d85b8894 1540 /** \li If redirection status is True force this to be a MISS */
7d5f62a4 1541 debugs(85, 3, "clientProcessRequest2: redirectStatus forced StoreEntry to NULL - MISS");
86a2f789 1542 http->storeEntry(NULL);
62e76326 1543 http->logType = LOG_TCP_MISS;
1544 doGetMoreData();
1545 return;
edce4d98 1546 }
62e76326 1547
3900307b 1548 if (!e->validToSend()) {
bf8fe701 1549 debugs(85, 3, "clientProcessRequest2: !storeEntryValidToSend MISS" );
86a2f789 1550 http->storeEntry(NULL);
62e76326 1551 http->logType = LOG_TCP_MISS;
1552 doGetMoreData();
1553 return;
edce4d98 1554 }
62e76326 1555
edce4d98 1556 if (EBIT_TEST(e->flags, ENTRY_SPECIAL)) {
d85b8894 1557 /* \li Special entries are always hits, no matter what the client says */
bf8fe701 1558 debugs(85, 3, "clientProcessRequest2: ENTRY_SPECIAL HIT");
62e76326 1559 http->logType = LOG_TCP_HIT;
1560 doGetMoreData();
1561 return;
edce4d98 1562 }
62e76326 1563
edce4d98 1564 if (r->flags.nocache) {
bf8fe701 1565 debugs(85, 3, "clientProcessRequest2: no-cache REFRESH MISS");
86a2f789 1566 http->storeEntry(NULL);
62e76326 1567 http->logType = LOG_TCP_CLIENT_REFRESH_MISS;
1568 doGetMoreData();
1569 return;
edce4d98 1570 }
62e76326 1571
bf8fe701 1572 debugs(85, 3, "clientProcessRequest2: default HIT");
e6ccf245 1573 http->logType = LOG_TCP_HIT;
1574 doGetMoreData();
edce4d98 1575}
1576
d85b8894
AJ
1577/**
1578 * Request more data from the store for the client Stream
edce4d98 1579 * This is *the* entry point to this module.
1580 *
1581 * Preconditions:
d85b8894
AJ
1582 * - This is the head of the list.
1583 * - There is at least one more node.
1584 * - Data context is not null
edce4d98 1585 */
1586void
59a1efb2 1587clientGetMoreData(clientStreamNode * aNode, ClientHttpRequest * http)
edce4d98 1588{
edce4d98 1589 /* Test preconditions */
e6ccf245 1590 assert(aNode != NULL);
1591 assert(cbdataReferenceValid(aNode));
e6ccf245 1592 assert(aNode->node.prev == NULL);
1593 assert(aNode->node.next != NULL);
0655fa4d 1594 clientReplyContext *context = dynamic_cast<clientReplyContext *>(aNode->data.getRaw());
1595 assert (context);
edce4d98 1596 assert(context->http == http);
1597
559da936 1598
0655fa4d 1599 clientStreamNode *next = ( clientStreamNode *)aNode->node.next->data;
62e76326 1600
edce4d98 1601 if (!context->ourNode)
62e76326 1602 context->ourNode = aNode;
1603
e6ccf245 1604 /* no cbdatareference, this is only used once, and safely */
edce4d98 1605 if (context->flags.storelogiccomplete) {
62e76326 1606 StoreIOBuffer tempBuffer;
1607 tempBuffer.offset = next->readBuffer.offset + context->headers_sz;
1608 tempBuffer.length = next->readBuffer.length;
1609 tempBuffer.data = next->readBuffer.data;
1610
86a2f789 1611 storeClientCopy(context->sc, http->storeEntry(),
0655fa4d 1612 tempBuffer, clientReplyContext::SendMoreData, context);
62e76326 1613 return;
edce4d98 1614 }
62e76326 1615
edce4d98 1616 if (context->http->request->method == METHOD_PURGE) {
62e76326 1617 context->purgeRequest();
1618 return;
edce4d98 1619 }
62e76326 1620
fc90edc3
AJ
1621 /* TODO: handle OPTIONS request on max_forwards == 0 as well */
1622
edce4d98 1623 if (context->http->request->method == METHOD_TRACE) {
62e76326 1624 if (context->http->request->max_forwards == 0) {
0655fa4d 1625 context->traceReply(aNode);
62e76326 1626 return;
1627 }
1628
1629 /* continue forwarding, not finished yet. */
1630 http->logType = LOG_TCP_MISS;
1631
1632 context->doGetMoreData();
edce4d98 1633 } else
62e76326 1634 context->identifyStoreObject();
e6ccf245 1635}
1636
1637void
1638clientReplyContext::doGetMoreData()
1639{
edce4d98 1640 /* We still have to do store logic processing - vary, cache hit etc */
86a2f789 1641 if (http->storeEntry() != NULL) {
62e76326 1642 /* someone found the object in the cache for us */
1643 StoreIOBuffer tempBuffer;
34266cde 1644
3d0ac046 1645 http->storeEntry()->lock();
62e76326 1646
86a2f789 1647 if (http->storeEntry()->mem_obj == NULL) {
62e76326 1648 /*
1649 * This if-block exists because we don't want to clobber
1650 * a preexiting mem_obj->method value if the mem_obj
1651 * already exists. For example, when a HEAD request
1652 * is a cache hit for a GET response, we want to keep
1653 * the method as GET.
1654 */
3900307b 1655 http->storeEntry()->createMemObject(http->uri, http->log_uri);
7d5f62a4 1656 http->storeEntry()->mem_obj->method = http->request->method;
62e76326 1657 }
1658
86a2f789 1659 sc = storeClientListAdd(http->storeEntry(), this);
edce4d98 1660#if DELAY_POOLS
62e76326 1661
1662 sc->setDelayId(DelayId::DelayClient(http));
edce4d98 1663#endif
62e76326 1664
1665 assert(http->logType == LOG_TCP_HIT);
1666 reqofs = 0;
1667 /* guarantee nothing has been sent yet! */
1668 assert(http->out.size == 0);
1669 assert(http->out.offset == 0);
b86ab75b 1670#if USE_ZPH_QOS
575cb927
AJ
1671 if (Config.zph.tos_local_hit) {
1672 debugs(33, 2, "ZPH Local hit, TOS=" << Config.zph.tos_local_hit);
1673 comm_set_tos(http->getConn()->fd, Config.zph.tos_local_hit);
b86ab75b
AJ
1674 }
1675#endif /* USE_ZPH_QOS */
62e76326 1676 tempBuffer.offset = reqofs;
1677 tempBuffer.length = getNextNode()->readBuffer.length;
1678 tempBuffer.data = getNextNode()->readBuffer.data;
559da936 1679 storeClientCopy(sc, http->storeEntry(), tempBuffer, CacheHit, this);
edce4d98 1680 } else {
62e76326 1681 /* MISS CASE, http->logType is already set! */
0655fa4d 1682 processMiss();
edce4d98 1683 }
1684}
1685
d85b8894 1686/** The next node has removed itself from the stream. */
edce4d98 1687void
59a1efb2 1688clientReplyDetach(clientStreamNode * node, ClientHttpRequest * http)
edce4d98 1689{
d85b8894 1690 /** detach from the stream */
edce4d98 1691 clientStreamDetach(node, http);
1692}
1693
d85b8894
AJ
1694/**
1695 * Accepts chunk of a http message in buf, parses prefix, filters headers and
edce4d98 1696 * such, writes processed message to the message recipient
1697 */
1698void
0655fa4d 1699clientReplyContext::SendMoreData(void *data, StoreIOBuffer result)
edce4d98 1700{
e6ccf245 1701 clientReplyContext *context = static_cast<clientReplyContext *>(data);
528b2c61 1702 context->sendMoreData (result);
1703}
1704
1705void
1706clientReplyContext::makeThisHead()
1707{
1708 /* At least, I think thats what this does */
1709 dlinkDelete(&http->active, &ClientActiveRequests);
1710 dlinkAdd(http, &http->active, &ClientActiveRequests);
1711}
1712
1713bool
1714clientReplyContext::errorInStream(StoreIOBuffer const &result, size_t const &sizeToProcess)const
1715{
1716 return /* aborted request */
86a2f789 1717 (http->storeEntry() && EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) ||
62e76326 1718 /* Upstream read error */ (result.flags.error) ||
1719 /* Upstream EOF */ (sizeToProcess == 0);
528b2c61 1720}
1721
1722void
1723clientReplyContext::sendStreamError(StoreIOBuffer const &result)
1724{
d85b8894 1725 /** call clientWriteComplete so the client socket gets closed
af6a12ee 1726 *
d85b8894 1727 * We call into the stream, because we don't know that there is a
528b2c61 1728 * client socket!
1729 */
26ac0430 1730 debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.");
528b2c61 1731 StoreIOBuffer tempBuffer;
1732 flags.complete = 1;
1733 tempBuffer.flags.error = result.flags.error;
1734 clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
62e76326 1735 tempBuffer);
528b2c61 1736}
1737
1738void
1739clientReplyContext::pushStreamData(StoreIOBuffer const &result, char *source)
1740{
1741 StoreIOBuffer tempBuffer;
62e76326 1742
528b2c61 1743 if (result.length == 0) {
bf8fe701 1744 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
62e76326 1745 flags.complete = 1;
528b2c61 1746 }
62e76326 1747
43ae1d95 1748 assert(result.offset - headers_sz == next()->readBuffer.offset);
528b2c61 1749 tempBuffer.offset = result.offset - headers_sz;
1750 tempBuffer.length = result.length;
62e76326 1751
43ae1d95 1752 if (tempBuffer.length)
1753 tempBuffer.data = source;
62e76326 1754
528b2c61 1755 clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
62e76326 1756 tempBuffer);
528b2c61 1757}
1758
1759clientStreamNode *
1760clientReplyContext::next() const
1761{
1762 assert ( (clientStreamNode*)http->client_stream.head->next->data == getNextNode());
1763 return getNextNode();
1764}
1765
b51aec66 1766void
16611143 1767clientReplyContext::sendBodyTooLargeError()
b51aec66 1768{
ad61a2b4 1769 IpAddress tmp_noaddr;
26ac0430 1770 tmp_noaddr.SetNoAddr(); // TODO: make a global const
16611143 1771 ErrorState *err = clientBuildError(ERR_TOO_BIG, HTTP_FORBIDDEN, NULL,
26ac0430
AJ
1772 http->getConn() != NULL ? http->getConn()->peer : tmp_noaddr,
1773 http->request);
16611143 1774 removeClientStoreReference(&(sc), http);
1775 HTTPMSGUNLOCK(reply);
1776 startError(err);
26ac0430 1777
b51aec66 1778}
1779
4993f571 1780void
1781clientReplyContext::processReplyAccess ()
1782{
b50e327b 1783 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
7dc5f514 1784 assert(reply);
b50e327b
AJ
1785
1786 /** Don't block our own responses or HTTP status messages */
16611143 1787 if (http->logType == LOG_TCP_DENIED ||
26ac0430
AJ
1788 http->logType == LOG_TCP_DENIED_REPLY ||
1789 alwaysAllowResponse(reply->sline.status)) {
acbf9428 1790 headers_sz = reply->hdr_sz;
26ac0430
AJ
1791 processReplyAccessResult(1);
1792 return;
230a8cc6 1793 }
26ac0430 1794
b50e327b 1795 /** Check for reply to big error */
16611143 1796 if (reply->expectedBodyTooLarge(*http->request)) {
1797 sendBodyTooLargeError();
62e76326 1798 return;
1799 }
1800
7dc5f514 1801 headers_sz = reply->hdr_sz;
230a8cc6 1802
b50e327b 1803 /** check for absent access controls (permit by default) */
230a8cc6 1804 if (!Config.accessList.reply) {
26ac0430
AJ
1805 processReplyAccessResult(1);
1806 return;
230a8cc6 1807 }
1808
b50e327b 1809 /** Process http_reply_access lists */
127dce76
AR
1810 ACLFilledChecklist *replyChecklist =
1811 clientAclChecklistCreate(Config.accessList.reply, http);
7dc5f514 1812 replyChecklist->reply = HTTPMSGLOCK(reply);
0655fa4d 1813 replyChecklist->nonBlockingCheck(ProcessReplyAccessResult, this);
4993f571 1814}
1815
1816void
0655fa4d 1817clientReplyContext::ProcessReplyAccessResult (int rv, void *voidMe)
4993f571 1818{
1819 clientReplyContext *me = static_cast<clientReplyContext *>(voidMe);
0655fa4d 1820 me->processReplyAccessResult(rv);
4993f571 1821}
1822
1823void
0655fa4d 1824clientReplyContext::processReplyAccessResult(bool accessAllowed)
4993f571 1825{
26ac0430
AJ
1826 debugs(88, 2, "The reply for " << RequestMethodStr(http->request->method)
1827 << " " << http->uri << " is "
1828 << ( accessAllowed ? "ALLOWED" : "DENIED")
1829 << ", because it matched '"
bf8fe701 1830 << (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" );
62e76326 1831
230a8cc6 1832 if (!accessAllowed) {
62e76326 1833 ErrorState *err;
0185bd6f 1834 err_type page_id;
9ce7856a 1835 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, 1);
0185bd6f 1836
c466369c 1837 http->logType = LOG_TCP_DENIED_REPLY;
1838
0185bd6f 1839 if (page_id == ERR_NONE)
1840 page_id = ERR_ACCESS_DENIED;
1841
ad61a2b4 1842 IpAddress tmp_noaddr;
26ac0430 1843 tmp_noaddr.SetNoAddr();
cc192b50 1844 err = clientBuildError(page_id, HTTP_FORBIDDEN, NULL,
26ac0430
AJ
1845 http->getConn() != NULL ? http->getConn()->peer : tmp_noaddr,
1846 http->request);
0185bd6f 1847
86a2f789 1848 removeClientStoreReference(&sc, http);
0185bd6f 1849
7dc5f514 1850 HTTPMSGUNLOCK(reply);
0185bd6f 1851
3c2c1d31 1852 startError(err);
1853
0185bd6f 1854
62e76326 1855 return;
1856 }
1857
0976f8db 1858 /* Ok, the reply is allowed, */
1859 http->loggingEntry(http->storeEntry());
1860
7dc5f514 1861 ssize_t body_size = reqofs - reply->hdr_sz;
b297bcd0 1862 if (body_size < 0) {
26ac0430
AJ
1863 reqofs = reply->hdr_sz;
1864 body_size = 0;
b297bcd0 1865 }
0976f8db 1866
bf8fe701 1867 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
1868 (int) body_size << " bytes after " << reply->hdr_sz <<
1869 " bytes of headers");
0976f8db 1870
f41735ea 1871#if USE_SQUID_ESI
62e76326 1872
7dc5f514 1873 if (http->flags.accel && reply->sline.status != HTTP_FORBIDDEN &&
1874 !alwaysAllowResponse(reply->sline.status) &&
1875 esiEnableProcessing(reply)) {
bf8fe701 1876 debugs(88, 2, "Enabling ESI processing for " << http->uri);
43ae1d95 1877 clientStreamInsertHead(&http->client_stream, esiStreamRead,
1878 esiProcessStream, esiStreamDetach, esiStreamStatus, NULL);
1879 }
1880
5ef38a13 1881#endif
1882
62e76326 1883 if (http->request->method == METHOD_HEAD) {
1884 /* do not forward body for HEAD replies */
1885 body_size = 0;
1886 http->flags.done_copying = 1;
1887 flags.complete = 1;
1888 }
1889
1890 assert (!flags.headersSent);
1891 flags.headersSent = true;
1892
1893 StoreIOBuffer tempBuffer;
1894 char *buf = next()->readBuffer.data;
e85eb4e1 1895 char *body_buf = buf + reply->hdr_sz;
62e76326 1896
49ea0125 1897 //Server side may disable ranges under some circumstances.
1898
1899 if ((!http->request->range))
1900 next()->readBuffer.offset = 0;
1901
e85eb4e1
AJ
1902 body_buf -= next()->readBuffer.offset;
1903
62e76326 1904 if (next()->readBuffer.offset != 0) {
1905 if (next()->readBuffer.offset > body_size) {
2324cda2 1906 /* Can't use any of the body we received. send nothing */
62e76326 1907 tempBuffer.length = 0;
1908 tempBuffer.data = NULL;
1909 } else {
1910 tempBuffer.length = body_size - next()->readBuffer.offset;
1911 tempBuffer.data = body_buf + next()->readBuffer.offset;
1912 }
1913 } else {
1914 tempBuffer.length = body_size;
1915 tempBuffer.data = body_buf;
1916 }
1917
0655fa4d 1918 /* TODO??: move the data in the buffer back by the request header size */
62e76326 1919 clientStreamCallback((clientStreamNode *)http->client_stream.head->data,
7dc5f514 1920 http, reply, tempBuffer);
62e76326 1921
1922 return;
4993f571 1923}
1924
528b2c61 1925void
1926clientReplyContext::sendMoreData (StoreIOBuffer result)
1927{
50c09fc4 1928 if (deleting)
1929 return;
1930
86a2f789 1931 StoreEntry *entry = http->storeEntry();
50c09fc4 1932
1cf238db 1933 ConnStateData * conn = http->getConn();
50c09fc4 1934
94a396a3 1935 int fd = conn != NULL ? conn->fd : -1;
9af2f95b
AR
1936 if (fd >= 0 && fd_table[fd].closing()) { // too late, our conn is closing
1937 // TODO: should we also quit when fd is negative?
1938 debugs(33,3, HERE << "not sending more data to a closing FD " << fd);
1939 return;
1940 }
50c09fc4 1941
528b2c61 1942 char *buf = next()->readBuffer.data;
50c09fc4 1943
c8be6d7b 1944 char *body_buf = buf;
edce4d98 1945
da33c835 1946 if (buf != result.data) {
62e76326 1947 /* we've got to copy some data */
1948 assert(result.length <= next()->readBuffer.length);
1949 xmemcpy(buf, result.data, result.length);
1950 body_buf = buf;
edce4d98 1951 }
62e76326 1952
452bb8e2 1953#if USE_ZPH_QOS
26ac0430 1954 if (reqofs==0 && !logTypeIsATcpHit(http->logType)) {
9af2f95b 1955 assert(fd >= 0); // the beginning of this method implies fd may be -1
452bb8e2 1956 int tos = 0;
575cb927
AJ
1957 if (Config.zph.tos_sibling_hit && http->request->hier.code==SIBLING_HIT ) {
1958 tos = Config.zph.tos_sibling_hit;
1959 debugs(33, 2, "ZPH: Sibling Peer hit with hier.code=" << http->request->hier.code << ", TOS=" << tos);
1960 } else if (Config.zph.tos_parent_hit && http->request->hier.code==PARENT_HIT) {
1961 tos = Config.zph.tos_parent_hit;
1962 debugs(33, 2, "ZPH: Parent Peer hit with hier.code=" << http->request->hier.code << ", TOS=" << tos);
1963 } else if (Config.zph.preserve_miss_tos && Config.zph.preserve_miss_tos_mask) {
1964 tos = fd_table[fd].upstreamTOS & Config.zph.preserve_miss_tos_mask;
452bb8e2
AJ
1965 debugs(33, 2, "ZPH: Preserving TOS on miss, TOS="<<tos);
1966 }
1967 comm_set_tos(fd,tos);
7172612f 1968 }
26ac0430 1969#endif
7172612f 1970
ab9c533b
HN
1971 /* We've got the final data to start pushing... */
1972 flags.storelogiccomplete = 1;
1973
4993f571 1974 reqofs += result.length;
1975
1976 assert(reqofs <= HTTP_REQBUF_SZ || flags.headersSent);
62e76326 1977
edce4d98 1978 assert(http->request != NULL);
62e76326 1979
edce4d98 1980 /* ESI TODO: remove this assert once everything is stable */
1981 assert(http->client_stream.head->data
62e76326 1982 && cbdataReferenceValid(http->client_stream.head->data));
528b2c61 1983
1984 makeThisHead();
62e76326 1985
bf8fe701 1986 debugs(88, 5, "clientReplyContext::sendMoreData: " << http->uri << ", " <<
47f6e231 1987 reqofs << " bytes (" << result.length <<
bf8fe701 1988 " new bytes)");
47f6e231 1989 debugs(88, 5, "clientReplyContext::sendMoreData:"
26ac0430
AJ
1990 " FD " << fd <<
1991 " '" << entry->url() << "'" <<
1992 " out.offset=" << http->out.offset);
528b2c61 1993
edce4d98 1994 /* update size of the request */
4993f571 1995 reqsize = reqofs;
62e76326 1996
4993f571 1997 if (errorInStream(result, reqofs)) {
62e76326 1998 sendStreamError(result);
1999 return;
edce4d98 2000 }
528b2c61 2001
2002 if (flags.headersSent) {
62e76326 2003 pushStreamData (result, buf);
2004 return;
edce4d98 2005 }
62e76326 2006
b297bcd0 2007 cloneReply();
21b92762 2008
b297bcd0 2009 /* handle headers */
21b92762 2010
b297bcd0 2011 if (Config.onoff.log_mime_hdrs) {
26ac0430 2012 size_t k;
43ae1d95 2013
26ac0430
AJ
2014 if ((k = headersEnd(buf, reqofs))) {
2015 safe_free(http->al.headers.reply);
2016 http->al.headers.reply = (char *)xcalloc(k + 1, 1);
2017 xstrncpy(http->al.headers.reply, buf, k);
2018 }
edce4d98 2019 }
b297bcd0
HN
2020
2021 holdingBuffer = result;
2022 processReplyAccess();
2023 return;
edce4d98 2024}
2025
62e76326 2026
edce4d98 2027
2028/* Using this breaks the client layering just a little!
2029 */
0655fa4d 2030void
60745f24 2031clientReplyContext::createStoreEntry(const HttpRequestMethod& m, request_flags flags)
edce4d98 2032{
0655fa4d 2033 assert(http != NULL);
edce4d98 2034 /*
2035 * For erroneous requests, we might not have a h->request,
2036 * so make a fake one.
2037 */
62e76326 2038
0655fa4d 2039 if (http->request == NULL)
6dd9f4bd 2040 http->request = HTTPMSGLOCK(new HttpRequest(m, PROTO_NONE, null_string));
62e76326 2041
0655fa4d 2042 StoreEntry *e = storeCreateEntry(http->uri, http->log_uri, flags, m);
62e76326 2043
0655fa4d 2044 sc = storeClientListAdd(e, this);
62e76326 2045
edce4d98 2046#if DELAY_POOLS
62e76326 2047
0655fa4d 2048 sc->setDelayId(DelayId::DelayClient(http));
62e76326 2049
edce4d98 2050#endif
62e76326 2051
0655fa4d 2052 reqofs = 0;
62e76326 2053
0655fa4d 2054 reqsize = 0;
62e76326 2055
edce4d98 2056 /* I don't think this is actually needed! -- adrian */
0655fa4d 2057 /* http->reqbuf = http->norm_reqbuf; */
2058 // assert(http->reqbuf == http->norm_reqbuf);
edce4d98 2059 /* The next line is illegal because we don't know if the client stream
26ac0430 2060 * buffers have been set up
edce4d98 2061 */
0655fa4d 2062 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2063 // SendMoreData, this);
edce4d98 2064 /* So, we mark the store logic as complete */
0655fa4d 2065 this->flags.storelogiccomplete = 1;
62e76326 2066
edce4d98 2067 /* and get the caller to request a read, from whereever they are */
62e76326 2068 /* NOTE: after ANY data flows down the pipe, even one step,
26ac0430 2069 * this function CAN NOT be used to manage errors
edce4d98 2070 */
86a2f789 2071 http->storeEntry(e);
edce4d98 2072}
2073
2074ErrorState *
2075clientBuildError(err_type page_id, http_status status, char const *url,
ad61a2b4 2076 IpAddress &src_addr, HttpRequest * request)
edce4d98 2077{
2cc81f1f 2078 ErrorState *err = errorCon(page_id, status, request);
cc192b50 2079 err->src_addr = src_addr;
62e76326 2080
edce4d98 2081 if (url)
62e76326 2082 err->url = xstrdup(url);
2083
edce4d98 2084 return err;
2085}