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/http/http_network_session.h"
15 #include "net/http/http_proxy_client_socket.h"
16 #include "net/socket/client_socket_factory.h"
17 #include "net/socket/client_socket_handle.h"
18 #include "net/socket/client_socket_pool_base.h"
19 #include "net/socket/ssl_client_socket.h"
20 #include "net/socket/ssl_client_socket_pool.h"
21 #include "net/socket/transport_client_socket_pool.h"
22 #include "net/spdy/spdy_proxy_client_socket.h"
23 #include "net/spdy/spdy_session.h"
24 #include "net/spdy/spdy_session_pool.h"
25 #include "net/spdy/spdy_stream.h"
26 #include "net/ssl/ssl_cert_request_info.h"
31 HttpProxySocketParams::HttpProxySocketParams(
32 const scoped_refptr
<TransportSocketParams
>& transport_params
,
33 const scoped_refptr
<SSLSocketParams
>& ssl_params
,
34 const GURL
& request_url
,
35 const std::string
& user_agent
,
36 const HostPortPair
& endpoint
,
37 HttpAuthCache
* http_auth_cache
,
38 HttpAuthHandlerFactory
* http_auth_handler_factory
,
39 SpdySessionPool
* spdy_session_pool
,
41 ProxyDelegate
* proxy_delegate
)
42 : transport_params_(transport_params
),
43 ssl_params_(ssl_params
),
44 spdy_session_pool_(spdy_session_pool
),
45 request_url_(request_url
),
46 user_agent_(user_agent
),
48 http_auth_cache_(tunnel
? http_auth_cache
: NULL
),
49 http_auth_handler_factory_(tunnel
? http_auth_handler_factory
: NULL
),
51 proxy_delegate_(proxy_delegate
) {
52 DCHECK((transport_params
.get() == NULL
&& ssl_params
.get() != NULL
) ||
53 (transport_params
.get() != NULL
&& ssl_params
.get() == NULL
));
54 if (transport_params_
.get()) {
55 ignore_limits_
= transport_params
->ignore_limits();
57 ignore_limits_
= ssl_params
->ignore_limits();
61 const HostResolver::RequestInfo
& HttpProxySocketParams::destination() const {
62 if (transport_params_
.get() == NULL
) {
63 return ssl_params_
->GetDirectConnectionParams()->destination();
65 return transport_params_
->destination();
69 HttpProxySocketParams::~HttpProxySocketParams() {}
71 // HttpProxyConnectJobs will time out after this many seconds. Note this is on
72 // top of the timeout for the transport socket.
73 // TODO(kundaji): Proxy connect timeout should be independent of platform and be
74 // based on proxy. Bug http://crbug.com/407446.
75 #if defined(OS_ANDROID) || defined(OS_IOS)
76 static const int kHttpProxyConnectJobTimeoutInSeconds
= 10;
78 static const int kHttpProxyConnectJobTimeoutInSeconds
= 30;
81 HttpProxyConnectJob::HttpProxyConnectJob(
82 const std::string
& group_name
,
83 RequestPriority priority
,
84 const scoped_refptr
<HttpProxySocketParams
>& params
,
85 const base::TimeDelta
& timeout_duration
,
86 TransportClientSocketPool
* transport_pool
,
87 SSLClientSocketPool
* ssl_pool
,
88 HostResolver
* host_resolver
,
91 : ConnectJob(group_name
, timeout_duration
, priority
, delegate
,
92 BoundNetLog::Make(net_log
, NetLog::SOURCE_CONNECT_JOB
)),
94 transport_pool_(transport_pool
),
96 resolver_(host_resolver
),
98 protocol_negotiated_(kProtoUnknown
),
99 weak_ptr_factory_(this) {
100 callback_
= base::Bind(&HttpProxyConnectJob::OnIOComplete
,
101 weak_ptr_factory_
.GetWeakPtr());
104 HttpProxyConnectJob::~HttpProxyConnectJob() {}
106 LoadState
HttpProxyConnectJob::GetLoadState() const {
107 switch (next_state_
) {
108 case STATE_TCP_CONNECT
:
109 case STATE_TCP_CONNECT_COMPLETE
:
110 case STATE_SSL_CONNECT
:
111 case STATE_SSL_CONNECT_COMPLETE
:
112 return transport_socket_handle_
->GetLoadState();
113 case STATE_HTTP_PROXY_CONNECT
:
114 case STATE_HTTP_PROXY_CONNECT_COMPLETE
:
115 case STATE_SPDY_PROXY_CREATE_STREAM
:
116 case STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE
:
117 return LOAD_STATE_ESTABLISHING_PROXY_TUNNEL
;
120 return LOAD_STATE_IDLE
;
124 void HttpProxyConnectJob::GetAdditionalErrorState(ClientSocketHandle
* handle
) {
125 if (error_response_info_
.cert_request_info
.get()) {
126 handle
->set_ssl_error_response_info(error_response_info_
);
127 handle
->set_is_ssl_error(true);
131 void HttpProxyConnectJob::OnIOComplete(int result
) {
132 int rv
= DoLoop(result
);
133 if (rv
!= ERR_IO_PENDING
)
134 NotifyDelegateOfCompletion(rv
); // Deletes |this|
137 int HttpProxyConnectJob::DoLoop(int result
) {
138 DCHECK_NE(next_state_
, STATE_NONE
);
142 State state
= next_state_
;
143 next_state_
= STATE_NONE
;
145 case STATE_TCP_CONNECT
:
147 rv
= DoTransportConnect();
149 case STATE_TCP_CONNECT_COMPLETE
:
150 rv
= DoTransportConnectComplete(rv
);
152 case STATE_SSL_CONNECT
:
156 case STATE_SSL_CONNECT_COMPLETE
:
157 rv
= DoSSLConnectComplete(rv
);
159 case STATE_HTTP_PROXY_CONNECT
:
161 rv
= DoHttpProxyConnect();
163 case STATE_HTTP_PROXY_CONNECT_COMPLETE
:
164 rv
= DoHttpProxyConnectComplete(rv
);
166 case STATE_SPDY_PROXY_CREATE_STREAM
:
168 rv
= DoSpdyProxyCreateStream();
170 case STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE
:
171 rv
= DoSpdyProxyCreateStreamComplete(rv
);
174 NOTREACHED() << "bad state";
178 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
183 int HttpProxyConnectJob::DoTransportConnect() {
184 next_state_
= STATE_TCP_CONNECT_COMPLETE
;
185 transport_socket_handle_
.reset(new ClientSocketHandle());
186 return transport_socket_handle_
->Init(group_name(),
187 params_
->transport_params(),
194 int HttpProxyConnectJob::DoTransportConnectComplete(int result
) {
196 return ERR_PROXY_CONNECTION_FAILED
;
198 // Reset the timer to just the length of time allowed for HttpProxy handshake
199 // so that a fast TCP connection plus a slow HttpProxy failure doesn't take
200 // longer to timeout than it should.
201 ResetTimer(base::TimeDelta::FromSeconds(
202 kHttpProxyConnectJobTimeoutInSeconds
));
204 next_state_
= STATE_HTTP_PROXY_CONNECT
;
208 int HttpProxyConnectJob::DoSSLConnect() {
209 if (params_
->tunnel()) {
210 SpdySessionKey
key(params_
->destination().host_port_pair(),
211 ProxyServer::Direct(),
212 PRIVACY_MODE_DISABLED
);
213 if (params_
->spdy_session_pool()->FindAvailableSession(key
, net_log())) {
215 next_state_
= STATE_SPDY_PROXY_CREATE_STREAM
;
219 next_state_
= STATE_SSL_CONNECT_COMPLETE
;
220 transport_socket_handle_
.reset(new ClientSocketHandle());
221 return transport_socket_handle_
->Init(
222 group_name(), params_
->ssl_params(), priority(), callback_
,
223 ssl_pool_
, net_log());
226 int HttpProxyConnectJob::DoSSLConnectComplete(int result
) {
227 if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
228 error_response_info_
= transport_socket_handle_
->ssl_error_response_info();
229 DCHECK(error_response_info_
.cert_request_info
.get());
230 error_response_info_
.cert_request_info
->is_proxy
= true;
233 if (IsCertificateError(result
)) {
234 if (params_
->ssl_params()->load_flags() & LOAD_IGNORE_ALL_CERT_ERRORS
) {
237 // TODO(rch): allow the user to deal with proxy cert errors in the
238 // same way as server cert errors.
239 transport_socket_handle_
->socket()->Disconnect();
240 return ERR_PROXY_CERTIFICATE_INVALID
;
243 // A SPDY session to the proxy completed prior to resolving the proxy
244 // hostname. Surface this error, and allow the delegate to retry.
245 // See crbug.com/334413.
246 if (result
== ERR_SPDY_SESSION_ALREADY_EXISTS
) {
247 DCHECK(!transport_socket_handle_
->socket());
248 return ERR_SPDY_SESSION_ALREADY_EXISTS
;
251 if (transport_socket_handle_
->socket())
252 transport_socket_handle_
->socket()->Disconnect();
253 return ERR_PROXY_CONNECTION_FAILED
;
256 SSLClientSocket
* ssl
=
257 static_cast<SSLClientSocket
*>(transport_socket_handle_
->socket());
258 using_spdy_
= ssl
->was_spdy_negotiated();
259 protocol_negotiated_
= ssl
->GetNegotiatedProtocol();
261 // Reset the timer to just the length of time allowed for HttpProxy handshake
262 // so that a fast SSL connection plus a slow HttpProxy failure doesn't take
263 // longer to timeout than it should.
264 ResetTimer(base::TimeDelta::FromSeconds(
265 kHttpProxyConnectJobTimeoutInSeconds
));
266 // TODO(rch): If we ever decide to implement a "trusted" SPDY proxy
267 // (one that we speak SPDY over SSL to, but to which we send HTTPS
268 // request directly instead of through CONNECT tunnels, then we
269 // need to add a predicate to this if statement so we fall through
270 // to the else case. (HttpProxyClientSocket currently acts as
271 // a "trusted" SPDY proxy).
272 if (using_spdy_
&& params_
->tunnel()) {
273 next_state_
= STATE_SPDY_PROXY_CREATE_STREAM
;
275 next_state_
= STATE_HTTP_PROXY_CONNECT
;
280 int HttpProxyConnectJob::DoHttpProxyConnect() {
281 next_state_
= STATE_HTTP_PROXY_CONNECT_COMPLETE
;
282 const HostResolver::RequestInfo
& tcp_destination
= params_
->destination();
283 const HostPortPair
& proxy_server
= tcp_destination
.host_port_pair();
285 // Add a HttpProxy connection on top of the tcp socket.
286 transport_socket_
.reset(
287 new HttpProxyClientSocket(transport_socket_handle_
.release(),
288 params_
->request_url(),
289 params_
->user_agent(),
292 params_
->http_auth_cache(),
293 params_
->http_auth_handler_factory(),
296 protocol_negotiated_
,
297 params_
->proxy_delegate(),
298 params_
->ssl_params().get() != NULL
));
299 return transport_socket_
->Connect(callback_
);
302 int HttpProxyConnectJob::DoHttpProxyConnectComplete(int result
) {
303 if (result
== OK
|| result
== ERR_PROXY_AUTH_REQUESTED
||
304 result
== ERR_HTTPS_PROXY_TUNNEL_RESPONSE
) {
305 SetSocket(transport_socket_
.Pass());
311 int HttpProxyConnectJob::DoSpdyProxyCreateStream() {
313 DCHECK(params_
->tunnel());
314 SpdySessionKey
key(params_
->destination().host_port_pair(),
315 ProxyServer::Direct(),
316 PRIVACY_MODE_DISABLED
);
317 SpdySessionPool
* spdy_pool
= params_
->spdy_session_pool();
318 base::WeakPtr
<SpdySession
> spdy_session
=
319 spdy_pool
->FindAvailableSession(key
, net_log());
320 // It's possible that a session to the proxy has recently been created
322 if (transport_socket_handle_
.get()) {
323 if (transport_socket_handle_
->socket())
324 transport_socket_handle_
->socket()->Disconnect();
325 transport_socket_handle_
->Reset();
328 // Create a session direct to the proxy itself
330 spdy_pool
->CreateAvailableSessionFromSocket(
331 key
, transport_socket_handle_
.Pass(),
332 net_log(), OK
, /*using_ssl_*/ true);
333 DCHECK(spdy_session
);
336 next_state_
= STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE
;
337 return spdy_stream_request_
.StartRequest(SPDY_BIDIRECTIONAL_STREAM
,
339 params_
->request_url(),
341 spdy_session
->net_log(),
345 int HttpProxyConnectJob::DoSpdyProxyCreateStreamComplete(int result
) {
349 next_state_
= STATE_HTTP_PROXY_CONNECT_COMPLETE
;
350 base::WeakPtr
<SpdyStream
> stream
= spdy_stream_request_
.ReleaseStream();
351 DCHECK(stream
.get());
352 // |transport_socket_| will set itself as |stream|'s delegate.
353 transport_socket_
.reset(
354 new SpdyProxyClientSocket(stream
,
355 params_
->user_agent(),
357 params_
->request_url(),
358 params_
->destination().host_port_pair(),
360 params_
->http_auth_cache(),
361 params_
->http_auth_handler_factory()));
362 return transport_socket_
->Connect(callback_
);
365 int HttpProxyConnectJob::ConnectInternal() {
366 if (params_
->transport_params().get()) {
367 next_state_
= STATE_TCP_CONNECT
;
369 next_state_
= STATE_SSL_CONNECT
;
374 HttpProxyClientSocketPool::
375 HttpProxyConnectJobFactory::HttpProxyConnectJobFactory(
376 TransportClientSocketPool
* transport_pool
,
377 SSLClientSocketPool
* ssl_pool
,
378 HostResolver
* host_resolver
,
379 const ProxyDelegate
* proxy_delegate
,
381 : transport_pool_(transport_pool
),
383 host_resolver_(host_resolver
),
384 proxy_delegate_(proxy_delegate
),
386 base::TimeDelta max_pool_timeout
= base::TimeDelta();
388 // TODO(kundaji): Proxy connect timeout should be independent of platform and be
389 // based on proxy. Bug http://crbug.com/407446.
390 #if (defined(OS_ANDROID) || defined(OS_IOS))
393 max_pool_timeout
= transport_pool_
->ConnectionTimeout();
395 max_pool_timeout
= std::max(max_pool_timeout
,
396 ssl_pool_
->ConnectionTimeout());
398 timeout_
= max_pool_timeout
+
399 base::TimeDelta::FromSeconds(kHttpProxyConnectJobTimeoutInSeconds
);
403 scoped_ptr
<ConnectJob
>
404 HttpProxyClientSocketPool::HttpProxyConnectJobFactory::NewConnectJob(
405 const std::string
& group_name
,
406 const PoolBase::Request
& request
,
407 ConnectJob::Delegate
* delegate
) const {
408 return scoped_ptr
<ConnectJob
>(new HttpProxyConnectJob(group_name
,
420 HttpProxyClientSocketPool::HttpProxyConnectJobFactory::ConnectionTimeout(
425 HttpProxyClientSocketPool::HttpProxyClientSocketPool(
427 int max_sockets_per_group
,
428 ClientSocketPoolHistograms
* histograms
,
429 HostResolver
* host_resolver
,
430 TransportClientSocketPool
* transport_pool
,
431 SSLClientSocketPool
* ssl_pool
,
432 const ProxyDelegate
* proxy_delegate
,
434 : transport_pool_(transport_pool
),
436 base_(this, max_sockets
, max_sockets_per_group
, histograms
,
437 ClientSocketPool::unused_idle_socket_timeout(),
438 ClientSocketPool::used_idle_socket_timeout(),
439 new HttpProxyConnectJobFactory(transport_pool
,
444 // We should always have a |transport_pool_| except in unit tests.
446 base_
.AddLowerLayeredPool(transport_pool_
);
448 base_
.AddLowerLayeredPool(ssl_pool_
);
451 HttpProxyClientSocketPool::~HttpProxyClientSocketPool() {
454 int HttpProxyClientSocketPool::RequestSocket(
455 const std::string
& group_name
, const void* socket_params
,
456 RequestPriority priority
, ClientSocketHandle
* handle
,
457 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
458 const scoped_refptr
<HttpProxySocketParams
>* casted_socket_params
=
459 static_cast<const scoped_refptr
<HttpProxySocketParams
>*>(socket_params
);
461 return base_
.RequestSocket(group_name
, *casted_socket_params
, priority
,
462 handle
, callback
, net_log
);
465 void HttpProxyClientSocketPool::RequestSockets(
466 const std::string
& group_name
,
469 const BoundNetLog
& net_log
) {
470 const scoped_refptr
<HttpProxySocketParams
>* casted_params
=
471 static_cast<const scoped_refptr
<HttpProxySocketParams
>*>(params
);
473 base_
.RequestSockets(group_name
, *casted_params
, num_sockets
, net_log
);
476 void HttpProxyClientSocketPool::CancelRequest(
477 const std::string
& group_name
,
478 ClientSocketHandle
* handle
) {
479 base_
.CancelRequest(group_name
, handle
);
482 void HttpProxyClientSocketPool::ReleaseSocket(const std::string
& group_name
,
483 scoped_ptr
<StreamSocket
> socket
,
485 base_
.ReleaseSocket(group_name
, socket
.Pass(), id
);
488 void HttpProxyClientSocketPool::FlushWithError(int error
) {
489 base_
.FlushWithError(error
);
492 void HttpProxyClientSocketPool::CloseIdleSockets() {
493 base_
.CloseIdleSockets();
496 int HttpProxyClientSocketPool::IdleSocketCount() const {
497 return base_
.idle_socket_count();
500 int HttpProxyClientSocketPool::IdleSocketCountInGroup(
501 const std::string
& group_name
) const {
502 return base_
.IdleSocketCountInGroup(group_name
);
505 LoadState
HttpProxyClientSocketPool::GetLoadState(
506 const std::string
& group_name
, const ClientSocketHandle
* handle
) const {
507 return base_
.GetLoadState(group_name
, handle
);
510 base::DictionaryValue
* HttpProxyClientSocketPool::GetInfoAsValue(
511 const std::string
& name
,
512 const std::string
& type
,
513 bool include_nested_pools
) const {
514 base::DictionaryValue
* dict
= base_
.GetInfoAsValue(name
, type
);
515 if (include_nested_pools
) {
516 base::ListValue
* list
= new base::ListValue();
517 if (transport_pool_
) {
518 list
->Append(transport_pool_
->GetInfoAsValue("transport_socket_pool",
519 "transport_socket_pool",
523 list
->Append(ssl_pool_
->GetInfoAsValue("ssl_socket_pool",
527 dict
->Set("nested_pools", list
);
532 base::TimeDelta
HttpProxyClientSocketPool::ConnectionTimeout() const {
533 return base_
.ConnectionTimeout();
536 ClientSocketPoolHistograms
* HttpProxyClientSocketPool::histograms() const {
537 return base_
.histograms();
540 bool HttpProxyClientSocketPool::IsStalled() const {
541 return base_
.IsStalled();
544 void HttpProxyClientSocketPool::AddHigherLayeredPool(
545 HigherLayeredPool
* higher_pool
) {
546 base_
.AddHigherLayeredPool(higher_pool
);
549 void HttpProxyClientSocketPool::RemoveHigherLayeredPool(
550 HigherLayeredPool
* higher_pool
) {
551 base_
.RemoveHigherLayeredPool(higher_pool
);
554 bool HttpProxyClientSocketPool::CloseOneIdleConnection() {
555 if (base_
.CloseOneIdleSocket())
557 return base_
.CloseOneIdleConnectionInHigherLayeredPool();