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