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_network_session.h"
16 #include "net/socket/client_socket_handle.h"
17 #include "net/socket/client_socket_pool_manager.h"
18 #include "net/url_request/url_request_context.h"
19 #include "net/url_request/url_request_context_getter.h"
21 namespace jingle_glue
{
23 ProxyResolvingClientSocket::ProxyResolvingClientSocket(
24 net::ClientSocketFactory
* socket_factory
,
25 const scoped_refptr
<net::URLRequestContextGetter
>& request_context_getter
,
26 const net::SSLConfig
& ssl_config
,
27 const net::HostPortPair
& dest_host_port_pair
)
28 : proxy_resolve_callback_(
29 base::Bind(&ProxyResolvingClientSocket::ProcessProxyResolveDone
,
30 base::Unretained(this))),
32 base::Bind(&ProxyResolvingClientSocket::ProcessConnectDone
,
33 base::Unretained(this))),
34 ssl_config_(ssl_config
),
36 dest_host_port_pair_(dest_host_port_pair
),
37 // Assume that we intend to do TLS on this socket; all
38 // current use cases do.
39 proxy_url_("https://" + dest_host_port_pair_
.ToString()),
40 tried_direct_connect_fallback_(false),
42 net::BoundNetLog::Make(
43 request_context_getter
->GetURLRequestContext()->net_log(),
44 net::NetLog::SOURCE_SOCKET
)),
46 DCHECK(request_context_getter
.get());
47 net::URLRequestContext
* request_context
=
48 request_context_getter
->GetURLRequestContext();
49 DCHECK(request_context
);
50 DCHECK(!dest_host_port_pair_
.host().empty());
51 DCHECK_GT(dest_host_port_pair_
.port(), 0);
52 DCHECK(proxy_url_
.is_valid());
54 net::HttpNetworkSession::Params session_params
;
55 session_params
.client_socket_factory
= socket_factory
;
56 session_params
.host_resolver
= request_context
->host_resolver();
57 session_params
.cert_verifier
= request_context
->cert_verifier();
58 session_params
.transport_security_state
=
59 request_context
->transport_security_state();
60 // TODO(rkn): This is NULL because ChannelIDService is not thread safe.
61 session_params
.channel_id_service
= NULL
;
62 session_params
.proxy_service
= request_context
->proxy_service();
63 session_params
.ssl_config_service
= request_context
->ssl_config_service();
64 session_params
.http_auth_handler_factory
=
65 request_context
->http_auth_handler_factory();
66 session_params
.network_delegate
= request_context
->network_delegate();
67 session_params
.http_server_properties
=
68 request_context
->http_server_properties();
69 session_params
.net_log
= request_context
->net_log();
71 const net::HttpNetworkSession::Params
* reference_params
=
72 request_context
->GetNetworkSessionParams();
73 if (reference_params
) {
74 // TODO(mmenke): Just copying specific parameters seems highly regression
75 // prone. Should have a better way to do this.
76 session_params
.host_mapping_rules
= reference_params
->host_mapping_rules
;
77 session_params
.ignore_certificate_errors
=
78 reference_params
->ignore_certificate_errors
;
79 session_params
.testing_fixed_http_port
=
80 reference_params
->testing_fixed_http_port
;
81 session_params
.testing_fixed_https_port
=
82 reference_params
->testing_fixed_https_port
;
83 session_params
.next_protos
= reference_params
->next_protos
;
84 session_params
.trusted_spdy_proxy
= reference_params
->trusted_spdy_proxy
;
85 session_params
.force_spdy_over_ssl
= reference_params
->force_spdy_over_ssl
;
86 session_params
.force_spdy_always
= reference_params
->force_spdy_always
;
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
;
277 if (proxy_info_
.is_https() && ssl_config_
.send_client_cert
) {
278 network_session_
->ssl_client_auth_cache()->Remove(
279 proxy_info_
.proxy_server().host_port_pair());
282 int rv
= network_session_
->proxy_service()->ReconsiderProxyAfterError(
283 proxy_url_
, net::LOAD_NORMAL
, error
, &proxy_info_
,
284 proxy_resolve_callback_
, &pac_request_
, NULL
, bound_net_log_
);
285 if (rv
== net::OK
|| rv
== net::ERR_IO_PENDING
) {
286 CloseTransportSocket();
288 // If ReconsiderProxyAfterError() failed synchronously, it means
289 // there was nothing left to fall-back to, so fail the transaction
290 // with the last connection error we got.
294 // We either have new proxy info or there was an error in falling back.
295 // In both cases we want to post ProcessProxyResolveDone (in the error case
296 // we might still want to fall back a direct connection).
297 if (rv
!= net::ERR_IO_PENDING
) {
298 base::MessageLoop
* message_loop
= base::MessageLoop::current();
300 message_loop
->PostTask(
302 base::Bind(&ProxyResolvingClientSocket::ProcessProxyResolveDone
,
303 weak_factory_
.GetWeakPtr(), rv
));
304 // Since we potentially have another try to go (trying the direct connect)
305 // set the return code code to ERR_IO_PENDING.
306 rv
= net::ERR_IO_PENDING
;
311 void ProxyResolvingClientSocket::ReportSuccessfulProxyConnection() {
312 network_session_
->proxy_service()->ReportSuccess(proxy_info_
, NULL
);
315 void ProxyResolvingClientSocket::Disconnect() {
316 CloseTransportSocket();
318 network_session_
->proxy_service()->CancelPacRequest(pac_request_
);
321 user_connect_callback_
.Reset();
324 bool ProxyResolvingClientSocket::IsConnected() const {
325 if (!transport_
.get() || !transport_
->socket())
327 return transport_
->socket()->IsConnected();
330 bool ProxyResolvingClientSocket::IsConnectedAndIdle() const {
331 if (!transport_
.get() || !transport_
->socket())
333 return transport_
->socket()->IsConnectedAndIdle();
336 int ProxyResolvingClientSocket::GetPeerAddress(
337 net::IPEndPoint
* address
) const {
338 if (transport_
.get() && transport_
->socket())
339 return transport_
->socket()->GetPeerAddress(address
);
341 return net::ERR_SOCKET_NOT_CONNECTED
;
344 int ProxyResolvingClientSocket::GetLocalAddress(
345 net::IPEndPoint
* address
) const {
346 if (transport_
.get() && transport_
->socket())
347 return transport_
->socket()->GetLocalAddress(address
);
349 return net::ERR_SOCKET_NOT_CONNECTED
;
352 const net::BoundNetLog
& ProxyResolvingClientSocket::NetLog() const {
353 if (transport_
.get() && transport_
->socket())
354 return transport_
->socket()->NetLog();
356 return bound_net_log_
;
359 void ProxyResolvingClientSocket::SetSubresourceSpeculation() {
360 if (transport_
.get() && transport_
->socket())
361 transport_
->socket()->SetSubresourceSpeculation();
366 void ProxyResolvingClientSocket::SetOmniboxSpeculation() {
367 if (transport_
.get() && transport_
->socket())
368 transport_
->socket()->SetOmniboxSpeculation();
373 bool ProxyResolvingClientSocket::WasEverUsed() const {
374 if (transport_
.get() && transport_
->socket())
375 return transport_
->socket()->WasEverUsed();
380 bool ProxyResolvingClientSocket::UsingTCPFastOpen() const {
381 if (transport_
.get() && transport_
->socket())
382 return transport_
->socket()->UsingTCPFastOpen();
387 bool ProxyResolvingClientSocket::WasNpnNegotiated() const {
391 net::NextProto
ProxyResolvingClientSocket::GetNegotiatedProtocol() const {
392 if (transport_
.get() && transport_
->socket())
393 return transport_
->socket()->GetNegotiatedProtocol();
395 return net::kProtoUnknown
;
398 bool ProxyResolvingClientSocket::GetSSLInfo(net::SSLInfo
* ssl_info
) {
402 void ProxyResolvingClientSocket::CloseTransportSocket() {
403 if (transport_
.get() && transport_
->socket())
404 transport_
->socket()->Disconnect();
408 } // namespace jingle_glue