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