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