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/socket_test_util.h"
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/compiler_specific.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/run_loop.h"
16 #include "base/time/time.h"
17 #include "net/base/address_family.h"
18 #include "net/base/address_list.h"
19 #include "net/base/auth.h"
20 #include "net/base/load_timing_info.h"
21 #include "net/http/http_network_session.h"
22 #include "net/http/http_request_headers.h"
23 #include "net/http/http_response_headers.h"
24 #include "net/socket/client_socket_pool_histograms.h"
25 #include "net/socket/socket.h"
26 #include "net/socket/websocket_endpoint_lock_manager.h"
27 #include "net/ssl/ssl_cert_request_info.h"
28 #include "net/ssl/ssl_connection_status_flags.h"
29 #include "net/ssl/ssl_info.h"
30 #include "testing/gtest/include/gtest/gtest.h"
32 // Socket events are easier to debug if you log individual reads and writes.
33 // Enable these if locally debugging, but they are too noisy for the waterfall.
35 #define NET_TRACE(level, s) DLOG(level) << s << __FUNCTION__ << "() "
37 #define NET_TRACE(level, s) EAT_STREAM_PARAMETERS
44 inline char AsciifyHigh(char x
) {
45 char nybble
= static_cast<char>((x
>> 4) & 0x0F);
46 return nybble
+ ((nybble
< 0x0A) ? '0' : 'A' - 10);
49 inline char AsciifyLow(char x
) {
50 char nybble
= static_cast<char>((x
>> 0) & 0x0F);
51 return nybble
+ ((nybble
< 0x0A) ? '0' : 'A' - 10);
54 inline char Asciify(char x
) {
55 if ((x
< 0) || !isprint(x
))
60 void DumpData(const char* data
, int data_len
) {
61 if (logging::LOG_INFO
< logging::GetMinLogLevel())
63 DVLOG(1) << "Length: " << data_len
;
64 const char* pfx
= "Data: ";
65 if (!data
|| (data_len
<= 0)) {
66 DVLOG(1) << pfx
<< "<None>";
69 for (i
= 0; i
<= (data_len
- 4); i
+= 4) {
71 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
72 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
73 << AsciifyHigh(data
[i
+ 2]) << AsciifyLow(data
[i
+ 2])
74 << AsciifyHigh(data
[i
+ 3]) << AsciifyLow(data
[i
+ 3])
76 << Asciify(data
[i
+ 0])
77 << Asciify(data
[i
+ 1])
78 << Asciify(data
[i
+ 2])
79 << Asciify(data
[i
+ 3])
83 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
84 switch (data_len
- i
) {
87 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
88 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
89 << AsciifyHigh(data
[i
+ 2]) << AsciifyLow(data
[i
+ 2])
91 << Asciify(data
[i
+ 0])
92 << Asciify(data
[i
+ 1])
93 << Asciify(data
[i
+ 2])
98 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
99 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
101 << Asciify(data
[i
+ 0])
102 << Asciify(data
[i
+ 1])
107 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
109 << Asciify(data
[i
+ 0])
116 template <MockReadWriteType type
>
117 void DumpMockReadWrite(const MockReadWrite
<type
>& r
) {
118 if (logging::LOG_INFO
< logging::GetMinLogLevel())
120 DVLOG(1) << "Async: " << (r
.mode
== ASYNC
)
121 << "\nResult: " << r
.result
;
122 DumpData(r
.data
, r
.data_len
);
123 const char* stop
= (r
.sequence_number
& MockRead::STOPLOOP
) ? " (STOP)" : "";
124 DVLOG(1) << "Stage: " << (r
.sequence_number
& ~MockRead::STOPLOOP
) << stop
125 << "\nTime: " << r
.time_stamp
.ToInternalValue();
130 MockConnect::MockConnect() : mode(ASYNC
), result(OK
) {
132 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
133 peer_addr
= IPEndPoint(ip
, 0);
136 MockConnect::MockConnect(IoMode io_mode
, int r
) : mode(io_mode
), result(r
) {
138 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
139 peer_addr
= IPEndPoint(ip
, 0);
142 MockConnect::MockConnect(IoMode io_mode
, int r
, IPEndPoint addr
) :
148 MockConnect::~MockConnect() {}
150 StaticSocketDataProvider::StaticSocketDataProvider()
159 StaticSocketDataProvider::StaticSocketDataProvider(MockRead
* reads
,
165 read_count_(reads_count
),
168 write_count_(writes_count
) {
171 StaticSocketDataProvider::~StaticSocketDataProvider() {}
173 const MockRead
& StaticSocketDataProvider::PeekRead() const {
174 CHECK(!at_read_eof());
175 return reads_
[read_index_
];
178 const MockWrite
& StaticSocketDataProvider::PeekWrite() const {
179 CHECK(!at_write_eof());
180 return writes_
[write_index_
];
183 const MockRead
& StaticSocketDataProvider::PeekRead(size_t index
) const {
184 CHECK_LT(index
, read_count_
);
185 return reads_
[index
];
188 const MockWrite
& StaticSocketDataProvider::PeekWrite(size_t index
) const {
189 CHECK_LT(index
, write_count_
);
190 return writes_
[index
];
193 MockRead
StaticSocketDataProvider::GetNextRead() {
194 CHECK(!at_read_eof());
195 reads_
[read_index_
].time_stamp
= base::Time::Now();
196 return reads_
[read_index_
++];
199 MockWriteResult
StaticSocketDataProvider::OnWrite(const std::string
& data
) {
201 // Not using mock writes; succeed synchronously.
202 return MockWriteResult(SYNCHRONOUS
, data
.length());
204 EXPECT_FALSE(at_write_eof());
205 if (at_write_eof()) {
206 // Show what the extra write actually consists of.
207 EXPECT_EQ("<unexpected write>", data
);
208 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
211 // Check that what we are writing matches the expectation.
212 // Then give the mocked return value.
213 MockWrite
* w
= &writes_
[write_index_
++];
214 w
->time_stamp
= base::Time::Now();
215 int result
= w
->result
;
217 // Note - we can simulate a partial write here. If the expected data
218 // is a match, but shorter than the write actually written, that is legal.
220 // Application writes "foobarbaz" (9 bytes)
221 // Expected write was "foo" (3 bytes)
222 // This is a success, and we return 3 to the application.
223 std::string
expected_data(w
->data
, w
->data_len
);
224 EXPECT_GE(data
.length(), expected_data
.length());
225 std::string
actual_data(data
.substr(0, w
->data_len
));
226 EXPECT_EQ(expected_data
, actual_data
);
227 if (expected_data
!= actual_data
)
228 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
230 result
= w
->data_len
;
232 return MockWriteResult(w
->mode
, result
);
235 void StaticSocketDataProvider::Reset() {
240 DynamicSocketDataProvider::DynamicSocketDataProvider()
241 : short_read_limit_(0),
242 allow_unconsumed_reads_(false) {
245 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
247 MockRead
DynamicSocketDataProvider::GetNextRead() {
249 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
250 MockRead result
= reads_
.front();
251 if (short_read_limit_
== 0 || result
.data_len
<= short_read_limit_
) {
254 result
.data_len
= short_read_limit_
;
255 reads_
.front().data
+= result
.data_len
;
256 reads_
.front().data_len
-= result
.data_len
;
261 void DynamicSocketDataProvider::Reset() {
265 void DynamicSocketDataProvider::SimulateRead(const char* data
,
266 const size_t length
) {
267 if (!allow_unconsumed_reads_
) {
268 EXPECT_TRUE(reads_
.empty()) << "Unconsumed read: " << reads_
.front().data
;
270 reads_
.push_back(MockRead(ASYNC
, data
, length
));
273 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode
, int result
)
274 : connect(mode
, result
),
275 next_proto_status(SSLClientSocket::kNextProtoUnsupported
),
276 was_npn_negotiated(false),
277 protocol_negotiated(kProtoUnknown
),
278 client_cert_sent(false),
279 cert_request_info(NULL
),
280 channel_id_sent(false),
281 connection_status(0) {
282 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2
,
284 // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
285 SSLConnectionStatusSetCipherSuite(0xcc14, &connection_status
);
288 SSLSocketDataProvider::~SSLSocketDataProvider() {
291 void SSLSocketDataProvider::SetNextProto(NextProto proto
) {
292 was_npn_negotiated
= true;
293 next_proto_status
= SSLClientSocket::kNextProtoNegotiated
;
294 protocol_negotiated
= proto
;
295 next_proto
= SSLClientSocket::NextProtoToString(proto
);
298 DelayedSocketData::DelayedSocketData(
299 int write_delay
, MockRead
* reads
, size_t reads_count
,
300 MockWrite
* writes
, size_t writes_count
)
301 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
302 write_delay_(write_delay
),
303 read_in_progress_(false),
304 weak_factory_(this) {
305 DCHECK_GE(write_delay_
, 0);
308 DelayedSocketData::DelayedSocketData(
309 const MockConnect
& connect
, int write_delay
, MockRead
* reads
,
310 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
311 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
312 write_delay_(write_delay
),
313 read_in_progress_(false),
314 weak_factory_(this) {
315 DCHECK_GE(write_delay_
, 0);
316 set_connect_data(connect
);
319 DelayedSocketData::~DelayedSocketData() {
322 void DelayedSocketData::ForceNextRead() {
323 DCHECK(read_in_progress_
);
328 MockRead
DelayedSocketData::GetNextRead() {
329 MockRead out
= MockRead(ASYNC
, ERR_IO_PENDING
);
330 if (write_delay_
<= 0)
331 out
= StaticSocketDataProvider::GetNextRead();
332 read_in_progress_
= (out
.result
== ERR_IO_PENDING
);
336 MockWriteResult
DelayedSocketData::OnWrite(const std::string
& data
) {
337 MockWriteResult rv
= StaticSocketDataProvider::OnWrite(data
);
338 // Now that our write has completed, we can allow reads to continue.
339 if (!--write_delay_
&& read_in_progress_
)
340 base::MessageLoop::current()->PostDelayedTask(
342 base::Bind(&DelayedSocketData::CompleteRead
,
343 weak_factory_
.GetWeakPtr()),
344 base::TimeDelta::FromMilliseconds(100));
348 void DelayedSocketData::Reset() {
350 read_in_progress_
= false;
351 weak_factory_
.InvalidateWeakPtrs();
352 StaticSocketDataProvider::Reset();
355 void DelayedSocketData::CompleteRead() {
356 if (socket() && read_in_progress_
)
357 socket()->OnReadComplete(GetNextRead());
360 OrderedSocketData::OrderedSocketData(
361 MockRead
* reads
, size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
362 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
363 sequence_number_(0), loop_stop_stage_(0),
364 blocked_(false), weak_factory_(this) {
367 OrderedSocketData::OrderedSocketData(
368 const MockConnect
& connect
,
369 MockRead
* reads
, size_t reads_count
,
370 MockWrite
* writes
, size_t writes_count
)
371 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
372 sequence_number_(0), loop_stop_stage_(0),
373 blocked_(false), weak_factory_(this) {
374 set_connect_data(connect
);
377 void OrderedSocketData::EndLoop() {
378 // If we've already stopped the loop, don't do it again until we've advanced
379 // to the next sequence_number.
380 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
<< ": EndLoop()";
381 if (loop_stop_stage_
> 0) {
382 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
383 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) >
385 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
386 << ": Clearing stop index";
387 loop_stop_stage_
= 0;
392 // Record the sequence_number at which we stopped the loop.
393 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
394 << ": Posting Quit at read " << read_index();
395 loop_stop_stage_
= sequence_number_
;
398 MockRead
OrderedSocketData::GetNextRead() {
399 weak_factory_
.InvalidateWeakPtrs();
401 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
402 if (next_read
.sequence_number
& MockRead::STOPLOOP
)
404 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) <=
405 sequence_number_
++) {
406 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
407 << ": Read " << read_index();
408 DumpMockReadWrite(next_read
);
409 blocked_
= (next_read
.result
== ERR_IO_PENDING
);
410 return StaticSocketDataProvider::GetNextRead();
412 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
414 MockRead result
= MockRead(ASYNC
, ERR_IO_PENDING
);
415 DumpMockReadWrite(result
);
420 MockWriteResult
OrderedSocketData::OnWrite(const std::string
& data
) {
421 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
422 << ": Write " << write_index();
423 DumpMockReadWrite(PeekWrite());
426 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
427 // should probably fix the weirdness. One example is in SpdyStream,
428 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
429 // SYN_REPLY causes OnResponseReceived() to get called before
430 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
431 base::MessageLoop::current()->PostDelayedTask(
433 base::Bind(&OrderedSocketData::CompleteRead
,
434 weak_factory_
.GetWeakPtr()),
435 base::TimeDelta::FromMilliseconds(100));
437 return StaticSocketDataProvider::OnWrite(data
);
440 void OrderedSocketData::Reset() {
441 NET_TRACE(INFO
, " *** ") << "Stage "
442 << sequence_number_
<< ": Reset()";
443 sequence_number_
= 0;
444 loop_stop_stage_
= 0;
446 weak_factory_
.InvalidateWeakPtrs();
447 StaticSocketDataProvider::Reset();
450 void OrderedSocketData::CompleteRead() {
451 if (socket() && blocked_
) {
452 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
;
453 socket()->OnReadComplete(GetNextRead());
457 OrderedSocketData::~OrderedSocketData() {}
459 DeterministicSocketData::DeterministicSocketData(MockRead
* reads
,
460 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
461 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
465 stopping_sequence_number_(0),
469 VerifyCorrectSequenceNumbers(reads
, reads_count
, writes
, writes_count
);
472 DeterministicSocketData::~DeterministicSocketData() {}
474 void DeterministicSocketData::Run() {
475 DCHECK(!is_running_
);
480 // Continue to consume data until all data has run out, or the stopped_ flag
481 // has been set. Consuming data requires two separate operations -- running
482 // the tasks in the message loop, and explicitly invoking the read/write
483 // callbacks (simulating network I/O). We check our conditions between each,
484 // since they can change in either.
485 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
486 if (counter
% 2 == 0)
487 base::RunLoop().RunUntilIdle();
488 if (counter
% 2 == 1) {
493 // We're done consuming new data, but it is possible there are still some
494 // pending callbacks which we expect to complete before returning.
495 while (delegate_
.get() &&
496 (delegate_
->WritePending() || delegate_
->ReadPending()) &&
499 base::RunLoop().RunUntilIdle();
505 void DeterministicSocketData::RunFor(int steps
) {
510 void DeterministicSocketData::SetStop(int seq
) {
511 DCHECK_LT(sequence_number_
, seq
);
512 stopping_sequence_number_
= seq
;
516 void DeterministicSocketData::StopAfter(int seq
) {
517 SetStop(sequence_number_
+ seq
);
520 MockRead
DeterministicSocketData::GetNextRead() {
521 current_read_
= StaticSocketDataProvider::PeekRead();
523 // Synchronous read while stopped is an error
524 if (stopped() && current_read_
.mode
== SYNCHRONOUS
) {
525 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
526 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
529 // Async read which will be called back in a future step.
530 if (sequence_number_
< current_read_
.sequence_number
) {
531 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
533 MockRead result
= MockRead(SYNCHRONOUS
, ERR_IO_PENDING
);
534 if (current_read_
.mode
== SYNCHRONOUS
) {
535 LOG(ERROR
) << "Unable to perform synchronous read: "
536 << current_read_
.sequence_number
537 << " at stage: " << sequence_number_
;
538 result
= MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
541 DumpMockReadWrite(result
);
545 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
546 << ": Read " << read_index();
548 DumpMockReadWrite(current_read_
);
550 // Increment the sequence number if IO is complete
551 if (current_read_
.mode
== SYNCHRONOUS
)
554 DCHECK_NE(ERR_IO_PENDING
, current_read_
.result
);
555 StaticSocketDataProvider::GetNextRead();
557 return current_read_
;
560 MockWriteResult
DeterministicSocketData::OnWrite(const std::string
& data
) {
561 const MockWrite
& next_write
= StaticSocketDataProvider::PeekWrite();
562 current_write_
= next_write
;
564 // Synchronous write while stopped is an error
565 if (stopped() && next_write
.mode
== SYNCHRONOUS
) {
566 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
567 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
570 // Async write which will be called back in a future step.
571 if (sequence_number_
< next_write
.sequence_number
) {
572 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
574 if (next_write
.mode
== SYNCHRONOUS
) {
575 LOG(ERROR
) << "Unable to perform synchronous write: "
576 << next_write
.sequence_number
<< " at stage: " << sequence_number_
;
577 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
580 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
581 << ": Write " << write_index();
585 DumpMockReadWrite(next_write
);
587 // Move to the next step if I/O is synchronous, since the operation will
588 // complete when this method returns.
589 if (next_write
.mode
== SYNCHRONOUS
)
592 // This is either a sync write for this step, or an async write.
593 return StaticSocketDataProvider::OnWrite(data
);
596 void DeterministicSocketData::Reset() {
597 NET_TRACE(INFO
, " *** ") << "Stage "
598 << sequence_number_
<< ": Reset()";
599 sequence_number_
= 0;
600 StaticSocketDataProvider::Reset();
604 void DeterministicSocketData::InvokeCallbacks() {
605 if (delegate_
.get() && delegate_
->WritePending() &&
606 (current_write().sequence_number
== sequence_number())) {
608 delegate_
->CompleteWrite();
611 if (delegate_
.get() && delegate_
->ReadPending() &&
612 (current_read().sequence_number
== sequence_number())) {
614 delegate_
->CompleteRead();
619 void DeterministicSocketData::NextStep() {
620 // Invariant: Can never move *past* the stopping step.
621 DCHECK_LT(sequence_number_
, stopping_sequence_number_
);
623 if (sequence_number_
== stopping_sequence_number_
)
627 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
628 MockRead
* reads
, size_t reads_count
,
629 MockWrite
* writes
, size_t writes_count
) {
633 while (read
< reads_count
|| write
< writes_count
) {
634 // Check to see that we have a read or write at the expected
636 if (read
< reads_count
&& reads
[read
].sequence_number
== expected
) {
641 if (write
< writes_count
&& writes
[write
].sequence_number
== expected
) {
646 NOTREACHED() << "Missing sequence number: " << expected
;
649 DCHECK_EQ(read
, reads_count
);
650 DCHECK_EQ(write
, writes_count
);
653 MockClientSocketFactory::MockClientSocketFactory() {}
655 MockClientSocketFactory::~MockClientSocketFactory() {}
657 void MockClientSocketFactory::AddSocketDataProvider(
658 SocketDataProvider
* data
) {
659 mock_data_
.Add(data
);
662 void MockClientSocketFactory::AddSSLSocketDataProvider(
663 SSLSocketDataProvider
* data
) {
664 mock_ssl_data_
.Add(data
);
667 void MockClientSocketFactory::ResetNextMockIndexes() {
668 mock_data_
.ResetNextIndex();
669 mock_ssl_data_
.ResetNextIndex();
672 scoped_ptr
<DatagramClientSocket
>
673 MockClientSocketFactory::CreateDatagramClientSocket(
674 DatagramSocket::BindType bind_type
,
675 const RandIntCallback
& rand_int_cb
,
676 net::NetLog
* net_log
,
677 const net::NetLog::Source
& source
) {
678 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
679 scoped_ptr
<MockUDPClientSocket
> socket(
680 new MockUDPClientSocket(data_provider
, net_log
));
681 data_provider
->set_socket(socket
.get());
682 if (bind_type
== DatagramSocket::RANDOM_BIND
)
683 socket
->set_source_port(static_cast<uint16
>(rand_int_cb
.Run(1025, 65535)));
684 return socket
.Pass();
687 scoped_ptr
<StreamSocket
> MockClientSocketFactory::CreateTransportClientSocket(
688 const AddressList
& addresses
,
689 net::NetLog
* net_log
,
690 const net::NetLog::Source
& source
) {
691 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
692 scoped_ptr
<MockTCPClientSocket
> socket(
693 new MockTCPClientSocket(addresses
, net_log
, data_provider
));
694 data_provider
->set_socket(socket
.get());
695 return socket
.Pass();
698 scoped_ptr
<SSLClientSocket
> MockClientSocketFactory::CreateSSLClientSocket(
699 scoped_ptr
<ClientSocketHandle
> transport_socket
,
700 const HostPortPair
& host_and_port
,
701 const SSLConfig
& ssl_config
,
702 const SSLClientSocketContext
& context
) {
703 SSLSocketDataProvider
* next_ssl_data
= mock_ssl_data_
.GetNext();
704 if (!next_ssl_data
->next_protos_expected_in_ssl_config
.empty()) {
705 EXPECT_EQ(next_ssl_data
->next_protos_expected_in_ssl_config
.size(),
706 ssl_config
.next_protos
.size());
708 std::equal(next_ssl_data
->next_protos_expected_in_ssl_config
.begin(),
709 next_ssl_data
->next_protos_expected_in_ssl_config
.end(),
710 ssl_config
.next_protos
.begin()));
712 return scoped_ptr
<SSLClientSocket
>(new MockSSLClientSocket(
713 transport_socket
.Pass(), host_and_port
, ssl_config
, next_ssl_data
));
716 void MockClientSocketFactory::ClearSSLSessionCache() {
719 const char MockClientSocket::kTlsUnique
[] = "MOCK_TLSUNIQ";
721 MockClientSocket::MockClientSocket(const BoundNetLog
& net_log
)
724 weak_factory_(this) {
726 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
727 peer_addr_
= IPEndPoint(ip
, 0);
730 int MockClientSocket::SetReceiveBufferSize(int32 size
) {
734 int MockClientSocket::SetSendBufferSize(int32 size
) {
738 void MockClientSocket::Disconnect() {
742 bool MockClientSocket::IsConnected() const {
746 bool MockClientSocket::IsConnectedAndIdle() const {
750 int MockClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
752 return ERR_SOCKET_NOT_CONNECTED
;
753 *address
= peer_addr_
;
757 int MockClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
759 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
761 *address
= IPEndPoint(ip
, 123);
765 const BoundNetLog
& MockClientSocket::NetLog() const {
769 void MockClientSocket::GetSSLCertRequestInfo(
770 SSLCertRequestInfo
* cert_request_info
) {
773 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece
& label
,
775 const base::StringPiece
& context
,
777 unsigned int outlen
) {
778 memset(out
, 'A', outlen
);
782 int MockClientSocket::GetTLSUniqueChannelBinding(std::string
* out
) {
783 out
->assign(MockClientSocket::kTlsUnique
);
787 ChannelIDService
* MockClientSocket::GetChannelIDService() const {
792 SSLClientSocket::NextProtoStatus
793 MockClientSocket::GetNextProto(std::string
* proto
) {
795 return SSLClientSocket::kNextProtoUnsupported
;
798 scoped_refptr
<X509Certificate
>
799 MockClientSocket::GetUnverifiedServerCertificateChain() const {
804 MockClientSocket::~MockClientSocket() {}
806 void MockClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
808 base::MessageLoop::current()->PostTask(
810 base::Bind(&MockClientSocket::RunCallback
,
811 weak_factory_
.GetWeakPtr(),
816 void MockClientSocket::RunCallback(const net::CompletionCallback
& callback
,
818 if (!callback
.is_null())
819 callback
.Run(result
);
822 MockTCPClientSocket::MockTCPClientSocket(const AddressList
& addresses
,
823 net::NetLog
* net_log
,
824 SocketDataProvider
* data
)
825 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
826 addresses_(addresses
),
829 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
830 need_read_data_(true),
831 peer_closed_connection_(false),
834 was_used_to_convey_data_(false) {
836 peer_addr_
= data
->connect_data().peer_addr
;
840 MockTCPClientSocket::~MockTCPClientSocket() {}
842 int MockTCPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
843 const CompletionCallback
& callback
) {
845 return ERR_UNEXPECTED
;
847 // If the buffer is already in use, a read is already in progress!
848 DCHECK(pending_buf_
.get() == NULL
);
850 // Store our async IO data.
852 pending_buf_len_
= buf_len
;
853 pending_callback_
= callback
;
855 if (need_read_data_
) {
856 read_data_
= data_
->GetNextRead();
857 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
858 // This MockRead is just a marker to instruct us to set
859 // peer_closed_connection_.
860 peer_closed_connection_
= true;
862 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
863 // This MockRead is just a marker to instruct us to set
864 // peer_closed_connection_. Skip it and get the next one.
865 read_data_
= data_
->GetNextRead();
866 peer_closed_connection_
= true;
868 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
869 // to complete the async IO manually later (via OnReadComplete).
870 if (read_data_
.result
== ERR_IO_PENDING
) {
871 // We need to be using async IO in this case.
872 DCHECK(!callback
.is_null());
873 return ERR_IO_PENDING
;
875 need_read_data_
= false;
878 return CompleteRead();
881 int MockTCPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
882 const CompletionCallback
& callback
) {
884 DCHECK_GT(buf_len
, 0);
887 return ERR_UNEXPECTED
;
889 std::string
data(buf
->data(), buf_len
);
890 MockWriteResult write_result
= data_
->OnWrite(data
);
892 was_used_to_convey_data_
= true;
894 if (write_result
.mode
== ASYNC
) {
895 RunCallbackAsync(callback
, write_result
.result
);
896 return ERR_IO_PENDING
;
899 return write_result
.result
;
902 int MockTCPClientSocket::Connect(const CompletionCallback
& callback
) {
906 peer_closed_connection_
= false;
907 if (data_
->connect_data().mode
== ASYNC
) {
908 if (data_
->connect_data().result
== ERR_IO_PENDING
)
909 pending_callback_
= callback
;
911 RunCallbackAsync(callback
, data_
->connect_data().result
);
912 return ERR_IO_PENDING
;
914 return data_
->connect_data().result
;
917 void MockTCPClientSocket::Disconnect() {
918 MockClientSocket::Disconnect();
919 pending_callback_
.Reset();
922 bool MockTCPClientSocket::IsConnected() const {
923 return connected_
&& !peer_closed_connection_
;
926 bool MockTCPClientSocket::IsConnectedAndIdle() const {
927 return IsConnected();
930 int MockTCPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
931 if (addresses_
.empty())
932 return MockClientSocket::GetPeerAddress(address
);
934 *address
= addresses_
[0];
938 bool MockTCPClientSocket::WasEverUsed() const {
939 return was_used_to_convey_data_
;
942 bool MockTCPClientSocket::UsingTCPFastOpen() const {
946 bool MockTCPClientSocket::WasNpnNegotiated() const {
950 bool MockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
954 void MockTCPClientSocket::OnReadComplete(const MockRead
& data
) {
955 // There must be a read pending.
956 DCHECK(pending_buf_
.get());
957 // You can't complete a read with another ERR_IO_PENDING status code.
958 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
959 // Since we've been waiting for data, need_read_data_ should be true.
960 DCHECK(need_read_data_
);
963 need_read_data_
= false;
965 // The caller is simulating that this IO completes right now. Don't
966 // let CompleteRead() schedule a callback.
967 read_data_
.mode
= SYNCHRONOUS
;
969 CompletionCallback callback
= pending_callback_
;
970 int rv
= CompleteRead();
971 RunCallback(callback
, rv
);
974 void MockTCPClientSocket::OnConnectComplete(const MockConnect
& data
) {
975 CompletionCallback callback
= pending_callback_
;
976 RunCallback(callback
, data
.result
);
979 int MockTCPClientSocket::CompleteRead() {
980 DCHECK(pending_buf_
.get());
981 DCHECK(pending_buf_len_
> 0);
983 was_used_to_convey_data_
= true;
985 // Save the pending async IO data and reset our |pending_| state.
986 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
987 int buf_len
= pending_buf_len_
;
988 CompletionCallback callback
= pending_callback_
;
990 pending_buf_len_
= 0;
991 pending_callback_
.Reset();
993 int result
= read_data_
.result
;
994 DCHECK(result
!= ERR_IO_PENDING
);
996 if (read_data_
.data
) {
997 if (read_data_
.data_len
- read_offset_
> 0) {
998 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
999 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
1000 read_offset_
+= result
;
1001 if (read_offset_
== read_data_
.data_len
) {
1002 need_read_data_
= true;
1010 if (read_data_
.mode
== ASYNC
) {
1011 DCHECK(!callback
.is_null());
1012 RunCallbackAsync(callback
, result
);
1013 return ERR_IO_PENDING
;
1018 DeterministicSocketHelper::DeterministicSocketHelper(
1019 net::NetLog
* net_log
,
1020 DeterministicSocketData
* data
)
1021 : write_pending_(false),
1026 read_pending_(false),
1028 was_used_to_convey_data_(false),
1029 peer_closed_connection_(false),
1030 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)) {
1033 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1035 void DeterministicSocketHelper::CompleteWrite() {
1036 was_used_to_convey_data_
= true;
1037 write_pending_
= false;
1038 write_callback_
.Run(write_result_
);
1041 int DeterministicSocketHelper::CompleteRead() {
1042 DCHECK_GT(read_buf_len_
, 0);
1043 DCHECK_LE(read_data_
.data_len
, read_buf_len_
);
1046 was_used_to_convey_data_
= true;
1048 if (read_data_
.result
== ERR_IO_PENDING
)
1049 read_data_
= data_
->GetNextRead();
1050 DCHECK_NE(ERR_IO_PENDING
, read_data_
.result
);
1051 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1052 // the callback. Therefore we don't even bother to check it.
1053 int result
= read_data_
.result
;
1055 if (read_data_
.data_len
> 0) {
1056 DCHECK(read_data_
.data
);
1057 result
= std::min(read_buf_len_
, read_data_
.data_len
);
1058 memcpy(read_buf_
->data(), read_data_
.data
, result
);
1061 if (read_pending_
) {
1062 read_pending_
= false;
1063 read_callback_
.Run(result
);
1069 int DeterministicSocketHelper::Write(
1070 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1072 DCHECK_GT(buf_len
, 0);
1074 std::string
data(buf
->data(), buf_len
);
1075 MockWriteResult write_result
= data_
->OnWrite(data
);
1077 if (write_result
.mode
== ASYNC
) {
1078 write_callback_
= callback
;
1079 write_result_
= write_result
.result
;
1080 DCHECK(!write_callback_
.is_null());
1081 write_pending_
= true;
1082 return ERR_IO_PENDING
;
1085 was_used_to_convey_data_
= true;
1086 write_pending_
= false;
1087 return write_result
.result
;
1090 int DeterministicSocketHelper::Read(
1091 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1093 read_data_
= data_
->GetNextRead();
1094 // The buffer should always be big enough to contain all the MockRead data. To
1095 // use small buffers, split the data into multiple MockReads.
1096 DCHECK_LE(read_data_
.data_len
, buf_len
);
1098 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
1099 // This MockRead is just a marker to instruct us to set
1100 // peer_closed_connection_.
1101 peer_closed_connection_
= true;
1103 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
1104 // This MockRead is just a marker to instruct us to set
1105 // peer_closed_connection_. Skip it and get the next one.
1106 read_data_
= data_
->GetNextRead();
1107 peer_closed_connection_
= true;
1111 read_buf_len_
= buf_len
;
1112 read_callback_
= callback
;
1114 if (read_data_
.mode
== ASYNC
|| (read_data_
.result
== ERR_IO_PENDING
)) {
1115 read_pending_
= true;
1116 DCHECK(!read_callback_
.is_null());
1117 return ERR_IO_PENDING
;
1120 was_used_to_convey_data_
= true;
1121 return CompleteRead();
1124 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1125 net::NetLog
* net_log
,
1126 DeterministicSocketData
* data
)
1127 : connected_(false),
1128 helper_(net_log
, data
),
1132 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1134 bool DeterministicMockUDPClientSocket::WritePending() const {
1135 return helper_
.write_pending();
1138 bool DeterministicMockUDPClientSocket::ReadPending() const {
1139 return helper_
.read_pending();
1142 void DeterministicMockUDPClientSocket::CompleteWrite() {
1143 helper_
.CompleteWrite();
1146 int DeterministicMockUDPClientSocket::CompleteRead() {
1147 return helper_
.CompleteRead();
1150 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1154 peer_address_
= address
;
1155 return helper_
.data()->connect_data().result
;
1158 int DeterministicMockUDPClientSocket::Write(
1161 const CompletionCallback
& callback
) {
1163 return ERR_UNEXPECTED
;
1165 return helper_
.Write(buf
, buf_len
, callback
);
1168 int DeterministicMockUDPClientSocket::Read(
1171 const CompletionCallback
& callback
) {
1173 return ERR_UNEXPECTED
;
1175 return helper_
.Read(buf
, buf_len
, callback
);
1178 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1182 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size
) {
1186 void DeterministicMockUDPClientSocket::Close() {
1190 int DeterministicMockUDPClientSocket::GetPeerAddress(
1191 IPEndPoint
* address
) const {
1192 *address
= peer_address_
;
1196 int DeterministicMockUDPClientSocket::GetLocalAddress(
1197 IPEndPoint
* address
) const {
1199 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1201 *address
= IPEndPoint(ip
, source_port_
);
1205 const BoundNetLog
& DeterministicMockUDPClientSocket::NetLog() const {
1206 return helper_
.net_log();
1209 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead
& data
) {}
1211 void DeterministicMockUDPClientSocket::OnConnectComplete(
1212 const MockConnect
& data
) {
1216 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1217 net::NetLog
* net_log
,
1218 DeterministicSocketData
* data
)
1219 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1220 helper_(net_log
, data
) {
1221 peer_addr_
= data
->connect_data().peer_addr
;
1224 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1226 bool DeterministicMockTCPClientSocket::WritePending() const {
1227 return helper_
.write_pending();
1230 bool DeterministicMockTCPClientSocket::ReadPending() const {
1231 return helper_
.read_pending();
1234 void DeterministicMockTCPClientSocket::CompleteWrite() {
1235 helper_
.CompleteWrite();
1238 int DeterministicMockTCPClientSocket::CompleteRead() {
1239 return helper_
.CompleteRead();
1242 int DeterministicMockTCPClientSocket::Write(
1245 const CompletionCallback
& callback
) {
1247 return ERR_UNEXPECTED
;
1249 return helper_
.Write(buf
, buf_len
, callback
);
1252 int DeterministicMockTCPClientSocket::Read(
1255 const CompletionCallback
& callback
) {
1257 return ERR_UNEXPECTED
;
1259 return helper_
.Read(buf
, buf_len
, callback
);
1262 // TODO(erikchen): Support connect sequencing.
1263 int DeterministicMockTCPClientSocket::Connect(
1264 const CompletionCallback
& callback
) {
1268 if (helper_
.data()->connect_data().mode
== ASYNC
) {
1269 RunCallbackAsync(callback
, helper_
.data()->connect_data().result
);
1270 return ERR_IO_PENDING
;
1272 return helper_
.data()->connect_data().result
;
1275 void DeterministicMockTCPClientSocket::Disconnect() {
1276 MockClientSocket::Disconnect();
1279 bool DeterministicMockTCPClientSocket::IsConnected() const {
1280 return connected_
&& !helper_
.peer_closed_connection();
1283 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1284 return IsConnected();
1287 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1288 return helper_
.was_used_to_convey_data();
1291 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1295 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1299 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1303 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead
& data
) {}
1305 void DeterministicMockTCPClientSocket::OnConnectComplete(
1306 const MockConnect
& data
) {}
1309 void MockSSLClientSocket::ConnectCallback(
1310 MockSSLClientSocket
* ssl_client_socket
,
1311 const CompletionCallback
& callback
,
1314 ssl_client_socket
->connected_
= true;
1318 MockSSLClientSocket::MockSSLClientSocket(
1319 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1320 const HostPortPair
& host_port_pair
,
1321 const SSLConfig
& ssl_config
,
1322 SSLSocketDataProvider
* data
)
1324 // Have to use the right BoundNetLog for LoadTimingInfo regression
1326 transport_socket
->socket()->NetLog()),
1327 transport_(transport_socket
.Pass()),
1329 is_npn_state_set_(false),
1330 new_npn_value_(false),
1331 is_protocol_negotiated_set_(false),
1332 protocol_negotiated_(kProtoUnknown
) {
1334 peer_addr_
= data
->connect
.peer_addr
;
1337 MockSSLClientSocket::~MockSSLClientSocket() {
1341 int MockSSLClientSocket::Read(IOBuffer
* buf
, int buf_len
,
1342 const CompletionCallback
& callback
) {
1343 return transport_
->socket()->Read(buf
, buf_len
, callback
);
1346 int MockSSLClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1347 const CompletionCallback
& callback
) {
1348 return transport_
->socket()->Write(buf
, buf_len
, callback
);
1351 int MockSSLClientSocket::Connect(const CompletionCallback
& callback
) {
1352 int rv
= transport_
->socket()->Connect(
1353 base::Bind(&ConnectCallback
, base::Unretained(this), callback
));
1355 if (data_
->connect
.result
== OK
)
1357 if (data_
->connect
.mode
== ASYNC
) {
1358 RunCallbackAsync(callback
, data_
->connect
.result
);
1359 return ERR_IO_PENDING
;
1361 return data_
->connect
.result
;
1366 void MockSSLClientSocket::Disconnect() {
1367 MockClientSocket::Disconnect();
1368 if (transport_
->socket() != NULL
)
1369 transport_
->socket()->Disconnect();
1372 bool MockSSLClientSocket::IsConnected() const {
1373 return transport_
->socket()->IsConnected();
1376 bool MockSSLClientSocket::WasEverUsed() const {
1377 return transport_
->socket()->WasEverUsed();
1380 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1381 return transport_
->socket()->UsingTCPFastOpen();
1384 int MockSSLClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1385 return transport_
->socket()->GetPeerAddress(address
);
1388 bool MockSSLClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1390 ssl_info
->cert
= data_
->cert
;
1391 ssl_info
->client_cert_sent
= data_
->client_cert_sent
;
1392 ssl_info
->channel_id_sent
= data_
->channel_id_sent
;
1393 ssl_info
->connection_status
= data_
->connection_status
;
1397 void MockSSLClientSocket::GetSSLCertRequestInfo(
1398 SSLCertRequestInfo
* cert_request_info
) {
1399 DCHECK(cert_request_info
);
1400 if (data_
->cert_request_info
) {
1401 cert_request_info
->host_and_port
=
1402 data_
->cert_request_info
->host_and_port
;
1403 cert_request_info
->client_certs
= data_
->cert_request_info
->client_certs
;
1405 cert_request_info
->Reset();
1409 SSLClientSocket::NextProtoStatus
MockSSLClientSocket::GetNextProto(
1410 std::string
* proto
) {
1411 *proto
= data_
->next_proto
;
1412 return data_
->next_proto_status
;
1415 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated
) {
1416 is_npn_state_set_
= true;
1417 return new_npn_value_
= negotiated
;
1420 bool MockSSLClientSocket::WasNpnNegotiated() const {
1421 if (is_npn_state_set_
)
1422 return new_npn_value_
;
1423 return data_
->was_npn_negotiated
;
1426 NextProto
MockSSLClientSocket::GetNegotiatedProtocol() const {
1427 if (is_protocol_negotiated_set_
)
1428 return protocol_negotiated_
;
1429 return data_
->protocol_negotiated
;
1432 void MockSSLClientSocket::set_protocol_negotiated(
1433 NextProto protocol_negotiated
) {
1434 is_protocol_negotiated_set_
= true;
1435 protocol_negotiated_
= protocol_negotiated
;
1438 bool MockSSLClientSocket::WasChannelIDSent() const {
1439 return data_
->channel_id_sent
;
1442 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent
) {
1443 data_
->channel_id_sent
= channel_id_sent
;
1446 ChannelIDService
* MockSSLClientSocket::GetChannelIDService() const {
1447 return data_
->channel_id_service
;
1450 void MockSSLClientSocket::OnReadComplete(const MockRead
& data
) {
1454 void MockSSLClientSocket::OnConnectComplete(const MockConnect
& data
) {
1458 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider
* data
,
1459 net::NetLog
* net_log
)
1460 : connected_(false),
1463 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
1464 need_read_data_(true),
1467 pending_buf_len_(0),
1468 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1469 weak_factory_(this) {
1472 peer_addr_
= data
->connect_data().peer_addr
;
1475 MockUDPClientSocket::~MockUDPClientSocket() {}
1477 int MockUDPClientSocket::Read(IOBuffer
* buf
,
1479 const CompletionCallback
& callback
) {
1481 return ERR_UNEXPECTED
;
1483 // If the buffer is already in use, a read is already in progress!
1484 DCHECK(pending_buf_
.get() == NULL
);
1486 // Store our async IO data.
1488 pending_buf_len_
= buf_len
;
1489 pending_callback_
= callback
;
1491 if (need_read_data_
) {
1492 read_data_
= data_
->GetNextRead();
1493 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1494 // to complete the async IO manually later (via OnReadComplete).
1495 if (read_data_
.result
== ERR_IO_PENDING
) {
1496 // We need to be using async IO in this case.
1497 DCHECK(!callback
.is_null());
1498 return ERR_IO_PENDING
;
1500 need_read_data_
= false;
1503 return CompleteRead();
1506 int MockUDPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1507 const CompletionCallback
& callback
) {
1509 DCHECK_GT(buf_len
, 0);
1512 return ERR_UNEXPECTED
;
1514 std::string
data(buf
->data(), buf_len
);
1515 MockWriteResult write_result
= data_
->OnWrite(data
);
1517 if (write_result
.mode
== ASYNC
) {
1518 RunCallbackAsync(callback
, write_result
.result
);
1519 return ERR_IO_PENDING
;
1521 return write_result
.result
;
1524 int MockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1528 int MockUDPClientSocket::SetSendBufferSize(int32 size
) {
1532 void MockUDPClientSocket::Close() {
1536 int MockUDPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1537 *address
= peer_addr_
;
1541 int MockUDPClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
1543 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1545 *address
= IPEndPoint(ip
, source_port_
);
1549 const BoundNetLog
& MockUDPClientSocket::NetLog() const {
1553 int MockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1555 peer_addr_
= address
;
1556 return data_
->connect_data().result
;
1559 void MockUDPClientSocket::OnReadComplete(const MockRead
& data
) {
1560 // There must be a read pending.
1561 DCHECK(pending_buf_
.get());
1562 // You can't complete a read with another ERR_IO_PENDING status code.
1563 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
1564 // Since we've been waiting for data, need_read_data_ should be true.
1565 DCHECK(need_read_data_
);
1568 need_read_data_
= false;
1570 // The caller is simulating that this IO completes right now. Don't
1571 // let CompleteRead() schedule a callback.
1572 read_data_
.mode
= SYNCHRONOUS
;
1574 net::CompletionCallback callback
= pending_callback_
;
1575 int rv
= CompleteRead();
1576 RunCallback(callback
, rv
);
1579 void MockUDPClientSocket::OnConnectComplete(const MockConnect
& data
) {
1583 int MockUDPClientSocket::CompleteRead() {
1584 DCHECK(pending_buf_
.get());
1585 DCHECK(pending_buf_len_
> 0);
1587 // Save the pending async IO data and reset our |pending_| state.
1588 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
1589 int buf_len
= pending_buf_len_
;
1590 CompletionCallback callback
= pending_callback_
;
1591 pending_buf_
= NULL
;
1592 pending_buf_len_
= 0;
1593 pending_callback_
.Reset();
1595 int result
= read_data_
.result
;
1596 DCHECK(result
!= ERR_IO_PENDING
);
1598 if (read_data_
.data
) {
1599 if (read_data_
.data_len
- read_offset_
> 0) {
1600 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
1601 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
1602 read_offset_
+= result
;
1603 if (read_offset_
== read_data_
.data_len
) {
1604 need_read_data_
= true;
1612 if (read_data_
.mode
== ASYNC
) {
1613 DCHECK(!callback
.is_null());
1614 RunCallbackAsync(callback
, result
);
1615 return ERR_IO_PENDING
;
1620 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
1622 base::MessageLoop::current()->PostTask(
1624 base::Bind(&MockUDPClientSocket::RunCallback
,
1625 weak_factory_
.GetWeakPtr(),
1630 void MockUDPClientSocket::RunCallback(const CompletionCallback
& callback
,
1632 if (!callback
.is_null())
1633 callback
.Run(result
);
1636 TestSocketRequest::TestSocketRequest(
1637 std::vector
<TestSocketRequest
*>* request_order
, size_t* completion_count
)
1638 : request_order_(request_order
),
1639 completion_count_(completion_count
),
1640 callback_(base::Bind(&TestSocketRequest::OnComplete
,
1641 base::Unretained(this))) {
1642 DCHECK(request_order
);
1643 DCHECK(completion_count
);
1646 TestSocketRequest::~TestSocketRequest() {
1649 void TestSocketRequest::OnComplete(int result
) {
1651 (*completion_count_
)++;
1652 request_order_
->push_back(this);
1656 const int ClientSocketPoolTest::kIndexOutOfBounds
= -1;
1659 const int ClientSocketPoolTest::kRequestNotFound
= -2;
1661 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1662 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1664 int ClientSocketPoolTest::GetOrderOfRequest(size_t index
) const {
1666 if (index
>= requests_
.size())
1667 return kIndexOutOfBounds
;
1669 for (size_t i
= 0; i
< request_order_
.size(); i
++)
1670 if (requests_
[index
] == request_order_
[i
])
1673 return kRequestNotFound
;
1676 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive
) {
1677 ScopedVector
<TestSocketRequest
>::iterator i
;
1678 for (i
= requests_
.begin(); i
!= requests_
.end(); ++i
) {
1679 if ((*i
)->handle()->is_initialized()) {
1680 if (keep_alive
== NO_KEEP_ALIVE
)
1681 (*i
)->handle()->socket()->Disconnect();
1682 (*i
)->handle()->Reset();
1683 base::RunLoop().RunUntilIdle();
1690 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive
) {
1693 released_one
= ReleaseOneConnection(keep_alive
);
1694 } while (released_one
);
1697 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1698 scoped_ptr
<StreamSocket
> socket
,
1699 ClientSocketHandle
* handle
,
1700 const CompletionCallback
& callback
)
1701 : socket_(socket
.Pass()),
1703 user_callback_(callback
) {
1706 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1708 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1709 int rv
= socket_
->Connect(base::Bind(&MockConnectJob::OnConnect
,
1710 base::Unretained(this)));
1712 user_callback_
.Reset();
1718 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1719 const ClientSocketHandle
* handle
) {
1720 if (handle
!= handle_
)
1724 user_callback_
.Reset();
1728 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv
) {
1732 handle_
->SetSocket(socket_
.Pass());
1734 // Needed for socket pool tests that layer other sockets on top of mock
1736 LoadTimingInfo::ConnectTiming connect_timing
;
1737 base::TimeTicks now
= base::TimeTicks::Now();
1738 connect_timing
.dns_start
= now
;
1739 connect_timing
.dns_end
= now
;
1740 connect_timing
.connect_start
= now
;
1741 connect_timing
.connect_end
= now
;
1742 handle_
->set_connect_timing(connect_timing
);
1749 if (!user_callback_
.is_null()) {
1750 CompletionCallback callback
= user_callback_
;
1751 user_callback_
.Reset();
1756 MockTransportClientSocketPool::MockTransportClientSocketPool(
1758 int max_sockets_per_group
,
1759 ClientSocketPoolHistograms
* histograms
,
1760 ClientSocketFactory
* socket_factory
)
1761 : TransportClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1763 client_socket_factory_(socket_factory
),
1764 last_request_priority_(DEFAULT_PRIORITY
),
1769 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1771 int MockTransportClientSocketPool::RequestSocket(
1772 const std::string
& group_name
, const void* socket_params
,
1773 RequestPriority priority
, ClientSocketHandle
* handle
,
1774 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1775 last_request_priority_
= priority
;
1776 scoped_ptr
<StreamSocket
> socket
=
1777 client_socket_factory_
->CreateTransportClientSocket(
1778 AddressList(), net_log
.net_log(), net::NetLog::Source());
1779 MockConnectJob
* job
= new MockConnectJob(socket
.Pass(), handle
, callback
);
1780 job_list_
.push_back(job
);
1781 handle
->set_pool_id(1);
1782 return job
->Connect();
1785 void MockTransportClientSocketPool::CancelRequest(const std::string
& group_name
,
1786 ClientSocketHandle
* handle
) {
1787 std::vector
<MockConnectJob
*>::iterator i
;
1788 for (i
= job_list_
.begin(); i
!= job_list_
.end(); ++i
) {
1789 if ((*i
)->CancelHandle(handle
)) {
1796 void MockTransportClientSocketPool::ReleaseSocket(
1797 const std::string
& group_name
,
1798 scoped_ptr
<StreamSocket
> socket
,
1804 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1806 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1808 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1809 DeterministicSocketData
* data
) {
1810 mock_data_
.Add(data
);
1813 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1814 SSLSocketDataProvider
* data
) {
1815 mock_ssl_data_
.Add(data
);
1818 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1819 mock_data_
.ResetNextIndex();
1820 mock_ssl_data_
.ResetNextIndex();
1823 MockSSLClientSocket
* DeterministicMockClientSocketFactory::
1824 GetMockSSLClientSocket(size_t index
) const {
1825 DCHECK_LT(index
, ssl_client_sockets_
.size());
1826 return ssl_client_sockets_
[index
];
1829 scoped_ptr
<DatagramClientSocket
>
1830 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1831 DatagramSocket::BindType bind_type
,
1832 const RandIntCallback
& rand_int_cb
,
1833 net::NetLog
* net_log
,
1834 const NetLog::Source
& source
) {
1835 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1836 scoped_ptr
<DeterministicMockUDPClientSocket
> socket(
1837 new DeterministicMockUDPClientSocket(net_log
, data_provider
));
1838 data_provider
->set_delegate(socket
->AsWeakPtr());
1839 udp_client_sockets().push_back(socket
.get());
1840 if (bind_type
== DatagramSocket::RANDOM_BIND
)
1841 socket
->set_source_port(static_cast<uint16
>(rand_int_cb
.Run(1025, 65535)));
1842 return socket
.Pass();
1845 scoped_ptr
<StreamSocket
>
1846 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1847 const AddressList
& addresses
,
1848 net::NetLog
* net_log
,
1849 const net::NetLog::Source
& source
) {
1850 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1851 scoped_ptr
<DeterministicMockTCPClientSocket
> socket(
1852 new DeterministicMockTCPClientSocket(net_log
, data_provider
));
1853 data_provider
->set_delegate(socket
->AsWeakPtr());
1854 tcp_client_sockets().push_back(socket
.get());
1855 return socket
.Pass();
1858 scoped_ptr
<SSLClientSocket
>
1859 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1860 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1861 const HostPortPair
& host_and_port
,
1862 const SSLConfig
& ssl_config
,
1863 const SSLClientSocketContext
& context
) {
1864 scoped_ptr
<MockSSLClientSocket
> socket(
1865 new MockSSLClientSocket(transport_socket
.Pass(),
1866 host_and_port
, ssl_config
,
1867 mock_ssl_data_
.GetNext()));
1868 ssl_client_sockets_
.push_back(socket
.get());
1869 return socket
.Pass();
1872 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1875 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1877 int max_sockets_per_group
,
1878 ClientSocketPoolHistograms
* histograms
,
1879 TransportClientSocketPool
* transport_pool
)
1880 : SOCKSClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1881 NULL
, transport_pool
, NULL
),
1882 transport_pool_(transport_pool
) {
1885 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1887 int MockSOCKSClientSocketPool::RequestSocket(
1888 const std::string
& group_name
, const void* socket_params
,
1889 RequestPriority priority
, ClientSocketHandle
* handle
,
1890 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1891 return transport_pool_
->RequestSocket(
1892 group_name
, socket_params
, priority
, handle
, callback
, net_log
);
1895 void MockSOCKSClientSocketPool::CancelRequest(
1896 const std::string
& group_name
,
1897 ClientSocketHandle
* handle
) {
1898 return transport_pool_
->CancelRequest(group_name
, handle
);
1901 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string
& group_name
,
1902 scoped_ptr
<StreamSocket
> socket
,
1904 return transport_pool_
->ReleaseSocket(group_name
, socket
.Pass(), id
);
1907 ScopedWebSocketEndpointZeroUnlockDelay::
1908 ScopedWebSocketEndpointZeroUnlockDelay() {
1910 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
1914 ScopedWebSocketEndpointZeroUnlockDelay::
1915 ~ScopedWebSocketEndpointZeroUnlockDelay() {
1916 base::TimeDelta active_delay
=
1917 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
1919 EXPECT_EQ(active_delay
, base::TimeDelta());
1922 const char kSOCKS5GreetRequest
[] = { 0x05, 0x01, 0x00 };
1923 const int kSOCKS5GreetRequestLength
= arraysize(kSOCKS5GreetRequest
);
1925 const char kSOCKS5GreetResponse
[] = { 0x05, 0x00 };
1926 const int kSOCKS5GreetResponseLength
= arraysize(kSOCKS5GreetResponse
);
1928 const char kSOCKS5OkRequest
[] =
1929 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1930 const int kSOCKS5OkRequestLength
= arraysize(kSOCKS5OkRequest
);
1932 const char kSOCKS5OkResponse
[] =
1933 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1934 const int kSOCKS5OkResponseLength
= arraysize(kSOCKS5OkResponse
);