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