Don't add an aura tooltip to bubble close buttons on Windows.
[chromium-blink-merge.git] / net / socket / websocket_transport_client_socket_pool.cc
blobf01a4e8110943086f364949bd7e3e336a44585ea
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"
7 #include <algorithm>
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"
23 namespace net {
25 namespace {
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.
34 } // namespace
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,
45 Delegate* delegate,
46 NetLog* pool_net_log,
47 const BoundNetLog& request_net_log)
48 : ConnectJob(group_name,
49 timeout_duration,
50 priority,
51 delegate,
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),
55 handle_(handle),
56 callback_(callback),
57 request_net_log_(request_net_log),
58 had_ipv4_(false),
59 had_ipv6_(false) {
60 helper_.SetOnIOComplete(this);
63 WebSocketTransportConnectJob::~WebSocketTransportConnectJob() {}
65 LoadState WebSocketTransportConnectJob::GetLoadState() const {
66 LoadState load_state = LOAD_STATE_RESOLVING_HOST;
67 if (ipv6_job_)
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();
74 return load_state;
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();
94 ++it) {
95 switch (it->GetFamily()) {
96 case ADDRESS_FAMILY_IPV4:
97 ipv4_addresses.push_back(*it);
98 break;
100 case ADDRESS_FAMILY_IPV6:
101 ipv6_addresses.push_back(*it);
102 break;
104 default:
105 DVLOG(1) << "Unexpected ADDRESS_FAMILY: " << it->GetFamily();
106 break;
110 if (!ipv4_addresses.empty()) {
111 had_ipv4_ = true;
112 ipv4_job_.reset(new WebSocketTransportConnectSubJob(
113 ipv4_addresses, this, SUB_JOB_IPV4));
116 if (!ipv6_addresses.empty()) {
117 had_ipv6_ = true;
118 ipv6_job_.reset(new WebSocketTransportConnectSubJob(
119 ipv6_addresses, this, SUB_JOB_IPV6));
120 result = ipv6_job_->Start();
121 switch (result) {
122 case OK:
123 SetSocket(ipv6_job_->PassSocket());
124 race_result_ =
125 had_ipv4_
126 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_RACEABLE
127 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_SOLO;
128 return result;
130 case ERR_IO_PENDING:
131 if (ipv4_job_) {
132 // This use of base::Unretained is safe because |fallback_timer_| is
133 // owned by this object.
134 fallback_timer_.Start(
135 FROM_HERE,
136 TimeDelta::FromMilliseconds(
137 TransportConnectJobHelper::kIPv6FallbackTimerInMs),
138 base::Bind(&WebSocketTransportConnectJob::StartIPv4JobAsync,
139 base::Unretained(this)));
141 return result;
143 default:
144 ipv6_job_.reset();
148 DCHECK(!ipv6_job_);
149 if (ipv4_job_) {
150 result = ipv4_job_->Start();
151 if (result == OK) {
152 SetSocket(ipv4_job_->PassSocket());
153 race_result_ =
154 had_ipv6_
155 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_WINS_RACE
156 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_NO_RACE;
160 return result;
163 int WebSocketTransportConnectJob::DoTransportConnectComplete(int result) {
164 if (result == OK)
165 helper_.HistogramDuration(race_result_);
166 return result;
169 void WebSocketTransportConnectJob::OnSubJobComplete(
170 int result,
171 WebSocketTransportConnectSubJob* job) {
172 if (result == OK) {
173 switch (job->type()) {
174 case SUB_JOB_IPV4:
175 race_result_ =
176 had_ipv6_
177 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_WINS_RACE
178 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV4_NO_RACE;
179 break;
181 case SUB_JOB_IPV6:
182 race_result_ =
183 had_ipv4_
184 ? TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_RACEABLE
185 : TransportConnectJobHelper::CONNECTION_LATENCY_IPV6_SOLO;
186 break;
188 SetSocket(job->PassSocket());
190 // Make sure all connections are cancelled even if this object fails to be
191 // deleted.
192 ipv4_job_.reset();
193 ipv6_job_.reset();
194 } else {
195 switch (job->type()) {
196 case SUB_JOB_IPV4:
197 ipv4_job_.reset();
198 break;
200 case SUB_JOB_IPV6:
201 ipv6_job_.reset();
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());
207 return;
210 break;
212 if (ipv4_job_ || ipv6_job_)
213 return;
215 helper_.OnIOComplete(this, result);
218 void WebSocketTransportConnectJob::StartIPv4JobAsync() {
219 DCHECK(ipv4_job_);
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(
230 int max_sockets,
231 int max_sockets_per_group,
232 HostResolver* host_resolver,
233 ClientSocketFactory* client_socket_factory,
234 NetLog* net_log)
235 : TransportClientSocketPool(max_sockets,
236 max_sockets_per_group,
237 host_resolver,
238 client_socket_factory,
239 net_log),
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),
246 flushing_(false),
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());
258 // static
259 void WebSocketTransportClientSocketPool::UnlockEndpoint(
260 ClientSocketHandle* handle) {
261 DCHECK(handle->is_initialized());
262 DCHECK(handle->socket());
263 IPEndPoint address;
264 if (handle->socket()->GetPeerAddress(&address) == OK)
265 WebSocketEndpointLockManager::GetInstance()->UnlockEndpoint(address);
268 int WebSocketTransportClientSocketPool::RequestSocket(
269 const std::string& group_name,
270 const void* params,
271 RequestPriority priority,
272 ClientSocketHandle* handle,
273 const CompletionCallback& callback,
274 const BoundNetLog& request_net_log) {
275 DCHECK(params);
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());
282 CHECK(handle);
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();
293 --iterator;
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,
307 priority,
308 casted_params,
309 ConnectionTimeout(),
310 callback,
311 client_socket_factory_,
312 host_resolver_,
313 handle,
314 &connect_job_delegate_,
315 pool_net_log_,
316 request_net_log));
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());
325 if (rv == OK) {
326 HandOutSocket(connect_job->PassSocket(),
327 connect_job->connect_timing(),
328 handle,
329 request_net_log);
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());
334 } else {
335 scoped_ptr<StreamSocket> error_socket;
336 connect_job->GetAdditionalErrorState(handle);
337 error_socket = connect_job->PassSocket();
338 if (error_socket) {
339 HandOutSocket(error_socket.Pass(),
340 connect_job->connect_timing(),
341 handle,
342 request_net_log);
346 if (rv != ERR_IO_PENDING) {
347 request_net_log.EndEventWithNetErrorCode(NetLog::TYPE_SOCKET_POOL, rv);
350 return rv;
353 void WebSocketTransportClientSocketPool::RequestSockets(
354 const std::string& group_name,
355 const void* params,
356 int num_sockets,
357 const BoundNetLog& net_log) {
358 NOTIMPLEMENTED();
361 void WebSocketTransportClientSocketPool::CancelRequest(
362 const std::string& group_name,
363 ClientSocketHandle* handle) {
364 DCHECK(!handle->is_initialized());
365 if (DeleteStalledRequest(handle))
366 return;
367 scoped_ptr<StreamSocket> socket = handle->PassSocket();
368 if (socket)
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,
379 int id) {
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
393 // anyway.
394 flushing_ = true;
395 for (PendingConnectsMap::iterator it = pending_connects_.begin();
396 it != pending_connects_.end();
397 ++it) {
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();
405 ++it) {
406 InvokeUserCallbackLater(it->handle, it->callback, error);
408 stalled_request_map_.clear();
409 stalled_request_queue_.clear();
410 flushing_ = false;
413 void WebSocketTransportClientSocketPool::CloseIdleSockets() {
414 // We have no idle sockets.
417 int WebSocketTransportClientSocketPool::IdleSocketCount() const {
418 return 0;
421 int WebSocketTransportClientSocketPool::IdleSocketCountInGroup(
422 const std::string& group_name) const {
423 return 0;
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);
449 return dict;
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(
461 int result,
462 WebSocketTransportConnectJob* job) {
463 DCHECK_NE(ERR_IO_PENDING, result);
465 scoped_ptr<StreamSocket> socket = job->PassSocket();
467 // See comment in FlushWithError.
468 if (flushing_) {
469 WebSocketEndpointLockManager::GetInstance()->UnlockSocket(socket.get());
470 return;
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;
480 if (result == OK) {
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);
485 } else {
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);
489 if (socket.get()) {
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,
506 int rv) {
507 DCHECK(!pending_callbacks_.count(handle));
508 pending_callbacks_.insert(handle);
509 base::MessageLoop::current()->PostTask(
510 FROM_HERE,
511 base::Bind(&WebSocketTransportClientSocketPool::InvokeUserCallback,
512 weak_factory_.GetWeakPtr(),
513 handle,
514 callback,
515 rv));
518 void WebSocketTransportClientSocketPool::InvokeUserCallback(
519 ClientSocketHandle* handle,
520 const CompletionCallback& callback,
521 int rv) {
522 if (pending_callbacks_.erase(handle))
523 callback.Run(rv);
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) {
537 DCHECK(socket);
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);
544 net_log.AddEvent(
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) {
554 bool inserted =
555 pending_connects_.insert(PendingConnectsMap::value_type(
556 handle, connect_job.release())).second;
557 DCHECK(inserted);
560 bool WebSocketTransportClientSocketPool::DeleteJob(ClientSocketHandle* handle) {
561 PendingConnectsMap::iterator it = pending_connects_.find(handle);
562 if (it == pending_connects_.end())
563 return false;
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);
572 return true;
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());
580 return it->second;
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",
594 &request.params,
595 request.priority,
596 request.handle,
597 request.callback,
598 request.net_log);
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())
610 return false;
611 stalled_request_queue_.erase(it->second);
612 stalled_request_map_.erase(it);
613 return true;
616 WebSocketTransportClientSocketPool::ConnectJobDelegate::ConnectJobDelegate(
617 WebSocketTransportClientSocketPool* owner)
618 : owner_(owner) {}
620 WebSocketTransportClientSocketPool::ConnectJobDelegate::~ConnectJobDelegate() {}
622 void
623 WebSocketTransportClientSocketPool::ConnectJobDelegate::OnConnectJobComplete(
624 int result,
625 ConnectJob* job) {
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)
641 : params(params),
642 priority(priority),
643 handle(handle),
644 callback(callback),
645 net_log(net_log) {}
647 WebSocketTransportClientSocketPool::StalledRequest::~StalledRequest() {}
649 } // namespace net