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/socket/transport_client_socket_pool.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/compiler_specific.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/threading/platform_thread.h"
14 #include "net/base/capturing_net_log.h"
15 #include "net/base/ip_endpoint.h"
16 #include "net/base/load_timing_info.h"
17 #include "net/base/load_timing_info_test_util.h"
18 #include "net/base/net_errors.h"
19 #include "net/base/net_util.h"
20 #include "net/base/test_completion_callback.h"
21 #include "net/dns/mock_host_resolver.h"
22 #include "net/socket/client_socket_factory.h"
23 #include "net/socket/client_socket_handle.h"
24 #include "net/socket/client_socket_pool_histograms.h"
25 #include "net/socket/socket_test_util.h"
26 #include "net/socket/ssl_client_socket.h"
27 #include "net/socket/stream_socket.h"
28 #include "testing/gtest/include/gtest/gtest.h"
32 using internal::ClientSocketPoolBaseHelper
;
36 const int kMaxSockets
= 32;
37 const int kMaxSocketsPerGroup
= 6;
38 const net::RequestPriority kDefaultPriority
= LOW
;
40 // Make sure |handle| sets load times correctly when it has been assigned a
42 void TestLoadTimingInfoConnectedReused(const ClientSocketHandle
& handle
) {
43 LoadTimingInfo load_timing_info
;
44 // Only pass true in as |is_reused|, as in general, HttpStream types should
45 // have stricter concepts of reuse than socket pools.
46 EXPECT_TRUE(handle
.GetLoadTimingInfo(true, &load_timing_info
));
48 EXPECT_TRUE(load_timing_info
.socket_reused
);
49 EXPECT_NE(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
51 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
52 ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info
);
55 // Make sure |handle| sets load times correctly when it has been assigned a
56 // fresh socket. Also runs TestLoadTimingInfoConnectedReused, since the owner
57 // of a connection where |is_reused| is false may consider the connection
59 void TestLoadTimingInfoConnectedNotReused(const ClientSocketHandle
& handle
) {
60 EXPECT_FALSE(handle
.is_reused());
62 LoadTimingInfo load_timing_info
;
63 EXPECT_TRUE(handle
.GetLoadTimingInfo(false, &load_timing_info
));
65 EXPECT_FALSE(load_timing_info
.socket_reused
);
66 EXPECT_NE(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
68 ExpectConnectTimingHasTimes(load_timing_info
.connect_timing
,
69 CONNECT_TIMING_HAS_DNS_TIMES
);
70 ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info
);
72 TestLoadTimingInfoConnectedReused(handle
);
75 void SetIPv4Address(IPEndPoint
* address
) {
76 IPAddressNumber number
;
77 CHECK(ParseIPLiteralToNumber("1.1.1.1", &number
));
78 *address
= IPEndPoint(number
, 80);
81 void SetIPv6Address(IPEndPoint
* address
) {
82 IPAddressNumber number
;
83 CHECK(ParseIPLiteralToNumber("1:abcd::3:4:ff", &number
));
84 *address
= IPEndPoint(number
, 80);
87 class MockClientSocket
: public StreamSocket
{
89 MockClientSocket(const AddressList
& addrlist
, net::NetLog
* net_log
)
92 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_SOCKET
)) {
95 // StreamSocket implementation.
96 virtual int Connect(const CompletionCallback
& callback
) OVERRIDE
{
100 virtual void Disconnect() OVERRIDE
{
103 virtual bool IsConnected() const OVERRIDE
{
106 virtual bool IsConnectedAndIdle() const OVERRIDE
{
109 virtual int GetPeerAddress(IPEndPoint
* address
) const OVERRIDE
{
110 return ERR_UNEXPECTED
;
112 virtual int GetLocalAddress(IPEndPoint
* address
) const OVERRIDE
{
114 return ERR_SOCKET_NOT_CONNECTED
;
115 if (addrlist_
.front().GetFamily() == ADDRESS_FAMILY_IPV4
)
116 SetIPv4Address(address
);
118 SetIPv6Address(address
);
121 virtual const BoundNetLog
& NetLog() const OVERRIDE
{
125 virtual void SetSubresourceSpeculation() OVERRIDE
{}
126 virtual void SetOmniboxSpeculation() OVERRIDE
{}
127 virtual bool WasEverUsed() const OVERRIDE
{ return false; }
128 virtual bool UsingTCPFastOpen() const OVERRIDE
{ return false; }
129 virtual bool WasNpnNegotiated() const OVERRIDE
{
132 virtual NextProto
GetNegotiatedProtocol() const OVERRIDE
{
133 return kProtoUnknown
;
135 virtual bool GetSSLInfo(SSLInfo
* ssl_info
) OVERRIDE
{
139 // Socket implementation.
140 virtual int Read(IOBuffer
* buf
, int buf_len
,
141 const CompletionCallback
& callback
) OVERRIDE
{
144 virtual int Write(IOBuffer
* buf
, int buf_len
,
145 const CompletionCallback
& callback
) OVERRIDE
{
148 virtual bool SetReceiveBufferSize(int32 size
) OVERRIDE
{ return true; }
149 virtual bool SetSendBufferSize(int32 size
) OVERRIDE
{ return true; }
153 const AddressList addrlist_
;
154 BoundNetLog net_log_
;
157 class MockFailingClientSocket
: public StreamSocket
{
159 MockFailingClientSocket(const AddressList
& addrlist
, net::NetLog
* net_log
)
160 : addrlist_(addrlist
),
161 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_SOCKET
)) {
164 // StreamSocket implementation.
165 virtual int Connect(const CompletionCallback
& callback
) OVERRIDE
{
166 return ERR_CONNECTION_FAILED
;
169 virtual void Disconnect() OVERRIDE
{}
171 virtual bool IsConnected() const OVERRIDE
{
174 virtual bool IsConnectedAndIdle() const OVERRIDE
{
177 virtual int GetPeerAddress(IPEndPoint
* address
) const OVERRIDE
{
178 return ERR_UNEXPECTED
;
180 virtual int GetLocalAddress(IPEndPoint
* address
) const OVERRIDE
{
181 return ERR_UNEXPECTED
;
183 virtual const BoundNetLog
& NetLog() const OVERRIDE
{
187 virtual void SetSubresourceSpeculation() OVERRIDE
{}
188 virtual void SetOmniboxSpeculation() OVERRIDE
{}
189 virtual bool WasEverUsed() const OVERRIDE
{ return false; }
190 virtual bool UsingTCPFastOpen() const OVERRIDE
{ return false; }
191 virtual bool WasNpnNegotiated() const OVERRIDE
{
194 virtual NextProto
GetNegotiatedProtocol() const OVERRIDE
{
195 return kProtoUnknown
;
197 virtual bool GetSSLInfo(SSLInfo
* ssl_info
) OVERRIDE
{
201 // Socket implementation.
202 virtual int Read(IOBuffer
* buf
, int buf_len
,
203 const CompletionCallback
& callback
) OVERRIDE
{
207 virtual int Write(IOBuffer
* buf
, int buf_len
,
208 const CompletionCallback
& callback
) OVERRIDE
{
211 virtual bool SetReceiveBufferSize(int32 size
) OVERRIDE
{ return true; }
212 virtual bool SetSendBufferSize(int32 size
) OVERRIDE
{ return true; }
215 const AddressList addrlist_
;
216 BoundNetLog net_log_
;
219 class MockPendingClientSocket
: public StreamSocket
{
221 // |should_connect| indicates whether the socket should successfully complete
223 // |should_stall| indicates that this socket should never connect.
224 // |delay_ms| is the delay, in milliseconds, before simulating a connect.
225 MockPendingClientSocket(
226 const AddressList
& addrlist
,
229 base::TimeDelta delay
,
230 net::NetLog
* net_log
)
231 : weak_factory_(this),
232 should_connect_(should_connect
),
233 should_stall_(should_stall
),
235 is_connected_(false),
237 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_SOCKET
)) {
240 // StreamSocket implementation.
241 virtual int Connect(const CompletionCallback
& callback
) OVERRIDE
{
242 base::MessageLoop::current()->PostDelayedTask(
244 base::Bind(&MockPendingClientSocket::DoCallback
,
245 weak_factory_
.GetWeakPtr(), callback
),
247 return ERR_IO_PENDING
;
250 virtual void Disconnect() OVERRIDE
{}
252 virtual bool IsConnected() const OVERRIDE
{
253 return is_connected_
;
255 virtual bool IsConnectedAndIdle() const OVERRIDE
{
256 return is_connected_
;
258 virtual int GetPeerAddress(IPEndPoint
* address
) const OVERRIDE
{
259 return ERR_UNEXPECTED
;
261 virtual int GetLocalAddress(IPEndPoint
* address
) const OVERRIDE
{
263 return ERR_SOCKET_NOT_CONNECTED
;
264 if (addrlist_
.front().GetFamily() == ADDRESS_FAMILY_IPV4
)
265 SetIPv4Address(address
);
267 SetIPv6Address(address
);
270 virtual const BoundNetLog
& NetLog() const OVERRIDE
{
274 virtual void SetSubresourceSpeculation() OVERRIDE
{}
275 virtual void SetOmniboxSpeculation() OVERRIDE
{}
276 virtual bool WasEverUsed() const OVERRIDE
{ return false; }
277 virtual bool UsingTCPFastOpen() const OVERRIDE
{ return false; }
278 virtual bool WasNpnNegotiated() const OVERRIDE
{
281 virtual NextProto
GetNegotiatedProtocol() const OVERRIDE
{
282 return kProtoUnknown
;
284 virtual bool GetSSLInfo(SSLInfo
* ssl_info
) OVERRIDE
{
288 // Socket implementation.
289 virtual int Read(IOBuffer
* buf
, int buf_len
,
290 const CompletionCallback
& callback
) OVERRIDE
{
294 virtual int Write(IOBuffer
* buf
, int buf_len
,
295 const CompletionCallback
& callback
) OVERRIDE
{
298 virtual bool SetReceiveBufferSize(int32 size
) OVERRIDE
{ return true; }
299 virtual bool SetSendBufferSize(int32 size
) OVERRIDE
{ return true; }
302 void DoCallback(const CompletionCallback
& callback
) {
306 if (should_connect_
) {
307 is_connected_
= true;
310 is_connected_
= false;
311 callback
.Run(ERR_CONNECTION_FAILED
);
315 base::WeakPtrFactory
<MockPendingClientSocket
> weak_factory_
;
316 bool should_connect_
;
318 base::TimeDelta delay_
;
320 const AddressList addrlist_
;
321 BoundNetLog net_log_
;
324 class MockClientSocketFactory
: public ClientSocketFactory
{
326 enum ClientSocketType
{
328 MOCK_FAILING_CLIENT_SOCKET
,
329 MOCK_PENDING_CLIENT_SOCKET
,
330 MOCK_PENDING_FAILING_CLIENT_SOCKET
,
331 // A delayed socket will pause before connecting through the message loop.
332 MOCK_DELAYED_CLIENT_SOCKET
,
333 // A stalled socket that never connects at all.
334 MOCK_STALLED_CLIENT_SOCKET
,
337 explicit MockClientSocketFactory(NetLog
* net_log
)
338 : net_log_(net_log
), allocation_count_(0),
339 client_socket_type_(MOCK_CLIENT_SOCKET
), client_socket_types_(NULL
),
340 client_socket_index_(0), client_socket_index_max_(0),
341 delay_(base::TimeDelta::FromMilliseconds(
342 ClientSocketPool::kMaxConnectRetryIntervalMs
)) {}
344 virtual scoped_ptr
<DatagramClientSocket
> CreateDatagramClientSocket(
345 DatagramSocket::BindType bind_type
,
346 const RandIntCallback
& rand_int_cb
,
348 const NetLog::Source
& source
) OVERRIDE
{
350 return scoped_ptr
<DatagramClientSocket
>();
353 virtual scoped_ptr
<StreamSocket
> CreateTransportClientSocket(
354 const AddressList
& addresses
,
355 NetLog
* /* net_log */,
356 const NetLog::Source
& /* source */) OVERRIDE
{
359 ClientSocketType type
= client_socket_type_
;
360 if (client_socket_types_
&&
361 client_socket_index_
< client_socket_index_max_
) {
362 type
= client_socket_types_
[client_socket_index_
++];
366 case MOCK_CLIENT_SOCKET
:
367 return scoped_ptr
<StreamSocket
>(
368 new MockClientSocket(addresses
, net_log_
));
369 case MOCK_FAILING_CLIENT_SOCKET
:
370 return scoped_ptr
<StreamSocket
>(
371 new MockFailingClientSocket(addresses
, net_log_
));
372 case MOCK_PENDING_CLIENT_SOCKET
:
373 return scoped_ptr
<StreamSocket
>(
374 new MockPendingClientSocket(
375 addresses
, true, false, base::TimeDelta(), net_log_
));
376 case MOCK_PENDING_FAILING_CLIENT_SOCKET
:
377 return scoped_ptr
<StreamSocket
>(
378 new MockPendingClientSocket(
379 addresses
, false, false, base::TimeDelta(), net_log_
));
380 case MOCK_DELAYED_CLIENT_SOCKET
:
381 return scoped_ptr
<StreamSocket
>(
382 new MockPendingClientSocket(
383 addresses
, true, false, delay_
, net_log_
));
384 case MOCK_STALLED_CLIENT_SOCKET
:
385 return scoped_ptr
<StreamSocket
>(
386 new MockPendingClientSocket(
387 addresses
, true, true, base::TimeDelta(), net_log_
));
390 return scoped_ptr
<StreamSocket
>(
391 new MockClientSocket(addresses
, net_log_
));
395 virtual scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
396 scoped_ptr
<ClientSocketHandle
> transport_socket
,
397 const HostPortPair
& host_and_port
,
398 const SSLConfig
& ssl_config
,
399 const SSLClientSocketContext
& context
) OVERRIDE
{
401 return scoped_ptr
<SSLClientSocket
>();
404 virtual void ClearSSLSessionCache() OVERRIDE
{
408 int allocation_count() const { return allocation_count_
; }
410 // Set the default ClientSocketType.
411 void set_client_socket_type(ClientSocketType type
) {
412 client_socket_type_
= type
;
415 // Set a list of ClientSocketTypes to be used.
416 void set_client_socket_types(ClientSocketType
* type_list
, int num_types
) {
417 DCHECK_GT(num_types
, 0);
418 client_socket_types_
= type_list
;
419 client_socket_index_
= 0;
420 client_socket_index_max_
= num_types
;
423 void set_delay(base::TimeDelta delay
) { delay_
= delay
; }
427 int allocation_count_
;
428 ClientSocketType client_socket_type_
;
429 ClientSocketType
* client_socket_types_
;
430 int client_socket_index_
;
431 int client_socket_index_max_
;
432 base::TimeDelta delay_
;
435 class TransportClientSocketPoolTest
: public testing::Test
{
437 TransportClientSocketPoolTest()
438 : connect_backup_jobs_enabled_(
439 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(true)),
441 new TransportSocketParams(HostPortPair("www.google.com", 80),
443 OnHostResolutionCallback())),
444 histograms_(new ClientSocketPoolHistograms("TCPUnitTest")),
445 host_resolver_(new MockHostResolver
),
446 client_socket_factory_(&net_log_
),
450 host_resolver_
.get(),
451 &client_socket_factory_
,
455 virtual ~TransportClientSocketPoolTest() {
456 internal::ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(
457 connect_backup_jobs_enabled_
);
460 int StartRequest(const std::string
& group_name
, RequestPriority priority
) {
461 scoped_refptr
<TransportSocketParams
> params(new TransportSocketParams(
462 HostPortPair("www.google.com", 80), false, false,
463 OnHostResolutionCallback()));
464 return test_base_
.StartRequestUsingPool(
465 &pool_
, group_name
, priority
, params
);
468 int GetOrderOfRequest(size_t index
) {
469 return test_base_
.GetOrderOfRequest(index
);
472 bool ReleaseOneConnection(ClientSocketPoolTest::KeepAlive keep_alive
) {
473 return test_base_
.ReleaseOneConnection(keep_alive
);
476 void ReleaseAllConnections(ClientSocketPoolTest::KeepAlive keep_alive
) {
477 test_base_
.ReleaseAllConnections(keep_alive
);
480 ScopedVector
<TestSocketRequest
>* requests() { return test_base_
.requests(); }
481 size_t completion_count() const { return test_base_
.completion_count(); }
483 bool connect_backup_jobs_enabled_
;
484 CapturingNetLog net_log_
;
485 scoped_refptr
<TransportSocketParams
> params_
;
486 scoped_ptr
<ClientSocketPoolHistograms
> histograms_
;
487 scoped_ptr
<MockHostResolver
> host_resolver_
;
488 MockClientSocketFactory client_socket_factory_
;
489 TransportClientSocketPool pool_
;
490 ClientSocketPoolTest test_base_
;
493 TEST(TransportConnectJobTest
, MakeAddrListStartWithIPv4
) {
494 IPAddressNumber ip_number
;
495 ASSERT_TRUE(ParseIPLiteralToNumber("192.168.1.1", &ip_number
));
496 IPEndPoint
addrlist_v4_1(ip_number
, 80);
497 ASSERT_TRUE(ParseIPLiteralToNumber("192.168.1.2", &ip_number
));
498 IPEndPoint
addrlist_v4_2(ip_number
, 80);
499 ASSERT_TRUE(ParseIPLiteralToNumber("2001:4860:b006::64", &ip_number
));
500 IPEndPoint
addrlist_v6_1(ip_number
, 80);
501 ASSERT_TRUE(ParseIPLiteralToNumber("2001:4860:b006::66", &ip_number
));
502 IPEndPoint
addrlist_v6_2(ip_number
, 80);
504 AddressList addrlist
;
506 // Test 1: IPv4 only. Expect no change.
508 addrlist
.push_back(addrlist_v4_1
);
509 addrlist
.push_back(addrlist_v4_2
);
510 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist
);
511 ASSERT_EQ(2u, addrlist
.size());
512 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, addrlist
[0].GetFamily());
513 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, addrlist
[1].GetFamily());
515 // Test 2: IPv6 only. Expect no change.
517 addrlist
.push_back(addrlist_v6_1
);
518 addrlist
.push_back(addrlist_v6_2
);
519 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist
);
520 ASSERT_EQ(2u, addrlist
.size());
521 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, addrlist
[0].GetFamily());
522 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, addrlist
[1].GetFamily());
524 // Test 3: IPv4 then IPv6. Expect no change.
526 addrlist
.push_back(addrlist_v4_1
);
527 addrlist
.push_back(addrlist_v4_2
);
528 addrlist
.push_back(addrlist_v6_1
);
529 addrlist
.push_back(addrlist_v6_2
);
530 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist
);
531 ASSERT_EQ(4u, addrlist
.size());
532 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, addrlist
[0].GetFamily());
533 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, addrlist
[1].GetFamily());
534 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, addrlist
[2].GetFamily());
535 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, addrlist
[3].GetFamily());
537 // Test 4: IPv6, IPv4, IPv6, IPv4. Expect first IPv6 moved to the end.
539 addrlist
.push_back(addrlist_v6_1
);
540 addrlist
.push_back(addrlist_v4_1
);
541 addrlist
.push_back(addrlist_v6_2
);
542 addrlist
.push_back(addrlist_v4_2
);
543 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist
);
544 ASSERT_EQ(4u, addrlist
.size());
545 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, addrlist
[0].GetFamily());
546 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, addrlist
[1].GetFamily());
547 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, addrlist
[2].GetFamily());
548 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, addrlist
[3].GetFamily());
550 // Test 5: IPv6, IPv6, IPv4, IPv4. Expect first two IPv6's moved to the end.
552 addrlist
.push_back(addrlist_v6_1
);
553 addrlist
.push_back(addrlist_v6_2
);
554 addrlist
.push_back(addrlist_v4_1
);
555 addrlist
.push_back(addrlist_v4_2
);
556 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist
);
557 ASSERT_EQ(4u, addrlist
.size());
558 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, addrlist
[0].GetFamily());
559 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, addrlist
[1].GetFamily());
560 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, addrlist
[2].GetFamily());
561 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, addrlist
[3].GetFamily());
564 TEST_F(TransportClientSocketPoolTest
, Basic
) {
565 TestCompletionCallback callback
;
566 ClientSocketHandle handle
;
567 int rv
= handle
.Init("a", params_
, LOW
, callback
.callback(), &pool_
,
569 EXPECT_EQ(ERR_IO_PENDING
, rv
);
570 EXPECT_FALSE(handle
.is_initialized());
571 EXPECT_FALSE(handle
.socket());
573 EXPECT_EQ(OK
, callback
.WaitForResult());
574 EXPECT_TRUE(handle
.is_initialized());
575 EXPECT_TRUE(handle
.socket());
576 TestLoadTimingInfoConnectedNotReused(handle
);
579 // Make sure that TransportConnectJob passes on its priority to its
580 // HostResolver request on Init.
581 TEST_F(TransportClientSocketPoolTest
, SetResolvePriorityOnInit
) {
582 for (int i
= MINIMUM_PRIORITY
; i
<= MAXIMUM_PRIORITY
; ++i
) {
583 RequestPriority priority
= static_cast<RequestPriority
>(i
);
584 TestCompletionCallback callback
;
585 ClientSocketHandle handle
;
586 EXPECT_EQ(ERR_IO_PENDING
,
587 handle
.Init("a", params_
, priority
, callback
.callback(), &pool_
,
589 EXPECT_EQ(priority
, host_resolver_
->last_request_priority());
593 TEST_F(TransportClientSocketPoolTest
, InitHostResolutionFailure
) {
594 host_resolver_
->rules()->AddSimulatedFailure("unresolvable.host.name");
595 TestCompletionCallback callback
;
596 ClientSocketHandle handle
;
597 HostPortPair
host_port_pair("unresolvable.host.name", 80);
598 scoped_refptr
<TransportSocketParams
> dest(new TransportSocketParams(
599 host_port_pair
, false, false,
600 OnHostResolutionCallback()));
601 EXPECT_EQ(ERR_IO_PENDING
,
602 handle
.Init("a", dest
, kDefaultPriority
, callback
.callback(),
603 &pool_
, BoundNetLog()));
604 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, callback
.WaitForResult());
607 TEST_F(TransportClientSocketPoolTest
, InitConnectionFailure
) {
608 client_socket_factory_
.set_client_socket_type(
609 MockClientSocketFactory::MOCK_FAILING_CLIENT_SOCKET
);
610 TestCompletionCallback callback
;
611 ClientSocketHandle handle
;
612 EXPECT_EQ(ERR_IO_PENDING
,
613 handle
.Init("a", params_
, kDefaultPriority
, callback
.callback(),
614 &pool_
, BoundNetLog()));
615 EXPECT_EQ(ERR_CONNECTION_FAILED
, callback
.WaitForResult());
617 // Make the host resolutions complete synchronously this time.
618 host_resolver_
->set_synchronous_mode(true);
619 EXPECT_EQ(ERR_CONNECTION_FAILED
,
620 handle
.Init("a", params_
, kDefaultPriority
, callback
.callback(),
621 &pool_
, BoundNetLog()));
624 TEST_F(TransportClientSocketPoolTest
, PendingRequests
) {
625 // First request finishes asynchronously.
626 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
627 EXPECT_EQ(OK
, (*requests())[0]->WaitForResult());
629 // Make all subsequent host resolutions complete synchronously.
630 host_resolver_
->set_synchronous_mode(true);
632 // Rest of them finish synchronously, until we reach the per-group limit.
633 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
634 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
635 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
636 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
637 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
639 // The rest are pending since we've used all active sockets.
640 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", HIGHEST
));
641 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", LOWEST
));
642 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", LOWEST
));
643 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", MEDIUM
));
644 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", LOW
));
645 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", HIGHEST
));
646 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", LOWEST
));
647 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", MEDIUM
));
648 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", MEDIUM
));
649 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", HIGHEST
));
651 ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE
);
653 EXPECT_EQ(kMaxSocketsPerGroup
, client_socket_factory_
.allocation_count());
655 // One initial asynchronous request and then 10 pending requests.
656 EXPECT_EQ(11U, completion_count());
658 // First part of requests, all with the same priority, finishes in FIFO order.
659 EXPECT_EQ(1, GetOrderOfRequest(1));
660 EXPECT_EQ(2, GetOrderOfRequest(2));
661 EXPECT_EQ(3, GetOrderOfRequest(3));
662 EXPECT_EQ(4, GetOrderOfRequest(4));
663 EXPECT_EQ(5, GetOrderOfRequest(5));
664 EXPECT_EQ(6, GetOrderOfRequest(6));
666 // Make sure that rest of the requests complete in the order of priority.
667 EXPECT_EQ(7, GetOrderOfRequest(7));
668 EXPECT_EQ(14, GetOrderOfRequest(8));
669 EXPECT_EQ(15, GetOrderOfRequest(9));
670 EXPECT_EQ(10, GetOrderOfRequest(10));
671 EXPECT_EQ(13, GetOrderOfRequest(11));
672 EXPECT_EQ(8, GetOrderOfRequest(12));
673 EXPECT_EQ(16, GetOrderOfRequest(13));
674 EXPECT_EQ(11, GetOrderOfRequest(14));
675 EXPECT_EQ(12, GetOrderOfRequest(15));
676 EXPECT_EQ(9, GetOrderOfRequest(16));
678 // Make sure we test order of all requests made.
679 EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds
, GetOrderOfRequest(17));
682 TEST_F(TransportClientSocketPoolTest
, PendingRequests_NoKeepAlive
) {
683 // First request finishes asynchronously.
684 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
685 EXPECT_EQ(OK
, (*requests())[0]->WaitForResult());
687 // Make all subsequent host resolutions complete synchronously.
688 host_resolver_
->set_synchronous_mode(true);
690 // Rest of them finish synchronously, until we reach the per-group limit.
691 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
692 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
693 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
694 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
695 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
697 // The rest are pending since we've used all active sockets.
698 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
699 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
700 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
701 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
702 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
704 ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE
);
706 // The pending requests should finish successfully.
707 EXPECT_EQ(OK
, (*requests())[6]->WaitForResult());
708 EXPECT_EQ(OK
, (*requests())[7]->WaitForResult());
709 EXPECT_EQ(OK
, (*requests())[8]->WaitForResult());
710 EXPECT_EQ(OK
, (*requests())[9]->WaitForResult());
711 EXPECT_EQ(OK
, (*requests())[10]->WaitForResult());
713 EXPECT_EQ(static_cast<int>(requests()->size()),
714 client_socket_factory_
.allocation_count());
716 // First asynchronous request, and then last 5 pending requests.
717 EXPECT_EQ(6U, completion_count());
720 // This test will start up a RequestSocket() and then immediately Cancel() it.
721 // The pending host resolution will eventually complete, and destroy the
722 // ClientSocketPool which will crash if the group was not cleared properly.
723 TEST_F(TransportClientSocketPoolTest
, CancelRequestClearGroup
) {
724 TestCompletionCallback callback
;
725 ClientSocketHandle handle
;
726 EXPECT_EQ(ERR_IO_PENDING
,
727 handle
.Init("a", params_
, kDefaultPriority
, callback
.callback(),
728 &pool_
, BoundNetLog()));
732 TEST_F(TransportClientSocketPoolTest
, TwoRequestsCancelOne
) {
733 ClientSocketHandle handle
;
734 TestCompletionCallback callback
;
735 ClientSocketHandle handle2
;
736 TestCompletionCallback callback2
;
738 EXPECT_EQ(ERR_IO_PENDING
,
739 handle
.Init("a", params_
, kDefaultPriority
, callback
.callback(),
740 &pool_
, BoundNetLog()));
741 EXPECT_EQ(ERR_IO_PENDING
,
742 handle2
.Init("a", params_
, kDefaultPriority
, callback2
.callback(),
743 &pool_
, BoundNetLog()));
747 EXPECT_EQ(OK
, callback2
.WaitForResult());
751 TEST_F(TransportClientSocketPoolTest
, ConnectCancelConnect
) {
752 client_socket_factory_
.set_client_socket_type(
753 MockClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET
);
754 ClientSocketHandle handle
;
755 TestCompletionCallback callback
;
756 EXPECT_EQ(ERR_IO_PENDING
,
757 handle
.Init("a", params_
, kDefaultPriority
, callback
.callback(),
758 &pool_
, BoundNetLog()));
762 TestCompletionCallback callback2
;
763 EXPECT_EQ(ERR_IO_PENDING
,
764 handle
.Init("a", params_
, kDefaultPriority
, callback2
.callback(),
765 &pool_
, BoundNetLog()));
767 host_resolver_
->set_synchronous_mode(true);
768 // At this point, handle has two ConnectingSockets out for it. Due to the
769 // setting the mock resolver into synchronous mode, the host resolution for
770 // both will return in the same loop of the MessageLoop. The client socket
771 // is a pending socket, so the Connect() will asynchronously complete on the
772 // next loop of the MessageLoop. That means that the first
773 // ConnectingSocket will enter OnIOComplete, and then the second one will.
774 // If the first one is not cancelled, it will advance the load state, and
775 // then the second one will crash.
777 EXPECT_EQ(OK
, callback2
.WaitForResult());
778 EXPECT_FALSE(callback
.have_result());
783 TEST_F(TransportClientSocketPoolTest
, CancelRequest
) {
784 // First request finishes asynchronously.
785 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
786 EXPECT_EQ(OK
, (*requests())[0]->WaitForResult());
788 // Make all subsequent host resolutions complete synchronously.
789 host_resolver_
->set_synchronous_mode(true);
791 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
792 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
793 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
794 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
795 EXPECT_EQ(OK
, StartRequest("a", kDefaultPriority
));
797 // Reached per-group limit, queue up requests.
798 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", LOWEST
));
799 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", HIGHEST
));
800 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", HIGHEST
));
801 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", MEDIUM
));
802 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", MEDIUM
));
803 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", LOW
));
804 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", HIGHEST
));
805 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", LOW
));
806 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", LOW
));
807 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", LOWEST
));
810 size_t index_to_cancel
= kMaxSocketsPerGroup
+ 2;
811 EXPECT_FALSE((*requests())[index_to_cancel
]->handle()->is_initialized());
812 (*requests())[index_to_cancel
]->handle()->Reset();
814 ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE
);
816 EXPECT_EQ(kMaxSocketsPerGroup
,
817 client_socket_factory_
.allocation_count());
818 EXPECT_EQ(requests()->size() - kMaxSocketsPerGroup
, completion_count());
820 EXPECT_EQ(1, GetOrderOfRequest(1));
821 EXPECT_EQ(2, GetOrderOfRequest(2));
822 EXPECT_EQ(3, GetOrderOfRequest(3));
823 EXPECT_EQ(4, GetOrderOfRequest(4));
824 EXPECT_EQ(5, GetOrderOfRequest(5));
825 EXPECT_EQ(6, GetOrderOfRequest(6));
826 EXPECT_EQ(14, GetOrderOfRequest(7));
827 EXPECT_EQ(7, GetOrderOfRequest(8));
828 EXPECT_EQ(ClientSocketPoolTest::kRequestNotFound
,
829 GetOrderOfRequest(9)); // Canceled request.
830 EXPECT_EQ(9, GetOrderOfRequest(10));
831 EXPECT_EQ(10, GetOrderOfRequest(11));
832 EXPECT_EQ(11, GetOrderOfRequest(12));
833 EXPECT_EQ(8, GetOrderOfRequest(13));
834 EXPECT_EQ(12, GetOrderOfRequest(14));
835 EXPECT_EQ(13, GetOrderOfRequest(15));
836 EXPECT_EQ(15, GetOrderOfRequest(16));
838 // Make sure we test order of all requests made.
839 EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds
, GetOrderOfRequest(17));
842 class RequestSocketCallback
: public TestCompletionCallbackBase
{
844 RequestSocketCallback(ClientSocketHandle
* handle
,
845 TransportClientSocketPool
* pool
)
848 within_callback_(false),
849 callback_(base::Bind(&RequestSocketCallback::OnComplete
,
850 base::Unretained(this))) {
853 virtual ~RequestSocketCallback() {}
855 const CompletionCallback
& callback() const { return callback_
; }
858 void OnComplete(int result
) {
860 ASSERT_EQ(OK
, result
);
862 if (!within_callback_
) {
863 // Don't allow reuse of the socket. Disconnect it and then release it and
864 // run through the MessageLoop once to get it completely released.
865 handle_
->socket()->Disconnect();
868 base::MessageLoop::ScopedNestableTaskAllower
allow(
869 base::MessageLoop::current());
870 base::MessageLoop::current()->RunUntilIdle();
872 within_callback_
= true;
873 scoped_refptr
<TransportSocketParams
> dest(new TransportSocketParams(
874 HostPortPair("www.google.com", 80), false, false,
875 OnHostResolutionCallback()));
876 int rv
= handle_
->Init("a", dest
, LOWEST
, callback(), pool_
,
882 ClientSocketHandle
* const handle_
;
883 TransportClientSocketPool
* const pool_
;
884 bool within_callback_
;
885 CompletionCallback callback_
;
887 DISALLOW_COPY_AND_ASSIGN(RequestSocketCallback
);
890 TEST_F(TransportClientSocketPoolTest
, RequestTwice
) {
891 ClientSocketHandle handle
;
892 RequestSocketCallback
callback(&handle
, &pool_
);
893 scoped_refptr
<TransportSocketParams
> dest(new TransportSocketParams(
894 HostPortPair("www.google.com", 80), false, false,
895 OnHostResolutionCallback()));
896 int rv
= handle
.Init("a", dest
, LOWEST
, callback
.callback(), &pool_
,
898 ASSERT_EQ(ERR_IO_PENDING
, rv
);
900 // The callback is going to request "www.google.com". We want it to complete
901 // synchronously this time.
902 host_resolver_
->set_synchronous_mode(true);
904 EXPECT_EQ(OK
, callback
.WaitForResult());
909 // Make sure that pending requests get serviced after active requests get
911 TEST_F(TransportClientSocketPoolTest
, CancelActiveRequestWithPendingRequests
) {
912 client_socket_factory_
.set_client_socket_type(
913 MockClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET
);
915 // Queue up all the requests
916 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
917 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
918 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
919 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
920 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
921 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
922 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
923 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
924 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
926 // Now, kMaxSocketsPerGroup requests should be active. Let's cancel them.
927 ASSERT_LE(kMaxSocketsPerGroup
, static_cast<int>(requests()->size()));
928 for (int i
= 0; i
< kMaxSocketsPerGroup
; i
++)
929 (*requests())[i
]->handle()->Reset();
931 // Let's wait for the rest to complete now.
932 for (size_t i
= kMaxSocketsPerGroup
; i
< requests()->size(); ++i
) {
933 EXPECT_EQ(OK
, (*requests())[i
]->WaitForResult());
934 (*requests())[i
]->handle()->Reset();
937 EXPECT_EQ(requests()->size() - kMaxSocketsPerGroup
, completion_count());
940 // Make sure that pending requests get serviced after active requests fail.
941 TEST_F(TransportClientSocketPoolTest
, FailingActiveRequestWithPendingRequests
) {
942 client_socket_factory_
.set_client_socket_type(
943 MockClientSocketFactory::MOCK_PENDING_FAILING_CLIENT_SOCKET
);
945 const int kNumRequests
= 2 * kMaxSocketsPerGroup
+ 1;
946 ASSERT_LE(kNumRequests
, kMaxSockets
); // Otherwise the test will hang.
948 // Queue up all the requests
949 for (int i
= 0; i
< kNumRequests
; i
++)
950 EXPECT_EQ(ERR_IO_PENDING
, StartRequest("a", kDefaultPriority
));
952 for (int i
= 0; i
< kNumRequests
; i
++)
953 EXPECT_EQ(ERR_CONNECTION_FAILED
, (*requests())[i
]->WaitForResult());
956 TEST_F(TransportClientSocketPoolTest
, IdleSocketLoadTiming
) {
957 TestCompletionCallback callback
;
958 ClientSocketHandle handle
;
959 int rv
= handle
.Init("a", params_
, LOW
, callback
.callback(), &pool_
,
961 EXPECT_EQ(ERR_IO_PENDING
, rv
);
962 EXPECT_FALSE(handle
.is_initialized());
963 EXPECT_FALSE(handle
.socket());
965 EXPECT_EQ(OK
, callback
.WaitForResult());
966 EXPECT_TRUE(handle
.is_initialized());
967 EXPECT_TRUE(handle
.socket());
968 TestLoadTimingInfoConnectedNotReused(handle
);
971 // Need to run all pending to release the socket back to the pool.
972 base::MessageLoop::current()->RunUntilIdle();
974 // Now we should have 1 idle socket.
975 EXPECT_EQ(1, pool_
.IdleSocketCount());
977 rv
= handle
.Init("a", params_
, LOW
, callback
.callback(), &pool_
,
980 EXPECT_EQ(0, pool_
.IdleSocketCount());
981 TestLoadTimingInfoConnectedReused(handle
);
984 TEST_F(TransportClientSocketPoolTest
, ResetIdleSocketsOnIPAddressChange
) {
985 TestCompletionCallback callback
;
986 ClientSocketHandle handle
;
987 int rv
= handle
.Init("a", params_
, LOW
, callback
.callback(), &pool_
,
989 EXPECT_EQ(ERR_IO_PENDING
, rv
);
990 EXPECT_FALSE(handle
.is_initialized());
991 EXPECT_FALSE(handle
.socket());
993 EXPECT_EQ(OK
, callback
.WaitForResult());
994 EXPECT_TRUE(handle
.is_initialized());
995 EXPECT_TRUE(handle
.socket());
999 // Need to run all pending to release the socket back to the pool.
1000 base::MessageLoop::current()->RunUntilIdle();
1002 // Now we should have 1 idle socket.
1003 EXPECT_EQ(1, pool_
.IdleSocketCount());
1005 // After an IP address change, we should have 0 idle sockets.
1006 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1007 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1009 EXPECT_EQ(0, pool_
.IdleSocketCount());
1012 TEST_F(TransportClientSocketPoolTest
, BackupSocketConnect
) {
1013 // Case 1 tests the first socket stalling, and the backup connecting.
1014 MockClientSocketFactory::ClientSocketType case1_types
[] = {
1015 // The first socket will not connect.
1016 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET
,
1017 // The second socket will connect more quickly.
1018 MockClientSocketFactory::MOCK_CLIENT_SOCKET
1021 // Case 2 tests the first socket being slow, so that we start the
1022 // second connect, but the second connect stalls, and we still
1023 // complete the first.
1024 MockClientSocketFactory::ClientSocketType case2_types
[] = {
1025 // The first socket will connect, although delayed.
1026 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET
,
1027 // The second socket will not connect.
1028 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET
1031 MockClientSocketFactory::ClientSocketType
* cases
[2] = {
1036 for (size_t index
= 0; index
< arraysize(cases
); ++index
) {
1037 client_socket_factory_
.set_client_socket_types(cases
[index
], 2);
1039 EXPECT_EQ(0, pool_
.IdleSocketCount());
1041 TestCompletionCallback callback
;
1042 ClientSocketHandle handle
;
1043 int rv
= handle
.Init("b", params_
, LOW
, callback
.callback(), &pool_
,
1045 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1046 EXPECT_FALSE(handle
.is_initialized());
1047 EXPECT_FALSE(handle
.socket());
1049 // Create the first socket, set the timer.
1050 base::MessageLoop::current()->RunUntilIdle();
1052 // Wait for the backup socket timer to fire.
1053 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1054 ClientSocketPool::kMaxConnectRetryIntervalMs
+ 50));
1056 // Let the appropriate socket connect.
1057 base::MessageLoop::current()->RunUntilIdle();
1059 EXPECT_EQ(OK
, callback
.WaitForResult());
1060 EXPECT_TRUE(handle
.is_initialized());
1061 EXPECT_TRUE(handle
.socket());
1063 // One socket is stalled, the other is active.
1064 EXPECT_EQ(0, pool_
.IdleSocketCount());
1067 // Close all pending connect jobs and existing sockets.
1068 pool_
.FlushWithError(ERR_NETWORK_CHANGED
);
1072 // Test the case where a socket took long enough to start the creation
1073 // of the backup socket, but then we cancelled the request after that.
1074 TEST_F(TransportClientSocketPoolTest
, BackupSocketCancel
) {
1075 client_socket_factory_
.set_client_socket_type(
1076 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET
);
1078 enum { CANCEL_BEFORE_WAIT
, CANCEL_AFTER_WAIT
};
1080 for (int index
= CANCEL_BEFORE_WAIT
; index
< CANCEL_AFTER_WAIT
; ++index
) {
1081 EXPECT_EQ(0, pool_
.IdleSocketCount());
1083 TestCompletionCallback callback
;
1084 ClientSocketHandle handle
;
1085 int rv
= handle
.Init("c", params_
, LOW
, callback
.callback(), &pool_
,
1087 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1088 EXPECT_FALSE(handle
.is_initialized());
1089 EXPECT_FALSE(handle
.socket());
1091 // Create the first socket, set the timer.
1092 base::MessageLoop::current()->RunUntilIdle();
1094 if (index
== CANCEL_AFTER_WAIT
) {
1095 // Wait for the backup socket timer to fire.
1096 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1097 ClientSocketPool::kMaxConnectRetryIntervalMs
));
1100 // Let the appropriate socket connect.
1101 base::MessageLoop::current()->RunUntilIdle();
1105 EXPECT_FALSE(callback
.have_result());
1106 EXPECT_FALSE(handle
.is_initialized());
1107 EXPECT_FALSE(handle
.socket());
1109 // One socket is stalled, the other is active.
1110 EXPECT_EQ(0, pool_
.IdleSocketCount());
1114 // Test the case where a socket took long enough to start the creation
1115 // of the backup socket and never completes, and then the backup
1116 // connection fails.
1117 TEST_F(TransportClientSocketPoolTest
, BackupSocketFailAfterStall
) {
1118 MockClientSocketFactory::ClientSocketType case_types
[] = {
1119 // The first socket will not connect.
1120 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET
,
1121 // The second socket will fail immediately.
1122 MockClientSocketFactory::MOCK_FAILING_CLIENT_SOCKET
1125 client_socket_factory_
.set_client_socket_types(case_types
, 2);
1127 EXPECT_EQ(0, pool_
.IdleSocketCount());
1129 TestCompletionCallback callback
;
1130 ClientSocketHandle handle
;
1131 int rv
= handle
.Init("b", params_
, LOW
, callback
.callback(), &pool_
,
1133 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1134 EXPECT_FALSE(handle
.is_initialized());
1135 EXPECT_FALSE(handle
.socket());
1137 // Create the first socket, set the timer.
1138 base::MessageLoop::current()->RunUntilIdle();
1140 // Wait for the backup socket timer to fire.
1141 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1142 ClientSocketPool::kMaxConnectRetryIntervalMs
));
1144 // Let the second connect be synchronous. Otherwise, the emulated
1145 // host resolution takes an extra trip through the message loop.
1146 host_resolver_
->set_synchronous_mode(true);
1148 // Let the appropriate socket connect.
1149 base::MessageLoop::current()->RunUntilIdle();
1151 EXPECT_EQ(ERR_CONNECTION_FAILED
, callback
.WaitForResult());
1152 EXPECT_FALSE(handle
.is_initialized());
1153 EXPECT_FALSE(handle
.socket());
1154 EXPECT_EQ(0, pool_
.IdleSocketCount());
1157 // Reset for the next case.
1158 host_resolver_
->set_synchronous_mode(false);
1161 // Test the case where a socket took long enough to start the creation
1162 // of the backup socket and eventually completes, but the backup socket
1164 TEST_F(TransportClientSocketPoolTest
, BackupSocketFailAfterDelay
) {
1165 MockClientSocketFactory::ClientSocketType case_types
[] = {
1166 // The first socket will connect, although delayed.
1167 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET
,
1168 // The second socket will not connect.
1169 MockClientSocketFactory::MOCK_FAILING_CLIENT_SOCKET
1172 client_socket_factory_
.set_client_socket_types(case_types
, 2);
1173 client_socket_factory_
.set_delay(base::TimeDelta::FromSeconds(5));
1175 EXPECT_EQ(0, pool_
.IdleSocketCount());
1177 TestCompletionCallback callback
;
1178 ClientSocketHandle handle
;
1179 int rv
= handle
.Init("b", params_
, LOW
, callback
.callback(), &pool_
,
1181 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1182 EXPECT_FALSE(handle
.is_initialized());
1183 EXPECT_FALSE(handle
.socket());
1185 // Create the first socket, set the timer.
1186 base::MessageLoop::current()->RunUntilIdle();
1188 // Wait for the backup socket timer to fire.
1189 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1190 ClientSocketPool::kMaxConnectRetryIntervalMs
));
1192 // Let the second connect be synchronous. Otherwise, the emulated
1193 // host resolution takes an extra trip through the message loop.
1194 host_resolver_
->set_synchronous_mode(true);
1196 // Let the appropriate socket connect.
1197 base::MessageLoop::current()->RunUntilIdle();
1199 EXPECT_EQ(ERR_CONNECTION_FAILED
, callback
.WaitForResult());
1200 EXPECT_FALSE(handle
.is_initialized());
1201 EXPECT_FALSE(handle
.socket());
1204 // Reset for the next case.
1205 host_resolver_
->set_synchronous_mode(false);
1208 // Test the case of the IPv6 address stalling, and falling back to the IPv4
1209 // socket which finishes first.
1210 TEST_F(TransportClientSocketPoolTest
, IPv6FallbackSocketIPv4FinishesFirst
) {
1211 // Create a pool without backup jobs.
1212 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(false);
1213 TransportClientSocketPool
pool(kMaxSockets
,
1214 kMaxSocketsPerGroup
,
1216 host_resolver_
.get(),
1217 &client_socket_factory_
,
1220 MockClientSocketFactory::ClientSocketType case_types
[] = {
1221 // This is the IPv6 socket.
1222 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET
,
1223 // This is the IPv4 socket.
1224 MockClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET
1227 client_socket_factory_
.set_client_socket_types(case_types
, 2);
1229 // Resolve an AddressList with a IPv6 address first and then a IPv4 address.
1230 host_resolver_
->rules()
1231 ->AddIPLiteralRule("*", "2:abcd::3:4:ff,2.2.2.2", std::string());
1233 TestCompletionCallback callback
;
1234 ClientSocketHandle handle
;
1235 int rv
= handle
.Init("a", params_
, LOW
, callback
.callback(), &pool
,
1237 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1238 EXPECT_FALSE(handle
.is_initialized());
1239 EXPECT_FALSE(handle
.socket());
1241 EXPECT_EQ(OK
, callback
.WaitForResult());
1242 EXPECT_TRUE(handle
.is_initialized());
1243 EXPECT_TRUE(handle
.socket());
1244 IPEndPoint endpoint
;
1245 handle
.socket()->GetLocalAddress(&endpoint
);
1246 EXPECT_EQ(kIPv4AddressSize
, endpoint
.address().size());
1247 EXPECT_EQ(2, client_socket_factory_
.allocation_count());
1250 // Test the case of the IPv6 address being slow, thus falling back to trying to
1251 // connect to the IPv4 address, but having the connect to the IPv6 address
1253 TEST_F(TransportClientSocketPoolTest
, IPv6FallbackSocketIPv6FinishesFirst
) {
1254 // Create a pool without backup jobs.
1255 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(false);
1256 TransportClientSocketPool
pool(kMaxSockets
,
1257 kMaxSocketsPerGroup
,
1259 host_resolver_
.get(),
1260 &client_socket_factory_
,
1263 MockClientSocketFactory::ClientSocketType case_types
[] = {
1264 // This is the IPv6 socket.
1265 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET
,
1266 // This is the IPv4 socket.
1267 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET
1270 client_socket_factory_
.set_client_socket_types(case_types
, 2);
1271 client_socket_factory_
.set_delay(base::TimeDelta::FromMilliseconds(
1272 TransportConnectJob::kIPv6FallbackTimerInMs
+ 50));
1274 // Resolve an AddressList with a IPv6 address first and then a IPv4 address.
1275 host_resolver_
->rules()
1276 ->AddIPLiteralRule("*", "2:abcd::3:4:ff,2.2.2.2", std::string());
1278 TestCompletionCallback callback
;
1279 ClientSocketHandle handle
;
1280 int rv
= handle
.Init("a", params_
, LOW
, callback
.callback(), &pool
,
1282 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1283 EXPECT_FALSE(handle
.is_initialized());
1284 EXPECT_FALSE(handle
.socket());
1286 EXPECT_EQ(OK
, callback
.WaitForResult());
1287 EXPECT_TRUE(handle
.is_initialized());
1288 EXPECT_TRUE(handle
.socket());
1289 IPEndPoint endpoint
;
1290 handle
.socket()->GetLocalAddress(&endpoint
);
1291 EXPECT_EQ(kIPv6AddressSize
, endpoint
.address().size());
1292 EXPECT_EQ(2, client_socket_factory_
.allocation_count());
1295 TEST_F(TransportClientSocketPoolTest
, IPv6NoIPv4AddressesToFallbackTo
) {
1296 // Create a pool without backup jobs.
1297 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(false);
1298 TransportClientSocketPool
pool(kMaxSockets
,
1299 kMaxSocketsPerGroup
,
1301 host_resolver_
.get(),
1302 &client_socket_factory_
,
1305 client_socket_factory_
.set_client_socket_type(
1306 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET
);
1308 // Resolve an AddressList with only IPv6 addresses.
1309 host_resolver_
->rules()
1310 ->AddIPLiteralRule("*", "2:abcd::3:4:ff,3:abcd::3:4:ff", std::string());
1312 TestCompletionCallback callback
;
1313 ClientSocketHandle handle
;
1314 int rv
= handle
.Init("a", params_
, LOW
, callback
.callback(), &pool
,
1316 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1317 EXPECT_FALSE(handle
.is_initialized());
1318 EXPECT_FALSE(handle
.socket());
1320 EXPECT_EQ(OK
, callback
.WaitForResult());
1321 EXPECT_TRUE(handle
.is_initialized());
1322 EXPECT_TRUE(handle
.socket());
1323 IPEndPoint endpoint
;
1324 handle
.socket()->GetLocalAddress(&endpoint
);
1325 EXPECT_EQ(kIPv6AddressSize
, endpoint
.address().size());
1326 EXPECT_EQ(1, client_socket_factory_
.allocation_count());
1329 TEST_F(TransportClientSocketPoolTest
, IPv4HasNoFallback
) {
1330 // Create a pool without backup jobs.
1331 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(false);
1332 TransportClientSocketPool
pool(kMaxSockets
,
1333 kMaxSocketsPerGroup
,
1335 host_resolver_
.get(),
1336 &client_socket_factory_
,
1339 client_socket_factory_
.set_client_socket_type(
1340 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET
);
1342 // Resolve an AddressList with only IPv4 addresses.
1343 host_resolver_
->rules()->AddIPLiteralRule("*", "1.1.1.1", std::string());
1345 TestCompletionCallback callback
;
1346 ClientSocketHandle handle
;
1347 int rv
= handle
.Init("a", params_
, LOW
, callback
.callback(), &pool
,
1349 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1350 EXPECT_FALSE(handle
.is_initialized());
1351 EXPECT_FALSE(handle
.socket());
1353 EXPECT_EQ(OK
, callback
.WaitForResult());
1354 EXPECT_TRUE(handle
.is_initialized());
1355 EXPECT_TRUE(handle
.socket());
1356 IPEndPoint endpoint
;
1357 handle
.socket()->GetLocalAddress(&endpoint
);
1358 EXPECT_EQ(kIPv4AddressSize
, endpoint
.address().size());
1359 EXPECT_EQ(1, client_socket_factory_
.allocation_count());