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/socket.h"
25 #include "net/socket/websocket_endpoint_lock_manager.h"
26 #include "net/ssl/ssl_cert_request_info.h"
27 #include "net/ssl/ssl_connection_status_flags.h"
28 #include "net/ssl/ssl_info.h"
29 #include "testing/gtest/include/gtest/gtest.h"
31 // Socket events are easier to debug if you log individual reads and writes.
32 // Enable these if locally debugging, but they are too noisy for the waterfall.
34 #define NET_TRACE(level, s) DLOG(level) << s << __FUNCTION__ << "() "
36 #define NET_TRACE(level, s) EAT_STREAM_PARAMETERS
43 inline char AsciifyHigh(char x
) {
44 char nybble
= static_cast<char>((x
>> 4) & 0x0F);
45 return nybble
+ ((nybble
< 0x0A) ? '0' : 'A' - 10);
48 inline char AsciifyLow(char x
) {
49 char nybble
= static_cast<char>((x
>> 0) & 0x0F);
50 return nybble
+ ((nybble
< 0x0A) ? '0' : 'A' - 10);
53 inline char Asciify(char x
) {
54 if ((x
< 0) || !isprint(x
))
59 void DumpData(const char* data
, int data_len
) {
60 if (logging::LOG_INFO
< logging::GetMinLogLevel())
62 DVLOG(1) << "Length: " << data_len
;
63 const char* pfx
= "Data: ";
64 if (!data
|| (data_len
<= 0)) {
65 DVLOG(1) << pfx
<< "<None>";
68 for (i
= 0; i
<= (data_len
- 4); i
+= 4) {
70 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
71 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
72 << AsciifyHigh(data
[i
+ 2]) << AsciifyLow(data
[i
+ 2])
73 << AsciifyHigh(data
[i
+ 3]) << AsciifyLow(data
[i
+ 3])
75 << Asciify(data
[i
+ 0])
76 << Asciify(data
[i
+ 1])
77 << Asciify(data
[i
+ 2])
78 << Asciify(data
[i
+ 3])
82 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
83 switch (data_len
- i
) {
86 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
87 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
88 << AsciifyHigh(data
[i
+ 2]) << AsciifyLow(data
[i
+ 2])
90 << Asciify(data
[i
+ 0])
91 << Asciify(data
[i
+ 1])
92 << Asciify(data
[i
+ 2])
97 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
98 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
100 << Asciify(data
[i
+ 0])
101 << Asciify(data
[i
+ 1])
106 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
108 << Asciify(data
[i
+ 0])
115 template <MockReadWriteType type
>
116 void DumpMockReadWrite(const MockReadWrite
<type
>& r
) {
117 if (logging::LOG_INFO
< logging::GetMinLogLevel())
119 DVLOG(1) << "Async: " << (r
.mode
== ASYNC
)
120 << "\nResult: " << r
.result
;
121 DumpData(r
.data
, r
.data_len
);
122 const char* stop
= (r
.sequence_number
& MockRead::STOPLOOP
) ? " (STOP)" : "";
123 DVLOG(1) << "Stage: " << (r
.sequence_number
& ~MockRead::STOPLOOP
) << stop
124 << "\nTime: " << r
.time_stamp
.ToInternalValue();
129 MockConnect::MockConnect() : mode(ASYNC
), result(OK
) {
131 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
132 peer_addr
= IPEndPoint(ip
, 0);
135 MockConnect::MockConnect(IoMode io_mode
, int r
) : mode(io_mode
), result(r
) {
137 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
138 peer_addr
= IPEndPoint(ip
, 0);
141 MockConnect::MockConnect(IoMode io_mode
, int r
, IPEndPoint addr
) :
147 MockConnect::~MockConnect() {}
149 StaticSocketDataProvider::StaticSocketDataProvider()
158 StaticSocketDataProvider::StaticSocketDataProvider(MockRead
* reads
,
164 read_count_(reads_count
),
167 write_count_(writes_count
) {
170 StaticSocketDataProvider::~StaticSocketDataProvider() {}
172 const MockRead
& StaticSocketDataProvider::PeekRead() const {
173 CHECK(!at_read_eof());
174 return reads_
[read_index_
];
177 const MockWrite
& StaticSocketDataProvider::PeekWrite() const {
178 CHECK(!at_write_eof());
179 return writes_
[write_index_
];
182 const MockRead
& StaticSocketDataProvider::PeekRead(size_t index
) const {
183 CHECK_LT(index
, read_count_
);
184 return reads_
[index
];
187 const MockWrite
& StaticSocketDataProvider::PeekWrite(size_t index
) const {
188 CHECK_LT(index
, write_count_
);
189 return writes_
[index
];
192 MockRead
StaticSocketDataProvider::GetNextRead() {
193 CHECK(!at_read_eof());
194 reads_
[read_index_
].time_stamp
= base::Time::Now();
195 return reads_
[read_index_
++];
198 MockWriteResult
StaticSocketDataProvider::OnWrite(const std::string
& data
) {
200 // Not using mock writes; succeed synchronously.
201 return MockWriteResult(SYNCHRONOUS
, data
.length());
203 EXPECT_FALSE(at_write_eof());
204 if (at_write_eof()) {
205 // Show what the extra write actually consists of.
206 EXPECT_EQ("<unexpected write>", data
);
207 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
210 // Check that what we are writing matches the expectation.
211 // Then give the mocked return value.
212 MockWrite
* w
= &writes_
[write_index_
++];
213 w
->time_stamp
= base::Time::Now();
214 int result
= w
->result
;
216 // Note - we can simulate a partial write here. If the expected data
217 // is a match, but shorter than the write actually written, that is legal.
219 // Application writes "foobarbaz" (9 bytes)
220 // Expected write was "foo" (3 bytes)
221 // This is a success, and we return 3 to the application.
222 std::string
expected_data(w
->data
, w
->data_len
);
223 EXPECT_GE(data
.length(), expected_data
.length());
224 std::string
actual_data(data
.substr(0, w
->data_len
));
225 EXPECT_EQ(expected_data
, actual_data
);
226 if (expected_data
!= actual_data
)
227 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
229 result
= w
->data_len
;
231 return MockWriteResult(w
->mode
, result
);
234 void StaticSocketDataProvider::Reset() {
239 DynamicSocketDataProvider::DynamicSocketDataProvider()
240 : short_read_limit_(0),
241 allow_unconsumed_reads_(false) {
244 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
246 MockRead
DynamicSocketDataProvider::GetNextRead() {
248 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
249 MockRead result
= reads_
.front();
250 if (short_read_limit_
== 0 || result
.data_len
<= short_read_limit_
) {
253 result
.data_len
= short_read_limit_
;
254 reads_
.front().data
+= result
.data_len
;
255 reads_
.front().data_len
-= result
.data_len
;
260 void DynamicSocketDataProvider::Reset() {
264 void DynamicSocketDataProvider::SimulateRead(const char* data
,
265 const size_t length
) {
266 if (!allow_unconsumed_reads_
) {
267 EXPECT_TRUE(reads_
.empty()) << "Unconsumed read: " << reads_
.front().data
;
269 reads_
.push_back(MockRead(ASYNC
, data
, length
));
272 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode
, int result
)
273 : connect(mode
, result
),
274 next_proto_status(SSLClientSocket::kNextProtoUnsupported
),
275 was_npn_negotiated(false),
276 protocol_negotiated(kProtoUnknown
),
277 client_cert_sent(false),
278 cert_request_info(NULL
),
279 channel_id_sent(false),
280 connection_status(0) {
281 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2
,
283 // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
284 SSLConnectionStatusSetCipherSuite(0xcc14, &connection_status
);
287 SSLSocketDataProvider::~SSLSocketDataProvider() {
290 void SSLSocketDataProvider::SetNextProto(NextProto proto
) {
291 was_npn_negotiated
= true;
292 next_proto_status
= SSLClientSocket::kNextProtoNegotiated
;
293 protocol_negotiated
= proto
;
294 next_proto
= SSLClientSocket::NextProtoToString(proto
);
297 DelayedSocketData::DelayedSocketData(
298 int write_delay
, MockRead
* reads
, size_t reads_count
,
299 MockWrite
* writes
, size_t writes_count
)
300 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
301 write_delay_(write_delay
),
302 read_in_progress_(false),
303 weak_factory_(this) {
304 DCHECK_GE(write_delay_
, 0);
307 DelayedSocketData::DelayedSocketData(
308 const MockConnect
& connect
, int write_delay
, MockRead
* reads
,
309 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
310 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
311 write_delay_(write_delay
),
312 read_in_progress_(false),
313 weak_factory_(this) {
314 DCHECK_GE(write_delay_
, 0);
315 set_connect_data(connect
);
318 DelayedSocketData::~DelayedSocketData() {
321 void DelayedSocketData::ForceNextRead() {
322 DCHECK(read_in_progress_
);
327 MockRead
DelayedSocketData::GetNextRead() {
328 MockRead out
= MockRead(ASYNC
, ERR_IO_PENDING
);
329 if (write_delay_
<= 0)
330 out
= StaticSocketDataProvider::GetNextRead();
331 read_in_progress_
= (out
.result
== ERR_IO_PENDING
);
335 MockWriteResult
DelayedSocketData::OnWrite(const std::string
& data
) {
336 MockWriteResult rv
= StaticSocketDataProvider::OnWrite(data
);
337 // Now that our write has completed, we can allow reads to continue.
338 if (!--write_delay_
&& read_in_progress_
)
339 base::MessageLoop::current()->PostDelayedTask(
341 base::Bind(&DelayedSocketData::CompleteRead
,
342 weak_factory_
.GetWeakPtr()),
343 base::TimeDelta::FromMilliseconds(100));
347 void DelayedSocketData::Reset() {
349 read_in_progress_
= false;
350 weak_factory_
.InvalidateWeakPtrs();
351 StaticSocketDataProvider::Reset();
354 void DelayedSocketData::CompleteRead() {
355 if (socket() && read_in_progress_
)
356 socket()->OnReadComplete(GetNextRead());
359 OrderedSocketData::OrderedSocketData(
360 MockRead
* reads
, size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
361 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
362 sequence_number_(0), loop_stop_stage_(0),
363 blocked_(false), weak_factory_(this) {
366 OrderedSocketData::OrderedSocketData(
367 const MockConnect
& connect
,
368 MockRead
* reads
, size_t reads_count
,
369 MockWrite
* writes
, size_t writes_count
)
370 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
371 sequence_number_(0), loop_stop_stage_(0),
372 blocked_(false), weak_factory_(this) {
373 set_connect_data(connect
);
376 void OrderedSocketData::EndLoop() {
377 // If we've already stopped the loop, don't do it again until we've advanced
378 // to the next sequence_number.
379 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
<< ": EndLoop()";
380 if (loop_stop_stage_
> 0) {
381 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
382 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) >
384 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
385 << ": Clearing stop index";
386 loop_stop_stage_
= 0;
391 // Record the sequence_number at which we stopped the loop.
392 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
393 << ": Posting Quit at read " << read_index();
394 loop_stop_stage_
= sequence_number_
;
397 MockRead
OrderedSocketData::GetNextRead() {
398 weak_factory_
.InvalidateWeakPtrs();
400 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
401 if (next_read
.sequence_number
& MockRead::STOPLOOP
)
403 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) <=
404 sequence_number_
++) {
405 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
406 << ": Read " << read_index();
407 DumpMockReadWrite(next_read
);
408 blocked_
= (next_read
.result
== ERR_IO_PENDING
);
409 return StaticSocketDataProvider::GetNextRead();
411 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
413 MockRead result
= MockRead(ASYNC
, ERR_IO_PENDING
);
414 DumpMockReadWrite(result
);
419 MockWriteResult
OrderedSocketData::OnWrite(const std::string
& data
) {
420 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
421 << ": Write " << write_index();
422 DumpMockReadWrite(PeekWrite());
425 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
426 // should probably fix the weirdness. One example is in SpdyStream,
427 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
428 // SYN_REPLY causes OnResponseReceived() to get called before
429 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
430 base::MessageLoop::current()->PostDelayedTask(
432 base::Bind(&OrderedSocketData::CompleteRead
,
433 weak_factory_
.GetWeakPtr()),
434 base::TimeDelta::FromMilliseconds(100));
436 return StaticSocketDataProvider::OnWrite(data
);
439 void OrderedSocketData::Reset() {
440 NET_TRACE(INFO
, " *** ") << "Stage "
441 << sequence_number_
<< ": Reset()";
442 sequence_number_
= 0;
443 loop_stop_stage_
= 0;
445 weak_factory_
.InvalidateWeakPtrs();
446 StaticSocketDataProvider::Reset();
449 void OrderedSocketData::CompleteRead() {
450 if (socket() && blocked_
) {
451 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
;
452 socket()->OnReadComplete(GetNextRead());
456 OrderedSocketData::~OrderedSocketData() {}
458 DeterministicSocketData::DeterministicSocketData(MockRead
* reads
,
459 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
460 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
464 stopping_sequence_number_(0),
468 VerifyCorrectSequenceNumbers(reads
, reads_count
, writes
, writes_count
);
471 DeterministicSocketData::~DeterministicSocketData() {}
473 void DeterministicSocketData::Run() {
474 DCHECK(!is_running_
);
479 // Continue to consume data until all data has run out, or the stopped_ flag
480 // has been set. Consuming data requires two separate operations -- running
481 // the tasks in the message loop, and explicitly invoking the read/write
482 // callbacks (simulating network I/O). We check our conditions between each,
483 // since they can change in either.
484 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
485 if (counter
% 2 == 0)
486 base::RunLoop().RunUntilIdle();
487 if (counter
% 2 == 1) {
492 // We're done consuming new data, but it is possible there are still some
493 // pending callbacks which we expect to complete before returning.
494 while (delegate_
.get() &&
495 (delegate_
->WritePending() || delegate_
->ReadPending()) &&
498 base::RunLoop().RunUntilIdle();
504 void DeterministicSocketData::RunFor(int steps
) {
509 void DeterministicSocketData::SetStop(int seq
) {
510 DCHECK_LT(sequence_number_
, seq
);
511 stopping_sequence_number_
= seq
;
515 void DeterministicSocketData::StopAfter(int seq
) {
516 SetStop(sequence_number_
+ seq
);
519 MockRead
DeterministicSocketData::GetNextRead() {
520 current_read_
= StaticSocketDataProvider::PeekRead();
522 // Synchronous read while stopped is an error
523 if (stopped() && current_read_
.mode
== SYNCHRONOUS
) {
524 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
525 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
528 // Async read which will be called back in a future step.
529 if (sequence_number_
< current_read_
.sequence_number
) {
530 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
532 MockRead result
= MockRead(SYNCHRONOUS
, ERR_IO_PENDING
);
533 if (current_read_
.mode
== SYNCHRONOUS
) {
534 LOG(ERROR
) << "Unable to perform synchronous read: "
535 << current_read_
.sequence_number
536 << " at stage: " << sequence_number_
;
537 result
= MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
540 DumpMockReadWrite(result
);
544 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
545 << ": Read " << read_index();
547 DumpMockReadWrite(current_read_
);
549 // Increment the sequence number if IO is complete
550 if (current_read_
.mode
== SYNCHRONOUS
)
553 DCHECK_NE(ERR_IO_PENDING
, current_read_
.result
);
554 StaticSocketDataProvider::GetNextRead();
556 return current_read_
;
559 MockWriteResult
DeterministicSocketData::OnWrite(const std::string
& data
) {
560 const MockWrite
& next_write
= StaticSocketDataProvider::PeekWrite();
561 current_write_
= next_write
;
563 // Synchronous write while stopped is an error
564 if (stopped() && next_write
.mode
== SYNCHRONOUS
) {
565 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
566 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
569 // Async write which will be called back in a future step.
570 if (sequence_number_
< next_write
.sequence_number
) {
571 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
573 if (next_write
.mode
== SYNCHRONOUS
) {
574 LOG(ERROR
) << "Unable to perform synchronous write: "
575 << next_write
.sequence_number
<< " at stage: " << sequence_number_
;
576 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
579 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
580 << ": Write " << write_index();
584 DumpMockReadWrite(next_write
);
586 // Move to the next step if I/O is synchronous, since the operation will
587 // complete when this method returns.
588 if (next_write
.mode
== SYNCHRONOUS
)
591 // This is either a sync write for this step, or an async write.
592 return StaticSocketDataProvider::OnWrite(data
);
595 void DeterministicSocketData::Reset() {
596 NET_TRACE(INFO
, " *** ") << "Stage "
597 << sequence_number_
<< ": Reset()";
598 sequence_number_
= 0;
599 StaticSocketDataProvider::Reset();
603 void DeterministicSocketData::InvokeCallbacks() {
604 if (delegate_
.get() && delegate_
->WritePending() &&
605 (current_write().sequence_number
== sequence_number())) {
607 delegate_
->CompleteWrite();
610 if (delegate_
.get() && delegate_
->ReadPending() &&
611 (current_read().sequence_number
== sequence_number())) {
613 delegate_
->CompleteRead();
618 void DeterministicSocketData::NextStep() {
619 // Invariant: Can never move *past* the stopping step.
620 DCHECK_LT(sequence_number_
, stopping_sequence_number_
);
622 if (sequence_number_
== stopping_sequence_number_
)
626 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
627 MockRead
* reads
, size_t reads_count
,
628 MockWrite
* writes
, size_t writes_count
) {
632 while (read
< reads_count
|| write
< writes_count
) {
633 // Check to see that we have a read or write at the expected
635 if (read
< reads_count
&& reads
[read
].sequence_number
== expected
) {
640 if (write
< writes_count
&& writes
[write
].sequence_number
== expected
) {
645 NOTREACHED() << "Missing sequence number: " << expected
;
648 DCHECK_EQ(read
, reads_count
);
649 DCHECK_EQ(write
, writes_count
);
652 MockClientSocketFactory::MockClientSocketFactory() {}
654 MockClientSocketFactory::~MockClientSocketFactory() {}
656 void MockClientSocketFactory::AddSocketDataProvider(
657 SocketDataProvider
* data
) {
658 mock_data_
.Add(data
);
661 void MockClientSocketFactory::AddSSLSocketDataProvider(
662 SSLSocketDataProvider
* data
) {
663 mock_ssl_data_
.Add(data
);
666 void MockClientSocketFactory::ResetNextMockIndexes() {
667 mock_data_
.ResetNextIndex();
668 mock_ssl_data_
.ResetNextIndex();
671 scoped_ptr
<DatagramClientSocket
>
672 MockClientSocketFactory::CreateDatagramClientSocket(
673 DatagramSocket::BindType bind_type
,
674 const RandIntCallback
& rand_int_cb
,
675 net::NetLog
* net_log
,
676 const net::NetLog::Source
& source
) {
677 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
678 scoped_ptr
<MockUDPClientSocket
> socket(
679 new MockUDPClientSocket(data_provider
, net_log
));
680 data_provider
->set_socket(socket
.get());
681 if (bind_type
== DatagramSocket::RANDOM_BIND
)
682 socket
->set_source_port(static_cast<uint16
>(rand_int_cb
.Run(1025, 65535)));
683 return socket
.Pass();
686 scoped_ptr
<StreamSocket
> MockClientSocketFactory::CreateTransportClientSocket(
687 const AddressList
& addresses
,
688 net::NetLog
* net_log
,
689 const net::NetLog::Source
& source
) {
690 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
691 scoped_ptr
<MockTCPClientSocket
> socket(
692 new MockTCPClientSocket(addresses
, net_log
, data_provider
));
693 data_provider
->set_socket(socket
.get());
694 return socket
.Pass();
697 scoped_ptr
<SSLClientSocket
> MockClientSocketFactory::CreateSSLClientSocket(
698 scoped_ptr
<ClientSocketHandle
> transport_socket
,
699 const HostPortPair
& host_and_port
,
700 const SSLConfig
& ssl_config
,
701 const SSLClientSocketContext
& context
) {
702 SSLSocketDataProvider
* next_ssl_data
= mock_ssl_data_
.GetNext();
703 if (!next_ssl_data
->next_protos_expected_in_ssl_config
.empty()) {
704 EXPECT_EQ(next_ssl_data
->next_protos_expected_in_ssl_config
.size(),
705 ssl_config
.next_protos
.size());
707 std::equal(next_ssl_data
->next_protos_expected_in_ssl_config
.begin(),
708 next_ssl_data
->next_protos_expected_in_ssl_config
.end(),
709 ssl_config
.next_protos
.begin()));
711 return scoped_ptr
<SSLClientSocket
>(new MockSSLClientSocket(
712 transport_socket
.Pass(), host_and_port
, ssl_config
, next_ssl_data
));
715 void MockClientSocketFactory::ClearSSLSessionCache() {
718 const char MockClientSocket::kTlsUnique
[] = "MOCK_TLSUNIQ";
720 MockClientSocket::MockClientSocket(const BoundNetLog
& net_log
)
723 weak_factory_(this) {
725 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
726 peer_addr_
= IPEndPoint(ip
, 0);
729 int MockClientSocket::SetReceiveBufferSize(int32 size
) {
733 int MockClientSocket::SetSendBufferSize(int32 size
) {
737 void MockClientSocket::Disconnect() {
741 bool MockClientSocket::IsConnected() const {
745 bool MockClientSocket::IsConnectedAndIdle() const {
749 int MockClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
751 return ERR_SOCKET_NOT_CONNECTED
;
752 *address
= peer_addr_
;
756 int MockClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
758 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
760 *address
= IPEndPoint(ip
, 123);
764 const BoundNetLog
& MockClientSocket::NetLog() const {
768 void MockClientSocket::GetSSLCertRequestInfo(
769 SSLCertRequestInfo
* cert_request_info
) {
772 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece
& label
,
774 const base::StringPiece
& context
,
776 unsigned int outlen
) {
777 memset(out
, 'A', outlen
);
781 int MockClientSocket::GetTLSUniqueChannelBinding(std::string
* out
) {
782 out
->assign(MockClientSocket::kTlsUnique
);
786 ChannelIDService
* MockClientSocket::GetChannelIDService() const {
791 SSLClientSocket::NextProtoStatus
792 MockClientSocket::GetNextProto(std::string
* proto
) {
794 return SSLClientSocket::kNextProtoUnsupported
;
797 scoped_refptr
<X509Certificate
>
798 MockClientSocket::GetUnverifiedServerCertificateChain() const {
803 MockClientSocket::~MockClientSocket() {}
805 void MockClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
807 base::MessageLoop::current()->PostTask(
809 base::Bind(&MockClientSocket::RunCallback
,
810 weak_factory_
.GetWeakPtr(),
815 void MockClientSocket::RunCallback(const net::CompletionCallback
& callback
,
817 if (!callback
.is_null())
818 callback
.Run(result
);
821 MockTCPClientSocket::MockTCPClientSocket(const AddressList
& addresses
,
822 net::NetLog
* net_log
,
823 SocketDataProvider
* data
)
824 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
825 addresses_(addresses
),
828 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
829 need_read_data_(true),
830 peer_closed_connection_(false),
833 was_used_to_convey_data_(false) {
835 peer_addr_
= data
->connect_data().peer_addr
;
839 MockTCPClientSocket::~MockTCPClientSocket() {}
841 int MockTCPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
842 const CompletionCallback
& callback
) {
844 return ERR_UNEXPECTED
;
846 // If the buffer is already in use, a read is already in progress!
847 DCHECK(pending_buf_
.get() == NULL
);
849 // Store our async IO data.
851 pending_buf_len_
= buf_len
;
852 pending_callback_
= callback
;
854 if (need_read_data_
) {
855 read_data_
= data_
->GetNextRead();
856 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
857 // This MockRead is just a marker to instruct us to set
858 // peer_closed_connection_.
859 peer_closed_connection_
= true;
861 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
862 // This MockRead is just a marker to instruct us to set
863 // peer_closed_connection_. Skip it and get the next one.
864 read_data_
= data_
->GetNextRead();
865 peer_closed_connection_
= true;
867 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
868 // to complete the async IO manually later (via OnReadComplete).
869 if (read_data_
.result
== ERR_IO_PENDING
) {
870 // We need to be using async IO in this case.
871 DCHECK(!callback
.is_null());
872 return ERR_IO_PENDING
;
874 need_read_data_
= false;
877 return CompleteRead();
880 int MockTCPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
881 const CompletionCallback
& callback
) {
883 DCHECK_GT(buf_len
, 0);
886 return ERR_UNEXPECTED
;
888 std::string
data(buf
->data(), buf_len
);
889 MockWriteResult write_result
= data_
->OnWrite(data
);
891 was_used_to_convey_data_
= true;
893 if (write_result
.mode
== ASYNC
) {
894 RunCallbackAsync(callback
, write_result
.result
);
895 return ERR_IO_PENDING
;
898 return write_result
.result
;
901 int MockTCPClientSocket::Connect(const CompletionCallback
& callback
) {
905 peer_closed_connection_
= false;
906 if (data_
->connect_data().mode
== ASYNC
) {
907 if (data_
->connect_data().result
== ERR_IO_PENDING
)
908 pending_callback_
= callback
;
910 RunCallbackAsync(callback
, data_
->connect_data().result
);
911 return ERR_IO_PENDING
;
913 return data_
->connect_data().result
;
916 void MockTCPClientSocket::Disconnect() {
917 MockClientSocket::Disconnect();
918 pending_callback_
.Reset();
921 bool MockTCPClientSocket::IsConnected() const {
922 return connected_
&& !peer_closed_connection_
;
925 bool MockTCPClientSocket::IsConnectedAndIdle() const {
926 return IsConnected();
929 int MockTCPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
930 if (addresses_
.empty())
931 return MockClientSocket::GetPeerAddress(address
);
933 *address
= addresses_
[0];
937 bool MockTCPClientSocket::WasEverUsed() const {
938 return was_used_to_convey_data_
;
941 bool MockTCPClientSocket::UsingTCPFastOpen() const {
945 bool MockTCPClientSocket::WasNpnNegotiated() const {
949 bool MockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
953 void MockTCPClientSocket::OnReadComplete(const MockRead
& data
) {
954 // There must be a read pending.
955 DCHECK(pending_buf_
.get());
956 // You can't complete a read with another ERR_IO_PENDING status code.
957 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
958 // Since we've been waiting for data, need_read_data_ should be true.
959 DCHECK(need_read_data_
);
962 need_read_data_
= false;
964 // The caller is simulating that this IO completes right now. Don't
965 // let CompleteRead() schedule a callback.
966 read_data_
.mode
= SYNCHRONOUS
;
968 CompletionCallback callback
= pending_callback_
;
969 int rv
= CompleteRead();
970 RunCallback(callback
, rv
);
973 void MockTCPClientSocket::OnConnectComplete(const MockConnect
& data
) {
974 CompletionCallback callback
= pending_callback_
;
975 RunCallback(callback
, data
.result
);
978 int MockTCPClientSocket::CompleteRead() {
979 DCHECK(pending_buf_
.get());
980 DCHECK(pending_buf_len_
> 0);
982 was_used_to_convey_data_
= true;
984 // Save the pending async IO data and reset our |pending_| state.
985 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
986 int buf_len
= pending_buf_len_
;
987 CompletionCallback callback
= pending_callback_
;
989 pending_buf_len_
= 0;
990 pending_callback_
.Reset();
992 int result
= read_data_
.result
;
993 DCHECK(result
!= ERR_IO_PENDING
);
995 if (read_data_
.data
) {
996 if (read_data_
.data_len
- read_offset_
> 0) {
997 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
998 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
999 read_offset_
+= result
;
1000 if (read_offset_
== read_data_
.data_len
) {
1001 need_read_data_
= true;
1009 if (read_data_
.mode
== ASYNC
) {
1010 DCHECK(!callback
.is_null());
1011 RunCallbackAsync(callback
, result
);
1012 return ERR_IO_PENDING
;
1017 DeterministicSocketHelper::DeterministicSocketHelper(
1018 net::NetLog
* net_log
,
1019 DeterministicSocketData
* data
)
1020 : write_pending_(false),
1025 read_pending_(false),
1027 was_used_to_convey_data_(false),
1028 peer_closed_connection_(false),
1029 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)) {
1032 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1034 void DeterministicSocketHelper::CompleteWrite() {
1035 was_used_to_convey_data_
= true;
1036 write_pending_
= false;
1037 write_callback_
.Run(write_result_
);
1040 int DeterministicSocketHelper::CompleteRead() {
1041 DCHECK_GT(read_buf_len_
, 0);
1042 DCHECK_LE(read_data_
.data_len
, read_buf_len_
);
1045 was_used_to_convey_data_
= true;
1047 if (read_data_
.result
== ERR_IO_PENDING
)
1048 read_data_
= data_
->GetNextRead();
1049 DCHECK_NE(ERR_IO_PENDING
, read_data_
.result
);
1050 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1051 // the callback. Therefore we don't even bother to check it.
1052 int result
= read_data_
.result
;
1054 if (read_data_
.data_len
> 0) {
1055 DCHECK(read_data_
.data
);
1056 result
= std::min(read_buf_len_
, read_data_
.data_len
);
1057 memcpy(read_buf_
->data(), read_data_
.data
, result
);
1060 if (read_pending_
) {
1061 read_pending_
= false;
1062 read_callback_
.Run(result
);
1068 int DeterministicSocketHelper::Write(
1069 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1071 DCHECK_GT(buf_len
, 0);
1073 std::string
data(buf
->data(), buf_len
);
1074 MockWriteResult write_result
= data_
->OnWrite(data
);
1076 if (write_result
.mode
== ASYNC
) {
1077 write_callback_
= callback
;
1078 write_result_
= write_result
.result
;
1079 DCHECK(!write_callback_
.is_null());
1080 write_pending_
= true;
1081 return ERR_IO_PENDING
;
1084 was_used_to_convey_data_
= true;
1085 write_pending_
= false;
1086 return write_result
.result
;
1089 int DeterministicSocketHelper::Read(
1090 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1092 read_data_
= data_
->GetNextRead();
1093 // The buffer should always be big enough to contain all the MockRead data. To
1094 // use small buffers, split the data into multiple MockReads.
1095 DCHECK_LE(read_data_
.data_len
, buf_len
);
1097 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
1098 // This MockRead is just a marker to instruct us to set
1099 // peer_closed_connection_.
1100 peer_closed_connection_
= true;
1102 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
1103 // This MockRead is just a marker to instruct us to set
1104 // peer_closed_connection_. Skip it and get the next one.
1105 read_data_
= data_
->GetNextRead();
1106 peer_closed_connection_
= true;
1110 read_buf_len_
= buf_len
;
1111 read_callback_
= callback
;
1113 if (read_data_
.mode
== ASYNC
|| (read_data_
.result
== ERR_IO_PENDING
)) {
1114 read_pending_
= true;
1115 DCHECK(!read_callback_
.is_null());
1116 return ERR_IO_PENDING
;
1119 was_used_to_convey_data_
= true;
1120 return CompleteRead();
1123 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1124 net::NetLog
* net_log
,
1125 DeterministicSocketData
* data
)
1126 : connected_(false),
1127 helper_(net_log
, data
),
1131 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1133 bool DeterministicMockUDPClientSocket::WritePending() const {
1134 return helper_
.write_pending();
1137 bool DeterministicMockUDPClientSocket::ReadPending() const {
1138 return helper_
.read_pending();
1141 void DeterministicMockUDPClientSocket::CompleteWrite() {
1142 helper_
.CompleteWrite();
1145 int DeterministicMockUDPClientSocket::CompleteRead() {
1146 return helper_
.CompleteRead();
1149 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1153 peer_address_
= address
;
1154 return helper_
.data()->connect_data().result
;
1157 int DeterministicMockUDPClientSocket::Write(
1160 const CompletionCallback
& callback
) {
1162 return ERR_UNEXPECTED
;
1164 return helper_
.Write(buf
, buf_len
, callback
);
1167 int DeterministicMockUDPClientSocket::Read(
1170 const CompletionCallback
& callback
) {
1172 return ERR_UNEXPECTED
;
1174 return helper_
.Read(buf
, buf_len
, callback
);
1177 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1181 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size
) {
1185 void DeterministicMockUDPClientSocket::Close() {
1189 int DeterministicMockUDPClientSocket::GetPeerAddress(
1190 IPEndPoint
* address
) const {
1191 *address
= peer_address_
;
1195 int DeterministicMockUDPClientSocket::GetLocalAddress(
1196 IPEndPoint
* address
) const {
1198 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1200 *address
= IPEndPoint(ip
, source_port_
);
1204 const BoundNetLog
& DeterministicMockUDPClientSocket::NetLog() const {
1205 return helper_
.net_log();
1208 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead
& data
) {}
1210 void DeterministicMockUDPClientSocket::OnConnectComplete(
1211 const MockConnect
& data
) {
1215 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1216 net::NetLog
* net_log
,
1217 DeterministicSocketData
* data
)
1218 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1219 helper_(net_log
, data
) {
1220 peer_addr_
= data
->connect_data().peer_addr
;
1223 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1225 bool DeterministicMockTCPClientSocket::WritePending() const {
1226 return helper_
.write_pending();
1229 bool DeterministicMockTCPClientSocket::ReadPending() const {
1230 return helper_
.read_pending();
1233 void DeterministicMockTCPClientSocket::CompleteWrite() {
1234 helper_
.CompleteWrite();
1237 int DeterministicMockTCPClientSocket::CompleteRead() {
1238 return helper_
.CompleteRead();
1241 int DeterministicMockTCPClientSocket::Write(
1244 const CompletionCallback
& callback
) {
1246 return ERR_UNEXPECTED
;
1248 return helper_
.Write(buf
, buf_len
, callback
);
1251 int DeterministicMockTCPClientSocket::Read(
1254 const CompletionCallback
& callback
) {
1256 return ERR_UNEXPECTED
;
1258 return helper_
.Read(buf
, buf_len
, callback
);
1261 // TODO(erikchen): Support connect sequencing.
1262 int DeterministicMockTCPClientSocket::Connect(
1263 const CompletionCallback
& callback
) {
1267 if (helper_
.data()->connect_data().mode
== ASYNC
) {
1268 RunCallbackAsync(callback
, helper_
.data()->connect_data().result
);
1269 return ERR_IO_PENDING
;
1271 return helper_
.data()->connect_data().result
;
1274 void DeterministicMockTCPClientSocket::Disconnect() {
1275 MockClientSocket::Disconnect();
1278 bool DeterministicMockTCPClientSocket::IsConnected() const {
1279 return connected_
&& !helper_
.peer_closed_connection();
1282 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1283 return IsConnected();
1286 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1287 return helper_
.was_used_to_convey_data();
1290 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1294 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1298 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1302 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead
& data
) {}
1304 void DeterministicMockTCPClientSocket::OnConnectComplete(
1305 const MockConnect
& data
) {}
1308 void MockSSLClientSocket::ConnectCallback(
1309 MockSSLClientSocket
* ssl_client_socket
,
1310 const CompletionCallback
& callback
,
1313 ssl_client_socket
->connected_
= true;
1317 MockSSLClientSocket::MockSSLClientSocket(
1318 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1319 const HostPortPair
& host_port_pair
,
1320 const SSLConfig
& ssl_config
,
1321 SSLSocketDataProvider
* data
)
1323 // Have to use the right BoundNetLog for LoadTimingInfo regression
1325 transport_socket
->socket()->NetLog()),
1326 transport_(transport_socket
.Pass()),
1328 is_npn_state_set_(false),
1329 new_npn_value_(false),
1330 is_protocol_negotiated_set_(false),
1331 protocol_negotiated_(kProtoUnknown
) {
1333 peer_addr_
= data
->connect
.peer_addr
;
1336 MockSSLClientSocket::~MockSSLClientSocket() {
1340 int MockSSLClientSocket::Read(IOBuffer
* buf
, int buf_len
,
1341 const CompletionCallback
& callback
) {
1342 return transport_
->socket()->Read(buf
, buf_len
, callback
);
1345 int MockSSLClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1346 const CompletionCallback
& callback
) {
1347 return transport_
->socket()->Write(buf
, buf_len
, callback
);
1350 int MockSSLClientSocket::Connect(const CompletionCallback
& callback
) {
1351 int rv
= transport_
->socket()->Connect(
1352 base::Bind(&ConnectCallback
, base::Unretained(this), callback
));
1354 if (data_
->connect
.result
== OK
)
1356 if (data_
->connect
.mode
== ASYNC
) {
1357 RunCallbackAsync(callback
, data_
->connect
.result
);
1358 return ERR_IO_PENDING
;
1360 return data_
->connect
.result
;
1365 void MockSSLClientSocket::Disconnect() {
1366 MockClientSocket::Disconnect();
1367 if (transport_
->socket() != NULL
)
1368 transport_
->socket()->Disconnect();
1371 bool MockSSLClientSocket::IsConnected() const {
1372 return transport_
->socket()->IsConnected();
1375 bool MockSSLClientSocket::WasEverUsed() const {
1376 return transport_
->socket()->WasEverUsed();
1379 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1380 return transport_
->socket()->UsingTCPFastOpen();
1383 int MockSSLClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1384 return transport_
->socket()->GetPeerAddress(address
);
1387 bool MockSSLClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1389 ssl_info
->cert
= data_
->cert
;
1390 ssl_info
->client_cert_sent
= data_
->client_cert_sent
;
1391 ssl_info
->channel_id_sent
= data_
->channel_id_sent
;
1392 ssl_info
->connection_status
= data_
->connection_status
;
1396 void MockSSLClientSocket::GetSSLCertRequestInfo(
1397 SSLCertRequestInfo
* cert_request_info
) {
1398 DCHECK(cert_request_info
);
1399 if (data_
->cert_request_info
) {
1400 cert_request_info
->host_and_port
=
1401 data_
->cert_request_info
->host_and_port
;
1402 cert_request_info
->client_certs
= data_
->cert_request_info
->client_certs
;
1404 cert_request_info
->Reset();
1408 SSLClientSocket::NextProtoStatus
MockSSLClientSocket::GetNextProto(
1409 std::string
* proto
) {
1410 *proto
= data_
->next_proto
;
1411 return data_
->next_proto_status
;
1414 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated
) {
1415 is_npn_state_set_
= true;
1416 return new_npn_value_
= negotiated
;
1419 bool MockSSLClientSocket::WasNpnNegotiated() const {
1420 if (is_npn_state_set_
)
1421 return new_npn_value_
;
1422 return data_
->was_npn_negotiated
;
1425 NextProto
MockSSLClientSocket::GetNegotiatedProtocol() const {
1426 if (is_protocol_negotiated_set_
)
1427 return protocol_negotiated_
;
1428 return data_
->protocol_negotiated
;
1431 void MockSSLClientSocket::set_protocol_negotiated(
1432 NextProto protocol_negotiated
) {
1433 is_protocol_negotiated_set_
= true;
1434 protocol_negotiated_
= protocol_negotiated
;
1437 bool MockSSLClientSocket::WasChannelIDSent() const {
1438 return data_
->channel_id_sent
;
1441 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent
) {
1442 data_
->channel_id_sent
= channel_id_sent
;
1445 ChannelIDService
* MockSSLClientSocket::GetChannelIDService() const {
1446 return data_
->channel_id_service
;
1449 void MockSSLClientSocket::OnReadComplete(const MockRead
& data
) {
1453 void MockSSLClientSocket::OnConnectComplete(const MockConnect
& data
) {
1457 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider
* data
,
1458 net::NetLog
* net_log
)
1459 : connected_(false),
1462 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
1463 need_read_data_(true),
1466 pending_buf_len_(0),
1467 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1468 weak_factory_(this) {
1471 peer_addr_
= data
->connect_data().peer_addr
;
1474 MockUDPClientSocket::~MockUDPClientSocket() {}
1476 int MockUDPClientSocket::Read(IOBuffer
* buf
,
1478 const CompletionCallback
& callback
) {
1480 return ERR_UNEXPECTED
;
1482 // If the buffer is already in use, a read is already in progress!
1483 DCHECK(pending_buf_
.get() == NULL
);
1485 // Store our async IO data.
1487 pending_buf_len_
= buf_len
;
1488 pending_callback_
= callback
;
1490 if (need_read_data_
) {
1491 read_data_
= data_
->GetNextRead();
1492 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1493 // to complete the async IO manually later (via OnReadComplete).
1494 if (read_data_
.result
== ERR_IO_PENDING
) {
1495 // We need to be using async IO in this case.
1496 DCHECK(!callback
.is_null());
1497 return ERR_IO_PENDING
;
1499 need_read_data_
= false;
1502 return CompleteRead();
1505 int MockUDPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1506 const CompletionCallback
& callback
) {
1508 DCHECK_GT(buf_len
, 0);
1511 return ERR_UNEXPECTED
;
1513 std::string
data(buf
->data(), buf_len
);
1514 MockWriteResult write_result
= data_
->OnWrite(data
);
1516 if (write_result
.mode
== ASYNC
) {
1517 RunCallbackAsync(callback
, write_result
.result
);
1518 return ERR_IO_PENDING
;
1520 return write_result
.result
;
1523 int MockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1527 int MockUDPClientSocket::SetSendBufferSize(int32 size
) {
1531 void MockUDPClientSocket::Close() {
1535 int MockUDPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1536 *address
= peer_addr_
;
1540 int MockUDPClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
1542 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1544 *address
= IPEndPoint(ip
, source_port_
);
1548 const BoundNetLog
& MockUDPClientSocket::NetLog() const {
1552 int MockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1554 peer_addr_
= address
;
1555 return data_
->connect_data().result
;
1558 void MockUDPClientSocket::OnReadComplete(const MockRead
& data
) {
1559 // There must be a read pending.
1560 DCHECK(pending_buf_
.get());
1561 // You can't complete a read with another ERR_IO_PENDING status code.
1562 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
1563 // Since we've been waiting for data, need_read_data_ should be true.
1564 DCHECK(need_read_data_
);
1567 need_read_data_
= false;
1569 // The caller is simulating that this IO completes right now. Don't
1570 // let CompleteRead() schedule a callback.
1571 read_data_
.mode
= SYNCHRONOUS
;
1573 net::CompletionCallback callback
= pending_callback_
;
1574 int rv
= CompleteRead();
1575 RunCallback(callback
, rv
);
1578 void MockUDPClientSocket::OnConnectComplete(const MockConnect
& data
) {
1582 int MockUDPClientSocket::CompleteRead() {
1583 DCHECK(pending_buf_
.get());
1584 DCHECK(pending_buf_len_
> 0);
1586 // Save the pending async IO data and reset our |pending_| state.
1587 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
1588 int buf_len
= pending_buf_len_
;
1589 CompletionCallback callback
= pending_callback_
;
1590 pending_buf_
= NULL
;
1591 pending_buf_len_
= 0;
1592 pending_callback_
.Reset();
1594 int result
= read_data_
.result
;
1595 DCHECK(result
!= ERR_IO_PENDING
);
1597 if (read_data_
.data
) {
1598 if (read_data_
.data_len
- read_offset_
> 0) {
1599 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
1600 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
1601 read_offset_
+= result
;
1602 if (read_offset_
== read_data_
.data_len
) {
1603 need_read_data_
= true;
1611 if (read_data_
.mode
== ASYNC
) {
1612 DCHECK(!callback
.is_null());
1613 RunCallbackAsync(callback
, result
);
1614 return ERR_IO_PENDING
;
1619 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
1621 base::MessageLoop::current()->PostTask(
1623 base::Bind(&MockUDPClientSocket::RunCallback
,
1624 weak_factory_
.GetWeakPtr(),
1629 void MockUDPClientSocket::RunCallback(const CompletionCallback
& callback
,
1631 if (!callback
.is_null())
1632 callback
.Run(result
);
1635 TestSocketRequest::TestSocketRequest(
1636 std::vector
<TestSocketRequest
*>* request_order
, size_t* completion_count
)
1637 : request_order_(request_order
),
1638 completion_count_(completion_count
),
1639 callback_(base::Bind(&TestSocketRequest::OnComplete
,
1640 base::Unretained(this))) {
1641 DCHECK(request_order
);
1642 DCHECK(completion_count
);
1645 TestSocketRequest::~TestSocketRequest() {
1648 void TestSocketRequest::OnComplete(int result
) {
1650 (*completion_count_
)++;
1651 request_order_
->push_back(this);
1655 const int ClientSocketPoolTest::kIndexOutOfBounds
= -1;
1658 const int ClientSocketPoolTest::kRequestNotFound
= -2;
1660 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1661 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1663 int ClientSocketPoolTest::GetOrderOfRequest(size_t index
) const {
1665 if (index
>= requests_
.size())
1666 return kIndexOutOfBounds
;
1668 for (size_t i
= 0; i
< request_order_
.size(); i
++)
1669 if (requests_
[index
] == request_order_
[i
])
1672 return kRequestNotFound
;
1675 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive
) {
1676 ScopedVector
<TestSocketRequest
>::iterator i
;
1677 for (i
= requests_
.begin(); i
!= requests_
.end(); ++i
) {
1678 if ((*i
)->handle()->is_initialized()) {
1679 if (keep_alive
== NO_KEEP_ALIVE
)
1680 (*i
)->handle()->socket()->Disconnect();
1681 (*i
)->handle()->Reset();
1682 base::RunLoop().RunUntilIdle();
1689 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive
) {
1692 released_one
= ReleaseOneConnection(keep_alive
);
1693 } while (released_one
);
1696 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1697 scoped_ptr
<StreamSocket
> socket
,
1698 ClientSocketHandle
* handle
,
1699 const CompletionCallback
& callback
)
1700 : socket_(socket
.Pass()),
1702 user_callback_(callback
) {
1705 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1707 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1708 int rv
= socket_
->Connect(base::Bind(&MockConnectJob::OnConnect
,
1709 base::Unretained(this)));
1711 user_callback_
.Reset();
1717 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1718 const ClientSocketHandle
* handle
) {
1719 if (handle
!= handle_
)
1723 user_callback_
.Reset();
1727 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv
) {
1731 handle_
->SetSocket(socket_
.Pass());
1733 // Needed for socket pool tests that layer other sockets on top of mock
1735 LoadTimingInfo::ConnectTiming connect_timing
;
1736 base::TimeTicks now
= base::TimeTicks::Now();
1737 connect_timing
.dns_start
= now
;
1738 connect_timing
.dns_end
= now
;
1739 connect_timing
.connect_start
= now
;
1740 connect_timing
.connect_end
= now
;
1741 handle_
->set_connect_timing(connect_timing
);
1748 if (!user_callback_
.is_null()) {
1749 CompletionCallback callback
= user_callback_
;
1750 user_callback_
.Reset();
1755 MockTransportClientSocketPool::MockTransportClientSocketPool(
1757 int max_sockets_per_group
,
1758 ClientSocketFactory
* socket_factory
)
1759 : TransportClientSocketPool(max_sockets
,
1760 max_sockets_per_group
,
1764 client_socket_factory_(socket_factory
),
1765 last_request_priority_(DEFAULT_PRIORITY
),
1770 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1772 int MockTransportClientSocketPool::RequestSocket(
1773 const std::string
& group_name
, const void* socket_params
,
1774 RequestPriority priority
, ClientSocketHandle
* handle
,
1775 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1776 last_request_priority_
= priority
;
1777 scoped_ptr
<StreamSocket
> socket
=
1778 client_socket_factory_
->CreateTransportClientSocket(
1779 AddressList(), net_log
.net_log(), net::NetLog::Source());
1780 MockConnectJob
* job
= new MockConnectJob(socket
.Pass(), handle
, callback
);
1781 job_list_
.push_back(job
);
1782 handle
->set_pool_id(1);
1783 return job
->Connect();
1786 void MockTransportClientSocketPool::CancelRequest(const std::string
& group_name
,
1787 ClientSocketHandle
* handle
) {
1788 std::vector
<MockConnectJob
*>::iterator i
;
1789 for (i
= job_list_
.begin(); i
!= job_list_
.end(); ++i
) {
1790 if ((*i
)->CancelHandle(handle
)) {
1797 void MockTransportClientSocketPool::ReleaseSocket(
1798 const std::string
& group_name
,
1799 scoped_ptr
<StreamSocket
> socket
,
1805 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1807 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1809 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1810 DeterministicSocketData
* data
) {
1811 mock_data_
.Add(data
);
1814 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1815 SSLSocketDataProvider
* data
) {
1816 mock_ssl_data_
.Add(data
);
1819 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1820 mock_data_
.ResetNextIndex();
1821 mock_ssl_data_
.ResetNextIndex();
1824 MockSSLClientSocket
* DeterministicMockClientSocketFactory::
1825 GetMockSSLClientSocket(size_t index
) const {
1826 DCHECK_LT(index
, ssl_client_sockets_
.size());
1827 return ssl_client_sockets_
[index
];
1830 scoped_ptr
<DatagramClientSocket
>
1831 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1832 DatagramSocket::BindType bind_type
,
1833 const RandIntCallback
& rand_int_cb
,
1834 net::NetLog
* net_log
,
1835 const NetLog::Source
& source
) {
1836 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1837 scoped_ptr
<DeterministicMockUDPClientSocket
> socket(
1838 new DeterministicMockUDPClientSocket(net_log
, data_provider
));
1839 data_provider
->set_delegate(socket
->AsWeakPtr());
1840 udp_client_sockets().push_back(socket
.get());
1841 if (bind_type
== DatagramSocket::RANDOM_BIND
)
1842 socket
->set_source_port(static_cast<uint16
>(rand_int_cb
.Run(1025, 65535)));
1843 return socket
.Pass();
1846 scoped_ptr
<StreamSocket
>
1847 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1848 const AddressList
& addresses
,
1849 net::NetLog
* net_log
,
1850 const net::NetLog::Source
& source
) {
1851 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1852 scoped_ptr
<DeterministicMockTCPClientSocket
> socket(
1853 new DeterministicMockTCPClientSocket(net_log
, data_provider
));
1854 data_provider
->set_delegate(socket
->AsWeakPtr());
1855 tcp_client_sockets().push_back(socket
.get());
1856 return socket
.Pass();
1859 scoped_ptr
<SSLClientSocket
>
1860 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1861 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1862 const HostPortPair
& host_and_port
,
1863 const SSLConfig
& ssl_config
,
1864 const SSLClientSocketContext
& context
) {
1865 scoped_ptr
<MockSSLClientSocket
> socket(
1866 new MockSSLClientSocket(transport_socket
.Pass(),
1867 host_and_port
, ssl_config
,
1868 mock_ssl_data_
.GetNext()));
1869 ssl_client_sockets_
.push_back(socket
.get());
1870 return socket
.Pass();
1873 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1876 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1878 int max_sockets_per_group
,
1879 TransportClientSocketPool
* transport_pool
)
1880 : SOCKSClientSocketPool(max_sockets
,
1881 max_sockets_per_group
,
1885 transport_pool_(transport_pool
) {
1888 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1890 int MockSOCKSClientSocketPool::RequestSocket(
1891 const std::string
& group_name
, const void* socket_params
,
1892 RequestPriority priority
, ClientSocketHandle
* handle
,
1893 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1894 return transport_pool_
->RequestSocket(
1895 group_name
, socket_params
, priority
, handle
, callback
, net_log
);
1898 void MockSOCKSClientSocketPool::CancelRequest(
1899 const std::string
& group_name
,
1900 ClientSocketHandle
* handle
) {
1901 return transport_pool_
->CancelRequest(group_name
, handle
);
1904 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string
& group_name
,
1905 scoped_ptr
<StreamSocket
> socket
,
1907 return transport_pool_
->ReleaseSocket(group_name
, socket
.Pass(), id
);
1910 ScopedWebSocketEndpointZeroUnlockDelay::
1911 ScopedWebSocketEndpointZeroUnlockDelay() {
1913 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
1917 ScopedWebSocketEndpointZeroUnlockDelay::
1918 ~ScopedWebSocketEndpointZeroUnlockDelay() {
1919 base::TimeDelta active_delay
=
1920 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
1922 EXPECT_EQ(active_delay
, base::TimeDelta());
1925 const char kSOCKS5GreetRequest
[] = { 0x05, 0x01, 0x00 };
1926 const int kSOCKS5GreetRequestLength
= arraysize(kSOCKS5GreetRequest
);
1928 const char kSOCKS5GreetResponse
[] = { 0x05, 0x00 };
1929 const int kSOCKS5GreetResponseLength
= arraysize(kSOCKS5GreetResponse
);
1931 const char kSOCKS5OkRequest
[] =
1932 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1933 const int kSOCKS5OkRequestLength
= arraysize(kSOCKS5OkRequest
);
1935 const char kSOCKS5OkResponse
[] =
1936 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1937 const int kSOCKS5OkResponseLength
= arraysize(kSOCKS5OkResponse
);