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 "net/http/http_proxy_client_socket_pool.h"
9 #include "base/compiler_specific.h"
10 #include "base/time/time.h"
11 #include "base/values.h"
12 #include "net/base/load_flags.h"
13 #include "net/base/net_errors.h"
14 #include "net/base/proxy_delegate.h"
15 #include "net/http/http_network_session.h"
16 #include "net/http/http_proxy_client_socket.h"
17 #include "net/socket/client_socket_factory.h"
18 #include "net/socket/client_socket_handle.h"
19 #include "net/socket/client_socket_pool_base.h"
20 #include "net/socket/ssl_client_socket.h"
21 #include "net/socket/ssl_client_socket_pool.h"
22 #include "net/socket/transport_client_socket_pool.h"
23 #include "net/spdy/spdy_proxy_client_socket.h"
24 #include "net/spdy/spdy_session.h"
25 #include "net/spdy/spdy_session_pool.h"
26 #include "net/spdy/spdy_stream.h"
27 #include "net/ssl/ssl_cert_request_info.h"
32 HttpProxySocketParams::HttpProxySocketParams(
33 const scoped_refptr
<TransportSocketParams
>& transport_params
,
34 const scoped_refptr
<SSLSocketParams
>& ssl_params
,
35 const GURL
& request_url
,
36 const std::string
& user_agent
,
37 const HostPortPair
& endpoint
,
38 HttpAuthCache
* http_auth_cache
,
39 HttpAuthHandlerFactory
* http_auth_handler_factory
,
40 SpdySessionPool
* spdy_session_pool
,
42 ProxyDelegate
* proxy_delegate
)
43 : transport_params_(transport_params
),
44 ssl_params_(ssl_params
),
45 spdy_session_pool_(spdy_session_pool
),
46 request_url_(request_url
),
47 user_agent_(user_agent
),
49 http_auth_cache_(tunnel
? http_auth_cache
: NULL
),
50 http_auth_handler_factory_(tunnel
? http_auth_handler_factory
: NULL
),
52 proxy_delegate_(proxy_delegate
) {
53 DCHECK((transport_params
.get() == NULL
&& ssl_params
.get() != NULL
) ||
54 (transport_params
.get() != NULL
&& ssl_params
.get() == NULL
));
55 if (transport_params_
.get()) {
56 ignore_limits_
= transport_params
->ignore_limits();
58 ignore_limits_
= ssl_params
->ignore_limits();
62 const HostResolver::RequestInfo
& HttpProxySocketParams::destination() const {
63 if (transport_params_
.get() == NULL
) {
64 return ssl_params_
->GetDirectConnectionParams()->destination();
66 return transport_params_
->destination();
70 HttpProxySocketParams::~HttpProxySocketParams() {}
72 // HttpProxyConnectJobs will time out after this many seconds. Note this is on
73 // top of the timeout for the transport socket.
74 // TODO(kundaji): Proxy connect timeout should be independent of platform and be
75 // based on proxy. Bug http://crbug.com/407446.
76 #if defined(OS_ANDROID) || defined(OS_IOS)
77 static const int kHttpProxyConnectJobTimeoutInSeconds
= 10;
79 static const int kHttpProxyConnectJobTimeoutInSeconds
= 30;
82 HttpProxyConnectJob::HttpProxyConnectJob(
83 const std::string
& group_name
,
84 RequestPriority priority
,
85 const scoped_refptr
<HttpProxySocketParams
>& params
,
86 const base::TimeDelta
& timeout_duration
,
87 TransportClientSocketPool
* transport_pool
,
88 SSLClientSocketPool
* ssl_pool
,
91 : ConnectJob(group_name
, timeout_duration
, priority
, delegate
,
92 BoundNetLog::Make(net_log
, NetLog::SOURCE_CONNECT_JOB
)),
94 transport_pool_(transport_pool
),
97 protocol_negotiated_(kProtoUnknown
),
98 weak_ptr_factory_(this) {
99 callback_
= base::Bind(&HttpProxyConnectJob::OnIOComplete
,
100 weak_ptr_factory_
.GetWeakPtr());
103 HttpProxyConnectJob::~HttpProxyConnectJob() {}
105 LoadState
HttpProxyConnectJob::GetLoadState() const {
106 switch (next_state_
) {
107 case STATE_TCP_CONNECT
:
108 case STATE_TCP_CONNECT_COMPLETE
:
109 case STATE_SSL_CONNECT
:
110 case STATE_SSL_CONNECT_COMPLETE
:
111 return transport_socket_handle_
->GetLoadState();
112 case STATE_HTTP_PROXY_CONNECT
:
113 case STATE_HTTP_PROXY_CONNECT_COMPLETE
:
114 case STATE_SPDY_PROXY_CREATE_STREAM
:
115 case STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE
:
116 return LOAD_STATE_ESTABLISHING_PROXY_TUNNEL
;
119 return LOAD_STATE_IDLE
;
123 void HttpProxyConnectJob::GetAdditionalErrorState(ClientSocketHandle
* handle
) {
124 if (error_response_info_
.cert_request_info
.get()) {
125 handle
->set_ssl_error_response_info(error_response_info_
);
126 handle
->set_is_ssl_error(true);
130 void HttpProxyConnectJob::OnIOComplete(int result
) {
131 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
132 tracked_objects::ScopedTracker
tracking_profile(
133 FROM_HERE_WITH_EXPLICIT_FUNCTION(
134 "455884 HttpProxyConnectJob::OnIOComplete"));
135 int rv
= DoLoop(result
);
136 if (rv
!= ERR_IO_PENDING
) {
137 NotifyProxyDelegateOfCompletion(rv
);
138 NotifyDelegateOfCompletion(rv
); // Deletes |this|
142 int HttpProxyConnectJob::DoLoop(int result
) {
143 DCHECK_NE(next_state_
, STATE_NONE
);
147 State state
= next_state_
;
148 next_state_
= STATE_NONE
;
150 case STATE_TCP_CONNECT
:
152 rv
= DoTransportConnect();
154 case STATE_TCP_CONNECT_COMPLETE
:
155 rv
= DoTransportConnectComplete(rv
);
157 case STATE_SSL_CONNECT
:
161 case STATE_SSL_CONNECT_COMPLETE
:
162 rv
= DoSSLConnectComplete(rv
);
164 case STATE_HTTP_PROXY_CONNECT
:
166 rv
= DoHttpProxyConnect();
168 case STATE_HTTP_PROXY_CONNECT_COMPLETE
:
169 rv
= DoHttpProxyConnectComplete(rv
);
171 case STATE_SPDY_PROXY_CREATE_STREAM
:
173 rv
= DoSpdyProxyCreateStream();
175 case STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE
:
176 rv
= DoSpdyProxyCreateStreamComplete(rv
);
179 NOTREACHED() << "bad state";
183 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
188 int HttpProxyConnectJob::DoTransportConnect() {
189 next_state_
= STATE_TCP_CONNECT_COMPLETE
;
190 transport_socket_handle_
.reset(new ClientSocketHandle());
191 return transport_socket_handle_
->Init(group_name(),
192 params_
->transport_params(),
199 int HttpProxyConnectJob::DoTransportConnectComplete(int result
) {
201 return ERR_PROXY_CONNECTION_FAILED
;
203 // Reset the timer to just the length of time allowed for HttpProxy handshake
204 // so that a fast TCP connection plus a slow HttpProxy failure doesn't take
205 // longer to timeout than it should.
206 ResetTimer(base::TimeDelta::FromSeconds(
207 kHttpProxyConnectJobTimeoutInSeconds
));
209 next_state_
= STATE_HTTP_PROXY_CONNECT
;
213 int HttpProxyConnectJob::DoSSLConnect() {
214 if (params_
->tunnel()) {
215 SpdySessionKey
key(params_
->destination().host_port_pair(),
216 ProxyServer::Direct(),
217 PRIVACY_MODE_DISABLED
);
218 if (params_
->spdy_session_pool()->FindAvailableSession(key
, net_log())) {
220 next_state_
= STATE_SPDY_PROXY_CREATE_STREAM
;
224 next_state_
= STATE_SSL_CONNECT_COMPLETE
;
225 transport_socket_handle_
.reset(new ClientSocketHandle());
226 return transport_socket_handle_
->Init(
227 group_name(), params_
->ssl_params(), priority(), callback_
,
228 ssl_pool_
, net_log());
231 int HttpProxyConnectJob::DoSSLConnectComplete(int result
) {
232 if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
233 error_response_info_
= transport_socket_handle_
->ssl_error_response_info();
234 DCHECK(error_response_info_
.cert_request_info
.get());
235 error_response_info_
.cert_request_info
->is_proxy
= true;
238 if (IsCertificateError(result
)) {
239 if (params_
->ssl_params()->load_flags() & LOAD_IGNORE_ALL_CERT_ERRORS
) {
242 // TODO(rch): allow the user to deal with proxy cert errors in the
243 // same way as server cert errors.
244 transport_socket_handle_
->socket()->Disconnect();
245 return ERR_PROXY_CERTIFICATE_INVALID
;
248 // A SPDY session to the proxy completed prior to resolving the proxy
249 // hostname. Surface this error, and allow the delegate to retry.
250 // See crbug.com/334413.
251 if (result
== ERR_SPDY_SESSION_ALREADY_EXISTS
) {
252 DCHECK(!transport_socket_handle_
->socket());
253 return ERR_SPDY_SESSION_ALREADY_EXISTS
;
256 if (transport_socket_handle_
->socket())
257 transport_socket_handle_
->socket()->Disconnect();
258 return ERR_PROXY_CONNECTION_FAILED
;
261 SSLClientSocket
* ssl
=
262 static_cast<SSLClientSocket
*>(transport_socket_handle_
->socket());
263 using_spdy_
= ssl
->was_spdy_negotiated();
264 protocol_negotiated_
= ssl
->GetNegotiatedProtocol();
266 // Reset the timer to just the length of time allowed for HttpProxy handshake
267 // so that a fast SSL connection plus a slow HttpProxy failure doesn't take
268 // longer to timeout than it should.
269 ResetTimer(base::TimeDelta::FromSeconds(
270 kHttpProxyConnectJobTimeoutInSeconds
));
271 // TODO(rch): If we ever decide to implement a "trusted" SPDY proxy
272 // (one that we speak SPDY over SSL to, but to which we send HTTPS
273 // request directly instead of through CONNECT tunnels, then we
274 // need to add a predicate to this if statement so we fall through
275 // to the else case. (HttpProxyClientSocket currently acts as
276 // a "trusted" SPDY proxy).
277 if (using_spdy_
&& params_
->tunnel()) {
278 next_state_
= STATE_SPDY_PROXY_CREATE_STREAM
;
280 next_state_
= STATE_HTTP_PROXY_CONNECT
;
285 int HttpProxyConnectJob::DoHttpProxyConnect() {
286 next_state_
= STATE_HTTP_PROXY_CONNECT_COMPLETE
;
287 const HostResolver::RequestInfo
& tcp_destination
= params_
->destination();
288 const HostPortPair
& proxy_server
= tcp_destination
.host_port_pair();
290 // Add a HttpProxy connection on top of the tcp socket.
291 transport_socket_
.reset(
292 new HttpProxyClientSocket(transport_socket_handle_
.release(),
293 params_
->request_url(),
294 params_
->user_agent(),
297 params_
->http_auth_cache(),
298 params_
->http_auth_handler_factory(),
301 protocol_negotiated_
,
302 params_
->proxy_delegate(),
303 params_
->ssl_params().get() != NULL
));
304 return transport_socket_
->Connect(callback_
);
307 int HttpProxyConnectJob::DoHttpProxyConnectComplete(int result
) {
308 if (result
== OK
|| result
== ERR_PROXY_AUTH_REQUESTED
||
309 result
== ERR_HTTPS_PROXY_TUNNEL_RESPONSE
) {
310 SetSocket(transport_socket_
.Pass());
313 if (result
== ERR_HTTP_1_1_REQUIRED
)
314 return ERR_PROXY_HTTP_1_1_REQUIRED
;
319 int HttpProxyConnectJob::DoSpdyProxyCreateStream() {
321 DCHECK(params_
->tunnel());
322 SpdySessionKey
key(params_
->destination().host_port_pair(),
323 ProxyServer::Direct(),
324 PRIVACY_MODE_DISABLED
);
325 SpdySessionPool
* spdy_pool
= params_
->spdy_session_pool();
326 base::WeakPtr
<SpdySession
> spdy_session
=
327 spdy_pool
->FindAvailableSession(key
, net_log());
328 // It's possible that a session to the proxy has recently been created
330 if (transport_socket_handle_
.get()) {
331 if (transport_socket_handle_
->socket())
332 transport_socket_handle_
->socket()->Disconnect();
333 transport_socket_handle_
->Reset();
336 // Create a session direct to the proxy itself
338 spdy_pool
->CreateAvailableSessionFromSocket(
339 key
, transport_socket_handle_
.Pass(),
340 net_log(), OK
, /*using_ssl_*/ true);
341 DCHECK(spdy_session
);
344 next_state_
= STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE
;
345 return spdy_stream_request_
.StartRequest(SPDY_BIDIRECTIONAL_STREAM
,
347 params_
->request_url(),
349 spdy_session
->net_log(),
353 int HttpProxyConnectJob::DoSpdyProxyCreateStreamComplete(int result
) {
357 next_state_
= STATE_HTTP_PROXY_CONNECT_COMPLETE
;
358 base::WeakPtr
<SpdyStream
> stream
= spdy_stream_request_
.ReleaseStream();
359 DCHECK(stream
.get());
360 // |transport_socket_| will set itself as |stream|'s delegate.
361 transport_socket_
.reset(
362 new SpdyProxyClientSocket(stream
,
363 params_
->user_agent(),
365 params_
->request_url(),
366 params_
->destination().host_port_pair(),
368 params_
->http_auth_cache(),
369 params_
->http_auth_handler_factory()));
370 return transport_socket_
->Connect(callback_
);
373 void HttpProxyConnectJob::NotifyProxyDelegateOfCompletion(int result
) {
374 if (!params_
->proxy_delegate())
377 const HostPortPair
& proxy_server
= params_
->destination().host_port_pair();
378 params_
->proxy_delegate()->OnTunnelConnectCompleted(params_
->endpoint(),
383 int HttpProxyConnectJob::ConnectInternal() {
384 if (params_
->transport_params().get()) {
385 next_state_
= STATE_TCP_CONNECT
;
387 next_state_
= STATE_SSL_CONNECT
;
391 if (rv
!= ERR_IO_PENDING
) {
392 NotifyProxyDelegateOfCompletion(rv
);
398 HttpProxyClientSocketPool::
399 HttpProxyConnectJobFactory::HttpProxyConnectJobFactory(
400 TransportClientSocketPool
* transport_pool
,
401 SSLClientSocketPool
* ssl_pool
,
403 : transport_pool_(transport_pool
),
406 base::TimeDelta max_pool_timeout
= base::TimeDelta();
408 // TODO(kundaji): Proxy connect timeout should be independent of platform and be
409 // based on proxy. Bug http://crbug.com/407446.
410 #if (defined(OS_ANDROID) || defined(OS_IOS))
413 max_pool_timeout
= transport_pool_
->ConnectionTimeout();
415 max_pool_timeout
= std::max(max_pool_timeout
,
416 ssl_pool_
->ConnectionTimeout());
418 timeout_
= max_pool_timeout
+
419 base::TimeDelta::FromSeconds(kHttpProxyConnectJobTimeoutInSeconds
);
423 scoped_ptr
<ConnectJob
>
424 HttpProxyClientSocketPool::HttpProxyConnectJobFactory::NewConnectJob(
425 const std::string
& group_name
,
426 const PoolBase::Request
& request
,
427 ConnectJob::Delegate
* delegate
) const {
428 return scoped_ptr
<ConnectJob
>(new HttpProxyConnectJob(group_name
,
439 HttpProxyClientSocketPool::HttpProxyConnectJobFactory::ConnectionTimeout(
444 HttpProxyClientSocketPool::HttpProxyClientSocketPool(
446 int max_sockets_per_group
,
447 ClientSocketPoolHistograms
* histograms
,
448 TransportClientSocketPool
* transport_pool
,
449 SSLClientSocketPool
* ssl_pool
,
451 : transport_pool_(transport_pool
),
453 base_(this, max_sockets
, max_sockets_per_group
, histograms
,
454 ClientSocketPool::unused_idle_socket_timeout(),
455 ClientSocketPool::used_idle_socket_timeout(),
456 new HttpProxyConnectJobFactory(transport_pool
,
459 // We should always have a |transport_pool_| except in unit tests.
461 base_
.AddLowerLayeredPool(transport_pool_
);
463 base_
.AddLowerLayeredPool(ssl_pool_
);
466 HttpProxyClientSocketPool::~HttpProxyClientSocketPool() {
469 int HttpProxyClientSocketPool::RequestSocket(
470 const std::string
& group_name
, const void* socket_params
,
471 RequestPriority priority
, ClientSocketHandle
* handle
,
472 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
473 const scoped_refptr
<HttpProxySocketParams
>* casted_socket_params
=
474 static_cast<const scoped_refptr
<HttpProxySocketParams
>*>(socket_params
);
476 return base_
.RequestSocket(group_name
, *casted_socket_params
, priority
,
477 handle
, callback
, net_log
);
480 void HttpProxyClientSocketPool::RequestSockets(
481 const std::string
& group_name
,
484 const BoundNetLog
& net_log
) {
485 const scoped_refptr
<HttpProxySocketParams
>* casted_params
=
486 static_cast<const scoped_refptr
<HttpProxySocketParams
>*>(params
);
488 base_
.RequestSockets(group_name
, *casted_params
, num_sockets
, net_log
);
491 void HttpProxyClientSocketPool::CancelRequest(
492 const std::string
& group_name
,
493 ClientSocketHandle
* handle
) {
494 base_
.CancelRequest(group_name
, handle
);
497 void HttpProxyClientSocketPool::ReleaseSocket(const std::string
& group_name
,
498 scoped_ptr
<StreamSocket
> socket
,
500 base_
.ReleaseSocket(group_name
, socket
.Pass(), id
);
503 void HttpProxyClientSocketPool::FlushWithError(int error
) {
504 base_
.FlushWithError(error
);
507 void HttpProxyClientSocketPool::CloseIdleSockets() {
508 base_
.CloseIdleSockets();
511 int HttpProxyClientSocketPool::IdleSocketCount() const {
512 return base_
.idle_socket_count();
515 int HttpProxyClientSocketPool::IdleSocketCountInGroup(
516 const std::string
& group_name
) const {
517 return base_
.IdleSocketCountInGroup(group_name
);
520 LoadState
HttpProxyClientSocketPool::GetLoadState(
521 const std::string
& group_name
, const ClientSocketHandle
* handle
) const {
522 return base_
.GetLoadState(group_name
, handle
);
525 base::DictionaryValue
* HttpProxyClientSocketPool::GetInfoAsValue(
526 const std::string
& name
,
527 const std::string
& type
,
528 bool include_nested_pools
) const {
529 base::DictionaryValue
* dict
= base_
.GetInfoAsValue(name
, type
);
530 if (include_nested_pools
) {
531 base::ListValue
* list
= new base::ListValue();
532 if (transport_pool_
) {
533 list
->Append(transport_pool_
->GetInfoAsValue("transport_socket_pool",
534 "transport_socket_pool",
538 list
->Append(ssl_pool_
->GetInfoAsValue("ssl_socket_pool",
542 dict
->Set("nested_pools", list
);
547 base::TimeDelta
HttpProxyClientSocketPool::ConnectionTimeout() const {
548 return base_
.ConnectionTimeout();
551 ClientSocketPoolHistograms
* HttpProxyClientSocketPool::histograms() const {
552 return base_
.histograms();
555 bool HttpProxyClientSocketPool::IsStalled() const {
556 return base_
.IsStalled();
559 void HttpProxyClientSocketPool::AddHigherLayeredPool(
560 HigherLayeredPool
* higher_pool
) {
561 base_
.AddHigherLayeredPool(higher_pool
);
564 void HttpProxyClientSocketPool::RemoveHigherLayeredPool(
565 HigherLayeredPool
* higher_pool
) {
566 base_
.RemoveHigherLayeredPool(higher_pool
);
569 bool HttpProxyClientSocketPool::CloseOneIdleConnection() {
570 if (base_
.CloseOneIdleSocket())
572 return base_
.CloseOneIdleConnectionInHigherLayeredPool();