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