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