1 // Copyright 2014 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/socket/websocket_transport_client_socket_pool.h"
9 #include "base/compiler_specific.h"
10 #include "base/logging.h"
11 #include "base/numerics/safe_conversions.h"
12 #include "base/profiler/scoped_tracker.h"
13 #include "base/strings/string_util.h"
14 #include "base/time/time.h"
15 #include "base/values.h"
16 #include "net/base/net_errors.h"
17 #include "net/log/net_log.h"
18 #include "net/socket/client_socket_handle.h"
19 #include "net/socket/client_socket_pool_base.h"
20 #include "net/socket/websocket_endpoint_lock_manager.h"
21 #include "net/socket/websocket_transport_connect_sub_job.h"
27 using base::TimeDelta
;
29 // TODO(ricea): For now, we implement a global timeout for compatability with
30 // TransportConnectJob. Since WebSocketTransportConnectJob controls the address
31 // selection process more tightly, it could do something smarter here.
32 const int kTransportConnectJobTimeoutInSeconds
= 240; // 4 minutes.
36 WebSocketTransportConnectJob::WebSocketTransportConnectJob(
37 const std::string
& group_name
,
38 RequestPriority priority
,
39 const scoped_refptr
<TransportSocketParams
>& params
,
40 TimeDelta timeout_duration
,
41 const CompletionCallback
& callback
,
42 ClientSocketFactory
* client_socket_factory
,
43 HostResolver
* host_resolver
,
44 ClientSocketHandle
* handle
,
47 const BoundNetLog
& request_net_log
)
48 : ConnectJob(group_name
,
52 BoundNetLog::Make(pool_net_log
, NetLog::SOURCE_CONNECT_JOB
)),
53 helper_(params
, client_socket_factory
, host_resolver
, &connect_timing_
),
54 race_result_(TransportConnectJobHelper::CONNECTION_LATENCY_UNKNOWN
),
57 request_net_log_(request_net_log
),
60 helper_
.SetOnIOComplete(this);
63 WebSocketTransportConnectJob::~WebSocketTransportConnectJob() {}
65 LoadState
WebSocketTransportConnectJob::GetLoadState() const {
66 LoadState load_state
= LOAD_STATE_RESOLVING_HOST
;
68 load_state
= ipv6_job_
->GetLoadState();
69 // This method should return LOAD_STATE_CONNECTING in preference to
70 // LOAD_STATE_WAITING_FOR_AVAILABLE_SOCKET when possible because "waiting for
71 // available socket" implies that nothing is happening.
72 if (ipv4_job_
&& load_state
!= LOAD_STATE_CONNECTING
)
73 load_state
= ipv4_job_
->GetLoadState();
77 int WebSocketTransportConnectJob::DoResolveHost() {
78 return helper_
.DoResolveHost(priority(), net_log());
81 int WebSocketTransportConnectJob::DoResolveHostComplete(int result
) {
82 return helper_
.DoResolveHostComplete(result
, net_log());
85 int WebSocketTransportConnectJob::DoTransportConnect() {
86 AddressList ipv4_addresses
;
87 AddressList ipv6_addresses
;
88 int result
= ERR_UNEXPECTED
;
89 helper_
.set_next_state(
90 TransportConnectJobHelper::STATE_TRANSPORT_CONNECT_COMPLETE
);
92 for (AddressList::const_iterator it
= helper_
.addresses().begin();
93 it
!= helper_
.addresses().end();
95 switch (it
->GetFamily()) {
96 case ADDRESS_FAMILY_IPV4
:
97 ipv4_addresses
.push_back(*it
);
100 case ADDRESS_FAMILY_IPV6
:
101 ipv6_addresses
.push_back(*it
);
105 DVLOG(1) << "Unexpected ADDRESS_FAMILY: " << it
->GetFamily();
110 if (!ipv4_addresses
.empty()) {
112 ipv4_job_
.reset(new WebSocketTransportConnectSubJob(
113 ipv4_addresses
, this, SUB_JOB_IPV4
));
116 if (!ipv6_addresses
.empty()) {
118 ipv6_job_
.reset(new WebSocketTransportConnectSubJob(
119 ipv6_addresses
, this, SUB_JOB_IPV6
));
120 result
= ipv6_job_
->Start();
123 SetSocket(ipv6_job_
->PassSocket());
126 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_RACEABLE
127 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_SOLO
;
132 // This use of base::Unretained is safe because |fallback_timer_| is
133 // owned by this object.
134 fallback_timer_
.Start(
136 TimeDelta::FromMilliseconds(
137 TransportConnectJobHelper::kIPv6FallbackTimerInMs
),
138 base::Bind(&WebSocketTransportConnectJob::StartIPv4JobAsync
,
139 base::Unretained(this)));
150 result
= ipv4_job_
->Start();
152 SetSocket(ipv4_job_
->PassSocket());
155 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_WINS_RACE
156 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_NO_RACE
;
163 int WebSocketTransportConnectJob::DoTransportConnectComplete(int result
) {
165 helper_
.HistogramDuration(race_result_
);
169 void WebSocketTransportConnectJob::OnSubJobComplete(
171 WebSocketTransportConnectSubJob
* job
) {
173 switch (job
->type()) {
177 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_WINS_RACE
178 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_NO_RACE
;
184 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_RACEABLE
185 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_SOLO
;
188 SetSocket(job
->PassSocket());
190 // Make sure all connections are cancelled even if this object fails to be
195 switch (job
->type()) {
202 if (ipv4_job_
&& !ipv4_job_
->started()) {
203 fallback_timer_
.Stop();
204 result
= ipv4_job_
->Start();
205 if (result
!= ERR_IO_PENDING
) {
206 OnSubJobComplete(result
, ipv4_job_
.get());
212 if (ipv4_job_
|| ipv6_job_
)
215 helper_
.OnIOComplete(this, result
);
218 void WebSocketTransportConnectJob::StartIPv4JobAsync() {
220 int result
= ipv4_job_
->Start();
221 if (result
!= ERR_IO_PENDING
)
222 OnSubJobComplete(result
, ipv4_job_
.get());
225 int WebSocketTransportConnectJob::ConnectInternal() {
226 return helper_
.DoConnectInternal(this);
229 WebSocketTransportClientSocketPool::WebSocketTransportClientSocketPool(
231 int max_sockets_per_group
,
232 HostResolver
* host_resolver
,
233 ClientSocketFactory
* client_socket_factory
,
235 : TransportClientSocketPool(max_sockets
,
236 max_sockets_per_group
,
238 client_socket_factory
,
240 connect_job_delegate_(this),
241 pool_net_log_(net_log
),
242 client_socket_factory_(client_socket_factory
),
243 host_resolver_(host_resolver
),
244 max_sockets_(max_sockets
),
245 handed_out_socket_count_(0),
247 weak_factory_(this) {}
249 WebSocketTransportClientSocketPool::~WebSocketTransportClientSocketPool() {
250 // Clean up any pending connect jobs.
251 FlushWithError(ERR_ABORTED
);
252 DCHECK(pending_connects_
.empty());
253 DCHECK_EQ(0, handed_out_socket_count_
);
254 DCHECK(stalled_request_queue_
.empty());
255 DCHECK(stalled_request_map_
.empty());
259 void WebSocketTransportClientSocketPool::UnlockEndpoint(
260 ClientSocketHandle
* handle
) {
261 DCHECK(handle
->is_initialized());
262 DCHECK(handle
->socket());
264 if (handle
->socket()->GetPeerAddress(&address
) == OK
)
265 WebSocketEndpointLockManager::GetInstance()->UnlockEndpoint(address
);
268 int WebSocketTransportClientSocketPool::RequestSocket(
269 const std::string
& group_name
,
271 RequestPriority priority
,
272 ClientSocketHandle
* handle
,
273 const CompletionCallback
& callback
,
274 const BoundNetLog
& request_net_log
) {
276 const scoped_refptr
<TransportSocketParams
>& casted_params
=
277 *static_cast<const scoped_refptr
<TransportSocketParams
>*>(params
);
279 NetLogTcpClientSocketPoolRequestedSocket(request_net_log
, &casted_params
);
281 CHECK(!callback
.is_null());
284 request_net_log
.BeginEvent(NetLog::TYPE_SOCKET_POOL
);
286 if (ReachedMaxSocketsLimit() && !casted_params
->ignore_limits()) {
287 request_net_log
.AddEvent(NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS
);
288 // TODO(ricea): Use emplace_back when C++11 becomes allowed.
289 StalledRequest
request(
290 casted_params
, priority
, handle
, callback
, request_net_log
);
291 stalled_request_queue_
.push_back(request
);
292 StalledRequestQueue::iterator iterator
= stalled_request_queue_
.end();
294 DCHECK_EQ(handle
, iterator
->handle
);
295 // Because StalledRequestQueue is a std::list, its iterators are guaranteed
296 // to remain valid as long as the elements are not removed. As long as
297 // stalled_request_queue_ and stalled_request_map_ are updated in sync, it
298 // is safe to dereference an iterator in stalled_request_map_ to find the
299 // corresponding list element.
300 stalled_request_map_
.insert(
301 StalledRequestMap::value_type(handle
, iterator
));
302 return ERR_IO_PENDING
;
305 scoped_ptr
<WebSocketTransportConnectJob
> connect_job(
306 new WebSocketTransportConnectJob(group_name
,
311 client_socket_factory_
,
314 &connect_job_delegate_
,
318 int rv
= connect_job
->Connect();
319 // Regardless of the outcome of |connect_job|, it will always be bound to
320 // |handle|, since this pool uses early-binding. So the binding is logged
321 // here, without waiting for the result.
322 request_net_log
.AddEvent(
323 NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB
,
324 connect_job
->net_log().source().ToEventParametersCallback());
326 HandOutSocket(connect_job
->PassSocket(),
327 connect_job
->connect_timing(),
330 request_net_log
.EndEvent(NetLog::TYPE_SOCKET_POOL
);
331 } else if (rv
== ERR_IO_PENDING
) {
332 // TODO(ricea): Implement backup job timer?
333 AddJob(handle
, connect_job
.Pass());
335 scoped_ptr
<StreamSocket
> error_socket
;
336 connect_job
->GetAdditionalErrorState(handle
);
337 error_socket
= connect_job
->PassSocket();
339 HandOutSocket(error_socket
.Pass(),
340 connect_job
->connect_timing(),
346 if (rv
!= ERR_IO_PENDING
) {
347 request_net_log
.EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL
, rv
);
353 void WebSocketTransportClientSocketPool::RequestSockets(
354 const std::string
& group_name
,
357 const BoundNetLog
& net_log
) {
361 void WebSocketTransportClientSocketPool::CancelRequest(
362 const std::string
& group_name
,
363 ClientSocketHandle
* handle
) {
364 DCHECK(!handle
->is_initialized());
365 if (DeleteStalledRequest(handle
))
367 scoped_ptr
<StreamSocket
> socket
= handle
->PassSocket();
369 ReleaseSocket(handle
->group_name(), socket
.Pass(), handle
->id());
370 if (!DeleteJob(handle
))
371 pending_callbacks_
.erase(handle
);
372 if (!ReachedMaxSocketsLimit() && !stalled_request_queue_
.empty())
373 ActivateStalledRequest();
376 void WebSocketTransportClientSocketPool::ReleaseSocket(
377 const std::string
& group_name
,
378 scoped_ptr
<StreamSocket
> socket
,
380 WebSocketEndpointLockManager::GetInstance()->UnlockSocket(socket
.get());
381 CHECK_GT(handed_out_socket_count_
, 0);
382 --handed_out_socket_count_
;
383 if (!ReachedMaxSocketsLimit() && !stalled_request_queue_
.empty())
384 ActivateStalledRequest();
387 void WebSocketTransportClientSocketPool::FlushWithError(int error
) {
388 // Sockets which are in LOAD_STATE_CONNECTING are in danger of unlocking
389 // sockets waiting for the endpoint lock. If they connected synchronously,
390 // then OnConnectJobComplete(). The |flushing_| flag tells this object to
391 // ignore spurious calls to OnConnectJobComplete(). It is safe to ignore those
392 // calls because this method will delete the jobs and call their callbacks
395 for (PendingConnectsMap::iterator it
= pending_connects_
.begin();
396 it
!= pending_connects_
.end();
398 InvokeUserCallbackLater(
399 it
->second
->handle(), it
->second
->callback(), error
);
400 delete it
->second
, it
->second
= NULL
;
402 pending_connects_
.clear();
403 for (StalledRequestQueue::iterator it
= stalled_request_queue_
.begin();
404 it
!= stalled_request_queue_
.end();
406 InvokeUserCallbackLater(it
->handle
, it
->callback
, error
);
408 stalled_request_map_
.clear();
409 stalled_request_queue_
.clear();
413 void WebSocketTransportClientSocketPool::CloseIdleSockets() {
414 // We have no idle sockets.
417 int WebSocketTransportClientSocketPool::IdleSocketCount() const {
421 int WebSocketTransportClientSocketPool::IdleSocketCountInGroup(
422 const std::string
& group_name
) const {
426 LoadState
WebSocketTransportClientSocketPool::GetLoadState(
427 const std::string
& group_name
,
428 const ClientSocketHandle
* handle
) const {
429 if (stalled_request_map_
.find(handle
) != stalled_request_map_
.end())
430 return LOAD_STATE_WAITING_FOR_AVAILABLE_SOCKET
;
431 if (pending_callbacks_
.count(handle
))
432 return LOAD_STATE_CONNECTING
;
433 return LookupConnectJob(handle
)->GetLoadState();
436 base::DictionaryValue
* WebSocketTransportClientSocketPool::GetInfoAsValue(
437 const std::string
& name
,
438 const std::string
& type
,
439 bool include_nested_pools
) const {
440 base::DictionaryValue
* dict
= new base::DictionaryValue();
441 dict
->SetString("name", name
);
442 dict
->SetString("type", type
);
443 dict
->SetInteger("handed_out_socket_count", handed_out_socket_count_
);
444 dict
->SetInteger("connecting_socket_count", pending_connects_
.size());
445 dict
->SetInteger("idle_socket_count", 0);
446 dict
->SetInteger("max_socket_count", max_sockets_
);
447 dict
->SetInteger("max_sockets_per_group", max_sockets_
);
448 dict
->SetInteger("pool_generation_number", 0);
452 TimeDelta
WebSocketTransportClientSocketPool::ConnectionTimeout() const {
453 return TimeDelta::FromSeconds(kTransportConnectJobTimeoutInSeconds
);
456 bool WebSocketTransportClientSocketPool::IsStalled() const {
457 return !stalled_request_queue_
.empty();
460 void WebSocketTransportClientSocketPool::OnConnectJobComplete(
462 WebSocketTransportConnectJob
* job
) {
463 DCHECK_NE(ERR_IO_PENDING
, result
);
465 scoped_ptr
<StreamSocket
> socket
= job
->PassSocket();
467 // See comment in FlushWithError.
469 WebSocketEndpointLockManager::GetInstance()->UnlockSocket(socket
.get());
473 BoundNetLog request_net_log
= job
->request_net_log();
474 CompletionCallback callback
= job
->callback();
475 LoadTimingInfo::ConnectTiming connect_timing
= job
->connect_timing();
477 ClientSocketHandle
* const handle
= job
->handle();
478 bool handed_out_socket
= false;
481 DCHECK(socket
.get());
482 handed_out_socket
= true;
483 HandOutSocket(socket
.Pass(), connect_timing
, handle
, request_net_log
);
484 request_net_log
.EndEvent(NetLog::TYPE_SOCKET_POOL
);
486 // If we got a socket, it must contain error information so pass that
487 // up so that the caller can retrieve it.
488 job
->GetAdditionalErrorState(handle
);
490 handed_out_socket
= true;
491 HandOutSocket(socket
.Pass(), connect_timing
, handle
, request_net_log
);
493 request_net_log
.EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL
, result
);
495 bool delete_succeeded
= DeleteJob(handle
);
496 DCHECK(delete_succeeded
);
497 if (!handed_out_socket
&& !stalled_request_queue_
.empty() &&
498 !ReachedMaxSocketsLimit())
499 ActivateStalledRequest();
500 InvokeUserCallbackLater(handle
, callback
, result
);
503 void WebSocketTransportClientSocketPool::InvokeUserCallbackLater(
504 ClientSocketHandle
* handle
,
505 const CompletionCallback
& callback
,
507 DCHECK(!pending_callbacks_
.count(handle
));
508 pending_callbacks_
.insert(handle
);
509 base::MessageLoop::current()->PostTask(
511 base::Bind(&WebSocketTransportClientSocketPool::InvokeUserCallback
,
512 weak_factory_
.GetWeakPtr(),
518 void WebSocketTransportClientSocketPool::InvokeUserCallback(
519 ClientSocketHandle
* handle
,
520 const CompletionCallback
& callback
,
522 if (pending_callbacks_
.erase(handle
))
526 bool WebSocketTransportClientSocketPool::ReachedMaxSocketsLimit() const {
527 return handed_out_socket_count_
>= max_sockets_
||
528 base::checked_cast
<int>(pending_connects_
.size()) >=
529 max_sockets_
- handed_out_socket_count_
;
532 void WebSocketTransportClientSocketPool::HandOutSocket(
533 scoped_ptr
<StreamSocket
> socket
,
534 const LoadTimingInfo::ConnectTiming
& connect_timing
,
535 ClientSocketHandle
* handle
,
536 const BoundNetLog
& net_log
) {
538 handle
->SetSocket(socket
.Pass());
539 DCHECK_EQ(ClientSocketHandle::UNUSED
, handle
->reuse_type());
540 DCHECK_EQ(0, handle
->idle_time().InMicroseconds());
541 handle
->set_pool_id(0);
542 handle
->set_connect_timing(connect_timing
);
545 NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET
,
546 handle
->socket()->NetLog().source().ToEventParametersCallback());
548 ++handed_out_socket_count_
;
551 void WebSocketTransportClientSocketPool::AddJob(
552 ClientSocketHandle
* handle
,
553 scoped_ptr
<WebSocketTransportConnectJob
> connect_job
) {
555 pending_connects_
.insert(PendingConnectsMap::value_type(
556 handle
, connect_job
.release())).second
;
560 bool WebSocketTransportClientSocketPool::DeleteJob(ClientSocketHandle
* handle
) {
561 PendingConnectsMap::iterator it
= pending_connects_
.find(handle
);
562 if (it
== pending_connects_
.end())
564 // Deleting a ConnectJob which holds an endpoint lock can lead to a different
565 // ConnectJob proceeding to connect. If the connect proceeds synchronously
566 // (usually because of a failure) then it can trigger that job to be
567 // deleted. |it| remains valid because std::map guarantees that erase() does
568 // not invalid iterators to other entries.
569 delete it
->second
, it
->second
= NULL
;
570 DCHECK(pending_connects_
.find(handle
) == it
);
571 pending_connects_
.erase(it
);
575 const WebSocketTransportConnectJob
*
576 WebSocketTransportClientSocketPool::LookupConnectJob(
577 const ClientSocketHandle
* handle
) const {
578 PendingConnectsMap::const_iterator it
= pending_connects_
.find(handle
);
579 CHECK(it
!= pending_connects_
.end());
583 void WebSocketTransportClientSocketPool::ActivateStalledRequest() {
584 DCHECK(!stalled_request_queue_
.empty());
585 DCHECK(!ReachedMaxSocketsLimit());
586 // Usually we will only be able to activate one stalled request at a time,
587 // however if all the connects fail synchronously for some reason, we may be
588 // able to clear the whole queue at once.
589 while (!stalled_request_queue_
.empty() && !ReachedMaxSocketsLimit()) {
590 StalledRequest
request(stalled_request_queue_
.front());
591 stalled_request_queue_
.pop_front();
592 stalled_request_map_
.erase(request
.handle
);
593 int rv
= RequestSocket("ignored",
599 // ActivateStalledRequest() never returns synchronously, so it is never
600 // called re-entrantly.
601 if (rv
!= ERR_IO_PENDING
)
602 InvokeUserCallbackLater(request
.handle
, request
.callback
, rv
);
606 bool WebSocketTransportClientSocketPool::DeleteStalledRequest(
607 ClientSocketHandle
* handle
) {
608 StalledRequestMap::iterator it
= stalled_request_map_
.find(handle
);
609 if (it
== stalled_request_map_
.end())
611 stalled_request_queue_
.erase(it
->second
);
612 stalled_request_map_
.erase(it
);
616 WebSocketTransportClientSocketPool::ConnectJobDelegate::ConnectJobDelegate(
617 WebSocketTransportClientSocketPool
* owner
)
620 WebSocketTransportClientSocketPool::ConnectJobDelegate::~ConnectJobDelegate() {}
623 WebSocketTransportClientSocketPool::ConnectJobDelegate::OnConnectJobComplete(
626 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
627 tracked_objects::ScopedTracker
tracking_profile(
628 FROM_HERE_WITH_EXPLICIT_FUNCTION(
629 "436634 WebSocket...::ConnectJobDelegate::OnConnectJobComplete"));
631 owner_
->OnConnectJobComplete(result
,
632 static_cast<WebSocketTransportConnectJob
*>(job
));
635 WebSocketTransportClientSocketPool::StalledRequest::StalledRequest(
636 const scoped_refptr
<TransportSocketParams
>& params
,
637 RequestPriority priority
,
638 ClientSocketHandle
* handle
,
639 const CompletionCallback
& callback
,
640 const BoundNetLog
& net_log
)
647 WebSocketTransportClientSocketPool::StalledRequest::~StalledRequest() {}