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