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