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/strings/string_util.h"
13 #include "base/time/time.h"
14 #include "base/values.h"
15 #include "net/base/net_errors.h"
16 #include "net/log/net_log.h"
17 #include "net/socket/client_socket_handle.h"
18 #include "net/socket/client_socket_pool_base.h"
19 #include "net/socket/websocket_endpoint_lock_manager.h"
20 #include "net/socket/websocket_transport_connect_sub_job.h"
26 using base::TimeDelta
;
28 // TODO(ricea): For now, we implement a global timeout for compatability with
29 // TransportConnectJob. Since WebSocketTransportConnectJob controls the address
30 // selection process more tightly, it could do something smarter here.
31 const int kTransportConnectJobTimeoutInSeconds
= 240; // 4 minutes.
35 WebSocketTransportConnectJob::WebSocketTransportConnectJob(
36 const std::string
& group_name
,
37 RequestPriority priority
,
38 const scoped_refptr
<TransportSocketParams
>& params
,
39 TimeDelta timeout_duration
,
40 const CompletionCallback
& callback
,
41 ClientSocketFactory
* client_socket_factory
,
42 HostResolver
* host_resolver
,
43 ClientSocketHandle
* handle
,
46 const BoundNetLog
& request_net_log
)
47 : ConnectJob(group_name
,
51 BoundNetLog::Make(pool_net_log
, NetLog::SOURCE_CONNECT_JOB
)),
52 helper_(params
, client_socket_factory
, host_resolver
, &connect_timing_
),
53 race_result_(TransportConnectJobHelper::CONNECTION_LATENCY_UNKNOWN
),
56 request_net_log_(request_net_log
),
59 helper_
.SetOnIOComplete(this);
62 WebSocketTransportConnectJob::~WebSocketTransportConnectJob() {}
64 LoadState
WebSocketTransportConnectJob::GetLoadState() const {
65 LoadState load_state
= LOAD_STATE_RESOLVING_HOST
;
67 load_state
= ipv6_job_
->GetLoadState();
68 // This method should return LOAD_STATE_CONNECTING in preference to
69 // LOAD_STATE_WAITING_FOR_AVAILABLE_SOCKET when possible because "waiting for
70 // available socket" implies that nothing is happening.
71 if (ipv4_job_
&& load_state
!= LOAD_STATE_CONNECTING
)
72 load_state
= ipv4_job_
->GetLoadState();
76 int WebSocketTransportConnectJob::DoResolveHost() {
77 return helper_
.DoResolveHost(priority(), net_log());
80 int WebSocketTransportConnectJob::DoResolveHostComplete(int result
) {
81 return helper_
.DoResolveHostComplete(result
, net_log());
84 int WebSocketTransportConnectJob::DoTransportConnect() {
85 AddressList ipv4_addresses
;
86 AddressList ipv6_addresses
;
87 int result
= ERR_UNEXPECTED
;
88 helper_
.set_next_state(
89 TransportConnectJobHelper::STATE_TRANSPORT_CONNECT_COMPLETE
);
91 for (AddressList::const_iterator it
= helper_
.addresses().begin();
92 it
!= helper_
.addresses().end();
94 switch (it
->GetFamily()) {
95 case ADDRESS_FAMILY_IPV4
:
96 ipv4_addresses
.push_back(*it
);
99 case ADDRESS_FAMILY_IPV6
:
100 ipv6_addresses
.push_back(*it
);
104 DVLOG(1) << "Unexpected ADDRESS_FAMILY: " << it
->GetFamily();
109 if (!ipv4_addresses
.empty()) {
111 ipv4_job_
.reset(new WebSocketTransportConnectSubJob(
112 ipv4_addresses
, this, SUB_JOB_IPV4
));
115 if (!ipv6_addresses
.empty()) {
117 ipv6_job_
.reset(new WebSocketTransportConnectSubJob(
118 ipv6_addresses
, this, SUB_JOB_IPV6
));
119 result
= ipv6_job_
->Start();
122 SetSocket(ipv6_job_
->PassSocket());
125 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_RACEABLE
126 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_SOLO
;
131 // This use of base::Unretained is safe because |fallback_timer_| is
132 // owned by this object.
133 fallback_timer_
.Start(
135 TimeDelta::FromMilliseconds(
136 TransportConnectJobHelper::kIPv6FallbackTimerInMs
),
137 base::Bind(&WebSocketTransportConnectJob::StartIPv4JobAsync
,
138 base::Unretained(this)));
149 result
= ipv4_job_
->Start();
151 SetSocket(ipv4_job_
->PassSocket());
154 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_WINS_RACE
155 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_NO_RACE
;
162 int WebSocketTransportConnectJob::DoTransportConnectComplete(int result
) {
164 helper_
.HistogramDuration(race_result_
);
168 void WebSocketTransportConnectJob::OnSubJobComplete(
170 WebSocketTransportConnectSubJob
* job
) {
172 switch (job
->type()) {
176 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_WINS_RACE
177 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_NO_RACE
;
183 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_RACEABLE
184 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_SOLO
;
187 SetSocket(job
->PassSocket());
189 // Make sure all connections are cancelled even if this object fails to be
194 switch (job
->type()) {
201 if (ipv4_job_
&& !ipv4_job_
->started()) {
202 fallback_timer_
.Stop();
203 result
= ipv4_job_
->Start();
204 if (result
!= ERR_IO_PENDING
) {
205 OnSubJobComplete(result
, ipv4_job_
.get());
211 if (ipv4_job_
|| ipv6_job_
)
214 helper_
.OnIOComplete(this, result
);
217 void WebSocketTransportConnectJob::StartIPv4JobAsync() {
219 int result
= ipv4_job_
->Start();
220 if (result
!= ERR_IO_PENDING
)
221 OnSubJobComplete(result
, ipv4_job_
.get());
224 int WebSocketTransportConnectJob::ConnectInternal() {
225 return helper_
.DoConnectInternal(this);
228 WebSocketTransportClientSocketPool::WebSocketTransportClientSocketPool(
230 int max_sockets_per_group
,
231 HostResolver
* host_resolver
,
232 ClientSocketFactory
* client_socket_factory
,
234 : TransportClientSocketPool(max_sockets
,
235 max_sockets_per_group
,
237 client_socket_factory
,
239 connect_job_delegate_(this),
240 pool_net_log_(net_log
),
241 client_socket_factory_(client_socket_factory
),
242 host_resolver_(host_resolver
),
243 max_sockets_(max_sockets
),
244 handed_out_socket_count_(0),
246 weak_factory_(this) {}
248 WebSocketTransportClientSocketPool::~WebSocketTransportClientSocketPool() {
249 // Clean up any pending connect jobs.
250 FlushWithError(ERR_ABORTED
);
251 DCHECK(pending_connects_
.empty());
252 DCHECK_EQ(0, handed_out_socket_count_
);
253 DCHECK(stalled_request_queue_
.empty());
254 DCHECK(stalled_request_map_
.empty());
258 void WebSocketTransportClientSocketPool::UnlockEndpoint(
259 ClientSocketHandle
* handle
) {
260 DCHECK(handle
->is_initialized());
261 DCHECK(handle
->socket());
263 if (handle
->socket()->GetPeerAddress(&address
) == OK
)
264 WebSocketEndpointLockManager::GetInstance()->UnlockEndpoint(address
);
267 int WebSocketTransportClientSocketPool::RequestSocket(
268 const std::string
& group_name
,
270 RequestPriority priority
,
271 ClientSocketHandle
* handle
,
272 const CompletionCallback
& callback
,
273 const BoundNetLog
& request_net_log
) {
275 const scoped_refptr
<TransportSocketParams
>& casted_params
=
276 *static_cast<const scoped_refptr
<TransportSocketParams
>*>(params
);
278 NetLogTcpClientSocketPoolRequestedSocket(request_net_log
, &casted_params
);
280 CHECK(!callback
.is_null());
283 request_net_log
.BeginEvent(NetLog::TYPE_SOCKET_POOL
);
285 if (ReachedMaxSocketsLimit() && !casted_params
->ignore_limits()) {
286 request_net_log
.AddEvent(NetLog::TYPE_SOCKET_POOL_STALLED_MAX_SOCKETS
);
287 // TODO(ricea): Use emplace_back when C++11 becomes allowed.
288 StalledRequest
request(
289 casted_params
, priority
, handle
, callback
, request_net_log
);
290 stalled_request_queue_
.push_back(request
);
291 StalledRequestQueue::iterator iterator
= stalled_request_queue_
.end();
293 DCHECK_EQ(handle
, iterator
->handle
);
294 // Because StalledRequestQueue is a std::list, its iterators are guaranteed
295 // to remain valid as long as the elements are not removed. As long as
296 // stalled_request_queue_ and stalled_request_map_ are updated in sync, it
297 // is safe to dereference an iterator in stalled_request_map_ to find the
298 // corresponding list element.
299 stalled_request_map_
.insert(
300 StalledRequestMap::value_type(handle
, iterator
));
301 return ERR_IO_PENDING
;
304 scoped_ptr
<WebSocketTransportConnectJob
> connect_job(
305 new WebSocketTransportConnectJob(group_name
,
310 client_socket_factory_
,
313 &connect_job_delegate_
,
317 int rv
= connect_job
->Connect();
318 // Regardless of the outcome of |connect_job|, it will always be bound to
319 // |handle|, since this pool uses early-binding. So the binding is logged
320 // here, without waiting for the result.
321 request_net_log
.AddEvent(
322 NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB
,
323 connect_job
->net_log().source().ToEventParametersCallback());
325 HandOutSocket(connect_job
->PassSocket(),
326 connect_job
->connect_timing(),
329 request_net_log
.EndEvent(NetLog::TYPE_SOCKET_POOL
);
330 } else if (rv
== ERR_IO_PENDING
) {
331 // TODO(ricea): Implement backup job timer?
332 AddJob(handle
, connect_job
.Pass());
334 scoped_ptr
<StreamSocket
> error_socket
;
335 connect_job
->GetAdditionalErrorState(handle
);
336 error_socket
= connect_job
->PassSocket();
338 HandOutSocket(error_socket
.Pass(),
339 connect_job
->connect_timing(),
345 if (rv
!= ERR_IO_PENDING
) {
346 request_net_log
.EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL
, rv
);
352 void WebSocketTransportClientSocketPool::RequestSockets(
353 const std::string
& group_name
,
356 const BoundNetLog
& net_log
) {
360 void WebSocketTransportClientSocketPool::CancelRequest(
361 const std::string
& group_name
,
362 ClientSocketHandle
* handle
) {
363 DCHECK(!handle
->is_initialized());
364 if (DeleteStalledRequest(handle
))
366 scoped_ptr
<StreamSocket
> socket
= handle
->PassSocket();
368 ReleaseSocket(handle
->group_name(), socket
.Pass(), handle
->id());
369 if (!DeleteJob(handle
))
370 pending_callbacks_
.erase(handle
);
371 if (!ReachedMaxSocketsLimit() && !stalled_request_queue_
.empty())
372 ActivateStalledRequest();
375 void WebSocketTransportClientSocketPool::ReleaseSocket(
376 const std::string
& group_name
,
377 scoped_ptr
<StreamSocket
> socket
,
379 WebSocketEndpointLockManager::GetInstance()->UnlockSocket(socket
.get());
380 CHECK_GT(handed_out_socket_count_
, 0);
381 --handed_out_socket_count_
;
382 if (!ReachedMaxSocketsLimit() && !stalled_request_queue_
.empty())
383 ActivateStalledRequest();
386 void WebSocketTransportClientSocketPool::FlushWithError(int error
) {
387 // Sockets which are in LOAD_STATE_CONNECTING are in danger of unlocking
388 // sockets waiting for the endpoint lock. If they connected synchronously,
389 // then OnConnectJobComplete(). The |flushing_| flag tells this object to
390 // ignore spurious calls to OnConnectJobComplete(). It is safe to ignore those
391 // calls because this method will delete the jobs and call their callbacks
394 for (PendingConnectsMap::iterator it
= pending_connects_
.begin();
395 it
!= pending_connects_
.end();
397 InvokeUserCallbackLater(
398 it
->second
->handle(), it
->second
->callback(), error
);
399 delete it
->second
, it
->second
= NULL
;
401 pending_connects_
.clear();
402 for (StalledRequestQueue::iterator it
= stalled_request_queue_
.begin();
403 it
!= stalled_request_queue_
.end();
405 InvokeUserCallbackLater(it
->handle
, it
->callback
, error
);
407 stalled_request_map_
.clear();
408 stalled_request_queue_
.clear();
412 void WebSocketTransportClientSocketPool::CloseIdleSockets() {
413 // We have no idle sockets.
416 int WebSocketTransportClientSocketPool::IdleSocketCount() const {
420 int WebSocketTransportClientSocketPool::IdleSocketCountInGroup(
421 const std::string
& group_name
) const {
425 LoadState
WebSocketTransportClientSocketPool::GetLoadState(
426 const std::string
& group_name
,
427 const ClientSocketHandle
* handle
) const {
428 if (stalled_request_map_
.find(handle
) != stalled_request_map_
.end())
429 return LOAD_STATE_WAITING_FOR_AVAILABLE_SOCKET
;
430 if (pending_callbacks_
.count(handle
))
431 return LOAD_STATE_CONNECTING
;
432 return LookupConnectJob(handle
)->GetLoadState();
435 scoped_ptr
<base::DictionaryValue
>
436 WebSocketTransportClientSocketPool::GetInfoAsValue(
437 const std::string
& name
,
438 const std::string
& type
,
439 bool include_nested_pools
) const {
440 scoped_ptr
<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 owner_
->OnConnectJobComplete(result
,
627 static_cast<WebSocketTransportConnectJob
*>(job
));
630 WebSocketTransportClientSocketPool::StalledRequest::StalledRequest(
631 const scoped_refptr
<TransportSocketParams
>& params
,
632 RequestPriority priority
,
633 ClientSocketHandle
* handle
,
634 const CompletionCallback
& callback
,
635 const BoundNetLog
& net_log
)
642 WebSocketTransportClientSocketPool::StalledRequest::~StalledRequest() {}