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