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