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