5 * DEBUG: section 85 Client-side Request Routines
6 * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c)
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
38 * General logic of request processing:
40 * We run a series of tests to determine if access will be permitted, and to do
41 * any redirection. Then we call into the result clientStream to retrieve data.
42 * From that point on it's up to reply management.
46 #include "clientStream.h"
47 #include "client_side_request.h"
48 #include "auth/UserRequest.h"
49 #include "HttpRequest.h"
50 #include "ProtoPort.h"
51 #include "acl/FilledChecklist.h"
52 #include "acl/Gadgets.h"
53 #include "client_side.h"
54 #include "client_side_reply.h"
56 #include "HttpReply.h"
57 #include "MemObject.h"
58 #include "ClientRequestContext.h"
59 #include "SquidTime.h"
61 #include "inet_pton.h"
65 #include "adaptation/AccessCheck.h"
66 #include "adaptation/Iterator.h"
67 #include "adaptation/Service.h"
69 #include "adaptation/icap/History.h"
71 //static void adaptationAclCheckDoneWrapper(Adaptation::ServicePointer service, void *data);
77 #define comm_close comm_lingering_close
80 static const char *const crlf
= "\r\n";
82 #if FOLLOW_X_FORWARDED_FOR
84 clientFollowXForwardedForCheck(int answer
, void *data
);
85 #endif /* FOLLOW_X_FORWARDED_FOR */
87 CBDATA_CLASS_INIT(ClientRequestContext
);
90 ClientRequestContext::operator new (size_t size
)
92 assert (size
== sizeof(ClientRequestContext
));
93 CBDATA_INIT_TYPE(ClientRequestContext
);
94 ClientRequestContext
*result
= cbdataAlloc(ClientRequestContext
);
99 ClientRequestContext::operator delete (void *address
)
101 ClientRequestContext
*t
= static_cast<ClientRequestContext
*>(address
);
105 /* Local functions */
107 static void clientAccessCheckDoneWrapper(int, void *);
108 static int clientHierarchical(ClientHttpRequest
* http
);
109 static void clientInterpretRequestHeaders(ClientHttpRequest
* http
);
110 static RH clientRedirectDoneWrapper
;
111 static PF checkNoCacheDoneWrapper
;
112 extern "C" CSR clientGetMoreData
;
113 extern "C" CSS clientReplyStatus
;
114 extern "C" CSD clientReplyDetach
;
115 static void checkFailureRatio(err_type
, hier_code
);
117 ClientRequestContext::~ClientRequestContext()
120 * Release our "lock" on our parent, ClientHttpRequest, if we
125 cbdataReferenceDone(http
);
127 debugs(85,3, HERE
<< this << " ClientRequestContext destructed");
130 ClientRequestContext::ClientRequestContext(ClientHttpRequest
*anHttp
) : http(cbdataReference(anHttp
)), acl_checklist (NULL
), redirect_state (REDIRECT_NONE
)
132 http_access_done
= false;
133 redirect_done
= false;
134 no_cache_done
= false;
135 interpreted_req_hdrs
= false;
136 debugs(85,3, HERE
<< this << " ClientRequestContext constructed");
139 CBDATA_CLASS_INIT(ClientHttpRequest
);
142 ClientHttpRequest::operator new (size_t size
)
144 assert (size
== sizeof (ClientHttpRequest
));
145 CBDATA_INIT_TYPE(ClientHttpRequest
);
146 ClientHttpRequest
*result
= cbdataAlloc(ClientHttpRequest
);
151 ClientHttpRequest::operator delete (void *address
)
153 ClientHttpRequest
*t
= static_cast<ClientHttpRequest
*>(address
);
157 ClientHttpRequest::ClientHttpRequest(ConnStateData
* aConn
) :
159 AsyncJob("ClientHttpRequest"),
163 start_time
= current_time
;
165 dlinkAdd(this, &active
, &ClientActiveRequests
);
167 request_satisfaction_mode
= false;
172 * returns true if client specified that the object must come from the cache
173 * without contacting origin server
176 ClientHttpRequest::onlyIfCached()const
179 return request
->cache_control
&&
180 EBIT_TEST(request
->cache_control
->mask
, CC_ONLY_IF_CACHED
);
184 * This function is designed to serve a fairly specific purpose.
185 * Occasionally our vBNS-connected caches can talk to each other, but not
186 * the rest of the world. Here we try to detect frequent failures which
187 * make the cache unusable (e.g. DNS lookup and connect() failures). If
188 * the failure:success ratio goes above 1.0 then we go into "hit only"
189 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
190 * will only fetch HITs from us if they are using the ICP protocol. We
191 * stay in this mode for 5 minutes.
193 * Duane W., Sept 16, 1996
196 #define FAILURE_MODE_TIME 300
199 checkFailureRatio(err_type etype
, hier_code hcode
)
201 static double magic_factor
= 100.0;
205 if (hcode
== HIER_NONE
)
208 n_good
= magic_factor
/ (1.0 + request_failure_ratio
);
210 n_bad
= magic_factor
- n_good
;
216 case ERR_CONNECT_FAIL
:
217 case ERR_SECURE_CONNECT_FAIL
:
227 request_failure_ratio
= n_bad
/ n_good
;
229 if (hit_only_mode_until
> squid_curtime
)
232 if (request_failure_ratio
< 1.0)
235 debugs(33, 0, "Failure Ratio at "<< std::setw(4)<<
236 std::setprecision(3) << request_failure_ratio
);
238 debugs(33, 0, "Going into hit-only-mode for " <<
239 FAILURE_MODE_TIME
/ 60 << " minutes...");
241 hit_only_mode_until
= squid_curtime
+ FAILURE_MODE_TIME
;
243 request_failure_ratio
= 0.8; /* reset to something less than 1.0 */
246 ClientHttpRequest::~ClientHttpRequest()
248 debugs(33, 3, "httpRequestFree: " << uri
);
249 PROF_start(httpRequestFree
);
251 // Even though freeResources() below may destroy the request,
252 // we no longer set request->body_pipe to NULL here
253 // because we did not initiate that pipe (ConnStateData did)
255 /* the ICP check here was erroneous
256 * - StoreEntry::releaseRequest was always called if entry was valid
258 assert(logType
< LOG_TYPE_MAX
);
265 checkFailureRatio(request
->errType
, al
.hier
.code
);
270 announceInitiatorAbort(virginHeadSource
);
272 if (adaptedBodySource
!= NULL
)
273 stopConsumingFrom(adaptedBodySource
);
277 delete calloutContext
;
280 cbdataReferenceDone(conn_
);
282 /* moving to the next connection is handled by the context free */
283 dlinkDelete(&active
, &ClientActiveRequests
);
285 PROF_stop(httpRequestFree
);
288 /* Create a request and kick it off */
290 * TODO: Pass in the buffers to be used in the inital Read request, as they are
291 * determined by the user
293 int /* returns nonzero on failure */
294 clientBeginRequest(const HttpRequestMethod
& method
, char const *url
, CSCB
* streamcallback
,
295 CSD
* streamdetach
, ClientStreamData streamdata
, HttpHeader
const *header
,
296 char *tailbuf
, size_t taillen
)
299 HttpVersion
http_ver (1, 0);
300 ClientHttpRequest
*http
= new ClientHttpRequest(NULL
);
301 HttpRequest
*request
;
302 StoreIOBuffer tempBuffer
;
303 http
->start_time
= current_time
;
304 /* this is only used to adjust the connection offset in client_side.c */
306 tempBuffer
.length
= taillen
;
307 tempBuffer
.data
= tailbuf
;
308 /* client stream setup */
309 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
310 clientReplyStatus
, new clientReplyContext(http
), streamcallback
,
311 streamdetach
, streamdata
, tempBuffer
);
312 /* make it visible in the 'current acctive requests list' */
314 /* internal requests only makes sense in an
315 * accelerator today. TODO: accept flags ? */
316 http
->flags
.accel
= 1;
317 /* allow size for url rewriting */
318 url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
319 http
->uri
= (char *)xcalloc(url_sz
, 1);
320 strcpy(http
->uri
, url
);
322 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
323 debugs(85, 5, "Invalid URL: " << http
->uri
);
328 * now update the headers in request with our supplied headers. urLParse
329 * should return a blank header set, but we use Update to be sure of
333 request
->header
.update(header
, NULL
);
335 http
->log_uri
= xstrdup(urlCanonicalClean(request
));
337 /* http struct now ready */
340 * build new header list *? TODO
342 request
->flags
.accelerated
= http
->flags
.accel
;
344 request
->flags
.internalclient
= 1;
346 /* this is an internally created
347 * request, not subject to acceleration
348 * target overrides */
350 * FIXME? Do we want to detect and handle internal requests of internal
354 /* Internally created requests cannot have bodies today */
355 request
->content_length
= 0;
357 request
->client_addr
.SetNoAddr();
359 #if FOLLOW_X_FORWARDED_FOR
360 request
->indirect_client_addr
.SetNoAddr();
361 #endif /* FOLLOW_X_FORWARDED_FOR */
363 request
->my_addr
.SetNoAddr(); /* undefined for internal requests */
365 request
->my_addr
.SetPort(0);
367 request
->http_ver
= http_ver
;
369 http
->request
= HTTPMSGLOCK(request
);
371 /* optional - skip the access check ? */
372 http
->calloutContext
= new ClientRequestContext(http
);
374 http
->calloutContext
->http_access_done
= false;
376 http
->calloutContext
->redirect_done
= true;
378 http
->calloutContext
->no_cache_done
= true;
386 ClientRequestContext::httpStateIsValid()
388 ClientHttpRequest
*http_
= http
;
390 if (cbdataReferenceValid(http_
))
395 cbdataReferenceDone(http_
);
400 #if FOLLOW_X_FORWARDED_FOR
402 * clientFollowXForwardedForCheck() checks the content of X-Forwarded-For:
403 * against the followXFF ACL, or cleans up and passes control to
404 * clientAccessCheck().
406 * The trust model here is a little ambiguous. So to clarify the logic:
407 * - we may always use the direct client address as the client IP.
408 * - these trust tests merey tell whether we trust given IP enough to believe the
409 * IP string which it appended to the X-Forwarded-For: header.
410 * - if at any point we don't trust what an IP adds we stop looking.
411 * - at that point the current contents of indirect_client_addr are the value set
412 * by the last previously trusted IP.
413 * ++ indirect_client_addr contains the remote direct client from the trusted peers viewpoint.
416 clientFollowXForwardedForCheck(int answer
, void *data
)
418 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
420 if (!calloutContext
->httpStateIsValid())
423 ClientHttpRequest
*http
= calloutContext
->http
;
424 HttpRequest
*request
= http
->request
;
427 * answer should be be ACCESS_ALLOWED or ACCESS_DENIED if we are
428 * called as a result of ACL checks, or -1 if we are called when
429 * there's nothing left to do.
431 if (answer
== ACCESS_ALLOWED
&&
432 request
->x_forwarded_for_iterator
.size () != 0) {
435 * Remove the last comma-delimited element from the
436 * x_forwarded_for_iterator and use it to repeat the cycle.
439 const char *asciiaddr
;
442 p
= request
->x_forwarded_for_iterator
.termedBuf();
443 l
= request
->x_forwarded_for_iterator
.size();
446 * XXX x_forwarded_for_iterator should really be a list of
447 * IP addresses, but it's a String instead. We have to
448 * walk backwards through the String, biting off the last
449 * comma-delimited part each time. As long as the data is in
450 * a String, we should probably implement and use a variant of
451 * strListGetItem() that walks backwards instead of forwards
452 * through a comma-separated list. But we don't even do that;
453 * we just do the work in-line here.
455 /* skip trailing space and commas */
456 while (l
> 0 && (p
[l
-1] == ',' || xisspace(p
[l
-1])))
458 request
->x_forwarded_for_iterator
.cut(l
);
459 /* look for start of last item in list */
460 while (l
> 0 && ! (p
[l
-1] == ',' || xisspace(p
[l
-1])))
463 if ((addr
= asciiaddr
)) {
464 request
->indirect_client_addr
= addr
;
465 request
->x_forwarded_for_iterator
.cut(l
);
466 calloutContext
->acl_checklist
= clientAclChecklistCreate(Config
.accessList
.followXFF
, http
);
467 if (!Config
.onoff
.acl_uses_indirect_client
) {
468 /* override the default src_addr tested if we have to go deeper than one level into XFF */
469 Filled(calloutContext
->acl_checklist
)->src_addr
= request
->indirect_client_addr
;
471 calloutContext
->acl_checklist
->nonBlockingCheck(clientFollowXForwardedForCheck
, data
);
474 } /*if (answer == ACCESS_ALLOWED &&
475 request->x_forwarded_for_iterator.size () != 0)*/
477 /* clean up, and pass control to clientAccessCheck */
478 if (Config
.onoff
.log_uses_indirect_client
) {
480 * Ensure that the access log shows the indirect client
481 * instead of the direct client.
483 ConnStateData
*conn
= http
->getConn();
484 conn
->log_addr
= request
->indirect_client_addr
;
486 request
->x_forwarded_for_iterator
.clean();
487 request
->flags
.done_follow_x_forwarded_for
= 1;
489 if (answer
!= ACCESS_ALLOWED
&& answer
!= ACCESS_DENIED
) {
490 debugs(28, DBG_CRITICAL
, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request
->indirect_client_addr
);
493 /* process actual access ACL as normal. */
494 calloutContext
->clientAccessCheck();
496 #endif /* FOLLOW_X_FORWARDED_FOR */
498 /* This is the entry point for external users of the client_side routines */
500 ClientRequestContext::clientAccessCheck()
502 #if FOLLOW_X_FORWARDED_FOR
503 if (!http
->request
->flags
.done_follow_x_forwarded_for
&&
504 Config
.accessList
.followXFF
&&
505 http
->request
->header
.has(HDR_X_FORWARDED_FOR
)) {
507 /* we always trust the direct client address for actual use */
508 http
->request
->indirect_client_addr
= http
->request
->client_addr
;
509 http
->request
->indirect_client_addr
.SetPort(0);
511 /* setup the XFF iterator for processing */
512 http
->request
->x_forwarded_for_iterator
= http
->request
->header
.getList(HDR_X_FORWARDED_FOR
);
514 /* begin by checking to see if we trust direct client enough to walk XFF */
515 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.followXFF
, http
);
516 acl_checklist
->nonBlockingCheck(clientFollowXForwardedForCheck
, this);
519 #endif /* FOLLOW_X_FORWARDED_FOR */
521 if (Config
.accessList
.http
) {
522 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.http
, http
);
523 acl_checklist
->nonBlockingCheck(clientAccessCheckDoneWrapper
, this);
525 debugs(0, DBG_CRITICAL
, "No http_access configuration found. This will block ALL traffic");
526 clientAccessCheckDone(ACCESS_DENIED
);
531 clientAccessCheckDoneWrapper(int answer
, void *data
)
533 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
535 if (!calloutContext
->httpStateIsValid())
538 calloutContext
->clientAccessCheckDone(answer
);
542 ClientRequestContext::clientAccessCheckDone(int answer
)
544 acl_checklist
= NULL
;
547 debugs(85, 2, "The request " <<
548 RequestMethodStr(http
->request
->method
) << " " <<
549 http
->uri
<< " is " <<
550 (answer
== ACCESS_ALLOWED
? "ALLOWED" : "DENIED") <<
551 ", because it matched '" <<
552 (AclMatchedName
? AclMatchedName
: "NO ACL's") << "'" );
553 char const *proxy_auth_msg
= "<null>";
555 if (http
->getConn() != NULL
&& http
->getConn()->auth_user_request
!= NULL
)
556 proxy_auth_msg
= http
->getConn()->auth_user_request
->denyMessage("<null>");
557 else if (http
->request
->auth_user_request
!= NULL
)
558 proxy_auth_msg
= http
->request
->auth_user_request
->denyMessage("<null>");
560 if (answer
!= ACCESS_ALLOWED
) {
562 int require_auth
= (answer
== ACCESS_REQ_PROXY_AUTH
|| aclIsProxyAuth(AclMatchedName
));
563 debugs(85, 5, "Access Denied: " << http
->uri
);
564 debugs(85, 5, "AclMatchedName = " << (AclMatchedName
? AclMatchedName
: "<null>"));
567 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg
? proxy_auth_msg
: "<null>"));
570 * NOTE: get page_id here, based on AclMatchedName because if
571 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
572 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
575 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, answer
!= ACCESS_REQ_PROXY_AUTH
);
577 http
->logType
= LOG_TCP_DENIED
;
580 if (!http
->flags
.accel
) {
581 /* Proxy authorisation needed */
582 status
= HTTP_PROXY_AUTHENTICATION_REQUIRED
;
584 /* WWW authorisation needed */
585 status
= HTTP_UNAUTHORIZED
;
588 if (page_id
== ERR_NONE
)
589 page_id
= ERR_CACHE_ACCESS_DENIED
;
591 status
= HTTP_FORBIDDEN
;
593 if (page_id
== ERR_NONE
)
594 page_id
= ERR_ACCESS_DENIED
;
597 clientStreamNode
*node
= (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
598 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
601 tmpnoaddr
.SetNoAddr();
602 repContext
->setReplyToError(page_id
, status
,
603 http
->request
->method
, NULL
,
604 http
->getConn() != NULL
? http
->getConn()->peer
: tmpnoaddr
,
607 http
->getConn() != NULL
&& http
->getConn()->auth_user_request
?
608 http
->getConn()->auth_user_request
: http
->request
->auth_user_request
);
610 node
= (clientStreamNode
*)http
->client_stream
.tail
->data
;
611 clientStreamRead(node
, http
, node
->readBuffer
);
615 /* ACCESS_ALLOWED continues here ... */
616 safe_free(http
->uri
);
618 http
->uri
= xstrdup(urlCanonical(http
->request
));
625 adaptationAclCheckDoneWrapper(Adaptation::ServiceGroupPointer g
, void *data
)
627 ClientRequestContext
*calloutContext
= (ClientRequestContext
*)data
;
629 if (!calloutContext
->httpStateIsValid())
632 calloutContext
->adaptationAclCheckDone(g
);
636 ClientRequestContext::adaptationAclCheckDone(Adaptation::ServiceGroupPointer g
)
638 debugs(93,3,HERE
<< this << " adaptationAclCheckDone called");
642 Adaptation::Icap::History::Pointer ih
= http
->request
->icapHistory();
644 if (http
->getConn() != NULL
) {
645 ih
->rfc931
= http
->getConn()->rfc931
;
647 ih
->ssluser
= sslGetUserEmail(fd_table
[http
->getConn()->fd
].ssl
);
650 ih
->log_uri
= http
->log_uri
;
651 ih
->req_sz
= http
->req_sz
;
656 debugs(85,3, HERE
<< "no adaptation needed");
661 http
->startAdaptation(g
);
667 clientRedirectAccessCheckDone(int answer
, void *data
)
669 ClientRequestContext
*context
= (ClientRequestContext
*)data
;
670 ClientHttpRequest
*http
= context
->http
;
671 context
->acl_checklist
= NULL
;
673 if (answer
== ACCESS_ALLOWED
)
674 redirectStart(http
, clientRedirectDoneWrapper
, context
);
676 context
->clientRedirectDone(NULL
);
680 ClientRequestContext::clientRedirectStart()
682 debugs(33, 5, "clientRedirectStart: '" << http
->uri
<< "'");
684 if (Config
.accessList
.redirector
) {
685 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.redirector
, http
);
686 acl_checklist
->nonBlockingCheck(clientRedirectAccessCheckDone
, this);
688 redirectStart(http
, clientRedirectDoneWrapper
, this);
692 clientHierarchical(ClientHttpRequest
* http
)
694 const char *url
= http
->uri
;
695 HttpRequest
*request
= http
->request
;
696 HttpRequestMethod method
= request
->method
;
697 const wordlist
*p
= NULL
;
700 * IMS needs a private key, so we can use the hierarchy for IMS only if our
701 * neighbors support private keys
704 if (request
->flags
.ims
&& !neighbors_do_private_keys
)
708 * This is incorrect: authenticating requests can be sent via a hierarchy
709 * (they can even be cached if the correct headers are set on the reply)
711 if (request
->flags
.auth
)
714 if (method
== METHOD_TRACE
)
717 if (method
!= METHOD_GET
)
720 /* scan hierarchy_stoplist */
721 for (p
= Config
.hierarchy_stoplist
; p
; p
= p
->next
)
722 if (strstr(url
, p
->key
))
725 if (request
->flags
.loopdetect
)
728 if (request
->protocol
== PROTO_HTTP
)
729 return httpCachable(method
);
731 if (request
->protocol
== PROTO_GOPHER
)
732 return gopherCachable(request
);
734 if (request
->protocol
== PROTO_CACHEOBJ
)
742 clientCheckPinning(ClientHttpRequest
* http
)
744 HttpRequest
*request
= http
->request
;
745 HttpHeader
*req_hdr
= &request
->header
;
746 ConnStateData
*http_conn
= http
->getConn();
748 /* Internal requests such as those from ESI includes may be without
749 * a client connection
754 request
->flags
.connection_auth_disabled
= http_conn
->port
->connection_auth_disabled
;
755 if (!request
->flags
.connection_auth_disabled
) {
756 if (http_conn
->pinning
.fd
!= -1) {
757 if (http_conn
->pinning
.auth
) {
758 request
->flags
.connection_auth
= 1;
759 request
->flags
.auth
= 1;
761 request
->flags
.connection_proxy_auth
= 1;
763 request
->setPinnedConnection(http_conn
);
767 /* check if connection auth is used, and flag as candidate for pinning
769 * Note: we may need to set flags.connection_auth even if the connection
770 * is already pinned if it was pinned earlier due to proxy auth
772 if (!request
->flags
.connection_auth
) {
773 if (req_hdr
->has(HDR_AUTHORIZATION
) || req_hdr
->has(HDR_PROXY_AUTHORIZATION
)) {
774 HttpHeaderPos pos
= HttpHeaderInitPos
;
777 while ((e
= req_hdr
->getEntry(&pos
))) {
778 if (e
->id
== HDR_AUTHORIZATION
|| e
->id
== HDR_PROXY_AUTHORIZATION
) {
779 const char *value
= e
->value
.rawBuf();
780 if (strncasecmp(value
, "NTLM ", 5) == 0
782 strncasecmp(value
, "Negotiate ", 10) == 0
784 strncasecmp(value
, "Kerberos ", 9) == 0) {
785 if (e
->id
== HDR_AUTHORIZATION
) {
786 request
->flags
.connection_auth
= 1;
789 request
->flags
.connection_proxy_auth
= 1;
795 if (may_pin
&& !request
->pinnedConnection()) {
796 request
->setPinnedConnection(http
->getConn());
803 clientInterpretRequestHeaders(ClientHttpRequest
* http
)
805 HttpRequest
*request
= http
->request
;
806 HttpHeader
*req_hdr
= &request
->header
;
810 request
->imslen
= -1;
811 request
->ims
= req_hdr
->getTime(HDR_IF_MODIFIED_SINCE
);
813 if (request
->ims
> 0)
814 request
->flags
.ims
= 1;
816 if (!request
->flags
.ignore_cc
) {
817 if (req_hdr
->has(HDR_PRAGMA
)) {
818 String s
= req_hdr
->getList(HDR_PRAGMA
);
820 if (strListIsMember(&s
, "no-cache", ','))
826 if (request
->cache_control
)
827 if (EBIT_TEST(request
->cache_control
->mask
, CC_NO_CACHE
))
831 * Work around for supporting the Reload button in IE browsers when Squid
832 * is used as an accelerator or transparent proxy, by turning accelerated
833 * IMS request to no-cache requests. Now knows about IE 5.5 fix (is
834 * actually only fixed in SP1, but we can't tell whether we are talking to
835 * SP1 or not so all 5.5 versions are treated 'normally').
837 if (Config
.onoff
.ie_refresh
) {
838 if (http
->flags
.accel
&& request
->flags
.ims
) {
839 if ((str
= req_hdr
->getStr(HDR_USER_AGENT
))) {
840 if (strstr(str
, "MSIE 5.01") != NULL
)
842 else if (strstr(str
, "MSIE 5.0") != NULL
)
844 else if (strstr(str
, "MSIE 4.") != NULL
)
846 else if (strstr(str
, "MSIE 3.") != NULL
)
853 if (request
->method
== METHOD_OTHER
) {
860 if (Config
.onoff
.reload_into_ims
)
861 request
->flags
.nocache_hack
= 1;
862 else if (refresh_nocache_hack
)
863 request
->flags
.nocache_hack
= 1;
867 request
->flags
.nocache
= 1;
870 /* ignore range header in non-GETs or non-HEADs */
871 if (request
->method
== METHOD_GET
|| request
->method
== METHOD_HEAD
) {
872 request
->range
= req_hdr
->getRange();
874 if (request
->range
) {
875 request
->flags
.range
= 1;
876 clientStreamNode
*node
= (clientStreamNode
*)http
->client_stream
.tail
->data
;
877 /* XXX: This is suboptimal. We should give the stream the range set,
878 * and thereby let the top of the stream set the offset when the
879 * size becomes known. As it is, we will end up requesting from 0
880 * for evey -X range specification.
881 * RBC - this may be somewhat wrong. We should probably set the range
882 * iter up at this point.
884 node
->readBuffer
.offset
= request
->range
->lowestOffset(0);
885 http
->range_iter
.pos
= request
->range
->begin();
886 http
->range_iter
.valid
= true;
890 /* Only HEAD and GET requests permit a Range or Request-Range header.
891 * If these headers appear on any other type of request, delete them now.
894 req_hdr
->delById(HDR_RANGE
);
895 req_hdr
->delById(HDR_REQUEST_RANGE
);
896 request
->range
= NULL
;
899 if (req_hdr
->has(HDR_AUTHORIZATION
))
900 request
->flags
.auth
= 1;
902 clientCheckPinning(http
);
904 if (request
->login
[0] != '\0')
905 request
->flags
.auth
= 1;
907 if (req_hdr
->has(HDR_VIA
)) {
908 String s
= req_hdr
->getList(HDR_VIA
);
910 * ThisCache cannot be a member of Via header, "1.0 ThisCache" can.
911 * Note ThisCache2 has a space prepended to the hostname so we don't
912 * accidentally match super-domains.
915 if (strListIsSubstr(&s
, ThisCache2
, ',')) {
916 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
917 request
, (ObjPackMethod
) & httpRequestPack
);
918 request
->flags
.loopdetect
= 1;
922 fvdbCountVia(s
.termedBuf());
930 \todo --enable-useragent-log and --enable-referer-log. We should
931 probably drop those two as the custom log formats accomplish pretty much the same thing..
933 #if USE_USERAGENT_LOG
934 if ((str
= req_hdr
->getStr(HDR_USER_AGENT
)))
935 logUserAgent(fqdnFromAddr(http
->getConn()->log_addr
), str
);
940 if ((str
= req_hdr
->getStr(HDR_REFERER
)))
941 logReferer(fqdnFromAddr(http
->getConn()->log_addr
), str
, http
->log_uri
);
946 if (req_hdr
->has(HDR_X_FORWARDED_FOR
)) {
947 String s
= req_hdr
->getList(HDR_X_FORWARDED_FOR
);
948 fvdbCountForw(s
.termedBuf());
953 if (request
->method
== METHOD_TRACE
|| request
->method
== METHOD_OPTIONS
) {
954 request
->max_forwards
= req_hdr
->getInt64(HDR_MAX_FORWARDS
);
957 request
->flags
.cachable
= http
->request
->cacheable();
959 if (clientHierarchical(http
))
960 request
->flags
.hierarchical
= 1;
962 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
963 (request
->flags
.nocache
? "SET" : "NOT SET"));
964 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
965 (request
->flags
.cachable
? "SET" : "NOT SET"));
966 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
967 (request
->flags
.hierarchical
? "SET" : "NOT SET"));
972 clientRedirectDoneWrapper(void *data
, char *result
)
974 ClientRequestContext
*calloutContext
= (ClientRequestContext
*)data
;
976 if (!calloutContext
->httpStateIsValid())
979 calloutContext
->clientRedirectDone(result
);
983 ClientRequestContext::clientRedirectDone(char *result
)
985 HttpRequest
*new_request
= NULL
;
986 HttpRequest
*old_request
= http
->request
;
987 debugs(85, 5, "clientRedirectDone: '" << http
->uri
<< "' result=" << (result
? result
: "NULL"));
988 assert(redirect_state
== REDIRECT_PENDING
);
989 redirect_state
= REDIRECT_DONE
;
992 http_status status
= (http_status
) atoi(result
);
994 if (status
== HTTP_MOVED_PERMANENTLY
995 || status
== HTTP_MOVED_TEMPORARILY
996 || status
== HTTP_SEE_OTHER
997 || status
== HTTP_TEMPORARY_REDIRECT
) {
1000 if ((t
= strchr(result
, ':')) != NULL
) {
1001 http
->redirect
.status
= status
;
1002 http
->redirect
.location
= xstrdup(t
+ 1);
1004 debugs(85, 1, "clientRedirectDone: bad input: " << result
);
1006 } else if (strcmp(result
, http
->uri
))
1007 new_request
= HttpRequest::CreateFromUrlAndMethod(result
, old_request
->method
);
1011 safe_free(http
->uri
);
1012 http
->uri
= xstrdup(urlCanonical(new_request
));
1013 new_request
->http_ver
= old_request
->http_ver
;
1014 new_request
->header
.append(&old_request
->header
);
1015 new_request
->client_addr
= old_request
->client_addr
;
1016 #if FOLLOW_X_FORWARDED_FOR
1017 new_request
->indirect_client_addr
= old_request
->indirect_client_addr
;
1018 #endif /* FOLLOW_X_FORWARDED_FOR */
1019 new_request
->my_addr
= old_request
->my_addr
;
1020 new_request
->flags
= old_request
->flags
;
1021 new_request
->flags
.redirected
= 1;
1023 if (old_request
->auth_user_request
) {
1024 new_request
->auth_user_request
= old_request
->auth_user_request
;
1025 AUTHUSERREQUESTLOCK(new_request
->auth_user_request
, "new request");
1028 if (old_request
->body_pipe
!= NULL
) {
1029 new_request
->body_pipe
= old_request
->body_pipe
;
1030 old_request
->body_pipe
= NULL
;
1031 debugs(0,0,HERE
<< "redirecting body_pipe " << new_request
->body_pipe
<< " from request " << old_request
<< " to " << new_request
);
1034 new_request
->content_length
= old_request
->content_length
;
1035 new_request
->extacl_user
= old_request
->extacl_user
;
1036 new_request
->extacl_passwd
= old_request
->extacl_passwd
;
1037 new_request
->flags
.proxy_keepalive
= old_request
->flags
.proxy_keepalive
;
1038 HTTPMSGUNLOCK(old_request
);
1039 http
->request
= HTTPMSGLOCK(new_request
);
1042 /* FIXME PIPELINE: This is innacurate during pipelining */
1044 if (http
->getConn() != NULL
)
1045 fd_note(http
->getConn()->fd
, http
->uri
);
1052 /** Test cache allow/deny configuration
1053 * Sets flags.cachable=1 if caching is not denied.
1056 ClientRequestContext::checkNoCache()
1058 if (Config
.accessList
.noCache
) {
1059 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.noCache
, http
);
1060 acl_checklist
->nonBlockingCheck(checkNoCacheDoneWrapper
, this);
1062 /* unless otherwise specified, we try to cache. */
1063 checkNoCacheDone(1);
1068 checkNoCacheDoneWrapper(int answer
, void *data
)
1070 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
1072 if (!calloutContext
->httpStateIsValid())
1075 calloutContext
->checkNoCacheDone(answer
);
1079 ClientRequestContext::checkNoCacheDone(int answer
)
1081 acl_checklist
= NULL
;
1082 http
->request
->flags
.cachable
= answer
;
1087 * Identify requests that do not go through the store and client side stream
1088 * and forward them to the appropriate location. All other requests, request
1092 ClientHttpRequest::processRequest()
1094 debugs(85, 4, "clientProcessRequest: " << RequestMethodStr(request
->method
) << " '" << uri
<< "'");
1097 if (request
->method
== METHOD_CONNECT
&& sslBumpNeeded()) {
1103 if (request
->method
== METHOD_CONNECT
&& !redirect
.status
) {
1104 logType
= LOG_TCP_MISS
;
1105 tunnelStart(this, &out
.size
, &al
.http
.code
);
1113 ClientHttpRequest::httpStart()
1115 PROF_start(httpStart
);
1116 logType
= LOG_TAG_NONE
;
1117 debugs(85, 4, "ClientHttpRequest::httpStart: " << log_tags
[logType
] << " for '" << uri
<< "'");
1119 /* no one should have touched this */
1120 assert(out
.offset
== 0);
1121 /* Use the Stream Luke */
1122 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->data
;
1123 clientStreamRead(node
, this, node
->readBuffer
);
1124 PROF_stop(httpStart
);
1129 // determines whether we should bump the CONNECT request
1131 ClientHttpRequest::sslBumpNeeded() const
1133 if (!getConn()->port
->sslBump
|| !Config
.accessList
.ssl_bump
)
1136 debugs(85, 5, HERE
<< "SslBump possible, checking ACL");
1138 ACLFilledChecklist
check(Config
.accessList
.ssl_bump
, request
, NULL
);
1139 check
.src_addr
= request
->client_addr
;
1140 check
.my_addr
= request
->my_addr
;
1141 return check
.fastCheck() == 1;
1144 // called when comm_write has completed
1146 SslBumpEstablish(int, char *, size_t, comm_err_t errflag
, int, void *data
)
1148 ClientHttpRequest
*r
= static_cast<ClientHttpRequest
*>(data
);
1149 debugs(85, 5, HERE
<< "responded to CONNECT: " << r
<< " ? " << errflag
);
1151 assert(r
&& cbdataReferenceValid(r
));
1152 r
->sslBumpEstablish(errflag
);
1156 ClientHttpRequest::sslBumpEstablish(comm_err_t errflag
)
1158 // Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up
1159 if (errflag
== COMM_ERR_CLOSING
)
1163 getConn()->startClosing("CONNECT response failure in SslBump");
1167 getConn()->switchToHttps();
1171 ClientHttpRequest::sslBumpStart()
1173 debugs(85, 5, HERE
<< "ClientHttpRequest::sslBumpStart");
1175 // send an HTTP 200 response to kick client SSL negotiation
1176 const int fd
= getConn()->fd
;
1177 debugs(33, 7, HERE
<< "Confirming CONNECT tunnel on FD " << fd
);
1179 // TODO: Unify with tunnel.cc and add a Server(?) header
1180 static const char *const conn_established
=
1181 "HTTP/1.0 200 Connection established\r\n\r\n";
1182 comm_write(fd
, conn_established
, strlen(conn_established
),
1183 &SslBumpEstablish
, this, NULL
);
1189 ClientHttpRequest::gotEnough() const
1191 /** TODO: should be querying the stream. */
1192 int64_t contentLength
=
1193 memObject()->getReply()->bodySize(request
->method
);
1194 assert(contentLength
>= 0);
1196 if (out
.offset
< contentLength
)
1203 ClientHttpRequest::storeEntry(StoreEntry
*newEntry
)
1209 ClientHttpRequest::loggingEntry(StoreEntry
*newEntry
)
1212 loggingEntry_
->unlock();
1214 loggingEntry_
= newEntry
;
1217 loggingEntry_
->lock();
1221 * doCallouts() - This function controls the order of "callout"
1222 * executions, including non-blocking access control checks, the
1223 * redirector, and ICAP. Previously, these callouts were chained
1224 * together such that "clientAccessCheckDone()" would call
1225 * "clientRedirectStart()" and so on.
1227 * The ClientRequestContext (aka calloutContext) class holds certain
1228 * state data for the callout/callback operations. Previously
1229 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1230 * for a short time. ClientRequestContext would then delete itself
1231 * and pass control back to ClientHttpRequest when all callouts
1234 * This caused some problems for ICAP because we want to make the
1235 * ICAP callout after checking ACLs, but before checking the no_cache
1236 * list. We can't stuff the ICAP state into the ClientRequestContext
1237 * class because we still need the ICAP state after ClientRequestContext
1240 * Note that ClientRequestContext is created before the first call
1243 * If one of the callouts notices that ClientHttpRequest is no
1244 * longer valid, it should call cbdataReferenceDone() so that
1245 * ClientHttpRequest's reference count goes to zero and it will get
1246 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1248 * Note that we set the _done flags here before actually starting
1249 * the callout. This is strictly for convenience.
1252 extern int aclMapTOS (acl_tos
* head
, ACLChecklist
* ch
);
1255 ClientHttpRequest::doCallouts()
1257 assert(calloutContext
);
1259 if (!calloutContext
->http_access_done
) {
1260 debugs(83, 3, HERE
<< "Doing calloutContext->clientAccessCheck()");
1261 calloutContext
->http_access_done
= true;
1262 calloutContext
->clientAccessCheck();
1267 if (!calloutContext
->adaptation_acl_check_done
) {
1268 calloutContext
->adaptation_acl_check_done
= true;
1269 if (Adaptation::AccessCheck::Start(
1270 Adaptation::methodReqmod
, Adaptation::pointPreCache
,
1271 request
, NULL
, adaptationAclCheckDoneWrapper
, calloutContext
))
1272 return; // will call callback
1276 if (!calloutContext
->redirect_done
) {
1277 calloutContext
->redirect_done
= true;
1278 assert(calloutContext
->redirect_state
== REDIRECT_NONE
);
1280 if (Config
.Program
.redirect
) {
1281 debugs(83, 3, HERE
<< "Doing calloutContext->clientRedirectStart()");
1282 calloutContext
->redirect_state
= REDIRECT_PENDING
;
1283 calloutContext
->clientRedirectStart();
1288 if (!calloutContext
->interpreted_req_hdrs
) {
1289 debugs(83, 3, HERE
<< "Doing clientInterpretRequestHeaders()");
1290 calloutContext
->interpreted_req_hdrs
= 1;
1291 clientInterpretRequestHeaders(this);
1294 if (!calloutContext
->no_cache_done
) {
1295 calloutContext
->no_cache_done
= true;
1297 if (Config
.accessList
.noCache
&& request
->flags
.cachable
) {
1298 debugs(83, 3, HERE
<< "Doing calloutContext->checkNoCache()");
1299 calloutContext
->checkNoCache();
1304 if (!calloutContext
->clientside_tos_done
) {
1305 calloutContext
->clientside_tos_done
= true;
1306 if (getConn() != NULL
) {
1307 ACLFilledChecklist
ch(NULL
, request
, NULL
);
1308 ch
.src_addr
= request
->client_addr
;
1309 ch
.my_addr
= request
->my_addr
;
1310 int tos
= aclMapTOS(Config
.accessList
.clientside_tos
, &ch
);
1312 comm_set_tos(getConn()->fd
, tos
);
1316 cbdataReferenceDone(calloutContext
->http
);
1317 delete calloutContext
;
1318 calloutContext
= NULL
;
1321 headersLog(0, 1, request
->method
, request
);
1324 debugs(83, 3, HERE
<< "calling processRequest()");
1328 Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
1330 ih
->logType
= logType
;
1334 #ifndef _USE_INLINE_
1335 #include "client_side_request.cci"
1339 /// Initiate an asynchronous adaptation transaction which will call us back.
1341 ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer
&g
)
1343 debugs(85, 3, HERE
<< "adaptation needed for " << this);
1344 assert(!virginHeadSource
);
1345 assert(!adaptedBodySource
);
1346 virginHeadSource
= initiateAdaptation(
1347 new Adaptation::Iterator(this, request
, NULL
, g
));
1349 // we could try to guess whether we can bypass this adaptation
1350 // initiation failure, but it should not really happen
1351 assert(virginHeadSource
!= NULL
); // Must, really
1355 ClientHttpRequest::noteAdaptationAnswer(HttpMsg
*msg
)
1357 assert(cbdataReferenceValid(this)); // indicates bug
1360 if (HttpRequest
*new_req
= dynamic_cast<HttpRequest
*>(msg
)) {
1362 * Replace the old request with the new request.
1364 HTTPMSGUNLOCK(request
);
1365 request
= HTTPMSGLOCK(new_req
);
1367 * Store the new URI for logging
1370 uri
= xstrdup(urlCanonical(request
));
1371 setLogUri(this, urlCanonicalClean(request
));
1372 assert(request
->method
.id());
1373 } else if (HttpReply
*new_rep
= dynamic_cast<HttpReply
*>(msg
)) {
1374 debugs(85,3,HERE
<< "REQMOD reply is HTTP reply");
1376 // subscribe to receive reply body
1377 if (new_rep
->body_pipe
!= NULL
) {
1378 adaptedBodySource
= new_rep
->body_pipe
;
1379 int consumer_ok
= adaptedBodySource
->setConsumerIfNotLate(this);
1380 assert(consumer_ok
);
1383 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
1384 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1385 repContext
->createStoreEntry(request
->method
, request
->flags
);
1387 EBIT_CLR(storeEntry()->flags
, ENTRY_FWD_HDR_WAIT
);
1388 request_satisfaction_mode
= true;
1389 request_satisfaction_offset
= 0;
1390 storeEntry()->replaceHttpReply(new_rep
);
1391 storeEntry()->timestampsSet();
1393 if (!adaptedBodySource
) // no body
1394 storeEntry()->complete();
1395 clientGetMoreData(node
, this);
1398 // we are done with getting headers (but may be receiving body)
1399 clearAdaptation(virginHeadSource
);
1401 if (!request_satisfaction_mode
)
1406 ClientHttpRequest::noteAdaptationQueryAbort(bool final
)
1408 clearAdaptation(virginHeadSource
);
1409 assert(!adaptedBodySource
);
1410 handleAdaptationFailure(!final
);
1414 ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
1416 assert(request_satisfaction_mode
);
1417 assert(adaptedBodySource
!= NULL
);
1419 if (const size_t contentSize
= adaptedBodySource
->buf().contentSize()) {
1420 BodyPipeCheckout
bpc(*adaptedBodySource
);
1421 const StoreIOBuffer
ioBuf(&bpc
.buf
, request_satisfaction_offset
);
1422 storeEntry()->write(ioBuf
);
1423 // assume can write everything
1424 request_satisfaction_offset
+= contentSize
;
1425 bpc
.buf
.consume(contentSize
);
1429 if (adaptedBodySource
->exhausted())
1430 endRequestSatisfaction();
1431 // else wait for more body data
1435 ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer
)
1437 assert(!virginHeadSource
);
1438 if (adaptedBodySource
!= NULL
) { // did not end request satisfaction yet
1439 // We do not expect more because noteMoreBodyDataAvailable always
1440 // consumes everything. We do not even have a mechanism to consume
1441 // leftovers after noteMoreBodyDataAvailable notifications seize.
1442 assert(adaptedBodySource
->exhausted());
1443 endRequestSatisfaction();
1448 ClientHttpRequest::endRequestSatisfaction()
1450 debugs(85,4, HERE
<< this << " ends request satisfaction");
1451 assert(request_satisfaction_mode
);
1452 stopConsumingFrom(adaptedBodySource
);
1454 // TODO: anything else needed to end store entry formation correctly?
1455 storeEntry()->complete();
1459 ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer
)
1461 assert(!virginHeadSource
);
1462 stopConsumingFrom(adaptedBodySource
);
1463 handleAdaptationFailure();
1467 ClientHttpRequest::handleAdaptationFailure(bool bypassable
)
1469 debugs(85,3, HERE
<< "handleAdaptationFailure(" << bypassable
<< ")");
1471 const bool usedStore
= storeEntry() && !storeEntry()->isEmpty();
1472 const bool usedPipe
= request
->body_pipe
!= NULL
&&
1473 request
->body_pipe
->consumedSize() > 0;
1475 if (bypassable
&& !usedStore
&& !usedPipe
) {
1476 debugs(85,3, HERE
<< "ICAP REQMOD callout failed, bypassing: " << calloutContext
);
1482 debugs(85,3, HERE
<< "ICAP REQMOD callout failed, responding with error");
1484 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
1485 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1488 // The original author of the code also wanted to pass an errno to
1489 // setReplyToError, but it seems unlikely that the errno reflects the
1490 // true cause of the error at this point, so I did not pass it.
1493 ConnStateData
* c
= getConn();
1494 repContext
->setReplyToError(ERR_ICAP_FAILURE
, HTTP_INTERNAL_SERVER_ERROR
,
1495 request
->method
, NULL
,
1496 (c
!= NULL
? c
->peer
: noAddr
), request
, NULL
,
1497 (c
!= NULL
&& c
->auth_user_request
?
1498 c
->auth_user_request
: request
->auth_user_request
));
1500 node
= (clientStreamNode
*)client_stream
.tail
->data
;
1501 clientStreamRead(node
, this, node
->readBuffer
);