]> git.ipfire.org Git - thirdparty/squid.git/blob - src/client_side_reply.cc
SourceFormat Enforcement
[thirdparty/squid.git] / src / client_side_reply.cc
1 /*
2 * $Id$
3 *
4 * DEBUG: section 88 Client-side Reply Routines
5 * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c)
6 *
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
9 *
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
32 *
33 */
34 #include "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 void
311 clientReplyContext::sendClientUpstreamResponse()
312 {
313 StoreIOBuffer tempresult;
314 removeStoreReference(&old_sc, &old_entry);
315 /* here the data to send is the data we just received */
316 tempBuffer.offset = 0;
317 old_reqsize = 0;
318 /* sendMoreData tracks the offset as well.
319 * Force it back to zero */
320 reqofs = 0;
321 assert(!EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED));
322 /* TODO: provide sendMoreData with the ready parsed reply */
323 tempresult.length = reqsize;
324 tempresult.data = tempbuf;
325 sendMoreData(tempresult);
326 }
327
328 void
329 clientReplyContext::HandleIMSReply(void *data, StoreIOBuffer result)
330 {
331 clientReplyContext *context = (clientReplyContext *)data;
332 context->handleIMSReply(result);
333 }
334
335 void
336 clientReplyContext::sendClientOldEntry()
337 {
338 /* Get the old request back */
339 restoreState();
340 /* here the data to send is in the next nodes buffers already */
341 assert(!EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED));
342 /* sendMoreData tracks the offset as well.
343 * Force it back to zero */
344 reqofs = 0;
345 StoreIOBuffer tempresult (reqsize, reqofs, next()->readBuffer.data);
346 sendMoreData(tempresult);
347 }
348
349 /* This is the workhorse of the HandleIMSReply callback.
350 *
351 * It is called when we've got data back from the origin following our
352 * IMS request to revalidate a stale entry.
353 */
354 void
355 clientReplyContext::handleIMSReply(StoreIOBuffer result)
356 {
357 if (deleting)
358 return;
359
360 debugs(88, 3, "handleIMSReply: " << http->storeEntry()->url() << ", " << (long unsigned) result.length << " bytes" );
361
362 if (http->storeEntry() == NULL)
363 return;
364
365 if (result.flags.error && !EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED))
366 return;
367
368 /* update size of the request */
369 reqsize = result.length + reqofs;
370
371 const http_status status = http->storeEntry()->getReply()->sline.status;
372
373 // request to origin was aborted
374 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) {
375 debugs(88, 3, "handleIMSReply: request to origin aborted '" << http->storeEntry()->url() << "', sending old entry to client" );
376 http->logType = LOG_TCP_REFRESH_FAIL_OLD;
377 sendClientOldEntry();
378 }
379
380 HttpReply *old_rep = (HttpReply *) old_entry->getReply();
381
382 // origin replied 304
383 if (status == HTTP_NOT_MODIFIED) {
384 http->logType = LOG_TCP_REFRESH_UNMODIFIED;
385 http->request->flags.stale_if_hit = 0; // old_entry is no longer stale
386
387 // update headers on existing entry
388 old_rep->updateOnNotModified(http->storeEntry()->getReply());
389 old_entry->timestampsSet();
390
391 // if client sent IMS
392
393 if (http->request->flags.ims && !old_entry->modifiedSince(http->request)) {
394 // forward the 304 from origin
395 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and forwarding 304 to client");
396 sendClientUpstreamResponse();
397 } else {
398 // send existing entry, it's still valid
399 debugs(88, 3, "handleIMSReply: origin replied 304, revalidating existing entry and sending " <<
400 old_rep->sline.status << " to client");
401 sendClientOldEntry();
402 }
403 }
404
405 // origin replied with a non-error code
406 else if (status > HTTP_STATUS_NONE && status < HTTP_INTERNAL_SERVER_ERROR) {
407 // forward response from origin
408 http->logType = LOG_TCP_REFRESH_MODIFIED;
409 debugs(88, 3, "handleIMSReply: origin replied " << status << ", replacing existing entry and forwarding to client");
410 sendClientUpstreamResponse();
411 }
412
413 // origin replied with an error
414 else if (http->request->flags.fail_on_validation_err) {
415 http->logType = LOG_TCP_REFRESH_FAIL_ERR;
416 debugs(88, 3, "handleIMSReply: origin replied with error " << status <<
417 ", forwarding to client due to fail_on_validation_err");
418 sendClientUpstreamResponse();
419 } else {
420 // ignore and let client have old entry
421 http->logType = LOG_TCP_REFRESH_FAIL_OLD;
422 debugs(88, 3, "handleIMSReply: origin replied with error " <<
423 status << ", sending old entry (" << old_rep->sline.status << ") to client");
424 sendClientOldEntry();
425 }
426 }
427
428 extern "C" CSR clientGetMoreData;
429 extern "C" CSD clientReplyDetach;
430
431 /**
432 * clientReplyContext::cacheHit Should only be called until the HTTP reply headers
433 * have been parsed. Normally this should be a single call, but
434 * it might take more than one. As soon as we have the headers,
435 * we hand off to clientSendMoreData, processExpired, or
436 * processMiss.
437 */
438 void
439 clientReplyContext::CacheHit(void *data, StoreIOBuffer result)
440 {
441 clientReplyContext *context = (clientReplyContext *)data;
442 context->cacheHit(result);
443 }
444
445 /**
446 * Process a possible cache HIT.
447 */
448 void
449 clientReplyContext::cacheHit(StoreIOBuffer result)
450 {
451 /** Ignore if the HIT object is being deleted. */
452 if (deleting)
453 return;
454
455 StoreEntry *e = http->storeEntry();
456
457 HttpRequest *r = http->request;
458
459 debugs(88, 3, "clientCacheHit: " << http->uri << ", " << result.length << " bytes");
460
461 if (http->storeEntry() == NULL) {
462 debugs(88, 3, "clientCacheHit: request aborted");
463 return;
464 } else if (result.flags.error) {
465 /* swap in failure */
466 debugs(88, 3, "clientCacheHit: swapin failure for " << http->uri);
467 http->logType = LOG_TCP_SWAPFAIL_MISS;
468 removeClientStoreReference(&sc, http);
469 processMiss();
470 return;
471 }
472
473 if (result.length == 0) {
474 /* the store couldn't get enough data from the file for us to id the
475 * object
476 */
477 /* treat as a miss */
478 http->logType = LOG_TCP_MISS;
479 processMiss();
480 return;
481 }
482
483 assert(!EBIT_TEST(e->flags, ENTRY_ABORTED));
484 /* update size of the request */
485 reqsize = result.length + reqofs;
486
487 /*
488 * Got the headers, now grok them
489 */
490 assert(http->logType == LOG_TCP_HIT);
491
492 if (strcmp(e->mem_obj->url, urlCanonical(r)) != 0) {
493 debugs(33, DBG_IMPORTANT, "clientProcessHit: URL mismatch, '" << e->mem_obj->url << "' != '" << urlCanonical(r) << "'");
494 processMiss();
495 return;
496 }
497
498 switch (varyEvaluateMatch(e, r)) {
499
500 case VARY_NONE:
501 /* No variance detected. Continue as normal */
502 break;
503
504 case VARY_MATCH:
505 /* This is the correct entity for this request. Continue */
506 debugs(88, 2, "clientProcessHit: Vary MATCH!");
507 break;
508
509 case VARY_OTHER:
510 /* This is not the correct entity for this request. We need
511 * to requery the cache.
512 */
513 removeClientStoreReference(&sc, http);
514 e = NULL;
515 /* Note: varyEvalyateMatch updates the request with vary information
516 * so we only get here once. (it also takes care of cancelling loops)
517 */
518 debugs(88, 2, "clientProcessHit: Vary detected!");
519 clientGetMoreData(ourNode, http);
520 return;
521
522 case VARY_CANCEL:
523 /* varyEvaluateMatch found a object loop. Process as miss */
524 debugs(88, DBG_IMPORTANT, "clientProcessHit: Vary object loop!");
525 processMiss();
526 return;
527 }
528
529 if (r->method == METHOD_PURGE) {
530 removeClientStoreReference(&sc, http);
531 e = NULL;
532 purgeRequest();
533 return;
534 }
535
536 if (e->checkNegativeHit()
537 #if USE_HTTP_VIOLATIONS
538 && !r->flags.nocache_hack
539 #endif
540 ) {
541 http->logType = LOG_TCP_NEGATIVE_HIT;
542 sendMoreData(result);
543 } else if (!http->flags.internal && refreshCheckHTTP(e, r)) {
544 debugs(88, 5, "clientCacheHit: in refreshCheck() block");
545 /*
546 * We hold a stale copy; it needs to be validated
547 */
548 /*
549 * The 'need_validation' flag is used to prevent forwarding
550 * loops between siblings. If our copy of the object is stale,
551 * then we should probably only use parents for the validation
552 * request. Otherwise two siblings could generate a loop if
553 * both have a stale version of the object.
554 */
555 r->flags.need_validation = 1;
556
557 if (e->lastmod < 0) {
558 /*
559 * Previous reply didn't have a Last-Modified header,
560 * we cannot revalidate it.
561 */
562 http->logType = LOG_TCP_MISS;
563 processMiss();
564 } else if (r->flags.nocache) {
565 /*
566 * This did not match a refresh pattern that overrides no-cache
567 * we should honour the client no-cache header.
568 */
569 http->logType = LOG_TCP_CLIENT_REFRESH_MISS;
570 processMiss();
571 } else if (r->protocol == AnyP::PROTO_HTTP) {
572 /*
573 * Object needs to be revalidated
574 * XXX This could apply to FTP as well, if Last-Modified is known.
575 */
576 processExpired();
577 } else {
578 /*
579 * We don't know how to re-validate other protocols. Handle
580 * them as if the object has expired.
581 */
582 http->logType = LOG_TCP_MISS;
583 processMiss();
584 }
585 } else if (r->conditional())
586 processConditional(result);
587 else {
588 /*
589 * plain ol' cache hit
590 */
591
592 #if USE_DELAY_POOLS
593 if (e->store_status != STORE_OK)
594 http->logType = LOG_TCP_MISS;
595 else
596 #endif
597 if (e->mem_status == IN_MEMORY)
598 http->logType = LOG_TCP_MEM_HIT;
599 else if (Config.onoff.offline)
600 http->logType = LOG_TCP_OFFLINE_HIT;
601
602 sendMoreData(result);
603 }
604 }
605
606 /**
607 * Prepare to fetch the object as it's a cache miss of some kind.
608 */
609 void
610 clientReplyContext::processMiss()
611 {
612 char *url = http->uri;
613 HttpRequest *r = http->request;
614 ErrorState *err = NULL;
615 debugs(88, 4, "clientProcessMiss: '" << RequestMethodStr(r->method) << " " << url << "'");
616
617 /**
618 * We might have a left-over StoreEntry from a failed cache hit
619 * or IMS request.
620 */
621 if (http->storeEntry()) {
622 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_SPECIAL)) {
623 debugs(88, DBG_CRITICAL, "clientProcessMiss: miss on a special object (" << url << ").");
624 debugs(88, DBG_CRITICAL, "\tlog_type = " << Format::log_tags[http->logType]);
625 http->storeEntry()->dump(1);
626 }
627
628 removeClientStoreReference(&sc, http);
629 }
630
631 /** Check if its a PURGE request to be actioned. */
632 if (r->method == METHOD_PURGE) {
633 purgeRequest();
634 return;
635 }
636
637 /** Check if its an 'OTHER' request. Purge all cached entries if so and continue. */
638 if (r->method == METHOD_OTHER) {
639 purgeAllCached();
640 }
641
642 /** Check if 'only-if-cached' flag is set. Action if so. */
643 if (http->onlyIfCached()) {
644 processOnlyIfCachedMiss();
645 return;
646 }
647
648 /// Deny loops for accelerator and interceptor. TODO: deny in all modes?
649 if (r->flags.loopdetect &&
650 (http->flags.accel || http->flags.intercepted)) {
651 http->al->http.code = HTTP_FORBIDDEN;
652 err = clientBuildError(ERR_ACCESS_DENIED, HTTP_FORBIDDEN, NULL, http->getConn()->clientConnection->remote, http->request);
653 createStoreEntry(r->method, request_flags());
654 errorAppendEntry(http->storeEntry(), err);
655 triggerInitialStoreRead();
656 return;
657 } else {
658 assert(http->out.offset == 0);
659 createStoreEntry(r->method, r->flags);
660 triggerInitialStoreRead();
661
662 if (http->redirect.status) {
663 HttpReply *rep = new HttpReply;
664 http->logType = LOG_TCP_REDIRECT;
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::Start(conn, http->storeEntry(), r, http->al);
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 /* A write has completed, what is the next status based on the
1109 * canonical request data?
1110 * 1 something is wrong
1111 * 0 nothing is wrong.
1112 *
1113 */
1114 int
1115 clientHttpRequestStatus(int fd, ClientHttpRequest const *http)
1116 {
1117 #if SIZEOF_INT64_T == 4
1118 if (http->out.size > 0x7FFF0000) {
1119 debugs(88, DBG_IMPORTANT, "WARNING: closing FD " << fd << " to prevent out.size counter overflow");
1120 debugs(88, DBG_IMPORTANT, "\tclient " << http->getConn()->peer);
1121 debugs(88, DBG_IMPORTANT, "\treceived " << http->out.size << " bytes");
1122 debugs(88, DBG_IMPORTANT, "\tURI " << http->log_uri);
1123 return 1;
1124 }
1125
1126 if (http->out.offset > 0x7FFF0000) {
1127 debugs(88, DBG_IMPORTANT, "WARNING: closing FD " << fd < " to prevent out.offset counter overflow");
1128 debugs(88, DBG_IMPORTANT, "\tclient " << http->getConn()->peer);
1129 debugs(88, DBG_IMPORTANT, "\treceived " << http->out.size << " bytes, offset " << http->out.offset);
1130 debugs(88, DBG_IMPORTANT, "\tURI " << http->log_uri);
1131 return 1;
1132 }
1133
1134 #endif
1135 return 0;
1136 }
1137
1138 /* Preconditions:
1139 * *http is a valid structure.
1140 * fd is either -1, or an open fd.
1141 *
1142 * TODO: enumify this
1143 *
1144 * This function is used by any http request sink, to determine the status
1145 * of the object.
1146 */
1147 clientStream_status_t
1148 clientReplyStatus(clientStreamNode * aNode, ClientHttpRequest * http)
1149 {
1150 clientReplyContext *context = dynamic_cast<clientReplyContext *>(aNode->data.getRaw());
1151 assert (context);
1152 assert (context->http == http);
1153 return context->replyStatus();
1154 }
1155
1156 clientStream_status_t
1157 clientReplyContext::replyStatus()
1158 {
1159 int done;
1160 /* Here because lower nodes don't need it */
1161
1162 if (http->storeEntry() == NULL) {
1163 debugs(88, 5, "clientReplyStatus: no storeEntry");
1164 return STREAM_FAILED; /* yuck, but what can we do? */
1165 }
1166
1167 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) {
1168 /* TODO: Could upstream read errors (result.flags.error) be
1169 * lost, and result in undersize requests being considered
1170 * complete. Should we tcp reset such connections ?
1171 */
1172 debugs(88, 5, "clientReplyStatus: aborted storeEntry");
1173 return STREAM_FAILED;
1174 }
1175
1176 if ((done = checkTransferDone()) != 0 || flags.complete) {
1177 debugs(88, 5, "clientReplyStatus: transfer is DONE");
1178 /* Ok we're finished, but how? */
1179
1180 const int64_t expectedBodySize =
1181 http->storeEntry()->getReply()->bodySize(http->request->method);
1182 if (!http->request->flags.proxy_keepalive && expectedBodySize < 0) {
1183 debugs(88, 5, "clientReplyStatus: closing, content_length < 0");
1184 return STREAM_FAILED;
1185 }
1186
1187 if (!done) {
1188 debugs(88, 5, "clientReplyStatus: closing, !done, but read 0 bytes");
1189 return STREAM_FAILED;
1190 }
1191
1192 if (expectedBodySize >= 0 && !http->gotEnough()) {
1193 debugs(88, 5, "clientReplyStatus: client didn't get all it expected");
1194 return STREAM_UNPLANNED_COMPLETE;
1195 }
1196
1197 if (http->request->flags.proxy_keepalive) {
1198 debugs(88, 5, "clientReplyStatus: stream complete and can keepalive");
1199 return STREAM_COMPLETE;
1200 }
1201
1202 debugs(88, 5, "clientReplyStatus: stream was not expected to complete!");
1203 return STREAM_UNPLANNED_COMPLETE;
1204 }
1205
1206 // XXX: Should this be checked earlier? We could return above w/o checking.
1207 if (reply->receivedBodyTooLarge(*http->request, http->out.offset - 4096)) {
1208 /* 4096 is a margin for the HTTP headers included in out.offset */
1209 debugs(88, 5, "clientReplyStatus: client reply body is too large");
1210 return STREAM_FAILED;
1211 }
1212
1213 return STREAM_NONE;
1214 }
1215
1216 /* Responses with no body will not have a content-type header,
1217 * which breaks the rep_mime_type acl, which
1218 * coincidentally, is the most common acl for reply access lists.
1219 * A better long term fix for this is to allow acl matchs on the various
1220 * status codes, and then supply a default ruleset that puts these
1221 * codes before any user defines access entries. That way the user
1222 * can choose to block these responses where appropriate, but won't get
1223 * mysterious breakages.
1224 */
1225 bool
1226 clientReplyContext::alwaysAllowResponse(http_status sline) const
1227 {
1228 bool result;
1229
1230 switch (sline) {
1231
1232 case HTTP_CONTINUE:
1233
1234 case HTTP_SWITCHING_PROTOCOLS:
1235
1236 case HTTP_PROCESSING:
1237
1238 case HTTP_NO_CONTENT:
1239
1240 case HTTP_NOT_MODIFIED:
1241 result = true;
1242 break;
1243
1244 default:
1245 result = false;
1246 }
1247
1248 return result;
1249 }
1250
1251 /**
1252 * Generate the reply headers sent to client.
1253 *
1254 * Filters out unwanted entries and hop-by-hop from original reply header
1255 * then adds extra entries if we have more info than origin server
1256 * then adds Squid specific entries
1257 */
1258 void
1259 clientReplyContext::buildReplyHeader()
1260 {
1261 HttpHeader *hdr = &reply->header;
1262 int is_hit = logTypeIsATcpHit(http->logType);
1263 HttpRequest *request = http->request;
1264 #if DONT_FILTER_THESE
1265 /* but you might want to if you run Squid as an HTTP accelerator */
1266 /* hdr->delById(HDR_ACCEPT_RANGES); */
1267 hdr->delById(HDR_ETAG);
1268 #endif
1269
1270 if (is_hit)
1271 hdr->delById(HDR_SET_COOKIE);
1272 // TODO: RFC 2965 : Must honour Cache-Control: no-cache="set-cookie2" and remove header.
1273
1274 // if there is not configured a peer proxy with login=PASS or login=PASSTHRU option enabled
1275 // remove the Proxy-Authenticate header
1276 if ( !request->peer_login || (strcmp(request->peer_login,"PASS") != 0 && strcmp(request->peer_login,"PASSTHRU") != 0))
1277 reply->header.delById(HDR_PROXY_AUTHENTICATE);
1278
1279 reply->header.removeHopByHopEntries();
1280
1281 // if (request->range)
1282 // clientBuildRangeHeader(http, reply);
1283
1284 /*
1285 * Add a estimated Age header on cache hits.
1286 */
1287 if (is_hit) {
1288 /*
1289 * Remove any existing Age header sent by upstream caches
1290 * (note that the existing header is passed along unmodified
1291 * on cache misses)
1292 */
1293 hdr->delById(HDR_AGE);
1294 /*
1295 * This adds the calculated object age. Note that the details of the
1296 * age calculation is performed by adjusting the timestamp in
1297 * StoreEntry::timestampsSet(), not here.
1298 */
1299 #if DEAD_CODE
1300 // XXX: realy useless? or is there a bug now that this is detatched from the below if-sequence ?
1301 // looks like this pre-if was supposed to be the browser workaround...
1302 if (NULL == http->storeEntry())
1303 (void) 0;
1304 else if (http->storeEntry()->timestamp < 0)
1305 (void) 0;
1306 #endif
1307
1308 if (EBIT_TEST(http->storeEntry()->flags, ENTRY_SPECIAL)) {
1309 hdr->delById(HDR_DATE);
1310 hdr->insertTime(HDR_DATE, squid_curtime);
1311 } else if (http->getConn() && http->getConn()->port->actAsOrigin) {
1312 // Swap the Date: header to current time if we are simulating an origin
1313 HttpHeaderEntry *h = hdr->findEntry(HDR_DATE);
1314 if (h)
1315 hdr->putExt("X-Origin-Date", h->value.termedBuf());
1316 hdr->delById(HDR_DATE);
1317 hdr->insertTime(HDR_DATE, squid_curtime);
1318 h = hdr->findEntry(HDR_EXPIRES);
1319 if (h && http->storeEntry()->expires >= 0) {
1320 hdr->putExt("X-Origin-Expires", h->value.termedBuf());
1321 hdr->delById(HDR_EXPIRES);
1322 hdr->insertTime(HDR_EXPIRES, squid_curtime + http->storeEntry()->expires - http->storeEntry()->timestamp);
1323 }
1324 if (http->storeEntry()->timestamp <= squid_curtime) {
1325 // put X-Cache-Age: instead of Age:
1326 char age[64];
1327 snprintf(age, sizeof(age), "%ld", (long int) squid_curtime - http->storeEntry()->timestamp);
1328 hdr->putExt("X-Cache-Age", age);
1329 }
1330 } else if (http->storeEntry()->timestamp <= squid_curtime) {
1331 hdr->putInt(HDR_AGE,
1332 squid_curtime - http->storeEntry()->timestamp);
1333 /* Signal old objects. NB: rfc 2616 is not clear,
1334 * by implication, on whether we should do this to all
1335 * responses, or only cache hits.
1336 * 14.46 states it ONLY applys for heuristically caclulated
1337 * freshness values, 13.2.4 doesn't specify the same limitation.
1338 * We interpret RFC 2616 under the combination.
1339 */
1340 /* TODO: if maxage or s-maxage is present, don't do this */
1341
1342 if (squid_curtime - http->storeEntry()->timestamp >= 86400) {
1343 char tbuf[512];
1344 snprintf (tbuf, sizeof(tbuf), "%s %s %s",
1345 "113", ThisCache,
1346 "This cache hit is still fresh and more than 1 day old");
1347 hdr->putStr(HDR_WARNING, tbuf);
1348 }
1349 }
1350 }
1351
1352 /* RFC 2616: Section 14.18
1353 *
1354 * Add a Date: header if missing.
1355 * We have access to a clock therefore are required to amend any shortcoming in servers.
1356 *
1357 * NP: done after Age: to prevent ENTRY_SPECIAL double-handling this header.
1358 */
1359 if ( !hdr->has(HDR_DATE) ) {
1360 if (!http->storeEntry())
1361 hdr->insertTime(HDR_DATE, squid_curtime);
1362 else if (http->storeEntry()->timestamp > 0)
1363 hdr->insertTime(HDR_DATE, http->storeEntry()->timestamp);
1364 else {
1365 debugs(88,DBG_IMPORTANT,"WARNING: An error inside Squid has caused an HTTP reply without Date:. Please report this:");
1366 /* dump something useful about the problem */
1367 http->storeEntry()->dump(DBG_IMPORTANT);
1368 }
1369 }
1370
1371 // add Warnings required by RFC 2616 if serving a stale hit
1372 if (http->request->flags.stale_if_hit && logTypeIsATcpHit(http->logType)) {
1373 hdr->putWarning(110, "Response is stale");
1374 if (http->request->flags.need_validation)
1375 hdr->putWarning(111, "Revalidation failed");
1376 }
1377
1378 /* Filter unproxyable authentication types */
1379 if (http->logType != LOG_TCP_DENIED &&
1380 hdr->has(HDR_WWW_AUTHENTICATE)) {
1381 HttpHeaderPos pos = HttpHeaderInitPos;
1382 HttpHeaderEntry *e;
1383
1384 int connection_auth_blocked = 0;
1385 while ((e = hdr->getEntry(&pos))) {
1386 if (e->id == HDR_WWW_AUTHENTICATE) {
1387 const char *value = e->value.rawBuf();
1388
1389 if ((strncasecmp(value, "NTLM", 4) == 0 &&
1390 (value[4] == '\0' || value[4] == ' '))
1391 ||
1392 (strncasecmp(value, "Negotiate", 9) == 0 &&
1393 (value[9] == '\0' || value[9] == ' '))
1394 ||
1395 (strncasecmp(value, "Kerberos", 8) == 0 &&
1396 (value[8] == '\0' || value[8] == ' '))) {
1397 if (request->flags.connection_auth_disabled) {
1398 hdr->delAt(pos, connection_auth_blocked);
1399 continue;
1400 }
1401 request->flags.must_keepalive = 1;
1402 if (!request->flags.accelerated && !request->flags.intercepted) {
1403 httpHeaderPutStrf(hdr, HDR_PROXY_SUPPORT, "Session-Based-Authentication");
1404 /*
1405 We send "[Proxy-]Connection: Proxy-Support" header to mark
1406 Proxy-Support as a hop-by-hop header for intermediaries that do not
1407 understand the semantics of this header. The RFC should have included
1408 this recommendation.
1409 */
1410 httpHeaderPutStrf(hdr, HDR_CONNECTION, "Proxy-support");
1411 }
1412 break;
1413 }
1414 }
1415 }
1416
1417 if (connection_auth_blocked)
1418 hdr->refreshMask();
1419 }
1420
1421 #if USE_AUTH
1422 /* Handle authentication headers */
1423 if (http->logType == LOG_TCP_DENIED &&
1424 ( reply->sline.status == HTTP_PROXY_AUTHENTICATION_REQUIRED ||
1425 reply->sline.status == HTTP_UNAUTHORIZED)
1426 ) {
1427 /* Add authentication header */
1428 /*! \todo alter errorstate to be accel on|off aware. The 0 on the next line
1429 * depends on authenticate behaviour: all schemes to date send no extra
1430 * data on 407/401 responses, and do not check the accel state on 401/407
1431 * responses
1432 */
1433 authenticateFixHeader(reply, request->auth_user_request, request, 0, 1);
1434 } else if (request->auth_user_request != NULL)
1435 authenticateFixHeader(reply, request->auth_user_request, request, http->flags.accel, 0);
1436 #endif
1437
1438 /* Append X-Cache */
1439 httpHeaderPutStrf(hdr, HDR_X_CACHE, "%s from %s",
1440 is_hit ? "HIT" : "MISS", getMyHostname());
1441
1442 #if USE_CACHE_DIGESTS
1443 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1444 httpHeaderPutStrf(hdr, HDR_X_CACHE_LOOKUP, "%s from %s:%d",
1445 lookup_type ? lookup_type : "NONE",
1446 getMyHostname(), getMyPort());
1447
1448 #endif
1449
1450 const bool maySendChunkedReply = !request->multipartRangeRequest() &&
1451 reply->sline.protocol == AnyP::PROTO_HTTP && // response is HTTP
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 } else if (request->flags.sslBumped && !reply->persistent()) {
1474 // We do not really have to close, but we pretend we are a tunnel.
1475 debugs(88, 3, "clientBuildReplyHeader: bumped reply forces close");
1476 request->flags.proxy_keepalive = 0;
1477 }
1478
1479 // Decide if we send chunked reply
1480 if (maySendChunkedReply &&
1481 request->flags.proxy_keepalive &&
1482 reply->bodySize(request->method) < 0) {
1483 debugs(88, 3, "clientBuildReplyHeader: chunked reply");
1484 request->flags.chunked_reply = 1;
1485 hdr->putStr(HDR_TRANSFER_ENCODING, "chunked");
1486 }
1487
1488 /* Append VIA */
1489 if (Config.onoff.via) {
1490 LOCAL_ARRAY(char, bbuf, MAX_URL + 32);
1491 String strVia;
1492 hdr->getList(HDR_VIA, &strVia);
1493 snprintf(bbuf, MAX_URL + 32, "%d.%d %s",
1494 reply->sline.version.major,
1495 reply->sline.version.minor,
1496 ThisCache);
1497 strListAdd(&strVia, bbuf, ',');
1498 hdr->delById(HDR_VIA);
1499 hdr->putStr(HDR_VIA, strVia.termedBuf());
1500 }
1501 /* Signal keep-alive or close explicitly */
1502 hdr->putStr(HDR_CONNECTION, request->flags.proxy_keepalive ? "keep-alive" : "close");
1503
1504 #if ADD_X_REQUEST_URI
1505 /*
1506 * Knowing the URI of the request is useful when debugging persistent
1507 * connections in a client; we cannot guarantee the order of http headers,
1508 * but X-Request-URI is likely to be the very last header to ease use from a
1509 * debugger [hdr->entries.count-1].
1510 */
1511 hdr->putStr(HDR_X_REQUEST_URI,
1512 http->memOjbect()->url ? http->memObject()->url : http->uri);
1513
1514 #endif
1515
1516 /* Surrogate-Control requires Surrogate-Capability from upstream to pass on */
1517 if ( hdr->has(HDR_SURROGATE_CONTROL) ) {
1518 if (!request->header.has(HDR_SURROGATE_CAPABILITY)) {
1519 hdr->delById(HDR_SURROGATE_CONTROL);
1520 }
1521 /* TODO: else case: drop any controls intended specifically for our surrogate ID */
1522 }
1523
1524 httpHdrMangleList(hdr, request, ROR_REPLY);
1525 }
1526
1527 void
1528 clientReplyContext::cloneReply()
1529 {
1530 assert(reply == NULL);
1531
1532 HttpReply *rep = http->storeEntry()->getReply()->clone();
1533
1534 reply = HTTPMSGLOCK(rep);
1535
1536 if (reply->sline.protocol == AnyP::PROTO_HTTP) {
1537 /* RFC 2616 requires us to advertise our 1.1 version (but only on real HTTP traffic) */
1538 reply->sline.version = HttpVersion(1,1);
1539 }
1540
1541 /* do header conversions */
1542 buildReplyHeader();
1543 }
1544
1545 void
1546 clientReplyContext::identifyStoreObject()
1547 {
1548 HttpRequest *r = http->request;
1549
1550 if (r->flags.cachable || r->flags.internal) {
1551 lookingforstore = 5;
1552 StoreEntry::getPublicByRequest (this, r);
1553 } else {
1554 identifyFoundObject (NullStoreEntry::getInstance());
1555 }
1556 }
1557
1558 /**
1559 * Check state of the current StoreEntry object.
1560 * to see if we can determine the final status of the request.
1561 */
1562 void
1563 clientReplyContext::identifyFoundObject(StoreEntry *newEntry)
1564 {
1565 StoreEntry *e = newEntry;
1566 HttpRequest *r = http->request;
1567
1568 /** \li If the entry received isNull() then we ignore it. */
1569 if (e->isNull()) {
1570 http->storeEntry(NULL);
1571 } else {
1572 http->storeEntry(e);
1573 }
1574
1575 e = http->storeEntry();
1576
1577 /* Release IP-cache entries on reload */
1578 /** \li If the request has no-cache flag set or some no_cache HACK in operation we
1579 * 'invalidate' the cached IP entries for this request ???
1580 */
1581 if (r->flags.nocache) {
1582
1583 #if USE_DNSHELPER
1584 ipcacheInvalidate(r->GetHost());
1585 #else
1586 ipcacheInvalidateNegative(r->GetHost());
1587 #endif /* USE_DNSHELPER */
1588
1589 }
1590
1591 #if USE_HTTP_VIOLATIONS
1592
1593 else if (r->flags.nocache_hack) {
1594
1595 #if USE_DNSHELPER
1596 ipcacheInvalidate(r->GetHost());
1597 #else
1598 ipcacheInvalidateNegative(r->GetHost());
1599 #endif /* USE_DNSHELPER */
1600
1601 }
1602
1603 #endif /* USE_HTTP_VIOLATIONS */
1604 #if USE_CACHE_DIGESTS
1605
1606 lookup_type = http->storeEntry() ? "HIT" : "MISS";
1607
1608 #endif
1609
1610 if (NULL == http->storeEntry()) {
1611 /** \li If no StoreEntry object is current assume this object isn't in the cache set MISS*/
1612 debugs(85, 3, "clientProcessRequest2: StoreEntry is NULL - MISS");
1613 http->logType = LOG_TCP_MISS;
1614 doGetMoreData();
1615 return;
1616 }
1617
1618 if (Config.onoff.offline) {
1619 /** \li If we are running in offline mode set to HIT */
1620 debugs(85, 3, "clientProcessRequest2: offline HIT");
1621 http->logType = LOG_TCP_HIT;
1622 doGetMoreData();
1623 return;
1624 }
1625
1626 if (http->redirect.status) {
1627 /** \li If redirection status is True force this to be a MISS */
1628 debugs(85, 3, HERE << "REDIRECT status forced StoreEntry to NULL (no body on 3XX responses)");
1629 http->storeEntry(NULL);
1630 http->logType = LOG_TCP_REDIRECT;
1631 doGetMoreData();
1632 return;
1633 }
1634
1635 if (!e->validToSend()) {
1636 debugs(85, 3, "clientProcessRequest2: !storeEntryValidToSend MISS" );
1637 http->storeEntry(NULL);
1638 http->logType = LOG_TCP_MISS;
1639 doGetMoreData();
1640 return;
1641 }
1642
1643 if (EBIT_TEST(e->flags, ENTRY_SPECIAL)) {
1644 /* \li Special entries are always hits, no matter what the client says */
1645 debugs(85, 3, "clientProcessRequest2: ENTRY_SPECIAL HIT");
1646 http->logType = LOG_TCP_HIT;
1647 doGetMoreData();
1648 return;
1649 }
1650
1651 if (r->flags.nocache) {
1652 debugs(85, 3, "clientProcessRequest2: no-cache REFRESH MISS");
1653 http->storeEntry(NULL);
1654 http->logType = LOG_TCP_CLIENT_REFRESH_MISS;
1655 doGetMoreData();
1656 return;
1657 }
1658
1659 debugs(85, 3, "clientProcessRequest2: default HIT");
1660 http->logType = LOG_TCP_HIT;
1661 doGetMoreData();
1662 }
1663
1664 /**
1665 * Request more data from the store for the client Stream
1666 * This is *the* entry point to this module.
1667 *
1668 * Preconditions:
1669 * - This is the head of the list.
1670 * - There is at least one more node.
1671 * - Data context is not null
1672 */
1673 void
1674 clientGetMoreData(clientStreamNode * aNode, ClientHttpRequest * http)
1675 {
1676 /* Test preconditions */
1677 assert(aNode != NULL);
1678 assert(cbdataReferenceValid(aNode));
1679 assert(aNode->node.prev == NULL);
1680 assert(aNode->node.next != NULL);
1681 clientReplyContext *context = dynamic_cast<clientReplyContext *>(aNode->data.getRaw());
1682 assert (context);
1683 assert(context->http == http);
1684
1685 clientStreamNode *next = ( clientStreamNode *)aNode->node.next->data;
1686
1687 if (!context->ourNode)
1688 context->ourNode = aNode;
1689
1690 /* no cbdatareference, this is only used once, and safely */
1691 if (context->flags.storelogiccomplete) {
1692 StoreIOBuffer tempBuffer;
1693 tempBuffer.offset = next->readBuffer.offset + context->headers_sz;
1694 tempBuffer.length = next->readBuffer.length;
1695 tempBuffer.data = next->readBuffer.data;
1696
1697 storeClientCopy(context->sc, http->storeEntry(),
1698 tempBuffer, clientReplyContext::SendMoreData, context);
1699 return;
1700 }
1701
1702 if (context->http->request->method == METHOD_PURGE) {
1703 context->purgeRequest();
1704 return;
1705 }
1706
1707 // OPTIONS with Max-Forwards:0 handled in clientProcessRequest()
1708
1709 if (context->http->request->method == METHOD_TRACE) {
1710 if (context->http->request->header.getInt64(HDR_MAX_FORWARDS) == 0) {
1711 context->traceReply(aNode);
1712 return;
1713 }
1714
1715 /* continue forwarding, not finished yet. */
1716 http->logType = LOG_TCP_MISS;
1717
1718 context->doGetMoreData();
1719 } else
1720 context->identifyStoreObject();
1721 }
1722
1723 void
1724 clientReplyContext::doGetMoreData()
1725 {
1726 /* We still have to do store logic processing - vary, cache hit etc */
1727 if (http->storeEntry() != NULL) {
1728 /* someone found the object in the cache for us */
1729 StoreIOBuffer localTempBuffer;
1730
1731 http->storeEntry()->lock();
1732
1733 if (http->storeEntry()->mem_obj == NULL) {
1734 /*
1735 * This if-block exists because we don't want to clobber
1736 * a preexiting mem_obj->method value if the mem_obj
1737 * already exists. For example, when a HEAD request
1738 * is a cache hit for a GET response, we want to keep
1739 * the method as GET.
1740 */
1741 http->storeEntry()->createMemObject(http->uri, http->log_uri);
1742 http->storeEntry()->mem_obj->method = http->request->method;
1743 }
1744
1745 sc = storeClientListAdd(http->storeEntry(), this);
1746 #if USE_DELAY_POOLS
1747 sc->setDelayId(DelayId::DelayClient(http));
1748 #endif
1749
1750 assert(http->logType == LOG_TCP_HIT);
1751 reqofs = 0;
1752 /* guarantee nothing has been sent yet! */
1753 assert(http->out.size == 0);
1754 assert(http->out.offset == 0);
1755
1756 if (Ip::Qos::TheConfig.isHitTosActive()) {
1757 Ip::Qos::doTosLocalHit(http->getConn()->clientConnection);
1758 }
1759
1760 if (Ip::Qos::TheConfig.isHitNfmarkActive()) {
1761 Ip::Qos::doNfmarkLocalHit(http->getConn()->clientConnection);
1762 }
1763
1764 localTempBuffer.offset = reqofs;
1765 localTempBuffer.length = getNextNode()->readBuffer.length;
1766 localTempBuffer.data = getNextNode()->readBuffer.data;
1767 storeClientCopy(sc, http->storeEntry(), localTempBuffer, CacheHit, this);
1768 } else {
1769 /* MISS CASE, http->logType is already set! */
1770 processMiss();
1771 }
1772 }
1773
1774 /** The next node has removed itself from the stream. */
1775 void
1776 clientReplyDetach(clientStreamNode * node, ClientHttpRequest * http)
1777 {
1778 /** detach from the stream */
1779 clientStreamDetach(node, http);
1780 }
1781
1782 /**
1783 * Accepts chunk of a http message in buf, parses prefix, filters headers and
1784 * such, writes processed message to the message recipient
1785 */
1786 void
1787 clientReplyContext::SendMoreData(void *data, StoreIOBuffer result)
1788 {
1789 clientReplyContext *context = static_cast<clientReplyContext *>(data);
1790 context->sendMoreData (result);
1791 }
1792
1793 void
1794 clientReplyContext::makeThisHead()
1795 {
1796 /* At least, I think thats what this does */
1797 dlinkDelete(&http->active, &ClientActiveRequests);
1798 dlinkAdd(http, &http->active, &ClientActiveRequests);
1799 }
1800
1801 bool
1802 clientReplyContext::errorInStream(StoreIOBuffer const &result, size_t const &sizeToProcess)const
1803 {
1804 return /* aborted request */
1805 (http->storeEntry() && EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)) ||
1806 /* Upstream read error */ (result.flags.error) ||
1807 /* Upstream EOF */ (sizeToProcess == 0);
1808 }
1809
1810 void
1811 clientReplyContext::sendStreamError(StoreIOBuffer const &result)
1812 {
1813 /** call clientWriteComplete so the client socket gets closed
1814 *
1815 * We call into the stream, because we don't know that there is a
1816 * client socket!
1817 */
1818 debugs(88, 5, "clientReplyContext::sendStreamError: A stream error has occured, marking as complete and sending no data.");
1819 StoreIOBuffer localTempBuffer;
1820 flags.complete = 1;
1821 http->request->flags.stream_error = 1;
1822 localTempBuffer.flags.error = result.flags.error;
1823 clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
1824 localTempBuffer);
1825 }
1826
1827 void
1828 clientReplyContext::pushStreamData(StoreIOBuffer const &result, char *source)
1829 {
1830 StoreIOBuffer localTempBuffer;
1831
1832 if (result.length == 0) {
1833 debugs(88, 5, "clientReplyContext::pushStreamData: marking request as complete due to 0 length store result");
1834 flags.complete = 1;
1835 }
1836
1837 assert(result.offset - headers_sz == next()->readBuffer.offset);
1838 localTempBuffer.offset = result.offset - headers_sz;
1839 localTempBuffer.length = result.length;
1840
1841 if (localTempBuffer.length)
1842 localTempBuffer.data = source;
1843
1844 clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
1845 localTempBuffer);
1846 }
1847
1848 clientStreamNode *
1849 clientReplyContext::next() const
1850 {
1851 assert ( (clientStreamNode*)http->client_stream.head->next->data == getNextNode());
1852 return getNextNode();
1853 }
1854
1855 void
1856 clientReplyContext::sendBodyTooLargeError()
1857 {
1858 Ip::Address tmp_noaddr;
1859 tmp_noaddr.SetNoAddr(); // TODO: make a global const
1860 http->logType = LOG_TCP_DENIED_REPLY;
1861 ErrorState *err = clientBuildError(ERR_TOO_BIG, HTTP_FORBIDDEN, NULL,
1862 http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmp_noaddr,
1863 http->request);
1864 removeClientStoreReference(&(sc), http);
1865 HTTPMSGUNLOCK(reply);
1866 startError(err);
1867
1868 }
1869
1870 /// send 412 (Precondition Failed) to client
1871 void
1872 clientReplyContext::sendPreconditionFailedError()
1873 {
1874 http->logType = LOG_TCP_HIT;
1875 ErrorState *const err =
1876 clientBuildError(ERR_PRECONDITION_FAILED, HTTP_PRECONDITION_FAILED,
1877 NULL, http->getConn()->clientConnection->remote, http->request);
1878 removeClientStoreReference(&sc, http);
1879 HTTPMSGUNLOCK(reply);
1880 startError(err);
1881 }
1882
1883 /// send 304 (Not Modified) to client
1884 void
1885 clientReplyContext::sendNotModified()
1886 {
1887 StoreEntry *e = http->storeEntry();
1888 const time_t timestamp = e->timestamp;
1889 HttpReply *const temprep = e->getReply()->make304();
1890 http->logType = LOG_TCP_IMS_HIT;
1891 removeClientStoreReference(&sc, http);
1892 createStoreEntry(http->request->method, request_flags());
1893 e = http->storeEntry();
1894 // Copy timestamp from the original entry so the 304
1895 // reply has a meaningful Age: header.
1896 e->timestampsSet();
1897 e->timestamp = timestamp;
1898 e->replaceHttpReply(temprep);
1899 e->complete();
1900 /*
1901 * TODO: why put this in the store and then serialise it and
1902 * then parse it again. Simply mark the request complete in
1903 * our context and write the reply struct to the client side.
1904 */
1905 triggerInitialStoreRead();
1906 }
1907
1908 /// send 304 (Not Modified) or 412 (Precondition Failed) to client
1909 /// depending on request method
1910 void
1911 clientReplyContext::sendNotModifiedOrPreconditionFailedError()
1912 {
1913 if (http->request->method == METHOD_GET ||
1914 http->request->method == METHOD_HEAD)
1915 sendNotModified();
1916 else
1917 sendPreconditionFailedError();
1918 }
1919
1920 void
1921 clientReplyContext::processReplyAccess ()
1922 {
1923 /* NP: this should probably soft-fail to a zero-sized-reply error ?? */
1924 assert(reply);
1925
1926 /** Don't block our own responses or HTTP status messages */
1927 if (http->logType == LOG_TCP_DENIED ||
1928 http->logType == LOG_TCP_DENIED_REPLY ||
1929 alwaysAllowResponse(reply->sline.status)) {
1930 headers_sz = reply->hdr_sz;
1931 processReplyAccessResult(ACCESS_ALLOWED);
1932 return;
1933 }
1934
1935 /** Check for reply to big error */
1936 if (reply->expectedBodyTooLarge(*http->request)) {
1937 sendBodyTooLargeError();
1938 return;
1939 }
1940
1941 headers_sz = reply->hdr_sz;
1942
1943 /** check for absent access controls (permit by default) */
1944 if (!Config.accessList.reply) {
1945 processReplyAccessResult(ACCESS_ALLOWED);
1946 return;
1947 }
1948
1949 /** Process http_reply_access lists */
1950 ACLFilledChecklist *replyChecklist =
1951 clientAclChecklistCreate(Config.accessList.reply, http);
1952 replyChecklist->reply = HTTPMSGLOCK(reply);
1953 replyChecklist->nonBlockingCheck(ProcessReplyAccessResult, this);
1954 }
1955
1956 void
1957 clientReplyContext::ProcessReplyAccessResult(allow_t rv, void *voidMe)
1958 {
1959 clientReplyContext *me = static_cast<clientReplyContext *>(voidMe);
1960 me->processReplyAccessResult(rv);
1961 }
1962
1963 void
1964 clientReplyContext::processReplyAccessResult(const allow_t &accessAllowed)
1965 {
1966 debugs(88, 2, "The reply for " << RequestMethodStr(http->request->method)
1967 << " " << http->uri << " is " << accessAllowed << ", because it matched '"
1968 << (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" );
1969
1970 if (accessAllowed != ACCESS_ALLOWED) {
1971 ErrorState *err;
1972 err_type page_id;
1973 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, 1);
1974
1975 http->logType = LOG_TCP_DENIED_REPLY;
1976
1977 if (page_id == ERR_NONE)
1978 page_id = ERR_ACCESS_DENIED;
1979
1980 Ip::Address tmp_noaddr;
1981 tmp_noaddr.SetNoAddr();
1982 err = clientBuildError(page_id, HTTP_FORBIDDEN, NULL,
1983 http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmp_noaddr,
1984 http->request);
1985
1986 removeClientStoreReference(&sc, http);
1987
1988 HTTPMSGUNLOCK(reply);
1989
1990 startError(err);
1991
1992 return;
1993 }
1994
1995 /* Ok, the reply is allowed, */
1996 http->loggingEntry(http->storeEntry());
1997
1998 ssize_t body_size = reqofs - reply->hdr_sz;
1999 if (body_size < 0) {
2000 reqofs = reply->hdr_sz;
2001 body_size = 0;
2002 }
2003
2004 debugs(88, 3, "clientReplyContext::sendMoreData: Appending " <<
2005 (int) body_size << " bytes after " << reply->hdr_sz <<
2006 " bytes of headers");
2007
2008 #if USE_SQUID_ESI
2009
2010 if (http->flags.accel && reply->sline.status != HTTP_FORBIDDEN &&
2011 !alwaysAllowResponse(reply->sline.status) &&
2012 esiEnableProcessing(reply)) {
2013 debugs(88, 2, "Enabling ESI processing for " << http->uri);
2014 clientStreamInsertHead(&http->client_stream, esiStreamRead,
2015 esiProcessStream, esiStreamDetach, esiStreamStatus, NULL);
2016 }
2017
2018 #endif
2019
2020 if (http->request->method == METHOD_HEAD) {
2021 /* do not forward body for HEAD replies */
2022 body_size = 0;
2023 http->flags.done_copying = 1;
2024 flags.complete = 1;
2025 }
2026
2027 assert (!flags.headersSent);
2028 flags.headersSent = true;
2029
2030 StoreIOBuffer localTempBuffer;
2031 char *buf = next()->readBuffer.data;
2032 char *body_buf = buf + reply->hdr_sz;
2033
2034 //Server side may disable ranges under some circumstances.
2035
2036 if ((!http->request->range))
2037 next()->readBuffer.offset = 0;
2038
2039 body_buf -= next()->readBuffer.offset;
2040
2041 if (next()->readBuffer.offset != 0) {
2042 if (next()->readBuffer.offset > body_size) {
2043 /* Can't use any of the body we received. send nothing */
2044 localTempBuffer.length = 0;
2045 localTempBuffer.data = NULL;
2046 } else {
2047 localTempBuffer.length = body_size - next()->readBuffer.offset;
2048 localTempBuffer.data = body_buf + next()->readBuffer.offset;
2049 }
2050 } else {
2051 localTempBuffer.length = body_size;
2052 localTempBuffer.data = body_buf;
2053 }
2054
2055 /* TODO??: move the data in the buffer back by the request header size */
2056 clientStreamCallback((clientStreamNode *)http->client_stream.head->data,
2057 http, reply, localTempBuffer);
2058
2059 return;
2060 }
2061
2062 void
2063 clientReplyContext::sendMoreData (StoreIOBuffer result)
2064 {
2065 if (deleting)
2066 return;
2067
2068 StoreEntry *entry = http->storeEntry();
2069
2070 ConnStateData * conn = http->getConn();
2071
2072 if (conn == NULL || !conn->isOpen()) {
2073 // too late, our conn is closing
2074 // TODO: should we also quit?
2075 debugs(33,3, HERE << "not sending more data to a closing " << conn->clientConnection);
2076 return;
2077 }
2078
2079 char *buf = next()->readBuffer.data;
2080
2081 if (buf != result.data) {
2082 /* we've got to copy some data */
2083 assert(result.length <= next()->readBuffer.length);
2084 memcpy(buf, result.data, result.length);
2085 }
2086
2087 if (reqofs==0 && !logTypeIsATcpHit(http->logType) && Comm::IsConnOpen(conn->clientConnection)) {
2088 if (Ip::Qos::TheConfig.isHitTosActive()) {
2089 Ip::Qos::doTosLocalMiss(conn->clientConnection, http->request->hier.code);
2090 }
2091 if (Ip::Qos::TheConfig.isHitNfmarkActive()) {
2092 Ip::Qos::doNfmarkLocalMiss(conn->clientConnection, http->request->hier.code);
2093 }
2094 }
2095
2096 /* We've got the final data to start pushing... */
2097 flags.storelogiccomplete = 1;
2098
2099 reqofs += result.length;
2100
2101 assert(reqofs <= HTTP_REQBUF_SZ || flags.headersSent);
2102
2103 assert(http->request != NULL);
2104
2105 /* ESI TODO: remove this assert once everything is stable */
2106 assert(http->client_stream.head->data
2107 && cbdataReferenceValid(http->client_stream.head->data));
2108
2109 makeThisHead();
2110
2111 debugs(88, 5, "clientReplyContext::sendMoreData: " << http->uri << ", " <<
2112 reqofs << " bytes (" << result.length <<
2113 " new bytes)");
2114 debugs(88, 5, "clientReplyContext::sendMoreData:"
2115 << conn->clientConnection <<
2116 " '" << entry->url() << "'" <<
2117 " out.offset=" << http->out.offset);
2118
2119 /* update size of the request */
2120 reqsize = reqofs;
2121
2122 if (errorInStream(result, reqofs)) {
2123 sendStreamError(result);
2124 return;
2125 }
2126
2127 if (flags.headersSent) {
2128 pushStreamData (result, buf);
2129 return;
2130 }
2131
2132 cloneReply();
2133
2134 /* handle headers */
2135
2136 if (Config.onoff.log_mime_hdrs) {
2137 size_t k;
2138
2139 if ((k = headersEnd(buf, reqofs))) {
2140 safe_free(http->al->headers.reply);
2141 http->al->headers.reply = (char *)xcalloc(k + 1, 1);
2142 xstrncpy(http->al->headers.reply, buf, k);
2143 }
2144 }
2145
2146 holdingBuffer = result;
2147 processReplyAccess();
2148 return;
2149 }
2150
2151 /* Using this breaks the client layering just a little!
2152 */
2153 void
2154 clientReplyContext::createStoreEntry(const HttpRequestMethod& m, request_flags reqFlags)
2155 {
2156 assert(http != NULL);
2157 /*
2158 * For erroneous requests, we might not have a h->request,
2159 * so make a fake one.
2160 */
2161
2162 if (http->request == NULL)
2163 http->request = HTTPMSGLOCK(new HttpRequest(m, AnyP::PROTO_NONE, null_string));
2164
2165 StoreEntry *e = storeCreateEntry(http->uri, http->log_uri, reqFlags, m);
2166
2167 sc = storeClientListAdd(e, this);
2168
2169 #if USE_DELAY_POOLS
2170 sc->setDelayId(DelayId::DelayClient(http));
2171 #endif
2172
2173 reqofs = 0;
2174
2175 reqsize = 0;
2176
2177 /* I don't think this is actually needed! -- adrian */
2178 /* http->reqbuf = http->norm_reqbuf; */
2179 // assert(http->reqbuf == http->norm_reqbuf);
2180 /* The next line is illegal because we don't know if the client stream
2181 * buffers have been set up
2182 */
2183 // storeClientCopy(http->sc, e, 0, HTTP_REQBUF_SZ, http->reqbuf,
2184 // SendMoreData, this);
2185 /* So, we mark the store logic as complete */
2186 flags.storelogiccomplete = 1;
2187
2188 /* and get the caller to request a read, from whereever they are */
2189 /* NOTE: after ANY data flows down the pipe, even one step,
2190 * this function CAN NOT be used to manage errors
2191 */
2192 http->storeEntry(e);
2193 }
2194
2195 ErrorState *
2196 clientBuildError(err_type page_id, http_status status, char const *url,
2197 Ip::Address &src_addr, HttpRequest * request)
2198 {
2199 ErrorState *err = new ErrorState(page_id, status, request);
2200 err->src_addr = src_addr;
2201
2202 if (url)
2203 err->url = xstrdup(url);
2204
2205 return err;
2206 }