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