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