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