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