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/callback_helpers.h"
14 #include "base/compiler_specific.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/run_loop.h"
17 #include "base/time/time.h"
18 #include "net/base/address_family.h"
19 #include "net/base/address_list.h"
20 #include "net/base/auth.h"
21 #include "net/base/load_timing_info.h"
22 #include "net/http/http_network_session.h"
23 #include "net/http/http_request_headers.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/socket/client_socket_pool_histograms.h"
26 #include "net/socket/socket.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 should_pause_on_connect(false),
283 is_in_session_cache(false) {
284 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2
,
286 // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
287 SSLConnectionStatusSetCipherSuite(0xcc14, &connection_status
);
290 SSLSocketDataProvider::~SSLSocketDataProvider() {
293 void SSLSocketDataProvider::SetNextProto(NextProto proto
) {
294 was_npn_negotiated
= true;
295 next_proto_status
= SSLClientSocket::kNextProtoNegotiated
;
296 protocol_negotiated
= proto
;
297 next_proto
= SSLClientSocket::NextProtoToString(proto
);
300 DelayedSocketData::DelayedSocketData(
301 int write_delay
, MockRead
* reads
, size_t reads_count
,
302 MockWrite
* writes
, size_t writes_count
)
303 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
304 write_delay_(write_delay
),
305 read_in_progress_(false),
306 weak_factory_(this) {
307 DCHECK_GE(write_delay_
, 0);
310 DelayedSocketData::DelayedSocketData(
311 const MockConnect
& connect
, int write_delay
, MockRead
* reads
,
312 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
313 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
314 write_delay_(write_delay
),
315 read_in_progress_(false),
316 weak_factory_(this) {
317 DCHECK_GE(write_delay_
, 0);
318 set_connect_data(connect
);
321 DelayedSocketData::~DelayedSocketData() {
324 void DelayedSocketData::ForceNextRead() {
325 DCHECK(read_in_progress_
);
330 MockRead
DelayedSocketData::GetNextRead() {
331 MockRead out
= MockRead(ASYNC
, ERR_IO_PENDING
);
332 if (write_delay_
<= 0)
333 out
= StaticSocketDataProvider::GetNextRead();
334 read_in_progress_
= (out
.result
== ERR_IO_PENDING
);
338 MockWriteResult
DelayedSocketData::OnWrite(const std::string
& data
) {
339 MockWriteResult rv
= StaticSocketDataProvider::OnWrite(data
);
340 // Now that our write has completed, we can allow reads to continue.
341 if (!--write_delay_
&& read_in_progress_
)
342 base::MessageLoop::current()->PostDelayedTask(
344 base::Bind(&DelayedSocketData::CompleteRead
,
345 weak_factory_
.GetWeakPtr()),
346 base::TimeDelta::FromMilliseconds(100));
350 void DelayedSocketData::Reset() {
352 read_in_progress_
= false;
353 weak_factory_
.InvalidateWeakPtrs();
354 StaticSocketDataProvider::Reset();
357 void DelayedSocketData::CompleteRead() {
358 if (socket() && read_in_progress_
)
359 socket()->OnReadComplete(GetNextRead());
362 OrderedSocketData::OrderedSocketData(
363 MockRead
* reads
, size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
364 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
365 sequence_number_(0), loop_stop_stage_(0),
366 blocked_(false), weak_factory_(this) {
369 OrderedSocketData::OrderedSocketData(
370 const MockConnect
& connect
,
371 MockRead
* reads
, size_t reads_count
,
372 MockWrite
* writes
, size_t writes_count
)
373 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
374 sequence_number_(0), loop_stop_stage_(0),
375 blocked_(false), weak_factory_(this) {
376 set_connect_data(connect
);
379 void OrderedSocketData::EndLoop() {
380 // If we've already stopped the loop, don't do it again until we've advanced
381 // to the next sequence_number.
382 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
<< ": EndLoop()";
383 if (loop_stop_stage_
> 0) {
384 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
385 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) >
387 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
388 << ": Clearing stop index";
389 loop_stop_stage_
= 0;
394 // Record the sequence_number at which we stopped the loop.
395 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
396 << ": Posting Quit at read " << read_index();
397 loop_stop_stage_
= sequence_number_
;
400 MockRead
OrderedSocketData::GetNextRead() {
401 weak_factory_
.InvalidateWeakPtrs();
403 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
404 if (next_read
.sequence_number
& MockRead::STOPLOOP
)
406 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) <=
407 sequence_number_
++) {
408 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
409 << ": Read " << read_index();
410 DumpMockReadWrite(next_read
);
411 blocked_
= (next_read
.result
== ERR_IO_PENDING
);
412 return StaticSocketDataProvider::GetNextRead();
414 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
416 MockRead result
= MockRead(ASYNC
, ERR_IO_PENDING
);
417 DumpMockReadWrite(result
);
422 MockWriteResult
OrderedSocketData::OnWrite(const std::string
& data
) {
423 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
424 << ": Write " << write_index();
425 DumpMockReadWrite(PeekWrite());
428 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
429 // should probably fix the weirdness. One example is in SpdyStream,
430 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
431 // SYN_REPLY causes OnResponseReceived() to get called before
432 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
433 base::MessageLoop::current()->PostDelayedTask(
435 base::Bind(&OrderedSocketData::CompleteRead
,
436 weak_factory_
.GetWeakPtr()),
437 base::TimeDelta::FromMilliseconds(100));
439 return StaticSocketDataProvider::OnWrite(data
);
442 void OrderedSocketData::Reset() {
443 NET_TRACE(INFO
, " *** ") << "Stage "
444 << sequence_number_
<< ": Reset()";
445 sequence_number_
= 0;
446 loop_stop_stage_
= 0;
448 weak_factory_
.InvalidateWeakPtrs();
449 StaticSocketDataProvider::Reset();
452 void OrderedSocketData::CompleteRead() {
453 if (socket() && blocked_
) {
454 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
;
455 socket()->OnReadComplete(GetNextRead());
459 OrderedSocketData::~OrderedSocketData() {}
461 DeterministicSocketData::DeterministicSocketData(MockRead
* reads
,
462 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
463 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
467 stopping_sequence_number_(0),
471 VerifyCorrectSequenceNumbers(reads
, reads_count
, writes
, writes_count
);
474 DeterministicSocketData::~DeterministicSocketData() {}
476 void DeterministicSocketData::Run() {
477 DCHECK(!is_running_
);
482 // Continue to consume data until all data has run out, or the stopped_ flag
483 // has been set. Consuming data requires two separate operations -- running
484 // the tasks in the message loop, and explicitly invoking the read/write
485 // callbacks (simulating network I/O). We check our conditions between each,
486 // since they can change in either.
487 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
488 if (counter
% 2 == 0)
489 base::RunLoop().RunUntilIdle();
490 if (counter
% 2 == 1) {
495 // We're done consuming new data, but it is possible there are still some
496 // pending callbacks which we expect to complete before returning.
497 while (delegate_
.get() &&
498 (delegate_
->WritePending() || delegate_
->ReadPending()) &&
501 base::RunLoop().RunUntilIdle();
507 void DeterministicSocketData::RunFor(int steps
) {
512 void DeterministicSocketData::SetStop(int seq
) {
513 DCHECK_LT(sequence_number_
, seq
);
514 stopping_sequence_number_
= seq
;
518 void DeterministicSocketData::StopAfter(int seq
) {
519 SetStop(sequence_number_
+ seq
);
522 MockRead
DeterministicSocketData::GetNextRead() {
523 current_read_
= StaticSocketDataProvider::PeekRead();
525 // Synchronous read while stopped is an error
526 if (stopped() && current_read_
.mode
== SYNCHRONOUS
) {
527 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
528 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
531 // Async read which will be called back in a future step.
532 if (sequence_number_
< current_read_
.sequence_number
) {
533 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
535 MockRead result
= MockRead(SYNCHRONOUS
, ERR_IO_PENDING
);
536 if (current_read_
.mode
== SYNCHRONOUS
) {
537 LOG(ERROR
) << "Unable to perform synchronous read: "
538 << current_read_
.sequence_number
539 << " at stage: " << sequence_number_
;
540 result
= MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
543 DumpMockReadWrite(result
);
547 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
548 << ": Read " << read_index();
550 DumpMockReadWrite(current_read_
);
552 // Increment the sequence number if IO is complete
553 if (current_read_
.mode
== SYNCHRONOUS
)
556 DCHECK_NE(ERR_IO_PENDING
, current_read_
.result
);
557 StaticSocketDataProvider::GetNextRead();
559 return current_read_
;
562 MockWriteResult
DeterministicSocketData::OnWrite(const std::string
& data
) {
563 const MockWrite
& next_write
= StaticSocketDataProvider::PeekWrite();
564 current_write_
= next_write
;
566 // Synchronous write while stopped is an error
567 if (stopped() && next_write
.mode
== SYNCHRONOUS
) {
568 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
569 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
572 // Async write which will be called back in a future step.
573 if (sequence_number_
< next_write
.sequence_number
) {
574 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
576 if (next_write
.mode
== SYNCHRONOUS
) {
577 LOG(ERROR
) << "Unable to perform synchronous write: "
578 << next_write
.sequence_number
<< " at stage: " << sequence_number_
;
579 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
582 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
583 << ": Write " << write_index();
587 DumpMockReadWrite(next_write
);
589 // Move to the next step if I/O is synchronous, since the operation will
590 // complete when this method returns.
591 if (next_write
.mode
== SYNCHRONOUS
)
594 // This is either a sync write for this step, or an async write.
595 return StaticSocketDataProvider::OnWrite(data
);
598 void DeterministicSocketData::Reset() {
599 NET_TRACE(INFO
, " *** ") << "Stage "
600 << sequence_number_
<< ": Reset()";
601 sequence_number_
= 0;
602 StaticSocketDataProvider::Reset();
606 void DeterministicSocketData::InvokeCallbacks() {
607 if (delegate_
.get() && delegate_
->WritePending() &&
608 (current_write().sequence_number
== sequence_number())) {
610 delegate_
->CompleteWrite();
613 if (delegate_
.get() && delegate_
->ReadPending() &&
614 (current_read().sequence_number
== sequence_number())) {
616 delegate_
->CompleteRead();
621 void DeterministicSocketData::NextStep() {
622 // Invariant: Can never move *past* the stopping step.
623 DCHECK_LT(sequence_number_
, stopping_sequence_number_
);
625 if (sequence_number_
== stopping_sequence_number_
)
629 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
630 MockRead
* reads
, size_t reads_count
,
631 MockWrite
* writes
, size_t writes_count
) {
635 while (read
< reads_count
|| write
< writes_count
) {
636 // Check to see that we have a read or write at the expected
638 if (read
< reads_count
&& reads
[read
].sequence_number
== expected
) {
643 if (write
< writes_count
&& writes
[write
].sequence_number
== expected
) {
648 NOTREACHED() << "Missing sequence number: " << expected
;
651 DCHECK_EQ(read
, reads_count
);
652 DCHECK_EQ(write
, writes_count
);
655 MockClientSocketFactory::MockClientSocketFactory() {}
657 MockClientSocketFactory::~MockClientSocketFactory() {}
659 void MockClientSocketFactory::AddSocketDataProvider(
660 SocketDataProvider
* data
) {
661 mock_data_
.Add(data
);
664 void MockClientSocketFactory::AddSSLSocketDataProvider(
665 SSLSocketDataProvider
* data
) {
666 mock_ssl_data_
.Add(data
);
669 void MockClientSocketFactory::ResetNextMockIndexes() {
670 mock_data_
.ResetNextIndex();
671 mock_ssl_data_
.ResetNextIndex();
674 scoped_ptr
<DatagramClientSocket
>
675 MockClientSocketFactory::CreateDatagramClientSocket(
676 DatagramSocket::BindType bind_type
,
677 const RandIntCallback
& rand_int_cb
,
678 net::NetLog
* net_log
,
679 const net::NetLog::Source
& source
) {
680 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
681 scoped_ptr
<MockUDPClientSocket
> socket(
682 new MockUDPClientSocket(data_provider
, net_log
));
683 data_provider
->set_socket(socket
.get());
684 if (bind_type
== DatagramSocket::RANDOM_BIND
)
685 socket
->set_source_port(rand_int_cb
.Run(1025, 65535));
686 return socket
.PassAs
<DatagramClientSocket
>();
689 scoped_ptr
<StreamSocket
> MockClientSocketFactory::CreateTransportClientSocket(
690 const AddressList
& addresses
,
691 net::NetLog
* net_log
,
692 const net::NetLog::Source
& source
) {
693 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
694 scoped_ptr
<MockTCPClientSocket
> socket(
695 new MockTCPClientSocket(addresses
, net_log
, data_provider
));
696 data_provider
->set_socket(socket
.get());
697 return socket
.PassAs
<StreamSocket
>();
700 scoped_ptr
<SSLClientSocket
> MockClientSocketFactory::CreateSSLClientSocket(
701 scoped_ptr
<ClientSocketHandle
> transport_socket
,
702 const HostPortPair
& host_and_port
,
703 const SSLConfig
& ssl_config
,
704 const SSLClientSocketContext
& context
) {
705 scoped_ptr
<MockSSLClientSocket
> socket(
706 new MockSSLClientSocket(transport_socket
.Pass(),
709 mock_ssl_data_
.GetNext()));
710 ssl_client_sockets_
.push_back(socket
.get());
711 return socket
.PassAs
<SSLClientSocket
>();
714 void MockClientSocketFactory::ClearSSLSessionCache() {
717 const char MockClientSocket::kTlsUnique
[] = "MOCK_TLSUNIQ";
719 MockClientSocket::MockClientSocket(const BoundNetLog
& net_log
)
722 weak_factory_(this) {
724 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
725 peer_addr_
= IPEndPoint(ip
, 0);
728 int MockClientSocket::SetReceiveBufferSize(int32 size
) {
732 int MockClientSocket::SetSendBufferSize(int32 size
) {
736 void MockClientSocket::Disconnect() {
740 bool MockClientSocket::IsConnected() const {
744 bool MockClientSocket::IsConnectedAndIdle() const {
748 int MockClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
750 return ERR_SOCKET_NOT_CONNECTED
;
751 *address
= peer_addr_
;
755 int MockClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
757 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
759 *address
= IPEndPoint(ip
, 123);
763 const BoundNetLog
& MockClientSocket::NetLog() const {
767 bool MockClientSocket::InSessionCache() const {
772 void MockClientSocket::SetHandshakeCompletionCallback(const base::Closure
& cb
) {
776 void MockClientSocket::GetSSLCertRequestInfo(
777 SSLCertRequestInfo
* cert_request_info
) {
780 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece
& label
,
782 const base::StringPiece
& context
,
784 unsigned int outlen
) {
785 memset(out
, 'A', outlen
);
789 int MockClientSocket::GetTLSUniqueChannelBinding(std::string
* out
) {
790 out
->assign(MockClientSocket::kTlsUnique
);
794 ChannelIDService
* MockClientSocket::GetChannelIDService() const {
799 SSLClientSocket::NextProtoStatus
800 MockClientSocket::GetNextProto(std::string
* proto
) {
802 return SSLClientSocket::kNextProtoUnsupported
;
805 scoped_refptr
<X509Certificate
>
806 MockClientSocket::GetUnverifiedServerCertificateChain() const {
811 MockClientSocket::~MockClientSocket() {}
813 void MockClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
815 base::MessageLoop::current()->PostTask(
817 base::Bind(&MockClientSocket::RunCallback
,
818 weak_factory_
.GetWeakPtr(),
823 void MockClientSocket::RunCallback(const net::CompletionCallback
& callback
,
825 if (!callback
.is_null())
826 callback
.Run(result
);
829 MockTCPClientSocket::MockTCPClientSocket(const AddressList
& addresses
,
830 net::NetLog
* net_log
,
831 SocketDataProvider
* data
)
832 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
833 addresses_(addresses
),
836 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
837 need_read_data_(true),
838 peer_closed_connection_(false),
841 was_used_to_convey_data_(false) {
843 peer_addr_
= data
->connect_data().peer_addr
;
847 MockTCPClientSocket::~MockTCPClientSocket() {}
849 int MockTCPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
850 const CompletionCallback
& callback
) {
852 return ERR_UNEXPECTED
;
854 // If the buffer is already in use, a read is already in progress!
855 DCHECK(pending_buf_
== NULL
);
857 // Store our async IO data.
859 pending_buf_len_
= buf_len
;
860 pending_callback_
= callback
;
862 if (need_read_data_
) {
863 read_data_
= data_
->GetNextRead();
864 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
865 // This MockRead is just a marker to instruct us to set
866 // peer_closed_connection_.
867 peer_closed_connection_
= true;
869 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
870 // This MockRead is just a marker to instruct us to set
871 // peer_closed_connection_. Skip it and get the next one.
872 read_data_
= data_
->GetNextRead();
873 peer_closed_connection_
= true;
875 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
876 // to complete the async IO manually later (via OnReadComplete).
877 if (read_data_
.result
== ERR_IO_PENDING
) {
878 // We need to be using async IO in this case.
879 DCHECK(!callback
.is_null());
880 return ERR_IO_PENDING
;
882 need_read_data_
= false;
885 return CompleteRead();
888 int MockTCPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
889 const CompletionCallback
& callback
) {
891 DCHECK_GT(buf_len
, 0);
894 return ERR_UNEXPECTED
;
896 std::string
data(buf
->data(), buf_len
);
897 MockWriteResult write_result
= data_
->OnWrite(data
);
899 was_used_to_convey_data_
= true;
901 if (write_result
.mode
== ASYNC
) {
902 RunCallbackAsync(callback
, write_result
.result
);
903 return ERR_IO_PENDING
;
906 return write_result
.result
;
909 int MockTCPClientSocket::Connect(const CompletionCallback
& callback
) {
913 peer_closed_connection_
= false;
914 if (data_
->connect_data().mode
== ASYNC
) {
915 if (data_
->connect_data().result
== ERR_IO_PENDING
)
916 pending_callback_
= callback
;
918 RunCallbackAsync(callback
, data_
->connect_data().result
);
919 return ERR_IO_PENDING
;
921 return data_
->connect_data().result
;
924 void MockTCPClientSocket::Disconnect() {
925 MockClientSocket::Disconnect();
926 pending_callback_
.Reset();
929 bool MockTCPClientSocket::IsConnected() const {
930 return connected_
&& !peer_closed_connection_
;
933 bool MockTCPClientSocket::IsConnectedAndIdle() const {
934 return IsConnected();
937 int MockTCPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
938 if (addresses_
.empty())
939 return MockClientSocket::GetPeerAddress(address
);
941 *address
= addresses_
[0];
945 bool MockTCPClientSocket::WasEverUsed() const {
946 return was_used_to_convey_data_
;
949 bool MockTCPClientSocket::UsingTCPFastOpen() const {
953 bool MockTCPClientSocket::WasNpnNegotiated() const {
957 bool MockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
961 void MockTCPClientSocket::OnReadComplete(const MockRead
& data
) {
962 // There must be a read pending.
963 DCHECK(pending_buf_
);
964 // You can't complete a read with another ERR_IO_PENDING status code.
965 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
966 // Since we've been waiting for data, need_read_data_ should be true.
967 DCHECK(need_read_data_
);
970 need_read_data_
= false;
972 // The caller is simulating that this IO completes right now. Don't
973 // let CompleteRead() schedule a callback.
974 read_data_
.mode
= SYNCHRONOUS
;
976 CompletionCallback callback
= pending_callback_
;
977 int rv
= CompleteRead();
978 RunCallback(callback
, rv
);
981 void MockTCPClientSocket::OnConnectComplete(const MockConnect
& data
) {
982 CompletionCallback callback
= pending_callback_
;
983 RunCallback(callback
, data
.result
);
986 int MockTCPClientSocket::CompleteRead() {
987 DCHECK(pending_buf_
);
988 DCHECK(pending_buf_len_
> 0);
990 was_used_to_convey_data_
= true;
992 // Save the pending async IO data and reset our |pending_| state.
993 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
994 int buf_len
= pending_buf_len_
;
995 CompletionCallback callback
= pending_callback_
;
997 pending_buf_len_
= 0;
998 pending_callback_
.Reset();
1000 int result
= read_data_
.result
;
1001 DCHECK(result
!= ERR_IO_PENDING
);
1003 if (read_data_
.data
) {
1004 if (read_data_
.data_len
- read_offset_
> 0) {
1005 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
1006 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
1007 read_offset_
+= result
;
1008 if (read_offset_
== read_data_
.data_len
) {
1009 need_read_data_
= true;
1017 if (read_data_
.mode
== ASYNC
) {
1018 DCHECK(!callback
.is_null());
1019 RunCallbackAsync(callback
, result
);
1020 return ERR_IO_PENDING
;
1025 DeterministicSocketHelper::DeterministicSocketHelper(
1026 net::NetLog
* net_log
,
1027 DeterministicSocketData
* data
)
1028 : write_pending_(false),
1033 read_pending_(false),
1035 was_used_to_convey_data_(false),
1036 peer_closed_connection_(false),
1037 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)) {
1040 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1042 void DeterministicSocketHelper::CompleteWrite() {
1043 was_used_to_convey_data_
= true;
1044 write_pending_
= false;
1045 write_callback_
.Run(write_result_
);
1048 int DeterministicSocketHelper::CompleteRead() {
1049 DCHECK_GT(read_buf_len_
, 0);
1050 DCHECK_LE(read_data_
.data_len
, read_buf_len_
);
1053 was_used_to_convey_data_
= true;
1055 if (read_data_
.result
== ERR_IO_PENDING
)
1056 read_data_
= data_
->GetNextRead();
1057 DCHECK_NE(ERR_IO_PENDING
, read_data_
.result
);
1058 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1059 // the callback. Therefore we don't even bother to check it.
1060 int result
= read_data_
.result
;
1062 if (read_data_
.data_len
> 0) {
1063 DCHECK(read_data_
.data
);
1064 result
= std::min(read_buf_len_
, read_data_
.data_len
);
1065 memcpy(read_buf_
->data(), read_data_
.data
, result
);
1068 if (read_pending_
) {
1069 read_pending_
= false;
1070 read_callback_
.Run(result
);
1076 int DeterministicSocketHelper::Write(
1077 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1079 DCHECK_GT(buf_len
, 0);
1081 std::string
data(buf
->data(), buf_len
);
1082 MockWriteResult write_result
= data_
->OnWrite(data
);
1084 if (write_result
.mode
== ASYNC
) {
1085 write_callback_
= callback
;
1086 write_result_
= write_result
.result
;
1087 DCHECK(!write_callback_
.is_null());
1088 write_pending_
= true;
1089 return ERR_IO_PENDING
;
1092 was_used_to_convey_data_
= true;
1093 write_pending_
= false;
1094 return write_result
.result
;
1097 int DeterministicSocketHelper::Read(
1098 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1100 read_data_
= data_
->GetNextRead();
1101 // The buffer should always be big enough to contain all the MockRead data. To
1102 // use small buffers, split the data into multiple MockReads.
1103 DCHECK_LE(read_data_
.data_len
, buf_len
);
1105 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
1106 // This MockRead is just a marker to instruct us to set
1107 // peer_closed_connection_.
1108 peer_closed_connection_
= true;
1110 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
1111 // This MockRead is just a marker to instruct us to set
1112 // peer_closed_connection_. Skip it and get the next one.
1113 read_data_
= data_
->GetNextRead();
1114 peer_closed_connection_
= true;
1118 read_buf_len_
= buf_len
;
1119 read_callback_
= callback
;
1121 if (read_data_
.mode
== ASYNC
|| (read_data_
.result
== ERR_IO_PENDING
)) {
1122 read_pending_
= true;
1123 DCHECK(!read_callback_
.is_null());
1124 return ERR_IO_PENDING
;
1127 was_used_to_convey_data_
= true;
1128 return CompleteRead();
1131 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1132 net::NetLog
* net_log
,
1133 DeterministicSocketData
* data
)
1134 : connected_(false),
1135 helper_(net_log
, data
),
1139 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1141 bool DeterministicMockUDPClientSocket::WritePending() const {
1142 return helper_
.write_pending();
1145 bool DeterministicMockUDPClientSocket::ReadPending() const {
1146 return helper_
.read_pending();
1149 void DeterministicMockUDPClientSocket::CompleteWrite() {
1150 helper_
.CompleteWrite();
1153 int DeterministicMockUDPClientSocket::CompleteRead() {
1154 return helper_
.CompleteRead();
1157 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1161 peer_address_
= address
;
1162 return helper_
.data()->connect_data().result
;
1165 int DeterministicMockUDPClientSocket::Write(
1168 const CompletionCallback
& callback
) {
1170 return ERR_UNEXPECTED
;
1172 return helper_
.Write(buf
, buf_len
, callback
);
1175 int DeterministicMockUDPClientSocket::Read(
1178 const CompletionCallback
& callback
) {
1180 return ERR_UNEXPECTED
;
1182 return helper_
.Read(buf
, buf_len
, callback
);
1185 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1189 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size
) {
1193 void DeterministicMockUDPClientSocket::Close() {
1197 int DeterministicMockUDPClientSocket::GetPeerAddress(
1198 IPEndPoint
* address
) const {
1199 *address
= peer_address_
;
1203 int DeterministicMockUDPClientSocket::GetLocalAddress(
1204 IPEndPoint
* address
) const {
1206 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1208 *address
= IPEndPoint(ip
, source_port_
);
1212 const BoundNetLog
& DeterministicMockUDPClientSocket::NetLog() const {
1213 return helper_
.net_log();
1216 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead
& data
) {}
1218 void DeterministicMockUDPClientSocket::OnConnectComplete(
1219 const MockConnect
& data
) {
1223 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1224 net::NetLog
* net_log
,
1225 DeterministicSocketData
* data
)
1226 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1227 helper_(net_log
, data
) {
1228 peer_addr_
= data
->connect_data().peer_addr
;
1231 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1233 bool DeterministicMockTCPClientSocket::WritePending() const {
1234 return helper_
.write_pending();
1237 bool DeterministicMockTCPClientSocket::ReadPending() const {
1238 return helper_
.read_pending();
1241 void DeterministicMockTCPClientSocket::CompleteWrite() {
1242 helper_
.CompleteWrite();
1245 int DeterministicMockTCPClientSocket::CompleteRead() {
1246 return helper_
.CompleteRead();
1249 int DeterministicMockTCPClientSocket::Write(
1252 const CompletionCallback
& callback
) {
1254 return ERR_UNEXPECTED
;
1256 return helper_
.Write(buf
, buf_len
, callback
);
1259 int DeterministicMockTCPClientSocket::Read(
1262 const CompletionCallback
& callback
) {
1264 return ERR_UNEXPECTED
;
1266 return helper_
.Read(buf
, buf_len
, callback
);
1269 // TODO(erikchen): Support connect sequencing.
1270 int DeterministicMockTCPClientSocket::Connect(
1271 const CompletionCallback
& callback
) {
1275 if (helper_
.data()->connect_data().mode
== ASYNC
) {
1276 RunCallbackAsync(callback
, helper_
.data()->connect_data().result
);
1277 return ERR_IO_PENDING
;
1279 return helper_
.data()->connect_data().result
;
1282 void DeterministicMockTCPClientSocket::Disconnect() {
1283 MockClientSocket::Disconnect();
1286 bool DeterministicMockTCPClientSocket::IsConnected() const {
1287 return connected_
&& !helper_
.peer_closed_connection();
1290 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1291 return IsConnected();
1294 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1295 return helper_
.was_used_to_convey_data();
1298 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1302 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1306 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1310 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead
& data
) {}
1312 void DeterministicMockTCPClientSocket::OnConnectComplete(
1313 const MockConnect
& data
) {}
1315 MockSSLClientSocket::MockSSLClientSocket(
1316 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1317 const HostPortPair
& host_port_pair
,
1318 const SSLConfig
& ssl_config
,
1319 SSLSocketDataProvider
* data
)
1321 // Have to use the right BoundNetLog for LoadTimingInfo regression
1323 transport_socket
->socket()->NetLog()),
1324 transport_(transport_socket
.Pass()),
1326 is_npn_state_set_(false),
1327 new_npn_value_(false),
1328 is_protocol_negotiated_set_(false),
1329 protocol_negotiated_(kProtoUnknown
),
1330 next_connect_state_(STATE_NONE
),
1331 reached_connect_(false),
1332 weak_factory_(this) {
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 next_connect_state_
= STATE_SSL_CONNECT
;
1353 reached_connect_
= true;
1354 int rv
= DoConnectLoop(OK
);
1355 if (rv
== ERR_IO_PENDING
)
1356 connect_callback_
= callback
;
1360 void MockSSLClientSocket::Disconnect() {
1361 weak_factory_
.InvalidateWeakPtrs();
1362 MockClientSocket::Disconnect();
1363 if (transport_
->socket() != NULL
)
1364 transport_
->socket()->Disconnect();
1367 bool MockSSLClientSocket::IsConnected() const {
1368 return transport_
->socket()->IsConnected() && connected_
;
1371 bool MockSSLClientSocket::WasEverUsed() const {
1372 return transport_
->socket()->WasEverUsed();
1375 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1376 return transport_
->socket()->UsingTCPFastOpen();
1379 int MockSSLClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1380 return transport_
->socket()->GetPeerAddress(address
);
1383 bool MockSSLClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1385 ssl_info
->cert
= data_
->cert
;
1386 ssl_info
->client_cert_sent
= data_
->client_cert_sent
;
1387 ssl_info
->channel_id_sent
= data_
->channel_id_sent
;
1388 ssl_info
->connection_status
= data_
->connection_status
;
1392 bool MockSSLClientSocket::InSessionCache() const {
1393 return data_
->is_in_session_cache
;
1396 void MockSSLClientSocket::SetHandshakeCompletionCallback(
1397 const base::Closure
& cb
) {
1398 handshake_completion_callback_
= cb
;
1401 void MockSSLClientSocket::GetSSLCertRequestInfo(
1402 SSLCertRequestInfo
* cert_request_info
) {
1403 DCHECK(cert_request_info
);
1404 if (data_
->cert_request_info
) {
1405 cert_request_info
->host_and_port
=
1406 data_
->cert_request_info
->host_and_port
;
1407 cert_request_info
->client_certs
= data_
->cert_request_info
->client_certs
;
1409 cert_request_info
->Reset();
1413 SSLClientSocket::NextProtoStatus
MockSSLClientSocket::GetNextProto(
1414 std::string
* proto
) {
1415 *proto
= data_
->next_proto
;
1416 return data_
->next_proto_status
;
1419 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated
) {
1420 is_npn_state_set_
= true;
1421 return new_npn_value_
= negotiated
;
1424 bool MockSSLClientSocket::WasNpnNegotiated() const {
1425 if (is_npn_state_set_
)
1426 return new_npn_value_
;
1427 return data_
->was_npn_negotiated
;
1430 NextProto
MockSSLClientSocket::GetNegotiatedProtocol() const {
1431 if (is_protocol_negotiated_set_
)
1432 return protocol_negotiated_
;
1433 return data_
->protocol_negotiated
;
1436 void MockSSLClientSocket::set_protocol_negotiated(
1437 NextProto protocol_negotiated
) {
1438 is_protocol_negotiated_set_
= true;
1439 protocol_negotiated_
= protocol_negotiated
;
1442 bool MockSSLClientSocket::WasChannelIDSent() const {
1443 return data_
->channel_id_sent
;
1446 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent
) {
1447 data_
->channel_id_sent
= channel_id_sent
;
1450 ChannelIDService
* MockSSLClientSocket::GetChannelIDService() const {
1451 return data_
->channel_id_service
;
1454 void MockSSLClientSocket::OnReadComplete(const MockRead
& data
) {
1458 void MockSSLClientSocket::OnConnectComplete(const MockConnect
& data
) {
1462 void MockSSLClientSocket::RestartPausedConnect() {
1463 DCHECK(data_
->should_pause_on_connect
);
1464 DCHECK_EQ(next_connect_state_
, STATE_SSL_CONNECT_COMPLETE
);
1465 OnIOComplete(data_
->connect
.result
);
1468 void MockSSLClientSocket::OnIOComplete(int result
) {
1469 int rv
= DoConnectLoop(result
);
1470 if (rv
!= ERR_IO_PENDING
)
1471 base::ResetAndReturn(&connect_callback_
).Run(rv
);
1474 int MockSSLClientSocket::DoConnectLoop(int result
) {
1475 DCHECK_NE(next_connect_state_
, STATE_NONE
);
1479 ConnectState state
= next_connect_state_
;
1480 next_connect_state_
= STATE_NONE
;
1482 case STATE_SSL_CONNECT
:
1483 rv
= DoSSLConnect();
1485 case STATE_SSL_CONNECT_COMPLETE
:
1486 rv
= DoSSLConnectComplete(rv
);
1489 NOTREACHED() << "bad state";
1490 rv
= ERR_UNEXPECTED
;
1493 } while (rv
!= ERR_IO_PENDING
&& next_connect_state_
!= STATE_NONE
);
1498 int MockSSLClientSocket::DoSSLConnect() {
1499 next_connect_state_
= STATE_SSL_CONNECT_COMPLETE
;
1501 if (data_
->should_pause_on_connect
)
1502 return ERR_IO_PENDING
;
1504 if (data_
->connect
.mode
== ASYNC
) {
1505 base::MessageLoop::current()->PostTask(
1507 base::Bind(&MockSSLClientSocket::OnIOComplete
,
1508 weak_factory_
.GetWeakPtr(),
1509 data_
->connect
.result
));
1510 return ERR_IO_PENDING
;
1513 return data_
->connect
.result
;
1516 int MockSSLClientSocket::DoSSLConnectComplete(int result
) {
1520 if (!handshake_completion_callback_
.is_null())
1521 base::ResetAndReturn(&handshake_completion_callback_
).Run();
1525 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider
* data
,
1526 net::NetLog
* net_log
)
1527 : connected_(false),
1530 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
1531 need_read_data_(true),
1534 pending_buf_len_(0),
1535 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1536 weak_factory_(this) {
1539 peer_addr_
= data
->connect_data().peer_addr
;
1542 MockUDPClientSocket::~MockUDPClientSocket() {}
1544 int MockUDPClientSocket::Read(IOBuffer
* buf
,
1546 const CompletionCallback
& callback
) {
1548 return ERR_UNEXPECTED
;
1550 // If the buffer is already in use, a read is already in progress!
1551 DCHECK(pending_buf_
== NULL
);
1553 // Store our async IO data.
1555 pending_buf_len_
= buf_len
;
1556 pending_callback_
= callback
;
1558 if (need_read_data_
) {
1559 read_data_
= data_
->GetNextRead();
1560 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1561 // to complete the async IO manually later (via OnReadComplete).
1562 if (read_data_
.result
== ERR_IO_PENDING
) {
1563 // We need to be using async IO in this case.
1564 DCHECK(!callback
.is_null());
1565 return ERR_IO_PENDING
;
1567 need_read_data_
= false;
1570 return CompleteRead();
1573 int MockUDPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1574 const CompletionCallback
& callback
) {
1576 DCHECK_GT(buf_len
, 0);
1579 return ERR_UNEXPECTED
;
1581 std::string
data(buf
->data(), buf_len
);
1582 MockWriteResult write_result
= data_
->OnWrite(data
);
1584 if (write_result
.mode
== ASYNC
) {
1585 RunCallbackAsync(callback
, write_result
.result
);
1586 return ERR_IO_PENDING
;
1588 return write_result
.result
;
1591 int MockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1595 int MockUDPClientSocket::SetSendBufferSize(int32 size
) {
1599 void MockUDPClientSocket::Close() {
1603 int MockUDPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1604 *address
= peer_addr_
;
1608 int MockUDPClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
1610 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1612 *address
= IPEndPoint(ip
, source_port_
);
1616 const BoundNetLog
& MockUDPClientSocket::NetLog() const {
1620 int MockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1622 peer_addr_
= address
;
1623 return data_
->connect_data().result
;
1626 void MockUDPClientSocket::OnReadComplete(const MockRead
& data
) {
1627 // There must be a read pending.
1628 DCHECK(pending_buf_
);
1629 // You can't complete a read with another ERR_IO_PENDING status code.
1630 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
1631 // Since we've been waiting for data, need_read_data_ should be true.
1632 DCHECK(need_read_data_
);
1635 need_read_data_
= false;
1637 // The caller is simulating that this IO completes right now. Don't
1638 // let CompleteRead() schedule a callback.
1639 read_data_
.mode
= SYNCHRONOUS
;
1641 net::CompletionCallback callback
= pending_callback_
;
1642 int rv
= CompleteRead();
1643 RunCallback(callback
, rv
);
1646 void MockUDPClientSocket::OnConnectComplete(const MockConnect
& data
) {
1650 int MockUDPClientSocket::CompleteRead() {
1651 DCHECK(pending_buf_
);
1652 DCHECK(pending_buf_len_
> 0);
1654 // Save the pending async IO data and reset our |pending_| state.
1655 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
1656 int buf_len
= pending_buf_len_
;
1657 CompletionCallback callback
= pending_callback_
;
1658 pending_buf_
= NULL
;
1659 pending_buf_len_
= 0;
1660 pending_callback_
.Reset();
1662 int result
= read_data_
.result
;
1663 DCHECK(result
!= ERR_IO_PENDING
);
1665 if (read_data_
.data
) {
1666 if (read_data_
.data_len
- read_offset_
> 0) {
1667 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
1668 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
1669 read_offset_
+= result
;
1670 if (read_offset_
== read_data_
.data_len
) {
1671 need_read_data_
= true;
1679 if (read_data_
.mode
== ASYNC
) {
1680 DCHECK(!callback
.is_null());
1681 RunCallbackAsync(callback
, result
);
1682 return ERR_IO_PENDING
;
1687 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
1689 base::MessageLoop::current()->PostTask(
1691 base::Bind(&MockUDPClientSocket::RunCallback
,
1692 weak_factory_
.GetWeakPtr(),
1697 void MockUDPClientSocket::RunCallback(const CompletionCallback
& callback
,
1699 if (!callback
.is_null())
1700 callback
.Run(result
);
1703 TestSocketRequest::TestSocketRequest(
1704 std::vector
<TestSocketRequest
*>* request_order
, size_t* completion_count
)
1705 : request_order_(request_order
),
1706 completion_count_(completion_count
),
1707 callback_(base::Bind(&TestSocketRequest::OnComplete
,
1708 base::Unretained(this))) {
1709 DCHECK(request_order
);
1710 DCHECK(completion_count
);
1713 TestSocketRequest::~TestSocketRequest() {
1716 void TestSocketRequest::OnComplete(int result
) {
1718 (*completion_count_
)++;
1719 request_order_
->push_back(this);
1723 const int ClientSocketPoolTest::kIndexOutOfBounds
= -1;
1726 const int ClientSocketPoolTest::kRequestNotFound
= -2;
1728 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1729 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1731 int ClientSocketPoolTest::GetOrderOfRequest(size_t index
) const {
1733 if (index
>= requests_
.size())
1734 return kIndexOutOfBounds
;
1736 for (size_t i
= 0; i
< request_order_
.size(); i
++)
1737 if (requests_
[index
] == request_order_
[i
])
1740 return kRequestNotFound
;
1743 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive
) {
1744 ScopedVector
<TestSocketRequest
>::iterator i
;
1745 for (i
= requests_
.begin(); i
!= requests_
.end(); ++i
) {
1746 if ((*i
)->handle()->is_initialized()) {
1747 if (keep_alive
== NO_KEEP_ALIVE
)
1748 (*i
)->handle()->socket()->Disconnect();
1749 (*i
)->handle()->Reset();
1750 base::RunLoop().RunUntilIdle();
1757 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive
) {
1760 released_one
= ReleaseOneConnection(keep_alive
);
1761 } while (released_one
);
1764 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1765 scoped_ptr
<StreamSocket
> socket
,
1766 ClientSocketHandle
* handle
,
1767 const CompletionCallback
& callback
)
1768 : socket_(socket
.Pass()),
1770 user_callback_(callback
) {
1773 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1775 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1776 int rv
= socket_
->Connect(base::Bind(&MockConnectJob::OnConnect
,
1777 base::Unretained(this)));
1779 user_callback_
.Reset();
1785 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1786 const ClientSocketHandle
* handle
) {
1787 if (handle
!= handle_
)
1791 user_callback_
.Reset();
1795 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv
) {
1799 handle_
->SetSocket(socket_
.Pass());
1801 // Needed for socket pool tests that layer other sockets on top of mock
1803 LoadTimingInfo::ConnectTiming connect_timing
;
1804 base::TimeTicks now
= base::TimeTicks::Now();
1805 connect_timing
.dns_start
= now
;
1806 connect_timing
.dns_end
= now
;
1807 connect_timing
.connect_start
= now
;
1808 connect_timing
.connect_end
= now
;
1809 handle_
->set_connect_timing(connect_timing
);
1816 if (!user_callback_
.is_null()) {
1817 CompletionCallback callback
= user_callback_
;
1818 user_callback_
.Reset();
1823 MockTransportClientSocketPool::MockTransportClientSocketPool(
1825 int max_sockets_per_group
,
1826 ClientSocketPoolHistograms
* histograms
,
1827 ClientSocketFactory
* socket_factory
)
1828 : TransportClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1830 client_socket_factory_(socket_factory
),
1831 last_request_priority_(DEFAULT_PRIORITY
),
1836 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1838 int MockTransportClientSocketPool::RequestSocket(
1839 const std::string
& group_name
, const void* socket_params
,
1840 RequestPriority priority
, ClientSocketHandle
* handle
,
1841 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1842 last_request_priority_
= priority
;
1843 scoped_ptr
<StreamSocket
> socket
=
1844 client_socket_factory_
->CreateTransportClientSocket(
1845 AddressList(), net_log
.net_log(), net::NetLog::Source());
1846 MockConnectJob
* job
= new MockConnectJob(socket
.Pass(), handle
, callback
);
1847 job_list_
.push_back(job
);
1848 handle
->set_pool_id(1);
1849 return job
->Connect();
1852 void MockTransportClientSocketPool::CancelRequest(const std::string
& group_name
,
1853 ClientSocketHandle
* handle
) {
1854 std::vector
<MockConnectJob
*>::iterator i
;
1855 for (i
= job_list_
.begin(); i
!= job_list_
.end(); ++i
) {
1856 if ((*i
)->CancelHandle(handle
)) {
1863 void MockTransportClientSocketPool::ReleaseSocket(
1864 const std::string
& group_name
,
1865 scoped_ptr
<StreamSocket
> socket
,
1871 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1873 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1875 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1876 DeterministicSocketData
* data
) {
1877 mock_data_
.Add(data
);
1880 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1881 SSLSocketDataProvider
* data
) {
1882 mock_ssl_data_
.Add(data
);
1885 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1886 mock_data_
.ResetNextIndex();
1887 mock_ssl_data_
.ResetNextIndex();
1890 MockSSLClientSocket
* DeterministicMockClientSocketFactory::
1891 GetMockSSLClientSocket(size_t index
) const {
1892 DCHECK_LT(index
, ssl_client_sockets_
.size());
1893 return ssl_client_sockets_
[index
];
1896 scoped_ptr
<DatagramClientSocket
>
1897 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1898 DatagramSocket::BindType bind_type
,
1899 const RandIntCallback
& rand_int_cb
,
1900 net::NetLog
* net_log
,
1901 const NetLog::Source
& source
) {
1902 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1903 scoped_ptr
<DeterministicMockUDPClientSocket
> socket(
1904 new DeterministicMockUDPClientSocket(net_log
, data_provider
));
1905 data_provider
->set_delegate(socket
->AsWeakPtr());
1906 udp_client_sockets().push_back(socket
.get());
1907 if (bind_type
== DatagramSocket::RANDOM_BIND
)
1908 socket
->set_source_port(rand_int_cb
.Run(1025, 65535));
1909 return socket
.PassAs
<DatagramClientSocket
>();
1912 scoped_ptr
<StreamSocket
>
1913 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1914 const AddressList
& addresses
,
1915 net::NetLog
* net_log
,
1916 const net::NetLog::Source
& source
) {
1917 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1918 scoped_ptr
<DeterministicMockTCPClientSocket
> socket(
1919 new DeterministicMockTCPClientSocket(net_log
, data_provider
));
1920 data_provider
->set_delegate(socket
->AsWeakPtr());
1921 tcp_client_sockets().push_back(socket
.get());
1922 return socket
.PassAs
<StreamSocket
>();
1925 scoped_ptr
<SSLClientSocket
>
1926 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1927 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1928 const HostPortPair
& host_and_port
,
1929 const SSLConfig
& ssl_config
,
1930 const SSLClientSocketContext
& context
) {
1931 scoped_ptr
<MockSSLClientSocket
> socket(
1932 new MockSSLClientSocket(transport_socket
.Pass(),
1933 host_and_port
, ssl_config
,
1934 mock_ssl_data_
.GetNext()));
1935 ssl_client_sockets_
.push_back(socket
.get());
1936 return socket
.PassAs
<SSLClientSocket
>();
1939 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1942 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1944 int max_sockets_per_group
,
1945 ClientSocketPoolHistograms
* histograms
,
1946 TransportClientSocketPool
* transport_pool
)
1947 : SOCKSClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1948 NULL
, transport_pool
, NULL
),
1949 transport_pool_(transport_pool
) {
1952 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1954 int MockSOCKSClientSocketPool::RequestSocket(
1955 const std::string
& group_name
, const void* socket_params
,
1956 RequestPriority priority
, ClientSocketHandle
* handle
,
1957 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1958 return transport_pool_
->RequestSocket(
1959 group_name
, socket_params
, priority
, handle
, callback
, net_log
);
1962 void MockSOCKSClientSocketPool::CancelRequest(
1963 const std::string
& group_name
,
1964 ClientSocketHandle
* handle
) {
1965 return transport_pool_
->CancelRequest(group_name
, handle
);
1968 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string
& group_name
,
1969 scoped_ptr
<StreamSocket
> socket
,
1971 return transport_pool_
->ReleaseSocket(group_name
, socket
.Pass(), id
);
1974 const char kSOCKS5GreetRequest
[] = { 0x05, 0x01, 0x00 };
1975 const int kSOCKS5GreetRequestLength
= arraysize(kSOCKS5GreetRequest
);
1977 const char kSOCKS5GreetResponse
[] = { 0x05, 0x00 };
1978 const int kSOCKS5GreetResponseLength
= arraysize(kSOCKS5GreetResponse
);
1980 const char kSOCKS5OkRequest
[] =
1981 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1982 const int kSOCKS5OkRequestLength
= arraysize(kSOCKS5OkRequest
);
1984 const char kSOCKS5OkResponse
[] =
1985 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1986 const int kSOCKS5OkResponseLength
= arraysize(kSOCKS5OkResponse
);