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