]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_reply.cc
Removing unused function httpHdrCcJoinWith()
[thirdparty/squid.git] / src / client_side_reply.cc
CommitLineData
edce4d98 1
2/*
f5e45ad8 3 * $Id: client_side_reply.cc,v 1.87 2005/09/14 17:10:38 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
ddfcbc22 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
59a1efb2 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
ddfcbc22 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
36e6655b 664 if (storeCheckNegativeHit(e)
665#if HTTP_VIOLATIONS
666 && !r->flags.nocache_hack
667#endif
668 ) {
62e76326 669 http->logType = LOG_TCP_NEGATIVE_HIT;
0655fa4d 670 sendMoreData(result);
f7cf9b8c 671 } else if (!Config.onoff.offline && refreshCheckHTTP(e, r) && !http->flags.internal) {
62e76326 672 debug(88, 5) ("clientCacheHit: in refreshCheck() block\n");
673 /*
674 * We hold a stale copy; it needs to be validated
675 */
676 /*
677 * The 'need_validation' flag is used to prevent forwarding
678 * loops between siblings. If our copy of the object is stale,
679 * then we should probably only use parents for the validation
680 * request. Otherwise two siblings could generate a loop if
681 * both have a stale version of the object.
682 */
683 r->flags.need_validation = 1;
684
685 if (e->lastmod < 0) {
686 /*
687 * Previous reply didn't have a Last-Modified header,
688 * we cannot revalidate it.
689 */
690 http->logType = LOG_TCP_MISS;
0655fa4d 691 processMiss();
62e76326 692 } else if (r->flags.nocache) {
693 /*
694 * This did not match a refresh pattern that overrides no-cache
695 * we should honour the client no-cache header.
696 */
697 http->logType = LOG_TCP_CLIENT_REFRESH_MISS;
0655fa4d 698 processMiss();
62e76326 699 } else if (r->protocol == PROTO_HTTP) {
700 /*
701 * Object needs to be revalidated
702 * XXX This could apply to FTP as well, if Last-Modified is known.
703 */
704 http->logType = LOG_TCP_REFRESH_MISS;
0655fa4d 705 processExpired();
62e76326 706 } else {
707 /*
708 * We don't know how to re-validate other protocols. Handle
709 * them as if the object has expired.
710 */
711 http->logType = LOG_TCP_MISS;
0655fa4d 712 processMiss();
62e76326 713 }
edce4d98 714 } else if (r->flags.ims) {
62e76326 715 /*
716 * Handle If-Modified-Since requests from the client
717 */
718
719 if (e->getReply()->sline.status != HTTP_OK) {
720 debug(88, 4) ("clientCacheHit: Reply code %d != 200\n",
721 e->getReply()->sline.status);
722 http->logType = LOG_TCP_MISS;
0655fa4d 723 processMiss();
724 } else if (e->modifiedSince(http->request)) {
62e76326 725 http->logType = LOG_TCP_IMS_HIT;
0655fa4d 726 sendMoreData(result);
62e76326 727 } else {
0655fa4d 728 time_t const timestamp = e->timestamp;
62e76326 729 HttpReply *temprep = httpReplyMake304 (e->getReply());
730 http->logType = LOG_TCP_IMS_HIT;
86a2f789 731 removeClientStoreReference(&sc, http);
0655fa4d 732 createStoreEntry(http->request->method,
733 request_flags());
86a2f789 734 e = http->storeEntry();
62e76326 735 /*
736 * Copy timestamp from the original entry so the 304
737 * reply has a meaningful Age: header.
738 */
739 e->timestamp = timestamp;
740 httpReplySwapOut (temprep, e);
741 e->complete();
742 /* TODO: why put this in the store and then serialise it and then parse it again.
743 * Simply mark the request complete in our context and
744 * write the reply struct to the client side
745 */
0655fa4d 746 triggerInitialStoreRead();
62e76326 747 }
edce4d98 748 } else {
62e76326 749 /*
750 * plain ol' cache hit
751 */
752
ffdf45f2 753 if (e->store_status != STORE_OK)
849b826a 754 http->logType = LOG_TCP_MISS;
ffdf45f2 755 else if (e->mem_status == IN_MEMORY)
62e76326 756 http->logType = LOG_TCP_MEM_HIT;
757 else if (Config.onoff.offline)
758 http->logType = LOG_TCP_OFFLINE_HIT;
759
0655fa4d 760 sendMoreData(result);
edce4d98 761 }
762}
763
764/*
765 * Prepare to fetch the object as it's a cache miss of some kind.
766 */
767void
0655fa4d 768clientReplyContext::processMiss()
edce4d98 769{
edce4d98 770 char *url = http->uri;
190154cf 771 HttpRequest *r = http->request;
edce4d98 772 ErrorState *err = NULL;
773 debug(88, 4) ("clientProcessMiss: '%s %s'\n",
62e76326 774 RequestMethodStr[r->method], url);
edce4d98 775 /*
776 * We might have a left-over StoreEntry from a failed cache hit
777 * or IMS request.
778 */
62e76326 779
86a2f789 780 if (http->storeEntry()) {
781 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_SPECIAL)) {
62e76326 782 debug(88, 0) ("clientProcessMiss: miss on a special object (%s).\n",
783 url);
784 debug(88, 0) ("\tlog_type = %s\n", log_tags[http->logType]);
86a2f789 785 storeEntryDump(http->storeEntry(), 1);
62e76326 786 }
787
86a2f789 788 removeClientStoreReference(&sc, http);
edce4d98 789 }
62e76326 790
edce4d98 791 if (r->method == METHOD_PURGE) {
0655fa4d 792 purgeRequest();
62e76326 793 return;
edce4d98 794 }
62e76326 795
0655fa4d 796 if (http->onlyIfCached()) {
797 processOnlyIfCachedMiss();
62e76326 798 return;
edce4d98 799 }
62e76326 800
edce4d98 801 /*
802 * Deny loops when running in accelerator/transproxy mode.
803 */
804 if (http->flags.accel && r->flags.loopdetect) {
62e76326 805 http->al.http.code = HTTP_FORBIDDEN;
806 err =
807 clientBuildError(ERR_ACCESS_DENIED, HTTP_FORBIDDEN, NULL,
98242069 808 &http->getConn()->peer.sin_addr, http->request);
0655fa4d 809 createStoreEntry(r->method, request_flags());
86a2f789 810 errorAppendEntry(http->storeEntry(), err);
0655fa4d 811 triggerInitialStoreRead();
62e76326 812 return;
edce4d98 813 } else {
62e76326 814 assert(http->out.offset == 0);
0655fa4d 815 createStoreEntry(r->method, r->flags);
816 triggerInitialStoreRead();
62e76326 817
818 if (http->redirect.status) {
819 HttpReply *rep = httpReplyCreate();
edce4d98 820#if LOG_TCP_REDIRECTS
62e76326 821
822 http->logType = LOG_TCP_REDIRECT;
edce4d98 823#endif
62e76326 824
86a2f789 825 storeReleaseRequest(http->storeEntry());
62e76326 826 httpRedirectReply(rep, http->redirect.status,
827 http->redirect.location);
86a2f789 828 httpReplySwapOut(rep, http->storeEntry());
829 http->storeEntry()->complete();
62e76326 830 return;
831 }
832
833 if (http->flags.internal)
834 r->protocol = PROTO_INTERNAL;
835
a2ac85d9 836 fwdStart(http->getConn().getRaw() != NULL ? http->getConn()->fd : -1, http->storeEntry(), r);
edce4d98 837 }
838}
839
840/*
841 * client issued a request with an only-if-cached cache-control directive;
842 * we did not find a cached object that can be returned without
843 * contacting other servers;
844 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
845 */
0655fa4d 846void
847clientReplyContext::processOnlyIfCachedMiss()
edce4d98 848{
edce4d98 849 ErrorState *err = NULL;
edce4d98 850 debug(88, 4) ("clientProcessOnlyIfCachedMiss: '%s %s'\n",
0655fa4d 851 RequestMethodStr[http->request->method], http->uri);
edce4d98 852 http->al.http.code = HTTP_GATEWAY_TIMEOUT;
853 err = clientBuildError(ERR_ONLY_IF_CACHED_MISS, HTTP_GATEWAY_TIMEOUT, NULL,
98242069 854 &http->getConn()->peer.sin_addr, http->request);
86a2f789 855 removeClientStoreReference(&sc, http);
0655fa4d 856 startError(err);
edce4d98 857}
858
859void
e6ccf245 860clientReplyContext::purgeRequestFindObjectToPurge()
861{
862 /* Try to find a base entry */
863 http->flags.purging = 1;
864 lookingforstore = 1;
3b13a8fd 865 StoreEntry::getPublicByRequestMethod(this, http->request, METHOD_GET);
e6ccf245 866}
867
868void
3b13a8fd 869clientReplyContext::created(StoreEntry *newEntry)
e6ccf245 870{
871 if (lookingforstore == 1)
62e76326 872 purgeFoundGet(newEntry);
e6ccf245 873 else if (lookingforstore == 2)
62e76326 874 purgeFoundHead(newEntry);
e6ccf245 875 else if (lookingforstore == 3)
62e76326 876 purgeDoPurgeGet(newEntry);
e6ccf245 877 else if (lookingforstore == 4)
62e76326 878 purgeDoPurgeHead(newEntry);
e6ccf245 879 else if (lookingforstore == 5)
62e76326 880 identifyFoundObject(newEntry);
e6ccf245 881}
882
883void
3b13a8fd 884clientReplyContext::purgeFoundGet(StoreEntry *newEntry)
e6ccf245 885{
886 if (newEntry->isNull()) {
62e76326 887 lookingforstore = 2;
888 StoreEntry::getPublicByRequestMethod(this, http->request, METHOD_HEAD);
e6ccf245 889 } else
62e76326 890 purgeFoundObject (newEntry);
e6ccf245 891}
892
893void
3b13a8fd 894clientReplyContext::purgeFoundHead(StoreEntry *newEntry)
e6ccf245 895{
896 if (newEntry->isNull())
62e76326 897 purgeDoMissPurge();
e6ccf245 898 else
62e76326 899 purgeFoundObject (newEntry);
e6ccf245 900}
62e76326 901
e6ccf245 902void
3b13a8fd 903clientReplyContext::purgeFoundObject(StoreEntry *entry)
e6ccf245 904{
905 assert (entry && !entry->isNull());
e4b9a2f0 906
907 if (EBIT_TEST(entry->flags, ENTRY_SPECIAL)) {
908 http->logType = LOG_TCP_DENIED;
909 ErrorState *err =
910 clientBuildError(ERR_ACCESS_DENIED, HTTP_FORBIDDEN, NULL,
911 &http->getConn()->peer.sin_addr, http->request);
912 startError(err);
913 return;
914 }
915
62e76326 916 StoreIOBuffer tempBuffer;
917 /* Swap in the metadata */
86a2f789 918 http->storeEntry(entry);
919 storeLockObject(http->storeEntry());
920 storeCreateMemObject(http->storeEntry(), http->uri, http->log_uri);
921 http->storeEntry()->mem_obj->method = http->request->method;
922 sc = storeClientListAdd(http->storeEntry(), this);
62e76326 923 http->logType = LOG_TCP_HIT;
924 reqofs = 0;
925 tempBuffer.offset = http->out.offset;
0655fa4d 926 tempBuffer.length = next()->readBuffer.length;
927 tempBuffer.data = next()->readBuffer.data;
86a2f789 928 storeClientCopy(sc, http->storeEntry(),
0655fa4d 929 tempBuffer, CacheHit, this);
e6ccf245 930}
931
932void
933clientReplyContext::purgeRequest()
edce4d98 934{
edce4d98 935 debug(88, 3) ("Config2.onoff.enable_purge = %d\n",
62e76326 936 Config2.onoff.enable_purge);
937
edce4d98 938 if (!Config2.onoff.enable_purge) {
62e76326 939 http->logType = LOG_TCP_DENIED;
940 ErrorState *err =
941 clientBuildError(ERR_ACCESS_DENIED, HTTP_FORBIDDEN, NULL,
98242069 942 &http->getConn()->peer.sin_addr, http->request);
0655fa4d 943 startError(err);
62e76326 944 return;
edce4d98 945 }
62e76326 946
edce4d98 947 /* Release both IP cache */
948 ipcacheInvalidate(http->request->host);
949
e6ccf245 950 if (!http->flags.purging)
62e76326 951 purgeRequestFindObjectToPurge();
e6ccf245 952 else
62e76326 953 purgeDoMissPurge();
e6ccf245 954}
955
956void
957clientReplyContext::purgeDoMissPurge()
958{
29b8d8d6 959 http->logType = LOG_TCP_MISS;
e6ccf245 960 lookingforstore = 3;
3b13a8fd 961 StoreEntry::getPublicByRequestMethod(this,http->request, METHOD_GET);
e6ccf245 962}
963
964void
3b13a8fd 965clientReplyContext::purgeDoPurgeGet(StoreEntry *newEntry)
e6ccf245 966{
967 assert (newEntry);
968 /* Move to new() when that is created */
969 purgeStatus = HTTP_NOT_FOUND;
970
971 if (!newEntry->isNull()) {
62e76326 972 /* Release the cached URI */
973 debug(88, 4) ("clientPurgeRequest: GET '%s'\n", storeUrl(newEntry));
974 storeRelease(newEntry);
975 purgeStatus = HTTP_OK;
edce4d98 976 }
62e76326 977
e6ccf245 978 lookingforstore = 4;
3b13a8fd 979 StoreEntry::getPublicByRequestMethod(this, http->request, METHOD_HEAD);
e6ccf245 980}
981
982void
3b13a8fd 983clientReplyContext::purgeDoPurgeHead(StoreEntry *newEntry)
e6ccf245 984{
4fc0ac76 985 if (newEntry && !newEntry->isNull()) {
62e76326 986 debug(88, 4) ("clientPurgeRequest: HEAD '%s'\n", storeUrl(newEntry));
987 storeRelease(newEntry);
988 purgeStatus = HTTP_OK;
edce4d98 989 }
62e76326 990
e6ccf245 991 HttpReply *r;
62e76326 992
edce4d98 993 /* And for Vary, release the base URI if none of the headers was included in the request */
62e76326 994
edce4d98 995 if (http->request->vary_headers
62e76326 996 && !strstr(http->request->vary_headers, "=")) {
997 StoreEntry *entry = storeGetPublic(urlCanonical(http->request), METHOD_GET);
998
999 if (entry) {
1000 debug(88, 4) ("clientPurgeRequest: Vary GET '%s'\n",
1001 storeUrl(entry));
1002 storeRelease(entry);
1003 purgeStatus = HTTP_OK;
1004 }
1005
1006 entry = storeGetPublic(urlCanonical(http->request), METHOD_HEAD);
1007
1008 if (entry) {
1009 debug(88, 4) ("clientPurgeRequest: Vary HEAD '%s'\n",
1010 storeUrl(entry));
1011 storeRelease(entry);
1012 purgeStatus = HTTP_OK;
1013 }
edce4d98 1014 }
62e76326 1015
edce4d98 1016 /*
1017 * Make a new entry to hold the reply to be written
1018 * to the client.
1019 */
528b2c61 1020 /* FIXME: This doesn't need to go through the store. Simply
1021 * push down the client chain
1022 */
0655fa4d 1023 createStoreEntry(http->request->method, request_flags());
62e76326 1024
0655fa4d 1025 triggerInitialStoreRead();
62e76326 1026
528b2c61 1027 r = httpReplyCreate();
62e76326 1028
450e0c10 1029 HttpVersion version(1,0);
62e76326 1030
e6ccf245 1031 httpReplySetHeaders(r, version, purgeStatus, NULL, NULL, 0, 0, -1);
62e76326 1032
86a2f789 1033 httpReplySwapOut(r, http->storeEntry());
62e76326 1034
86a2f789 1035 http->storeEntry()->complete();
edce4d98 1036}
1037
1038void
0655fa4d 1039clientReplyContext::traceReply(clientStreamNode * node)
edce4d98 1040{
1041 HttpReply *rep;
e6ccf245 1042 clientStreamNode *next = (clientStreamNode *)node->node.next->data;
528b2c61 1043 StoreIOBuffer tempBuffer;
0655fa4d 1044 assert(http->request->max_forwards == 0);
1045 createStoreEntry(http->request->method, request_flags());
1046 tempBuffer.offset = next->readBuffer.offset + headers_sz;
c8be6d7b 1047 tempBuffer.length = next->readBuffer.length;
1048 tempBuffer.data = next->readBuffer.data;
86a2f789 1049 storeClientCopy(sc, http->storeEntry(),
0655fa4d 1050 tempBuffer, SendMoreData, this);
86a2f789 1051 storeReleaseRequest(http->storeEntry());
1052 storeBuffer(http->storeEntry());
edce4d98 1053 rep = httpReplyCreate();
450e0c10 1054 HttpVersion version(1,0);
edce4d98 1055 httpReplySetHeaders(rep, version, HTTP_OK, NULL, "text/plain",
0655fa4d 1056 httpRequestPrefixLen(http->request), 0, squid_curtime);
86a2f789 1057 httpReplySwapOut(rep, http->storeEntry());
1058 httpRequestSwapOut(http->request, http->storeEntry());
1059 http->storeEntry()->complete();
edce4d98 1060}
1061
1062#define SENDING_BODY 0
1063#define SENDING_HDRSONLY 1
1064int
0655fa4d 1065clientReplyContext::checkTransferDone()
edce4d98 1066{
86a2f789 1067 StoreEntry *entry = http->storeEntry();
62e76326 1068
edce4d98 1069 if (entry == NULL)
62e76326 1070 return 0;
1071
1072 /*
edce4d98 1073 * For now, 'done_copying' is used for special cases like
1074 * Range and HEAD requests.
1075 */
0655fa4d 1076 if (http->flags.done_copying)
62e76326 1077 return 1;
1078
edce4d98 1079 /*
1080 * Handle STORE_OK objects.
1081 * objectLen(entry) will be set proprely.
1082 * RC: Does objectLen(entry) include the Headers?
0e3be1ea 1083 * RC: Yes.
edce4d98 1084 */
1085 if (entry->store_status == STORE_OK) {
0655fa4d 1086 return storeOKTransferDone();
e39b9382 1087 } else {
0655fa4d 1088 return storeNotOKTransferDone();
edce4d98 1089 }
e39b9382 1090}
1091
1092int
1093clientReplyContext::storeOKTransferDone() const
1094{
86a2f789 1095 if (http->out.offset >= objectLen(http->storeEntry()) - headers_sz)
62e76326 1096 return 1;
1097
e39b9382 1098 return 0;
1099}
1100
1101int
1102clientReplyContext::storeNotOKTransferDone() const
1103{
edce4d98 1104 /*
1105 * Now, handle STORE_PENDING objects
1106 */
86a2f789 1107 MemObject *mem = http->storeEntry()->mem_obj;
edce4d98 1108 assert(mem != NULL);
1109 assert(http->request != NULL);
0e3be1ea 1110 /* mem->reply was wrong because it uses the UPSTREAM header length!!! */
0353e724 1111 HttpReply const *reply = mem->getReply();
62e76326 1112
e39b9382 1113 if (headers_sz == 0)
62e76326 1114 /* haven't found end of headers yet */
1115 return 0;
e39b9382 1116
1117 int sending = SENDING_BODY;
62e76326 1118
e39b9382 1119 if (reply->sline.status == HTTP_NO_CONTENT ||
62e76326 1120 reply->sline.status == HTTP_NOT_MODIFIED ||
1121 reply->sline.status < HTTP_OK ||
1122 http->request->method == METHOD_HEAD)
1123 sending = SENDING_HDRSONLY;
1124
edce4d98 1125 /*
1126 * Figure out how much data we are supposed to send.
1127 * If we are sending a body and we don't have a content-length,
1128 * then we must wait for the object to become STORE_OK.
1129 */
0e3be1ea 1130 if (reply->content_length < 0)
62e76326 1131 return 0;
e39b9382 1132
1133 size_t expectedLength = http->out.headers_sz + reply->content_length;
62e76326 1134
e39b9382 1135 if (http->out.size < expectedLength)
62e76326 1136 return 0;
edce4d98 1137 else
62e76326 1138 return 1;
edce4d98 1139}
1140
1141
edce4d98 1142/* A write has completed, what is the next status based on the
1143 * canonical request data?
1144 * 1 something is wrong
1145 * 0 nothing is wrong.
1146 *
1147 */
1148int
59a1efb2 1149clientHttpRequestStatus(int fd, ClientHttpRequest const *http)
edce4d98 1150{
1151#if SIZEOF_SIZE_T == 4
62e76326 1152
edce4d98 1153 if (http->out.size > 0x7FFF0000) {
62e76326 1154 debug(88, 1) ("WARNING: closing FD %d to prevent counter overflow\n",
1155 fd);
1156 debug(88, 1) ("\tclient %s\n",
a2ac85d9 1157 inet_ntoa(http->getConn().getRaw() != NULL ? http->getConn()->peer.sin_addr : no_addr));
62e76326 1158 debug(88, 1) ("\treceived %d bytes\n", (int) http->out.size);
1159 debug(88, 1) ("\tURI %s\n", http->log_uri);
1160 return 1;
edce4d98 1161 }
62e76326 1162
edce4d98 1163#endif
1164#if SIZEOF_OFF_T == 4
1165 if (http->out.offset > 0x7FFF0000) {
62e76326 1166 debug(88, 1) ("WARNING: closing FD %d to prevent counter overflow\n",
1167 fd);
1168 debug(88, 1) ("\tclient %s\n",
a2ac85d9 1169 inet_ntoa(http->getConn().getRaw() != NULL ? http->getConn()->peer.sin_addr : no_addr));
62e76326 1170 debug(88, 1) ("\treceived %d bytes (offset %d)\n", (int) http->out.size,
1171 (int) http->out.offset);
1172 debug(88, 1) ("\tURI %s\n", http->log_uri);
1173 return 1;
edce4d98 1174 }
62e76326 1175
edce4d98 1176#endif
1177 return 0;
1178}
1179
62e76326 1180/* Preconditions:
edce4d98 1181 * *http is a valid structure.
1182 * fd is either -1, or an open fd.
1183 *
1184 * TODO: enumify this
1185 *
1186 * This function is used by any http request sink, to determine the status
1187 * of the object.
1188 */
1189clientStream_status_t
59a1efb2 1190clientReplyStatus(clientStreamNode * aNode, ClientHttpRequest * http)
edce4d98 1191{
0655fa4d 1192 clientReplyContext *context = dynamic_cast<clientReplyContext *>(aNode->data.getRaw());
1193 assert (context);
1194 assert (context->http == http);
1195 return context->replyStatus();
1196}
1197
1198clientStream_status_t
1199clientReplyContext::replyStatus()
1200{
edce4d98 1201 int done;
1202 /* Here because lower nodes don't need it */
62e76326 1203
86a2f789 1204 if (http->storeEntry() == NULL)
62e76326 1205 return STREAM_FAILED; /* yuck, but what can we do? */
1206
86a2f789 1207 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED))
62e76326 1208 /* TODO: Could upstream read errors (result.flags.error) be
1209 * lost, and result in undersize requests being considered
1210 * complete. Should we tcp reset such connections ?
1211 */
1212 return STREAM_FAILED;
1213
0655fa4d 1214 if ((done = checkTransferDone()) != 0 || flags.complete) {
62e76326 1215 debug(88, 5) ("clientReplyStatus: transfer is DONE\n");
1216 /* Ok we're finished, but how? */
1217
1218 if (httpReplyBodySize(http->request->method,
86a2f789 1219 http->storeEntry()->getReply()) < 0) {
62e76326 1220 debug(88, 5) ("clientReplyStatus: closing, content_length < 0\n");
1221 return STREAM_FAILED;
1222 }
1223
1224 if (!done) {
1225 debug(88, 5) ("clientReplyStatus: closing, !done, but read 0 bytes\n");
1226 return STREAM_FAILED;
1227 }
1228
0655fa4d 1229 if (!http->gotEnough()) {
62e76326 1230 debug(88, 5) ("clientReplyStatus: client didn't get all it expected\n");
1231 return STREAM_UNPLANNED_COMPLETE;
1232 }
1233
1234 if (http->request->flags.proxy_keepalive) {
1235 debug(88, 5) ("clientReplyStatus: stream complete and can keepalive\n");
1236 return STREAM_COMPLETE;
1237 }
1238
1239 debug(88, 5) ("clientReplyStatus: stream was not expected to complete!\n");
1240 return STREAM_UNPLANNED_COMPLETE;
edce4d98 1241 }
62e76326 1242
b51aec66 1243 if (http->isReplyBodyTooLarge(http->out.offset - 4096)) {
1244 /* 4096 is a margin for the HTTP headers included in out.offset */
62e76326 1245 debug(88, 5) ("clientReplyStatus: client reply body is too large\n");
1246 return STREAM_FAILED;
0e3be1ea 1247 }
62e76326 1248
edce4d98 1249 return STREAM_NONE;
1250}
1251
62e76326 1252/* Responses with no body will not have a content-type header,
edce4d98 1253 * which breaks the rep_mime_type acl, which
1254 * coincidentally, is the most common acl for reply access lists.
1255 * A better long term fix for this is to allow acl matchs on the various
1256 * status codes, and then supply a default ruleset that puts these
1257 * codes before any user defines access entries. That way the user
1258 * can choose to block these responses where appropriate, but won't get
1259 * mysterious breakages.
1260 */
0655fa4d 1261bool
1262clientReplyContext::alwaysAllowResponse(http_status sline) const
edce4d98 1263{
4ef4b952 1264 bool result;
1265
edce4d98 1266 switch (sline) {
62e76326 1267
edce4d98 1268 case HTTP_CONTINUE:
62e76326 1269
edce4d98 1270 case HTTP_SWITCHING_PROTOCOLS:
62e76326 1271
edce4d98 1272 case HTTP_PROCESSING:
62e76326 1273
edce4d98 1274 case HTTP_NO_CONTENT:
62e76326 1275
edce4d98 1276 case HTTP_NOT_MODIFIED:
4ef4b952 1277 result = true;
62e76326 1278 break;
1279
edce4d98 1280 default:
4ef4b952 1281 result = false;
edce4d98 1282 }
4ef4b952 1283
1284 return result;
edce4d98 1285}
1286
528b2c61 1287void
0655fa4d 1288clientReplyContext::obeyConnectionHeader()
528b2c61 1289{
0655fa4d 1290 HttpHeader *hdr = &holdingReply->header;
924f73bc 1291 hdr->removeConnectionHeaderEntries();
528b2c61 1292}
1293
edce4d98 1294/*
1295 * filters out unwanted entries from original reply header
1296 * adds extra entries if we have more info than origin server
1297 * adds Squid specific entries
1298 */
0655fa4d 1299void
1300clientReplyContext::buildReplyHeader()
edce4d98 1301{
0655fa4d 1302 HttpHeader *hdr = &holdingReply->header;
c8be6d7b 1303 int is_hit = logTypeIsATcpHit(http->logType);
190154cf 1304 HttpRequest *request = http->request;
edce4d98 1305#if DONT_FILTER_THESE
1306 /* but you might want to if you run Squid as an HTTP accelerator */
1307 /* httpHeaderDelById(hdr, HDR_ACCEPT_RANGES); */
1308 httpHeaderDelById(hdr, HDR_ETAG);
1309#endif
62e76326 1310
edce4d98 1311 httpHeaderDelById(hdr, HDR_PROXY_CONNECTION);
1312 /* here: Keep-Alive is a field-name, not a connection directive! */
1313 httpHeaderDelByName(hdr, "Keep-Alive");
1314 /* remove Set-Cookie if a hit */
62e76326 1315
edce4d98 1316 if (is_hit)
62e76326 1317 httpHeaderDelById(hdr, HDR_SET_COOKIE);
1318
0655fa4d 1319 obeyConnectionHeader();
62e76326 1320
1321 // if (request->range)
0655fa4d 1322 // clientBuildRangeHeader(http, holdingReply);
edce4d98 1323 /*
1324 * Add a estimated Age header on cache hits.
1325 */
1326 if (is_hit) {
62e76326 1327 /*
1328 * Remove any existing Age header sent by upstream caches
1329 * (note that the existing header is passed along unmodified
1330 * on cache misses)
1331 */
1332 httpHeaderDelById(hdr, HDR_AGE);
1333 /*
1334 * This adds the calculated object age. Note that the details of the
1335 * age calculation is performed by adjusting the timestamp in
1336 * storeTimestampsSet(), not here.
1337 *
1338 * BROWSER WORKAROUND: IE sometimes hangs when receiving a 0 Age
1339 * header, so don't use it unless there is a age to report. Please
1340 * note that Age is only used to make a conservative estimation of
1341 * the objects age, so a Age: 0 header does not add any useful
1342 * information to the reply in any case.
1343 */
1344
86a2f789 1345 if (NULL == http->storeEntry())
62e76326 1346 (void) 0;
86a2f789 1347 else if (http->storeEntry()->timestamp < 0)
62e76326 1348 (void) 0;
bbe58ab5 1349
1350 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_SPECIAL)) {
1351 httpHeaderDelById(hdr, HDR_DATE);
1352 httpHeaderInsertTime(hdr, HDR_DATE, squid_curtime);
1353 } else if (http->storeEntry()->timestamp < squid_curtime) {
62e76326 1354 httpHeaderPutInt(hdr, HDR_AGE,
86a2f789 1355 squid_curtime - http->storeEntry()->timestamp);
62e76326 1356 /* Signal old objects. NB: rfc 2616 is not clear,
1357 * by implication, on whether we should do this to all
1358 * responses, or only cache hits.
1359 * 14.46 states it ONLY applys for heuristically caclulated
1360 * freshness values, 13.2.4 doesn't specify the same limitation.
1361 * We interpret RFC 2616 under the combination.
1362 */
1363 /* TODO: if maxage or s-maxage is present, don't do this */
1364
86a2f789 1365 if (squid_curtime - http->storeEntry()->timestamp >= 86400) {
62e76326 1366 char tempbuf[512];
1367 snprintf (tempbuf, sizeof(tempbuf), "%s %s %s",
1368 "113", ThisCache,
1369 "This cache hit is still fresh and more than 1 day old");
1370 httpHeaderPutStr(hdr, HDR_WARNING, tempbuf);
1371 }
1372 }
528b2c61 1373
edce4d98 1374 }
62e76326 1375
0bd9aa82 1376 /* Filter unproxyable authentication types */
ddd31ed3 1377 if (http->logType != LOG_TCP_DENIED &&
62e76326 1378 (httpHeaderHas(hdr, HDR_WWW_AUTHENTICATE) || httpHeaderHas(hdr, HDR_PROXY_AUTHENTICATE))) {
1379 HttpHeaderPos pos = HttpHeaderInitPos;
1380 HttpHeaderEntry *e;
1381
1382 while ((e = httpHeaderGetEntry(hdr, &pos))) {
1383 if (e->id == HDR_WWW_AUTHENTICATE || e->id == HDR_PROXY_AUTHENTICATE) {
1384 const char *value = e->value.buf();
1385
1386 if ((strncasecmp(value, "NTLM", 4) == 0 &&
1387 (value[4] == '\0' || value[4] == ' '))
1388 ||
1389 (strncasecmp(value, "Negotiate", 9) == 0 &&
1390 (value[9] == '\0' || value[9] == ' ')))
1391 httpHeaderDelAt(hdr, pos);
1392 }
1393 }
0bd9aa82 1394 }
62e76326 1395
edce4d98 1396 /* Handle authentication headers */
1397 if (request->auth_user_request)
0655fa4d 1398 authenticateFixHeader(holdingReply, request->auth_user_request, request,
62e76326 1399 http->flags.accel, 0);
1400
edce4d98 1401 /* Append X-Cache */
1402 httpHeaderPutStrf(hdr, HDR_X_CACHE, "%s from %s",
62e76326 1403 is_hit ? "HIT" : "MISS", getMyHostname());
1404
edce4d98 1405#if USE_CACHE_DIGESTS
1406 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1407 httpHeaderPutStrf(hdr, HDR_X_CACHE_LOOKUP, "%s from %s:%d",
0655fa4d 1408 lookup_type ? lookup_type : "NONE",
62e76326 1409 getMyHostname(), getMyPort());
1410
edce4d98 1411#endif
62e76326 1412
0655fa4d 1413 if (httpReplyBodySize(request->method, holdingReply) < 0) {
62e76326 1414 debug(88,
1415 3)
1416 ("clientBuildReplyHeader: can't keep-alive, unknown body size\n");
1417 request->flags.proxy_keepalive = 0;
edce4d98 1418 }
62e76326 1419
f5e45ad8 1420 if (fdUsageHigh()&& !request->flags.must_keepalive) {
a1ca9253 1421 debug(88, 3) ("clientBuildReplyHeader: Not many unused FDs, can't keep-alive\n");
1422 request->flags.proxy_keepalive = 0;
1423 }
1424
f5e45ad8 1425 if (!Config.onoff.client_pconns && !request->flags.must_keepalive)
1426 request->flags.proxy_keepalive = 0;
1427
4dea3fdd 1428 /* Append VIA */
c8be6d7b 1429 {
62e76326 1430 LOCAL_ARRAY(char, bbuf, MAX_URL + 32);
1431 String strVia = httpHeaderGetList(hdr, HDR_VIA);
1432 snprintf(bbuf, sizeof(bbuf), "%d.%d %s",
0655fa4d 1433 holdingReply->sline.version.major,
1434 holdingReply->sline.version.minor,
62e76326 1435 ThisCache);
1436 strListAdd(&strVia, bbuf, ',');
1437 httpHeaderDelById(hdr, HDR_VIA);
1438 httpHeaderPutStr(hdr, HDR_VIA, strVia.buf());
1439 strVia.clean();
c8be6d7b 1440 }
edce4d98 1441 /* Signal keep-alive if needed */
1442 httpHeaderPutStr(hdr,
62e76326 1443 http->flags.accel ? HDR_CONNECTION : HDR_PROXY_CONNECTION,
1444 request->flags.proxy_keepalive ? "keep-alive" : "close");
1445
edce4d98 1446#if ADD_X_REQUEST_URI
1447 /*
1448 * Knowing the URI of the request is useful when debugging persistent
1449 * connections in a client; we cannot guarantee the order of http headers,
1450 * but X-Request-URI is likely to be the very last header to ease use from a
1451 * debugger [hdr->entries.count-1].
1452 */
1453 httpHeaderPutStr(hdr, HDR_X_REQUEST_URI,
86a2f789 1454 http->memOjbect()->url ? http->memObject()->url : http->uri);
62e76326 1455
edce4d98 1456#endif
62e76326 1457
8c01ada0 1458 httpHdrMangleList(hdr, request, ROR_REPLY);
edce4d98 1459}
1460
1461
0655fa4d 1462void
1463clientReplyContext::buildReply(const char *buf, size_t size)
edce4d98 1464{
edce4d98 1465 size_t k = headersEnd(buf, size);
62e76326 1466
0655fa4d 1467 if (!k)
1468 return;
1469
1470 holdReply(httpReplyCreate());
1471
1472 if (!httpReplyParse(holdingReply, buf, k)) {
62e76326 1473 /* parsing failure, get rid of the invalid reply */
0655fa4d 1474 httpReplyDestroy(holdingReply);
1475 holdReply (NULL);
62e76326 1476 /* This is wrong. httpReplyDestroy should to the rep
1477 * for us, and we can destroy our own range info
1478 */
1479
0655fa4d 1480 if (http->request->range) {
62e76326 1481 /* this will fail and destroy request->range */
0655fa4d 1482 // clientBuildRangeHeader(http, holdingReply);
62e76326 1483 }
b51aec66 1484
979da574 1485 return;
edce4d98 1486 }
62e76326 1487
0655fa4d 1488 /* enforce 1.0 reply version */
450e0c10 1489 holdingReply->sline.version = HttpVersion(1,0);
0655fa4d 1490
1491 /* do header conversions */
1492 buildReplyHeader();
edce4d98 1493}
1494
e6ccf245 1495void
1496clientReplyContext::identifyStoreObject()
edce4d98 1497{
190154cf 1498 HttpRequest *r = http->request;
62e76326 1499
e6ccf245 1500 if (r->flags.cachable || r->flags.internal) {
62e76326 1501 lookingforstore = 5;
1502 StoreEntry::getPublicByRequest (this, r);
e6ccf245 1503 } else
62e76326 1504 identifyFoundObject (NullStoreEntry::getInstance());
e6ccf245 1505}
1506
1507void
1508clientReplyContext::identifyFoundObject(StoreEntry *newEntry)
1509{
1510 StoreEntry *e = newEntry;
190154cf 1511 HttpRequest *r = http->request;
62e76326 1512
e6ccf245 1513 if (e->isNull()) {
86a2f789 1514 http->storeEntry(NULL);
e6ccf245 1515 } else {
86a2f789 1516 http->storeEntry(e);
e6ccf245 1517 }
62e76326 1518
86a2f789 1519 e = http->storeEntry();
a12a049a 1520 /* Release IP-cache entries on reload */
1521
1522 if (r->flags.nocache) {
1523
1524#if USE_DNSSERVERS
62e76326 1525
62e76326 1526 ipcacheInvalidate(r->host);
1527
a12a049a 1528#else
1529
1530 ipcacheInvalidateNegative(r->host);
1531
1532#endif /* USE_DNSSERVERS */
1533
1534 }
1535
edce4d98 1536#if HTTP_VIOLATIONS
62e76326 1537
a12a049a 1538 else if (r->flags.nocache_hack) {
1539
1540#if USE_DNSSERVERS
1541
62e76326 1542 ipcacheInvalidate(r->host);
1543
a12a049a 1544#else
1545
1546 ipcacheInvalidateNegative(r->host);
1547
1548#endif /* USE_DNSSERVERS */
1549
1550 }
1551
1552#endif /* HTTP_VIOLATIONS */
edce4d98 1553#if USE_CACHE_DIGESTS
62e76326 1554
86a2f789 1555 lookup_type = http->storeEntry() ? "HIT" : "MISS";
62e76326 1556
edce4d98 1557#endif
62e76326 1558
86a2f789 1559 if (NULL == http->storeEntry()) {
62e76326 1560 /* this object isn't in the cache */
1561 debug(85, 3) ("clientProcessRequest2: storeGet() MISS\n");
1562 http->logType = LOG_TCP_MISS;
1563 doGetMoreData();
1564 return;
edce4d98 1565 }
62e76326 1566
edce4d98 1567 if (Config.onoff.offline) {
62e76326 1568 debug(85, 3) ("clientProcessRequest2: offline HIT\n");
1569 http->logType = LOG_TCP_HIT;
1570 doGetMoreData();
1571 return;
edce4d98 1572 }
62e76326 1573
edce4d98 1574 if (http->redirect.status) {
62e76326 1575 /* force this to be a miss */
86a2f789 1576 http->storeEntry(NULL);
62e76326 1577 http->logType = LOG_TCP_MISS;
1578 doGetMoreData();
1579 return;
edce4d98 1580 }
62e76326 1581
edce4d98 1582 if (!storeEntryValidToSend(e)) {
62e76326 1583 debug(85, 3) ("clientProcessRequest2: !storeEntryValidToSend MISS\n");
86a2f789 1584 http->storeEntry(NULL);
62e76326 1585 http->logType = LOG_TCP_MISS;
1586 doGetMoreData();
1587 return;
edce4d98 1588 }
62e76326 1589
edce4d98 1590 if (EBIT_TEST(e->flags, ENTRY_SPECIAL)) {
62e76326 1591 /* Special entries are always hits, no matter what the client says */
1592 debug(85, 3) ("clientProcessRequest2: ENTRY_SPECIAL HIT\n");
1593 http->logType = LOG_TCP_HIT;
1594 doGetMoreData();
1595 return;
edce4d98 1596 }
62e76326 1597
edce4d98 1598 if (r->flags.nocache) {
62e76326 1599 debug(85, 3) ("clientProcessRequest2: no-cache REFRESH MISS\n");
86a2f789 1600 http->storeEntry(NULL);
62e76326 1601 http->logType = LOG_TCP_CLIENT_REFRESH_MISS;
1602 doGetMoreData();
1603 return;
edce4d98 1604 }
62e76326 1605
edce4d98 1606 debug(85, 3) ("clientProcessRequest2: default HIT\n");
e6ccf245 1607 http->logType = LOG_TCP_HIT;
1608 doGetMoreData();
edce4d98 1609}
1610
1611/* Request more data from the store for the client Stream
1612 * This is *the* entry point to this module.
1613 *
1614 * Preconditions:
1615 * This is the head of the list.
1616 * There is at least one more node.
1617 * data context is not null
1618 */
1619void
59a1efb2 1620clientGetMoreData(clientStreamNode * aNode, ClientHttpRequest * http)
edce4d98 1621{
edce4d98 1622 /* Test preconditions */
e6ccf245 1623 assert(aNode != NULL);
1624 assert(cbdataReferenceValid(aNode));
e6ccf245 1625 assert(aNode->node.prev == NULL);
1626 assert(aNode->node.next != NULL);
0655fa4d 1627 clientReplyContext *context = dynamic_cast<clientReplyContext *>(aNode->data.getRaw());
1628 assert (context);
edce4d98 1629 assert(context->http == http);
1630
0655fa4d 1631 clientStreamNode *next = ( clientStreamNode *)aNode->node.next->data;
62e76326 1632
edce4d98 1633 if (!context->ourNode)
62e76326 1634 context->ourNode = aNode;
1635
e6ccf245 1636 /* no cbdatareference, this is only used once, and safely */
edce4d98 1637 if (context->flags.storelogiccomplete) {
62e76326 1638 StoreIOBuffer tempBuffer;
1639 tempBuffer.offset = next->readBuffer.offset + context->headers_sz;
1640 tempBuffer.length = next->readBuffer.length;
1641 tempBuffer.data = next->readBuffer.data;
1642
86a2f789 1643 storeClientCopy(context->sc, http->storeEntry(),
0655fa4d 1644 tempBuffer, clientReplyContext::SendMoreData, context);
62e76326 1645 return;
edce4d98 1646 }
62e76326 1647
edce4d98 1648 if (context->http->request->method == METHOD_PURGE) {
62e76326 1649 context->purgeRequest();
1650 return;
edce4d98 1651 }
62e76326 1652
edce4d98 1653 if (context->http->request->method == METHOD_TRACE) {
62e76326 1654 if (context->http->request->max_forwards == 0) {
0655fa4d 1655 context->traceReply(aNode);
62e76326 1656 return;
1657 }
1658
1659 /* continue forwarding, not finished yet. */
1660 http->logType = LOG_TCP_MISS;
1661
1662 context->doGetMoreData();
edce4d98 1663 } else
62e76326 1664 context->identifyStoreObject();
e6ccf245 1665}
1666
1667void
1668clientReplyContext::doGetMoreData()
1669{
edce4d98 1670 /* We still have to do store logic processing - vary, cache hit etc */
62e76326 1671
86a2f789 1672 if (http->storeEntry() != NULL) {
62e76326 1673 /* someone found the object in the cache for us */
1674 StoreIOBuffer tempBuffer;
86a2f789 1675 storeLockObject(http->storeEntry());
62e76326 1676
86a2f789 1677 if (http->storeEntry()->mem_obj == NULL) {
62e76326 1678 /*
1679 * This if-block exists because we don't want to clobber
1680 * a preexiting mem_obj->method value if the mem_obj
1681 * already exists. For example, when a HEAD request
1682 * is a cache hit for a GET response, we want to keep
1683 * the method as GET.
1684 */
86a2f789 1685 storeCreateMemObject(http->storeEntry(), http->uri,
62e76326 1686 http->log_uri);
86a2f789 1687 http->storeEntry()->mem_obj->method =
62e76326 1688 http->request->method;
1689 }
1690
86a2f789 1691 sc = storeClientListAdd(http->storeEntry(), this);
edce4d98 1692#if DELAY_POOLS
62e76326 1693
1694 sc->setDelayId(DelayId::DelayClient(http));
edce4d98 1695#endif
62e76326 1696
1697 assert(http->logType == LOG_TCP_HIT);
1698 reqofs = 0;
1699 /* guarantee nothing has been sent yet! */
1700 assert(http->out.size == 0);
1701 assert(http->out.offset == 0);
1702 tempBuffer.offset = reqofs;
1703 tempBuffer.length = getNextNode()->readBuffer.length;
1704 tempBuffer.data = getNextNode()->readBuffer.data;
86a2f789 1705 storeClientCopy(sc, http->storeEntry(),
0655fa4d 1706 tempBuffer, CacheHit, this);
edce4d98 1707 } else {
62e76326 1708 /* MISS CASE, http->logType is already set! */
0655fa4d 1709 processMiss();
edce4d98 1710 }
1711}
1712
1713/* the next node has removed itself from the stream. */
1714void
59a1efb2 1715clientReplyDetach(clientStreamNode * node, ClientHttpRequest * http)
edce4d98 1716{
1717 /* detach from the stream */
edce4d98 1718 clientStreamDetach(node, http);
1719}
1720
1721/*
1722 * accepts chunk of a http message in buf, parses prefix, filters headers and
1723 * such, writes processed message to the message recipient
1724 */
1725void
0655fa4d 1726clientReplyContext::SendMoreData(void *data, StoreIOBuffer result)
edce4d98 1727{
e6ccf245 1728 clientReplyContext *context = static_cast<clientReplyContext *>(data);
528b2c61 1729 context->sendMoreData (result);
1730}
1731
1732void
1733clientReplyContext::makeThisHead()
1734{
1735 /* At least, I think thats what this does */
1736 dlinkDelete(&http->active, &ClientActiveRequests);
1737 dlinkAdd(http, &http->active, &ClientActiveRequests);
1738}
1739
1740bool
1741clientReplyContext::errorInStream(StoreIOBuffer const &result, size_t const &sizeToProcess)const
1742{
1743 return /* aborted request */
86a2f789 1744 (http->storeEntry() && EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) ||
62e76326 1745 /* Upstream read error */ (result.flags.error) ||
1746 /* Upstream EOF */ (sizeToProcess == 0);
528b2c61 1747}
1748
1749void
1750clientReplyContext::sendStreamError(StoreIOBuffer const &result)
1751{
1752 /* call clientWriteComplete so the client socket gets closed */
1753 /* We call into the stream, because we don't know that there is a
1754 * client socket!
1755 */
1756 debug(88,5)("clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.\n");
1757 StoreIOBuffer tempBuffer;
1758 flags.complete = 1;
1759 tempBuffer.flags.error = result.flags.error;
1760 clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
62e76326 1761 tempBuffer);
528b2c61 1762}
1763
1764void
1765clientReplyContext::pushStreamData(StoreIOBuffer const &result, char *source)
1766{
1767 StoreIOBuffer tempBuffer;
62e76326 1768
528b2c61 1769 if (result.length == 0) {
62e76326 1770 debug (88,5)("clientReplyContext::pushStreamData: marking request as complete due to 0 length store result\n");
1771 flags.complete = 1;
528b2c61 1772 }
62e76326 1773
43ae1d95 1774 assert(result.offset - headers_sz == next()->readBuffer.offset);
528b2c61 1775 tempBuffer.offset = result.offset - headers_sz;
1776 tempBuffer.length = result.length;
62e76326 1777
43ae1d95 1778 if (tempBuffer.length)
1779 tempBuffer.data = source;
62e76326 1780
528b2c61 1781 clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
62e76326 1782 tempBuffer);
528b2c61 1783}
1784
1785clientStreamNode *
1786clientReplyContext::next() const
1787{
1788 assert ( (clientStreamNode*)http->client_stream.head->next->data == getNextNode());
1789 return getNextNode();
1790}
1791
1792void
0655fa4d 1793clientReplyContext::waitForMoreData ()
528b2c61 1794{
1795 debug(88,5)("clientReplyContext::waitForMoreData: Waiting for more data to parse reply headers in client side.\n");
1796 /* We don't have enough to parse the metadata yet */
1797 /* TODO: the store should give us out of band metadata and
1798 * obsolete this routine
1799 */
1800 /* wait for more to arrive */
528b2c61 1801 startSendProcess();
1802}
1803
1804void
1805clientReplyContext::startSendProcess()
1806{
0655fa4d 1807 debug(88,5)("clientReplyContext::startSendProcess: triggering store read to SendMoreData\n");
528b2c61 1808 assert(reqofs <= HTTP_REQBUF_SZ);
1809 /* TODO: copy into the supplied buffer */
1810 StoreIOBuffer tempBuffer;
1811 tempBuffer.offset = reqofs;
1812 tempBuffer.length = next()->readBuffer.length - reqofs;
1813 tempBuffer.data = next()->readBuffer.data + reqofs;
86a2f789 1814 storeClientCopy(sc, http->storeEntry(),
0655fa4d 1815 tempBuffer, SendMoreData, this);
1816}
1817
1818void
1819clientReplyContext::holdReply(HttpReply *aReply)
1820{
1821 assert (!holdingReply || !aReply);
1822 holdingReply = aReply;
528b2c61 1823}
1824
b51aec66 1825/*
1826 * Calculates the maximum size allowed for an HTTP response
1827 */
1828void
1829clientReplyContext::buildMaxBodySize(HttpReply * reply)
1830{
ef1955a5 1831 acl_size_t *l = Config.ReplyBodySize;
1832 ACLChecklist *ch;
b51aec66 1833
8777d90e 1834 if (http->logType == LOG_TCP_DENIED)
1835 return;
1836
ef1955a5 1837 ch = clientAclChecklistCreate(NULL, http);
8777d90e 1838
ef1955a5 1839 ch->reply = reply;
1840
1841 for (l = Config.ReplyBodySize; l; l = l -> next) {
7684c4b1 1842 if (ch->matchAclListFast(l->aclList)) {
43cb430e 1843 if (l->size != static_cast<size_t>(-1)) {
1844 debug(58, 3) ("clientReplyContext: Setting maxBodySize to %ld\n", (long int) l->size);
ef1955a5 1845 http->maxReplyBodySize(l->size);
43cb430e 1846 }
b51aec66 1847
ef1955a5 1848 break;
1849 }
b51aec66 1850 }
ef1955a5 1851
1852 delete ch;
b51aec66 1853}
1854
4993f571 1855void
1856clientReplyContext::processReplyAccess ()
1857{
1858 HttpReply *rep = holdingReply;
0655fa4d 1859 holdReply(NULL);
b51aec66 1860 buildMaxBodySize(rep);
62e76326 1861
b51aec66 1862 if (http->isReplyBodyTooLarge(rep->content_length)) {
62e76326 1863 ErrorState *err =
1864 clientBuildError(ERR_TOO_BIG, HTTP_FORBIDDEN, NULL,
a2ac85d9 1865 http->getConn().getRaw() != NULL ? &http->getConn()->peer.sin_addr : &no_addr,
62e76326 1866 http->request);
86a2f789 1867 removeClientStoreReference(&sc, http);
0655fa4d 1868 startError(err);
62e76326 1869 httpReplyDestroy(rep);
1870 return;
1871 }
1872
1873 headers_sz = rep->hdr_sz;
1874 ACLChecklist *replyChecklist;
1875 replyChecklist = clientAclChecklistCreate(Config.accessList.reply, http);
1876 replyChecklist->reply = rep;
0655fa4d 1877 holdReply (rep);
1878 replyChecklist->nonBlockingCheck(ProcessReplyAccessResult, this);
4993f571 1879}
1880
1881void
0655fa4d 1882clientReplyContext::ProcessReplyAccessResult (int rv, void *voidMe)
4993f571 1883{
1884 clientReplyContext *me = static_cast<clientReplyContext *>(voidMe);
0655fa4d 1885 me->processReplyAccessResult(rv);
4993f571 1886}
1887
1888void
0655fa4d 1889clientReplyContext::processReplyAccessResult(bool accessAllowed)
4993f571 1890{
62e76326 1891 debug(88, 2) ("The reply for %s %s is %s, because it matched '%s'\n",
1892 RequestMethodStr[http->request->method], http->uri,
1893 accessAllowed ? "ALLOWED" : "DENIED",
1894 AclMatchedName ? AclMatchedName : "NO ACL's");
1895 HttpReply *rep = holdingReply;
0655fa4d 1896 holdReply (NULL);
62e76326 1897
1898 if (!accessAllowed && rep->sline.status != HTTP_FORBIDDEN
0655fa4d 1899 && !alwaysAllowResponse(rep->sline.status)) {
62e76326 1900 /* the if above is slightly broken, but there is no way
1901 * to tell if this is a squid generated error page, or one from
1902 * upstream at this point. */
1903 ErrorState *err;
0185bd6f 1904 err_type page_id;
1905 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName);
1906
1907 if (page_id == ERR_NONE)
1908 page_id = ERR_ACCESS_DENIED;
1909
62e76326 1910 err =
0185bd6f 1911 clientBuildError(page_id, HTTP_FORBIDDEN, NULL,
a2ac85d9 1912 http->getConn().getRaw() != NULL ? &http->getConn()->peer.sin_addr : &no_addr,
62e76326 1913 http->request);
0185bd6f 1914
86a2f789 1915 removeClientStoreReference(&sc, http);
0185bd6f 1916
0655fa4d 1917 startError(err);
0185bd6f 1918
62e76326 1919 httpReplyDestroy(rep);
0185bd6f 1920
c2cf9bea 1921 http->logType = LOG_TCP_DENIED_REPLY;
0185bd6f 1922
62e76326 1923 return;
1924 }
1925
0976f8db 1926 /* Ok, the reply is allowed, */
1927 http->loggingEntry(http->storeEntry());
1928
62e76326 1929 ssize_t body_size = reqofs - rep->hdr_sz;
0976f8db 1930
62e76326 1931 assert(body_size >= 0);
0976f8db 1932
62e76326 1933 debug(88,3)
0655fa4d 1934 ("clientReplyContext::sendMoreData: Appending %d bytes after %d bytes of headers\n",
62e76326 1935 (int) body_size, rep->hdr_sz);
0976f8db 1936
43ae1d95 1937#if ESI
62e76326 1938
43ae1d95 1939 if (http->flags.accel && rep->sline.status != HTTP_FORBIDDEN &&
0655fa4d 1940 !alwaysAllowResponse(rep->sline.status) &&
43ae1d95 1941 esiEnableProcessing(rep)) {
1942 debug(88, 2) ("Enabling ESI processing for %s\n", http->uri);
1943 clientStreamInsertHead(&http->client_stream, esiStreamRead,
1944 esiProcessStream, esiStreamDetach, esiStreamStatus, NULL);
1945 }
1946
1947#endif
62e76326 1948 if (http->request->method == METHOD_HEAD) {
1949 /* do not forward body for HEAD replies */
1950 body_size = 0;
1951 http->flags.done_copying = 1;
1952 flags.complete = 1;
1953 }
1954
1955 assert (!flags.headersSent);
1956 flags.headersSent = true;
1957
1958 StoreIOBuffer tempBuffer;
1959 char *buf = next()->readBuffer.data;
1960 char *body_buf = buf + rep->hdr_sz;
1961
49ea0125 1962 //Server side may disable ranges under some circumstances.
1963
1964 if ((!http->request->range))
1965 next()->readBuffer.offset = 0;
1966
62e76326 1967 if (next()->readBuffer.offset != 0) {
1968 if (next()->readBuffer.offset > body_size) {
1969 /* Can't use any of the body we recieved. send nothing */
1970 tempBuffer.length = 0;
1971 tempBuffer.data = NULL;
1972 } else {
1973 tempBuffer.length = body_size - next()->readBuffer.offset;
1974 tempBuffer.data = body_buf + next()->readBuffer.offset;
1975 }
1976 } else {
1977 tempBuffer.length = body_size;
1978 tempBuffer.data = body_buf;
1979 }
1980
0655fa4d 1981 /* TODO??: move the data in the buffer back by the request header size */
62e76326 1982 clientStreamCallback((clientStreamNode *)http->client_stream.head->data,
1983 http, rep, tempBuffer);
1984
1985 return;
4993f571 1986}
1987
528b2c61 1988void
1989clientReplyContext::sendMoreData (StoreIOBuffer result)
1990{
50c09fc4 1991 if (deleting)
1992 return;
1993
86a2f789 1994 StoreEntry *entry = http->storeEntry();
50c09fc4 1995
a2ac85d9 1996 ConnStateData::Pointer conn = http->getConn();
50c09fc4 1997
a2ac85d9 1998 int fd = conn.getRaw() != NULL ? conn->fd : -1;
50c09fc4 1999
528b2c61 2000 char *buf = next()->readBuffer.data;
50c09fc4 2001
c8be6d7b 2002 char *body_buf = buf;
edce4d98 2003
62e76326 2004 /* This is always valid until we get the headers as metadata from
528b2c61 2005 * storeClientCopy.
2006 * Then it becomes reqofs == next->readBuffer.offset()
af29fa86 2007 */
528b2c61 2008 assert(reqofs == 0 || flags.storelogiccomplete);
af29fa86 2009
528b2c61 2010 if (flags.headersSent && buf != result.data) {
62e76326 2011 /* we've got to copy some data */
2012 assert(result.length <= next()->readBuffer.length);
2013 xmemcpy(buf, result.data, result.length);
2014 body_buf = buf;
528b2c61 2015 } else if (!flags.headersSent &&
62e76326 2016 buf + reqofs !=result.data) {
2017 /* we've got to copy some data */
2018 assert(result.length + reqofs <= next()->readBuffer.length);
2019 xmemcpy(buf + reqofs, result.data, result.length);
2020 body_buf = buf;
edce4d98 2021 }
62e76326 2022
edce4d98 2023 /* We've got the final data to start pushing... */
528b2c61 2024 flags.storelogiccomplete = 1;
edce4d98 2025
4993f571 2026 reqofs += result.length;
2027
2028 assert(reqofs <= HTTP_REQBUF_SZ || flags.headersSent);
62e76326 2029
edce4d98 2030 assert(http->request != NULL);
62e76326 2031
edce4d98 2032 /* ESI TODO: remove this assert once everything is stable */
2033 assert(http->client_stream.head->data
62e76326 2034 && cbdataReferenceValid(http->client_stream.head->data));
528b2c61 2035
2036 makeThisHead();
62e76326 2037
0655fa4d 2038 debug(88, 5) ("clientReplyContext::sendMoreData: %s, %d bytes (%u new bytes)\n",
62e76326 2039 http->uri, (int) reqofs, (unsigned int)result.length);
2040
0655fa4d 2041 debug(88, 5) ("clientReplyContext::sendMoreData: FD %d '%s', out.offset=%ld \n",
62e76326 2042 fd, storeUrl(entry), (long int) http->out.offset);
528b2c61 2043
edce4d98 2044 /* update size of the request */
4993f571 2045 reqsize = reqofs;
62e76326 2046
e429f975 2047 if (http->request->flags.resetTCP()) {
62e76326 2048 /* yuck. FIXME: move to client_side.c */
2049
2050 if (fd != -1)
2051 comm_reset_close(fd);
2052
2053 return;
528b2c61 2054 }
62e76326 2055
4993f571 2056 if (errorInStream(result, reqofs)) {
62e76326 2057 sendStreamError(result);
2058 return;
edce4d98 2059 }
528b2c61 2060
2061 if (flags.headersSent) {
62e76326 2062 pushStreamData (result, buf);
2063 return;
edce4d98 2064 }
62e76326 2065
0655fa4d 2066 buildReply(buf, reqofs);
4993f571 2067 ssize_t body_size = reqofs;
62e76326 2068
0655fa4d 2069 if (holdingReply) {
21b92762 2070
2071 /* handle headers */
2072
2073 if (Config.onoff.log_mime_hdrs) {
2074 size_t k;
2075
2076 if ((k = headersEnd(buf, reqofs))) {
2077 safe_free(http->al.headers.reply);
2078 http->al.headers.reply = (char *)xcalloc(k + 1, 1);
2079 xstrncpy(http->al.headers.reply, buf, k);
2080 }
2081 }
2082
62e76326 2083 holdingBuffer = result;
2084 processReplyAccess ();
2085 return;
43ae1d95 2086
4993f571 2087 } else if (reqofs < HTTP_REQBUF_SZ && entry->store_status == STORE_PENDING) {
0655fa4d 2088 waitForMoreData();
62e76326 2089 return;
528b2c61 2090 } else if (http->request->method == METHOD_HEAD) {
62e76326 2091 /*
2092 * If we are here, then store_status == STORE_OK and it
2093 * seems we have a HEAD repsponse which is missing the
2094 * empty end-of-headers line (home.mira.net, phttpd/0.99.72
0655fa4d 2095 * does this). Because buildReply() fails we just
62e76326 2096 * call this reply a body, set the done_copying flag and
2097 * continue...
2098 */
2099 /* RBC: Note that this is seriously broken, as we *need* the
2100 * metadata to allow further client modules to work. As such
2101 * webservers are seriously broken, this is probably not
2102 * going to get fixed.. perhapos we should remove it?
2103 */
2104 debug (88,0)("Broken head response - probably phttpd/0.99.72\n");
2105 http->flags.done_copying = 1;
2106 flags.complete = 1;
2107 /*
2108 * And as this is a malformed HTTP reply we cannot keep
2109 * the connection persistent
2110 */
2111 http->request->flags.proxy_keepalive = 0;
2112
62e76326 2113 assert(body_buf && body_size);
0655fa4d 2114 StoreIOBuffer tempBuffer (body_size, 0 ,body_buf);
62e76326 2115 clientStreamCallback((clientStreamNode *)http->client_stream.head->data,
2116 http, NULL, tempBuffer);
528b2c61 2117 } else {
62e76326 2118 debug (88,0)("clientReplyContext::sendMoreData: Unable to parse reply headers within a single HTTP_REQBUF_SZ length buffer\n");
2119 StoreIOBuffer tempBuffer;
2120 tempBuffer.flags.error = 1;
0655fa4d 2121 /* XXX FIXME: make an html error page here */
62e76326 2122 sendStreamError(tempBuffer);
2123 return;
edce4d98 2124 }
62e76326 2125
528b2c61 2126 fatal ("clientReplyContext::sendMoreData: Unreachable code reached \n");
edce4d98 2127}
2128
62e76326 2129
edce4d98 2130
2131/* Using this breaks the client layering just a little!
2132 */
0655fa4d 2133void
2134clientReplyContext::createStoreEntry(method_t m, request_flags flags)
edce4d98 2135{
0655fa4d 2136 assert(http != NULL);
edce4d98 2137 /*
2138 * For erroneous requests, we might not have a h->request,
2139 * so make a fake one.
2140 */
62e76326 2141
0655fa4d 2142 if (http->request == NULL)
2143 http->request = requestLink(requestCreate(m, PROTO_NONE, null_string));
62e76326 2144
0655fa4d 2145 StoreEntry *e = storeCreateEntry(http->uri, http->log_uri, flags, m);
62e76326 2146
0655fa4d 2147 sc = storeClientListAdd(e, this);
62e76326 2148
edce4d98 2149#if DELAY_POOLS
62e76326 2150
0655fa4d 2151 sc->setDelayId(DelayId::DelayClient(http));
62e76326 2152
edce4d98 2153#endif
62e76326 2154
0655fa4d 2155 reqofs = 0;
62e76326 2156
0655fa4d 2157 reqsize = 0;
62e76326 2158
edce4d98 2159 /* I don't think this is actually needed! -- adrian */
0655fa4d 2160 /* http->reqbuf = http->norm_reqbuf; */
2161 // assert(http->reqbuf == http->norm_reqbuf);
edce4d98 2162 /* The next line is illegal because we don't know if the client stream
2163 * buffers have been set up
2164 */
0655fa4d 2165 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2166 // SendMoreData, this);
edce4d98 2167 /* So, we mark the store logic as complete */
0655fa4d 2168 this->flags.storelogiccomplete = 1;
62e76326 2169
edce4d98 2170 /* and get the caller to request a read, from whereever they are */
62e76326 2171 /* NOTE: after ANY data flows down the pipe, even one step,
edce4d98 2172 * this function CAN NOT be used to manage errors
2173 */
86a2f789 2174 http->storeEntry(e);
edce4d98 2175}
2176
2177ErrorState *
2178clientBuildError(err_type page_id, http_status status, char const *url,
62e76326 2179
ddfcbc22 2180 struct IN_ADDR * src_addr, HttpRequest * request)
edce4d98 2181{
2182 ErrorState *err = errorCon(page_id, status);
2183 err->src_addr = *src_addr;
62e76326 2184
edce4d98 2185 if (url)
62e76326 2186 err->url = xstrdup(url);
2187
edce4d98 2188 if (request)
62e76326 2189 err->request = requestLink(request);
2190
edce4d98 2191 return err;
2192}