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