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