1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "jingle/glue/proxy_resolving_client_socket.h"
7 #include "base/basictypes.h"
9 #include "base/bind_helpers.h"
10 #include "base/compiler_specific.h"
11 #include "base/logging.h"
12 #include "net/base/io_buffer.h"
13 #include "net/base/load_flags.h"
14 #include "net/base/net_errors.h"
15 #include "net/http/http_auth_controller.h"
16 #include "net/http/http_network_session.h"
17 #include "net/http/proxy_client_socket.h"
18 #include "net/socket/client_socket_handle.h"
19 #include "net/socket/client_socket_pool_manager.h"
20 #include "net/url_request/url_request_context.h"
21 #include "net/url_request/url_request_context_getter.h"
23 namespace jingle_glue
{
25 ProxyResolvingClientSocket::ProxyResolvingClientSocket(
26 net::ClientSocketFactory
* socket_factory
,
27 const scoped_refptr
<net::URLRequestContextGetter
>& request_context_getter
,
28 const net::SSLConfig
& ssl_config
,
29 const net::HostPortPair
& dest_host_port_pair
)
30 : proxy_resolve_callback_(
31 base::Bind(&ProxyResolvingClientSocket::ProcessProxyResolveDone
,
32 base::Unretained(this))),
34 base::Bind(&ProxyResolvingClientSocket::ProcessConnectDone
,
35 base::Unretained(this))),
36 ssl_config_(ssl_config
),
38 dest_host_port_pair_(dest_host_port_pair
),
39 // Assume that we intend to do TLS on this socket; all
40 // current use cases do.
41 proxy_url_("https://" + dest_host_port_pair_
.ToString()),
42 tried_direct_connect_fallback_(false),
44 net::BoundNetLog::Make(
45 request_context_getter
->GetURLRequestContext()->net_log(),
46 net::NetLog::SOURCE_SOCKET
)),
48 DCHECK(request_context_getter
.get());
49 net::URLRequestContext
* request_context
=
50 request_context_getter
->GetURLRequestContext();
51 DCHECK(request_context
);
52 DCHECK(!dest_host_port_pair_
.host().empty());
53 DCHECK_GT(dest_host_port_pair_
.port(), 0);
54 DCHECK(proxy_url_
.is_valid());
56 net::HttpNetworkSession::Params session_params
;
57 session_params
.client_socket_factory
= socket_factory
;
58 session_params
.host_resolver
= request_context
->host_resolver();
59 session_params
.cert_verifier
= request_context
->cert_verifier();
60 session_params
.transport_security_state
=
61 request_context
->transport_security_state();
62 // TODO(rkn): This is NULL because ChannelIDService is not thread safe.
63 session_params
.channel_id_service
= NULL
;
64 session_params
.proxy_service
= request_context
->proxy_service();
65 session_params
.ssl_config_service
= request_context
->ssl_config_service();
66 session_params
.http_auth_handler_factory
=
67 request_context
->http_auth_handler_factory();
68 session_params
.network_delegate
= request_context
->network_delegate();
69 session_params
.http_server_properties
=
70 request_context
->http_server_properties();
71 session_params
.net_log
= request_context
->net_log();
73 const net::HttpNetworkSession::Params
* reference_params
=
74 request_context
->GetNetworkSessionParams();
75 if (reference_params
) {
76 // TODO(mmenke): Just copying specific parameters seems highly regression
77 // prone. Should have a better way to do this.
78 session_params
.host_mapping_rules
= reference_params
->host_mapping_rules
;
79 session_params
.ignore_certificate_errors
=
80 reference_params
->ignore_certificate_errors
;
81 session_params
.testing_fixed_http_port
=
82 reference_params
->testing_fixed_http_port
;
83 session_params
.testing_fixed_https_port
=
84 reference_params
->testing_fixed_https_port
;
85 session_params
.next_protos
= reference_params
->next_protos
;
86 session_params
.trusted_spdy_proxy
= reference_params
->trusted_spdy_proxy
;
87 session_params
.forced_spdy_exclusions
=
88 reference_params
->forced_spdy_exclusions
;
89 session_params
.use_alternate_protocols
=
90 reference_params
->use_alternate_protocols
;
93 network_session_
= new net::HttpNetworkSession(session_params
);
96 ProxyResolvingClientSocket::~ProxyResolvingClientSocket() {
100 int ProxyResolvingClientSocket::Read(net::IOBuffer
* buf
, int buf_len
,
101 const net::CompletionCallback
& callback
) {
102 if (transport_
.get() && transport_
->socket())
103 return transport_
->socket()->Read(buf
, buf_len
, callback
);
105 return net::ERR_SOCKET_NOT_CONNECTED
;
108 int ProxyResolvingClientSocket::Write(
111 const net::CompletionCallback
& callback
) {
112 if (transport_
.get() && transport_
->socket())
113 return transport_
->socket()->Write(buf
, buf_len
, callback
);
115 return net::ERR_SOCKET_NOT_CONNECTED
;
118 int ProxyResolvingClientSocket::SetReceiveBufferSize(int32 size
) {
119 if (transport_
.get() && transport_
->socket())
120 return transport_
->socket()->SetReceiveBufferSize(size
);
122 return net::ERR_SOCKET_NOT_CONNECTED
;
125 int ProxyResolvingClientSocket::SetSendBufferSize(int32 size
) {
126 if (transport_
.get() && transport_
->socket())
127 return transport_
->socket()->SetSendBufferSize(size
);
129 return net::ERR_SOCKET_NOT_CONNECTED
;
132 int ProxyResolvingClientSocket::Connect(
133 const net::CompletionCallback
& callback
) {
134 DCHECK(user_connect_callback_
.is_null());
136 tried_direct_connect_fallback_
= false;
138 // First we try and resolve the proxy.
139 int status
= network_session_
->proxy_service()->ResolveProxy(
143 proxy_resolve_callback_
,
147 if (status
!= net::ERR_IO_PENDING
) {
148 // We defer execution of ProcessProxyResolveDone instead of calling it
149 // directly here for simplicity. From the caller's point of view,
150 // the connect always happens asynchronously.
151 base::MessageLoop
* message_loop
= base::MessageLoop::current();
153 message_loop
->PostTask(
155 base::Bind(&ProxyResolvingClientSocket::ProcessProxyResolveDone
,
156 weak_factory_
.GetWeakPtr(), status
));
158 user_connect_callback_
= callback
;
159 return net::ERR_IO_PENDING
;
162 void ProxyResolvingClientSocket::RunUserConnectCallback(int status
) {
163 DCHECK_LE(status
, net::OK
);
164 net::CompletionCallback user_connect_callback
= user_connect_callback_
;
165 user_connect_callback_
.Reset();
166 user_connect_callback
.Run(status
);
169 // Always runs asynchronously.
170 void ProxyResolvingClientSocket::ProcessProxyResolveDone(int status
) {
173 DCHECK_NE(status
, net::ERR_IO_PENDING
);
174 if (status
== net::OK
) {
175 // Remove unsupported proxies from the list.
176 proxy_info_
.RemoveProxiesWithoutScheme(
177 net::ProxyServer::SCHEME_DIRECT
|
178 net::ProxyServer::SCHEME_HTTP
| net::ProxyServer::SCHEME_HTTPS
|
179 net::ProxyServer::SCHEME_SOCKS4
| net::ProxyServer::SCHEME_SOCKS5
);
181 if (proxy_info_
.is_empty()) {
182 // No proxies/direct to choose from. This happens when we don't support
183 // any of the proxies in the returned list.
184 status
= net::ERR_NO_SUPPORTED_PROXIES
;
188 // Since we are faking the URL, it is possible that no proxies match our URL.
189 // Try falling back to a direct connection if we have not tried that before.
190 if (status
!= net::OK
) {
191 if (!tried_direct_connect_fallback_
) {
192 tried_direct_connect_fallback_
= true;
193 proxy_info_
.UseDirect();
195 CloseTransportSocket();
196 RunUserConnectCallback(status
);
201 transport_
.reset(new net::ClientSocketHandle
);
202 // Now that we have resolved the proxy, we need to connect.
203 status
= net::InitSocketHandleForRawConnect(
204 dest_host_port_pair_
, network_session_
.get(), proxy_info_
, ssl_config_
,
205 ssl_config_
, net::PRIVACY_MODE_DISABLED
, bound_net_log_
, transport_
.get(),
207 if (status
!= net::ERR_IO_PENDING
) {
208 // Since this method is always called asynchronously. it is OK to call
209 // ProcessConnectDone synchronously.
210 ProcessConnectDone(status
);
214 void ProxyResolvingClientSocket::ProcessConnectDone(int status
) {
215 if (status
!= net::OK
) {
216 // If the connection fails, try another proxy.
217 status
= ReconsiderProxyAfterError(status
);
218 // ReconsiderProxyAfterError either returns an error (in which case it is
219 // not reconsidering a proxy) or returns ERR_IO_PENDING if it is considering
221 DCHECK_NE(status
, net::OK
);
222 if (status
== net::ERR_IO_PENDING
)
223 // Proxy reconsideration pending. Return.
225 CloseTransportSocket();
227 ReportSuccessfulProxyConnection();
229 RunUserConnectCallback(status
);
232 // TODO(sanjeevr): This has largely been copied from
233 // HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError. This should be
234 // refactored into some common place.
235 // This method reconsiders the proxy on certain errors. If it does reconsider
236 // a proxy it always returns ERR_IO_PENDING and posts a call to
237 // ProcessProxyResolveDone with the result of the reconsideration.
238 int ProxyResolvingClientSocket::ReconsiderProxyAfterError(int error
) {
239 DCHECK(!pac_request_
);
240 DCHECK_NE(error
, net::OK
);
241 DCHECK_NE(error
, net::ERR_IO_PENDING
);
242 // A failure to resolve the hostname or any error related to establishing a
243 // TCP connection could be grounds for trying a new proxy configuration.
245 // Why do this when a hostname cannot be resolved? Some URLs only make sense
246 // to proxy servers. The hostname in those URLs might fail to resolve if we
247 // are still using a non-proxy config. We need to check if a proxy config
248 // now exists that corresponds to a proxy server that could load the URL.
251 case net::ERR_PROXY_CONNECTION_FAILED
:
252 case net::ERR_NAME_NOT_RESOLVED
:
253 case net::ERR_INTERNET_DISCONNECTED
:
254 case net::ERR_ADDRESS_UNREACHABLE
:
255 case net::ERR_CONNECTION_CLOSED
:
256 case net::ERR_CONNECTION_RESET
:
257 case net::ERR_CONNECTION_REFUSED
:
258 case net::ERR_CONNECTION_ABORTED
:
259 case net::ERR_TIMED_OUT
:
260 case net::ERR_TUNNEL_CONNECTION_FAILED
:
261 case net::ERR_SOCKS_CONNECTION_FAILED
:
263 case net::ERR_SOCKS_CONNECTION_HOST_UNREACHABLE
:
264 // Remap the SOCKS-specific "host unreachable" error to a more
265 // generic error code (this way consumers like the link doctor
266 // know to substitute their error page).
268 // Note that if the host resolving was done by the SOCSK5 proxy, we can't
269 // differentiate between a proxy-side "host not found" versus a proxy-side
270 // "address unreachable" error, and will report both of these failures as
271 // ERR_ADDRESS_UNREACHABLE.
272 return net::ERR_ADDRESS_UNREACHABLE
;
273 case net::ERR_PROXY_AUTH_REQUESTED
: {
274 net::ProxyClientSocket
* proxy_socket
=
275 static_cast<net::ProxyClientSocket
*>(transport_
->socket());
277 if (proxy_socket
->GetAuthController()->HaveAuth())
278 return proxy_socket
->RestartWithAuth(connect_callback_
);
286 if (proxy_info_
.is_https() && ssl_config_
.send_client_cert
) {
287 network_session_
->ssl_client_auth_cache()->Remove(
288 proxy_info_
.proxy_server().host_port_pair());
291 int rv
= network_session_
->proxy_service()->ReconsiderProxyAfterError(
292 proxy_url_
, net::LOAD_NORMAL
, error
, &proxy_info_
,
293 proxy_resolve_callback_
, &pac_request_
, NULL
, bound_net_log_
);
294 if (rv
== net::OK
|| rv
== net::ERR_IO_PENDING
) {
295 CloseTransportSocket();
297 // If ReconsiderProxyAfterError() failed synchronously, it means
298 // there was nothing left to fall-back to, so fail the transaction
299 // with the last connection error we got.
303 // We either have new proxy info or there was an error in falling back.
304 // In both cases we want to post ProcessProxyResolveDone (in the error case
305 // we might still want to fall back a direct connection).
306 if (rv
!= net::ERR_IO_PENDING
) {
307 base::MessageLoop
* message_loop
= base::MessageLoop::current();
309 message_loop
->PostTask(
311 base::Bind(&ProxyResolvingClientSocket::ProcessProxyResolveDone
,
312 weak_factory_
.GetWeakPtr(), rv
));
313 // Since we potentially have another try to go (trying the direct connect)
314 // set the return code code to ERR_IO_PENDING.
315 rv
= net::ERR_IO_PENDING
;
320 void ProxyResolvingClientSocket::ReportSuccessfulProxyConnection() {
321 network_session_
->proxy_service()->ReportSuccess(proxy_info_
, NULL
);
324 void ProxyResolvingClientSocket::Disconnect() {
325 CloseTransportSocket();
327 network_session_
->proxy_service()->CancelPacRequest(pac_request_
);
330 user_connect_callback_
.Reset();
333 bool ProxyResolvingClientSocket::IsConnected() const {
334 if (!transport_
.get() || !transport_
->socket())
336 return transport_
->socket()->IsConnected();
339 bool ProxyResolvingClientSocket::IsConnectedAndIdle() const {
340 if (!transport_
.get() || !transport_
->socket())
342 return transport_
->socket()->IsConnectedAndIdle();
345 int ProxyResolvingClientSocket::GetPeerAddress(
346 net::IPEndPoint
* address
) const {
347 if (!transport_
.get() || !transport_
->socket()) {
349 return net::ERR_SOCKET_NOT_CONNECTED
;
352 if (proxy_info_
.is_direct())
353 return transport_
->socket()->GetPeerAddress(address
);
355 net::IPAddressNumber ip_number
;
356 if (!net::ParseIPLiteralToNumber(dest_host_port_pair_
.host(), &ip_number
)) {
357 // Do not expose the proxy IP address to the caller.
358 return net::ERR_NAME_NOT_RESOLVED
;
361 *address
= net::IPEndPoint(ip_number
, dest_host_port_pair_
.port());
365 int ProxyResolvingClientSocket::GetLocalAddress(
366 net::IPEndPoint
* address
) const {
367 if (transport_
.get() && transport_
->socket())
368 return transport_
->socket()->GetLocalAddress(address
);
370 return net::ERR_SOCKET_NOT_CONNECTED
;
373 const net::BoundNetLog
& ProxyResolvingClientSocket::NetLog() const {
374 if (transport_
.get() && transport_
->socket())
375 return transport_
->socket()->NetLog();
377 return bound_net_log_
;
380 void ProxyResolvingClientSocket::SetSubresourceSpeculation() {
381 if (transport_
.get() && transport_
->socket())
382 transport_
->socket()->SetSubresourceSpeculation();
387 void ProxyResolvingClientSocket::SetOmniboxSpeculation() {
388 if (transport_
.get() && transport_
->socket())
389 transport_
->socket()->SetOmniboxSpeculation();
394 bool ProxyResolvingClientSocket::WasEverUsed() const {
395 if (transport_
.get() && transport_
->socket())
396 return transport_
->socket()->WasEverUsed();
401 bool ProxyResolvingClientSocket::UsingTCPFastOpen() const {
402 if (transport_
.get() && transport_
->socket())
403 return transport_
->socket()->UsingTCPFastOpen();
408 bool ProxyResolvingClientSocket::WasNpnNegotiated() const {
412 net::NextProto
ProxyResolvingClientSocket::GetNegotiatedProtocol() const {
413 if (transport_
.get() && transport_
->socket())
414 return transport_
->socket()->GetNegotiatedProtocol();
416 return net::kProtoUnknown
;
419 bool ProxyResolvingClientSocket::GetSSLInfo(net::SSLInfo
* ssl_info
) {
423 void ProxyResolvingClientSocket::GetConnectionAttempts(
424 net::ConnectionAttempts
* out
) const {
428 void ProxyResolvingClientSocket::CloseTransportSocket() {
429 if (transport_
.get() && transport_
->socket())
430 transport_
->socket()->Disconnect();
434 } // namespace jingle_glue