1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/socket/socket_test_util.h"
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/compiler_specific.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/run_loop.h"
16 #include "base/time/time.h"
17 #include "net/base/address_family.h"
18 #include "net/base/address_list.h"
19 #include "net/base/auth.h"
20 #include "net/base/load_timing_info.h"
21 #include "net/http/http_network_session.h"
22 #include "net/http/http_request_headers.h"
23 #include "net/http/http_response_headers.h"
24 #include "net/socket/client_socket_pool_histograms.h"
25 #include "net/socket/socket.h"
26 #include "net/ssl/ssl_cert_request_info.h"
27 #include "net/ssl/ssl_info.h"
28 #include "testing/gtest/include/gtest/gtest.h"
30 // Socket events are easier to debug if you log individual reads and writes.
31 // Enable these if locally debugging, but they are too noisy for the waterfall.
33 #define NET_TRACE(level, s) DLOG(level) << s << __FUNCTION__ << "() "
35 #define NET_TRACE(level, s) EAT_STREAM_PARAMETERS
42 inline char AsciifyHigh(char x
) {
43 char nybble
= static_cast<char>((x
>> 4) & 0x0F);
44 return nybble
+ ((nybble
< 0x0A) ? '0' : 'A' - 10);
47 inline char AsciifyLow(char x
) {
48 char nybble
= static_cast<char>((x
>> 0) & 0x0F);
49 return nybble
+ ((nybble
< 0x0A) ? '0' : 'A' - 10);
52 inline char Asciify(char x
) {
53 if ((x
< 0) || !isprint(x
))
58 void DumpData(const char* data
, int data_len
) {
59 if (logging::LOG_INFO
< logging::GetMinLogLevel())
61 DVLOG(1) << "Length: " << data_len
;
62 const char* pfx
= "Data: ";
63 if (!data
|| (data_len
<= 0)) {
64 DVLOG(1) << pfx
<< "<None>";
67 for (i
= 0; i
<= (data_len
- 4); i
+= 4) {
69 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
70 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
71 << AsciifyHigh(data
[i
+ 2]) << AsciifyLow(data
[i
+ 2])
72 << AsciifyHigh(data
[i
+ 3]) << AsciifyLow(data
[i
+ 3])
74 << Asciify(data
[i
+ 0])
75 << Asciify(data
[i
+ 1])
76 << Asciify(data
[i
+ 2])
77 << Asciify(data
[i
+ 3])
81 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
82 switch (data_len
- i
) {
85 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
86 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
87 << AsciifyHigh(data
[i
+ 2]) << AsciifyLow(data
[i
+ 2])
89 << Asciify(data
[i
+ 0])
90 << Asciify(data
[i
+ 1])
91 << Asciify(data
[i
+ 2])
96 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
97 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
99 << Asciify(data
[i
+ 0])
100 << Asciify(data
[i
+ 1])
105 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
107 << Asciify(data
[i
+ 0])
114 template <MockReadWriteType type
>
115 void DumpMockReadWrite(const MockReadWrite
<type
>& r
) {
116 if (logging::LOG_INFO
< logging::GetMinLogLevel())
118 DVLOG(1) << "Async: " << (r
.mode
== ASYNC
)
119 << "\nResult: " << r
.result
;
120 DumpData(r
.data
, r
.data_len
);
121 const char* stop
= (r
.sequence_number
& MockRead::STOPLOOP
) ? " (STOP)" : "";
122 DVLOG(1) << "Stage: " << (r
.sequence_number
& ~MockRead::STOPLOOP
) << stop
123 << "\nTime: " << r
.time_stamp
.ToInternalValue();
128 MockConnect::MockConnect() : mode(ASYNC
), result(OK
) {
130 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
131 peer_addr
= IPEndPoint(ip
, 0);
134 MockConnect::MockConnect(IoMode io_mode
, int r
) : mode(io_mode
), result(r
) {
136 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
137 peer_addr
= IPEndPoint(ip
, 0);
140 MockConnect::MockConnect(IoMode io_mode
, int r
, IPEndPoint addr
) :
146 MockConnect::~MockConnect() {}
148 StaticSocketDataProvider::StaticSocketDataProvider()
157 StaticSocketDataProvider::StaticSocketDataProvider(MockRead
* reads
,
163 read_count_(reads_count
),
166 write_count_(writes_count
) {
169 StaticSocketDataProvider::~StaticSocketDataProvider() {}
171 const MockRead
& StaticSocketDataProvider::PeekRead() const {
172 CHECK(!at_read_eof());
173 return reads_
[read_index_
];
176 const MockWrite
& StaticSocketDataProvider::PeekWrite() const {
177 CHECK(!at_write_eof());
178 return writes_
[write_index_
];
181 const MockRead
& StaticSocketDataProvider::PeekRead(size_t index
) const {
182 CHECK_LT(index
, read_count_
);
183 return reads_
[index
];
186 const MockWrite
& StaticSocketDataProvider::PeekWrite(size_t index
) const {
187 CHECK_LT(index
, write_count_
);
188 return writes_
[index
];
191 MockRead
StaticSocketDataProvider::GetNextRead() {
192 CHECK(!at_read_eof());
193 reads_
[read_index_
].time_stamp
= base::Time::Now();
194 return reads_
[read_index_
++];
197 MockWriteResult
StaticSocketDataProvider::OnWrite(const std::string
& data
) {
199 // Not using mock writes; succeed synchronously.
200 return MockWriteResult(SYNCHRONOUS
, data
.length());
202 EXPECT_FALSE(at_write_eof());
203 if (at_write_eof()) {
204 // Show what the extra write actually consists of.
205 EXPECT_EQ("<unexpected write>", data
);
206 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
209 // Check that what we are writing matches the expectation.
210 // Then give the mocked return value.
211 MockWrite
* w
= &writes_
[write_index_
++];
212 w
->time_stamp
= base::Time::Now();
213 int result
= w
->result
;
215 // Note - we can simulate a partial write here. If the expected data
216 // is a match, but shorter than the write actually written, that is legal.
218 // Application writes "foobarbaz" (9 bytes)
219 // Expected write was "foo" (3 bytes)
220 // This is a success, and we return 3 to the application.
221 std::string
expected_data(w
->data
, w
->data_len
);
222 EXPECT_GE(data
.length(), expected_data
.length());
223 std::string
actual_data(data
.substr(0, w
->data_len
));
224 EXPECT_EQ(expected_data
, actual_data
);
225 if (expected_data
!= actual_data
)
226 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
228 result
= w
->data_len
;
230 return MockWriteResult(w
->mode
, result
);
233 void StaticSocketDataProvider::Reset() {
238 DynamicSocketDataProvider::DynamicSocketDataProvider()
239 : short_read_limit_(0),
240 allow_unconsumed_reads_(false) {
243 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
245 MockRead
DynamicSocketDataProvider::GetNextRead() {
247 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
248 MockRead result
= reads_
.front();
249 if (short_read_limit_
== 0 || result
.data_len
<= short_read_limit_
) {
252 result
.data_len
= short_read_limit_
;
253 reads_
.front().data
+= result
.data_len
;
254 reads_
.front().data_len
-= result
.data_len
;
259 void DynamicSocketDataProvider::Reset() {
263 void DynamicSocketDataProvider::SimulateRead(const char* data
,
264 const size_t length
) {
265 if (!allow_unconsumed_reads_
) {
266 EXPECT_TRUE(reads_
.empty()) << "Unconsumed read: " << reads_
.front().data
;
268 reads_
.push_back(MockRead(ASYNC
, data
, length
));
271 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode
, int result
)
272 : connect(mode
, result
),
273 next_proto_status(SSLClientSocket::kNextProtoUnsupported
),
274 was_npn_negotiated(false),
275 protocol_negotiated(kProtoUnknown
),
276 client_cert_sent(false),
277 cert_request_info(NULL
),
278 channel_id_sent(false) {
281 SSLSocketDataProvider::~SSLSocketDataProvider() {
284 void SSLSocketDataProvider::SetNextProto(NextProto proto
) {
285 was_npn_negotiated
= true;
286 next_proto_status
= SSLClientSocket::kNextProtoNegotiated
;
287 protocol_negotiated
= proto
;
288 next_proto
= SSLClientSocket::NextProtoToString(proto
);
291 DelayedSocketData::DelayedSocketData(
292 int write_delay
, MockRead
* reads
, size_t reads_count
,
293 MockWrite
* writes
, size_t writes_count
)
294 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
295 write_delay_(write_delay
),
296 read_in_progress_(false),
297 weak_factory_(this) {
298 DCHECK_GE(write_delay_
, 0);
301 DelayedSocketData::DelayedSocketData(
302 const MockConnect
& connect
, int write_delay
, MockRead
* reads
,
303 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
304 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
305 write_delay_(write_delay
),
306 read_in_progress_(false),
307 weak_factory_(this) {
308 DCHECK_GE(write_delay_
, 0);
309 set_connect_data(connect
);
312 DelayedSocketData::~DelayedSocketData() {
315 void DelayedSocketData::ForceNextRead() {
316 DCHECK(read_in_progress_
);
321 MockRead
DelayedSocketData::GetNextRead() {
322 MockRead out
= MockRead(ASYNC
, ERR_IO_PENDING
);
323 if (write_delay_
<= 0)
324 out
= StaticSocketDataProvider::GetNextRead();
325 read_in_progress_
= (out
.result
== ERR_IO_PENDING
);
329 MockWriteResult
DelayedSocketData::OnWrite(const std::string
& data
) {
330 MockWriteResult rv
= StaticSocketDataProvider::OnWrite(data
);
331 // Now that our write has completed, we can allow reads to continue.
332 if (!--write_delay_
&& read_in_progress_
)
333 base::MessageLoop::current()->PostDelayedTask(
335 base::Bind(&DelayedSocketData::CompleteRead
,
336 weak_factory_
.GetWeakPtr()),
337 base::TimeDelta::FromMilliseconds(100));
341 void DelayedSocketData::Reset() {
343 read_in_progress_
= false;
344 weak_factory_
.InvalidateWeakPtrs();
345 StaticSocketDataProvider::Reset();
348 void DelayedSocketData::CompleteRead() {
349 if (socket() && read_in_progress_
)
350 socket()->OnReadComplete(GetNextRead());
353 OrderedSocketData::OrderedSocketData(
354 MockRead
* reads
, size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
355 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
356 sequence_number_(0), loop_stop_stage_(0),
357 blocked_(false), weak_factory_(this) {
360 OrderedSocketData::OrderedSocketData(
361 const MockConnect
& connect
,
362 MockRead
* reads
, size_t reads_count
,
363 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) {
367 set_connect_data(connect
);
370 void OrderedSocketData::EndLoop() {
371 // If we've already stopped the loop, don't do it again until we've advanced
372 // to the next sequence_number.
373 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
<< ": EndLoop()";
374 if (loop_stop_stage_
> 0) {
375 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
376 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) >
378 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
379 << ": Clearing stop index";
380 loop_stop_stage_
= 0;
385 // Record the sequence_number at which we stopped the loop.
386 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
387 << ": Posting Quit at read " << read_index();
388 loop_stop_stage_
= sequence_number_
;
391 MockRead
OrderedSocketData::GetNextRead() {
392 weak_factory_
.InvalidateWeakPtrs();
394 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
395 if (next_read
.sequence_number
& MockRead::STOPLOOP
)
397 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) <=
398 sequence_number_
++) {
399 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
400 << ": Read " << read_index();
401 DumpMockReadWrite(next_read
);
402 blocked_
= (next_read
.result
== ERR_IO_PENDING
);
403 return StaticSocketDataProvider::GetNextRead();
405 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
407 MockRead result
= MockRead(ASYNC
, ERR_IO_PENDING
);
408 DumpMockReadWrite(result
);
413 MockWriteResult
OrderedSocketData::OnWrite(const std::string
& data
) {
414 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
415 << ": Write " << write_index();
416 DumpMockReadWrite(PeekWrite());
419 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
420 // should probably fix the weirdness. One example is in SpdyStream,
421 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
422 // SYN_REPLY causes OnResponseReceived() to get called before
423 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
424 base::MessageLoop::current()->PostDelayedTask(
426 base::Bind(&OrderedSocketData::CompleteRead
,
427 weak_factory_
.GetWeakPtr()),
428 base::TimeDelta::FromMilliseconds(100));
430 return StaticSocketDataProvider::OnWrite(data
);
433 void OrderedSocketData::Reset() {
434 NET_TRACE(INFO
, " *** ") << "Stage "
435 << sequence_number_
<< ": Reset()";
436 sequence_number_
= 0;
437 loop_stop_stage_
= 0;
439 weak_factory_
.InvalidateWeakPtrs();
440 StaticSocketDataProvider::Reset();
443 void OrderedSocketData::CompleteRead() {
444 if (socket() && blocked_
) {
445 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
;
446 socket()->OnReadComplete(GetNextRead());
450 OrderedSocketData::~OrderedSocketData() {}
452 DeterministicSocketData::DeterministicSocketData(MockRead
* reads
,
453 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
454 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
458 stopping_sequence_number_(0),
462 VerifyCorrectSequenceNumbers(reads
, reads_count
, writes
, writes_count
);
465 DeterministicSocketData::~DeterministicSocketData() {}
467 void DeterministicSocketData::Run() {
468 DCHECK(!is_running_
);
473 // Continue to consume data until all data has run out, or the stopped_ flag
474 // has been set. Consuming data requires two separate operations -- running
475 // the tasks in the message loop, and explicitly invoking the read/write
476 // callbacks (simulating network I/O). We check our conditions between each,
477 // since they can change in either.
478 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
479 if (counter
% 2 == 0)
480 base::RunLoop().RunUntilIdle();
481 if (counter
% 2 == 1) {
486 // We're done consuming new data, but it is possible there are still some
487 // pending callbacks which we expect to complete before returning.
488 while (delegate_
.get() &&
489 (delegate_
->WritePending() || delegate_
->ReadPending()) &&
492 base::RunLoop().RunUntilIdle();
498 void DeterministicSocketData::RunFor(int steps
) {
503 void DeterministicSocketData::SetStop(int seq
) {
504 DCHECK_LT(sequence_number_
, seq
);
505 stopping_sequence_number_
= seq
;
509 void DeterministicSocketData::StopAfter(int seq
) {
510 SetStop(sequence_number_
+ seq
);
513 MockRead
DeterministicSocketData::GetNextRead() {
514 current_read_
= StaticSocketDataProvider::PeekRead();
516 // Synchronous read while stopped is an error
517 if (stopped() && current_read_
.mode
== SYNCHRONOUS
) {
518 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
519 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
522 // Async read which will be called back in a future step.
523 if (sequence_number_
< current_read_
.sequence_number
) {
524 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
526 MockRead result
= MockRead(SYNCHRONOUS
, ERR_IO_PENDING
);
527 if (current_read_
.mode
== SYNCHRONOUS
) {
528 LOG(ERROR
) << "Unable to perform synchronous read: "
529 << current_read_
.sequence_number
530 << " at stage: " << sequence_number_
;
531 result
= MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
534 DumpMockReadWrite(result
);
538 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
539 << ": Read " << read_index();
541 DumpMockReadWrite(current_read_
);
543 // Increment the sequence number if IO is complete
544 if (current_read_
.mode
== SYNCHRONOUS
)
547 DCHECK_NE(ERR_IO_PENDING
, current_read_
.result
);
548 StaticSocketDataProvider::GetNextRead();
550 return current_read_
;
553 MockWriteResult
DeterministicSocketData::OnWrite(const std::string
& data
) {
554 const MockWrite
& next_write
= StaticSocketDataProvider::PeekWrite();
555 current_write_
= next_write
;
557 // Synchronous write while stopped is an error
558 if (stopped() && next_write
.mode
== SYNCHRONOUS
) {
559 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
560 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
563 // Async write which will be called back in a future step.
564 if (sequence_number_
< next_write
.sequence_number
) {
565 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
567 if (next_write
.mode
== SYNCHRONOUS
) {
568 LOG(ERROR
) << "Unable to perform synchronous write: "
569 << next_write
.sequence_number
<< " at stage: " << sequence_number_
;
570 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
573 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
574 << ": Write " << write_index();
578 DumpMockReadWrite(next_write
);
580 // Move to the next step if I/O is synchronous, since the operation will
581 // complete when this method returns.
582 if (next_write
.mode
== SYNCHRONOUS
)
585 // This is either a sync write for this step, or an async write.
586 return StaticSocketDataProvider::OnWrite(data
);
589 void DeterministicSocketData::Reset() {
590 NET_TRACE(INFO
, " *** ") << "Stage "
591 << sequence_number_
<< ": Reset()";
592 sequence_number_
= 0;
593 StaticSocketDataProvider::Reset();
597 void DeterministicSocketData::InvokeCallbacks() {
598 if (delegate_
.get() && delegate_
->WritePending() &&
599 (current_write().sequence_number
== sequence_number())) {
601 delegate_
->CompleteWrite();
604 if (delegate_
.get() && delegate_
->ReadPending() &&
605 (current_read().sequence_number
== sequence_number())) {
607 delegate_
->CompleteRead();
612 void DeterministicSocketData::NextStep() {
613 // Invariant: Can never move *past* the stopping step.
614 DCHECK_LT(sequence_number_
, stopping_sequence_number_
);
616 if (sequence_number_
== stopping_sequence_number_
)
620 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
621 MockRead
* reads
, size_t reads_count
,
622 MockWrite
* writes
, size_t writes_count
) {
626 while (read
< reads_count
|| write
< writes_count
) {
627 // Check to see that we have a read or write at the expected
629 if (read
< reads_count
&& reads
[read
].sequence_number
== expected
) {
634 if (write
< writes_count
&& writes
[write
].sequence_number
== expected
) {
639 NOTREACHED() << "Missing sequence number: " << expected
;
642 DCHECK_EQ(read
, reads_count
);
643 DCHECK_EQ(write
, writes_count
);
646 MockClientSocketFactory::MockClientSocketFactory() {}
648 MockClientSocketFactory::~MockClientSocketFactory() {}
650 void MockClientSocketFactory::AddSocketDataProvider(
651 SocketDataProvider
* data
) {
652 mock_data_
.Add(data
);
655 void MockClientSocketFactory::AddSSLSocketDataProvider(
656 SSLSocketDataProvider
* data
) {
657 mock_ssl_data_
.Add(data
);
660 void MockClientSocketFactory::ResetNextMockIndexes() {
661 mock_data_
.ResetNextIndex();
662 mock_ssl_data_
.ResetNextIndex();
665 scoped_ptr
<DatagramClientSocket
>
666 MockClientSocketFactory::CreateDatagramClientSocket(
667 DatagramSocket::BindType bind_type
,
668 const RandIntCallback
& rand_int_cb
,
669 net::NetLog
* net_log
,
670 const net::NetLog::Source
& source
) {
671 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
672 scoped_ptr
<MockUDPClientSocket
> socket(
673 new MockUDPClientSocket(data_provider
, net_log
));
674 data_provider
->set_socket(socket
.get());
675 if (bind_type
== DatagramSocket::RANDOM_BIND
)
676 socket
->set_source_port(rand_int_cb
.Run(1025, 65535));
677 return socket
.PassAs
<DatagramClientSocket
>();
680 scoped_ptr
<StreamSocket
> MockClientSocketFactory::CreateTransportClientSocket(
681 const AddressList
& addresses
,
682 net::NetLog
* net_log
,
683 const net::NetLog::Source
& source
) {
684 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
685 scoped_ptr
<MockTCPClientSocket
> socket(
686 new MockTCPClientSocket(addresses
, net_log
, data_provider
));
687 data_provider
->set_socket(socket
.get());
688 return socket
.PassAs
<StreamSocket
>();
691 scoped_ptr
<SSLClientSocket
> MockClientSocketFactory::CreateSSLClientSocket(
692 scoped_ptr
<ClientSocketHandle
> transport_socket
,
693 const HostPortPair
& host_and_port
,
694 const SSLConfig
& ssl_config
,
695 const SSLClientSocketContext
& context
) {
696 return scoped_ptr
<SSLClientSocket
>(
697 new MockSSLClientSocket(transport_socket
.Pass(),
698 host_and_port
, ssl_config
,
699 mock_ssl_data_
.GetNext()));
702 void MockClientSocketFactory::ClearSSLSessionCache() {
705 const char MockClientSocket::kTlsUnique
[] = "MOCK_TLSUNIQ";
707 MockClientSocket::MockClientSocket(const BoundNetLog
& net_log
)
710 weak_factory_(this) {
712 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
713 peer_addr_
= IPEndPoint(ip
, 0);
716 int MockClientSocket::SetReceiveBufferSize(int32 size
) {
720 int MockClientSocket::SetSendBufferSize(int32 size
) {
724 void MockClientSocket::Disconnect() {
728 bool MockClientSocket::IsConnected() const {
732 bool MockClientSocket::IsConnectedAndIdle() const {
736 int MockClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
738 return ERR_SOCKET_NOT_CONNECTED
;
739 *address
= peer_addr_
;
743 int MockClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
745 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
747 *address
= IPEndPoint(ip
, 123);
751 const BoundNetLog
& MockClientSocket::NetLog() const {
755 void MockClientSocket::GetSSLCertRequestInfo(
756 SSLCertRequestInfo
* cert_request_info
) {
759 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece
& label
,
761 const base::StringPiece
& context
,
763 unsigned int outlen
) {
764 memset(out
, 'A', outlen
);
768 int MockClientSocket::GetTLSUniqueChannelBinding(std::string
* out
) {
769 out
->assign(MockClientSocket::kTlsUnique
);
773 ServerBoundCertService
* MockClientSocket::GetServerBoundCertService() const {
778 SSLClientSocket::NextProtoStatus
779 MockClientSocket::GetNextProto(std::string
* proto
, std::string
* server_protos
) {
781 server_protos
->clear();
782 return SSLClientSocket::kNextProtoUnsupported
;
785 scoped_refptr
<X509Certificate
>
786 MockClientSocket::GetUnverifiedServerCertificateChain() const {
791 MockClientSocket::~MockClientSocket() {}
793 void MockClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
795 base::MessageLoop::current()->PostTask(
797 base::Bind(&MockClientSocket::RunCallback
,
798 weak_factory_
.GetWeakPtr(),
803 void MockClientSocket::RunCallback(const net::CompletionCallback
& callback
,
805 if (!callback
.is_null())
806 callback
.Run(result
);
809 MockTCPClientSocket::MockTCPClientSocket(const AddressList
& addresses
,
810 net::NetLog
* net_log
,
811 SocketDataProvider
* data
)
812 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
813 addresses_(addresses
),
816 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
817 need_read_data_(true),
818 peer_closed_connection_(false),
821 was_used_to_convey_data_(false) {
823 peer_addr_
= data
->connect_data().peer_addr
;
827 MockTCPClientSocket::~MockTCPClientSocket() {}
829 int MockTCPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
830 const CompletionCallback
& callback
) {
832 return ERR_UNEXPECTED
;
834 // If the buffer is already in use, a read is already in progress!
835 DCHECK(pending_buf_
== NULL
);
837 // Store our async IO data.
839 pending_buf_len_
= buf_len
;
840 pending_callback_
= callback
;
842 if (need_read_data_
) {
843 read_data_
= data_
->GetNextRead();
844 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
845 // This MockRead is just a marker to instruct us to set
846 // peer_closed_connection_.
847 peer_closed_connection_
= true;
849 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
850 // This MockRead is just a marker to instruct us to set
851 // peer_closed_connection_. Skip it and get the next one.
852 read_data_
= data_
->GetNextRead();
853 peer_closed_connection_
= true;
855 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
856 // to complete the async IO manually later (via OnReadComplete).
857 if (read_data_
.result
== ERR_IO_PENDING
) {
858 // We need to be using async IO in this case.
859 DCHECK(!callback
.is_null());
860 return ERR_IO_PENDING
;
862 need_read_data_
= false;
865 return CompleteRead();
868 int MockTCPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
869 const CompletionCallback
& callback
) {
871 DCHECK_GT(buf_len
, 0);
874 return ERR_UNEXPECTED
;
876 std::string
data(buf
->data(), buf_len
);
877 MockWriteResult write_result
= data_
->OnWrite(data
);
879 was_used_to_convey_data_
= true;
881 if (write_result
.mode
== ASYNC
) {
882 RunCallbackAsync(callback
, write_result
.result
);
883 return ERR_IO_PENDING
;
886 return write_result
.result
;
889 int MockTCPClientSocket::Connect(const CompletionCallback
& callback
) {
893 peer_closed_connection_
= false;
894 if (data_
->connect_data().mode
== ASYNC
) {
895 if (data_
->connect_data().result
== ERR_IO_PENDING
)
896 pending_callback_
= callback
;
898 RunCallbackAsync(callback
, data_
->connect_data().result
);
899 return ERR_IO_PENDING
;
901 return data_
->connect_data().result
;
904 void MockTCPClientSocket::Disconnect() {
905 MockClientSocket::Disconnect();
906 pending_callback_
.Reset();
909 bool MockTCPClientSocket::IsConnected() const {
910 return connected_
&& !peer_closed_connection_
;
913 bool MockTCPClientSocket::IsConnectedAndIdle() const {
914 return IsConnected();
917 int MockTCPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
918 if (addresses_
.empty())
919 return MockClientSocket::GetPeerAddress(address
);
921 *address
= addresses_
[0];
925 bool MockTCPClientSocket::WasEverUsed() const {
926 return was_used_to_convey_data_
;
929 bool MockTCPClientSocket::UsingTCPFastOpen() const {
933 bool MockTCPClientSocket::WasNpnNegotiated() const {
937 bool MockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
941 void MockTCPClientSocket::OnReadComplete(const MockRead
& data
) {
942 // There must be a read pending.
943 DCHECK(pending_buf_
);
944 // You can't complete a read with another ERR_IO_PENDING status code.
945 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
946 // Since we've been waiting for data, need_read_data_ should be true.
947 DCHECK(need_read_data_
);
950 need_read_data_
= false;
952 // The caller is simulating that this IO completes right now. Don't
953 // let CompleteRead() schedule a callback.
954 read_data_
.mode
= SYNCHRONOUS
;
956 CompletionCallback callback
= pending_callback_
;
957 int rv
= CompleteRead();
958 RunCallback(callback
, rv
);
961 void MockTCPClientSocket::OnConnectComplete(const MockConnect
& data
) {
962 CompletionCallback callback
= pending_callback_
;
963 RunCallback(callback
, data
.result
);
966 int MockTCPClientSocket::CompleteRead() {
967 DCHECK(pending_buf_
);
968 DCHECK(pending_buf_len_
> 0);
970 was_used_to_convey_data_
= true;
972 // Save the pending async IO data and reset our |pending_| state.
973 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
974 int buf_len
= pending_buf_len_
;
975 CompletionCallback callback
= pending_callback_
;
977 pending_buf_len_
= 0;
978 pending_callback_
.Reset();
980 int result
= read_data_
.result
;
981 DCHECK(result
!= ERR_IO_PENDING
);
983 if (read_data_
.data
) {
984 if (read_data_
.data_len
- read_offset_
> 0) {
985 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
986 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
987 read_offset_
+= result
;
988 if (read_offset_
== read_data_
.data_len
) {
989 need_read_data_
= true;
997 if (read_data_
.mode
== ASYNC
) {
998 DCHECK(!callback
.is_null());
999 RunCallbackAsync(callback
, result
);
1000 return ERR_IO_PENDING
;
1005 DeterministicSocketHelper::DeterministicSocketHelper(
1006 net::NetLog
* net_log
,
1007 DeterministicSocketData
* data
)
1008 : write_pending_(false),
1013 read_pending_(false),
1015 was_used_to_convey_data_(false),
1016 peer_closed_connection_(false),
1017 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)) {
1020 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1022 void DeterministicSocketHelper::CompleteWrite() {
1023 was_used_to_convey_data_
= true;
1024 write_pending_
= false;
1025 write_callback_
.Run(write_result_
);
1028 int DeterministicSocketHelper::CompleteRead() {
1029 DCHECK_GT(read_buf_len_
, 0);
1030 DCHECK_LE(read_data_
.data_len
, read_buf_len_
);
1033 was_used_to_convey_data_
= true;
1035 if (read_data_
.result
== ERR_IO_PENDING
)
1036 read_data_
= data_
->GetNextRead();
1037 DCHECK_NE(ERR_IO_PENDING
, read_data_
.result
);
1038 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1039 // the callback. Therefore we don't even bother to check it.
1040 int result
= read_data_
.result
;
1042 if (read_data_
.data_len
> 0) {
1043 DCHECK(read_data_
.data
);
1044 result
= std::min(read_buf_len_
, read_data_
.data_len
);
1045 memcpy(read_buf_
->data(), read_data_
.data
, result
);
1048 if (read_pending_
) {
1049 read_pending_
= false;
1050 read_callback_
.Run(result
);
1056 int DeterministicSocketHelper::Write(
1057 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1059 DCHECK_GT(buf_len
, 0);
1061 std::string
data(buf
->data(), buf_len
);
1062 MockWriteResult write_result
= data_
->OnWrite(data
);
1064 if (write_result
.mode
== ASYNC
) {
1065 write_callback_
= callback
;
1066 write_result_
= write_result
.result
;
1067 DCHECK(!write_callback_
.is_null());
1068 write_pending_
= true;
1069 return ERR_IO_PENDING
;
1072 was_used_to_convey_data_
= true;
1073 write_pending_
= false;
1074 return write_result
.result
;
1077 int DeterministicSocketHelper::Read(
1078 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1080 read_data_
= data_
->GetNextRead();
1081 // The buffer should always be big enough to contain all the MockRead data. To
1082 // use small buffers, split the data into multiple MockReads.
1083 DCHECK_LE(read_data_
.data_len
, buf_len
);
1085 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
1086 // This MockRead is just a marker to instruct us to set
1087 // peer_closed_connection_.
1088 peer_closed_connection_
= true;
1090 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
1091 // This MockRead is just a marker to instruct us to set
1092 // peer_closed_connection_. Skip it and get the next one.
1093 read_data_
= data_
->GetNextRead();
1094 peer_closed_connection_
= true;
1098 read_buf_len_
= buf_len
;
1099 read_callback_
= callback
;
1101 if (read_data_
.mode
== ASYNC
|| (read_data_
.result
== ERR_IO_PENDING
)) {
1102 read_pending_
= true;
1103 DCHECK(!read_callback_
.is_null());
1104 return ERR_IO_PENDING
;
1107 was_used_to_convey_data_
= true;
1108 return CompleteRead();
1111 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1112 net::NetLog
* net_log
,
1113 DeterministicSocketData
* data
)
1114 : connected_(false),
1115 helper_(net_log
, data
),
1119 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1121 bool DeterministicMockUDPClientSocket::WritePending() const {
1122 return helper_
.write_pending();
1125 bool DeterministicMockUDPClientSocket::ReadPending() const {
1126 return helper_
.read_pending();
1129 void DeterministicMockUDPClientSocket::CompleteWrite() {
1130 helper_
.CompleteWrite();
1133 int DeterministicMockUDPClientSocket::CompleteRead() {
1134 return helper_
.CompleteRead();
1137 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1141 peer_address_
= address
;
1142 return helper_
.data()->connect_data().result
;
1145 int DeterministicMockUDPClientSocket::Write(
1148 const CompletionCallback
& callback
) {
1150 return ERR_UNEXPECTED
;
1152 return helper_
.Write(buf
, buf_len
, callback
);
1155 int DeterministicMockUDPClientSocket::Read(
1158 const CompletionCallback
& callback
) {
1160 return ERR_UNEXPECTED
;
1162 return helper_
.Read(buf
, buf_len
, callback
);
1165 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1169 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size
) {
1173 void DeterministicMockUDPClientSocket::Close() {
1177 int DeterministicMockUDPClientSocket::GetPeerAddress(
1178 IPEndPoint
* address
) const {
1179 *address
= peer_address_
;
1183 int DeterministicMockUDPClientSocket::GetLocalAddress(
1184 IPEndPoint
* address
) const {
1186 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1188 *address
= IPEndPoint(ip
, source_port_
);
1192 const BoundNetLog
& DeterministicMockUDPClientSocket::NetLog() const {
1193 return helper_
.net_log();
1196 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead
& data
) {}
1198 void DeterministicMockUDPClientSocket::OnConnectComplete(
1199 const MockConnect
& data
) {
1203 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1204 net::NetLog
* net_log
,
1205 DeterministicSocketData
* data
)
1206 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1207 helper_(net_log
, data
) {
1208 peer_addr_
= data
->connect_data().peer_addr
;
1211 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1213 bool DeterministicMockTCPClientSocket::WritePending() const {
1214 return helper_
.write_pending();
1217 bool DeterministicMockTCPClientSocket::ReadPending() const {
1218 return helper_
.read_pending();
1221 void DeterministicMockTCPClientSocket::CompleteWrite() {
1222 helper_
.CompleteWrite();
1225 int DeterministicMockTCPClientSocket::CompleteRead() {
1226 return helper_
.CompleteRead();
1229 int DeterministicMockTCPClientSocket::Write(
1232 const CompletionCallback
& callback
) {
1234 return ERR_UNEXPECTED
;
1236 return helper_
.Write(buf
, buf_len
, callback
);
1239 int DeterministicMockTCPClientSocket::Read(
1242 const CompletionCallback
& callback
) {
1244 return ERR_UNEXPECTED
;
1246 return helper_
.Read(buf
, buf_len
, callback
);
1249 // TODO(erikchen): Support connect sequencing.
1250 int DeterministicMockTCPClientSocket::Connect(
1251 const CompletionCallback
& callback
) {
1255 if (helper_
.data()->connect_data().mode
== ASYNC
) {
1256 RunCallbackAsync(callback
, helper_
.data()->connect_data().result
);
1257 return ERR_IO_PENDING
;
1259 return helper_
.data()->connect_data().result
;
1262 void DeterministicMockTCPClientSocket::Disconnect() {
1263 MockClientSocket::Disconnect();
1266 bool DeterministicMockTCPClientSocket::IsConnected() const {
1267 return connected_
&& !helper_
.peer_closed_connection();
1270 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1271 return IsConnected();
1274 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1275 return helper_
.was_used_to_convey_data();
1278 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1282 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1286 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1290 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead
& data
) {}
1292 void DeterministicMockTCPClientSocket::OnConnectComplete(
1293 const MockConnect
& data
) {}
1296 void MockSSLClientSocket::ConnectCallback(
1297 MockSSLClientSocket
* ssl_client_socket
,
1298 const CompletionCallback
& callback
,
1301 ssl_client_socket
->connected_
= true;
1305 MockSSLClientSocket::MockSSLClientSocket(
1306 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1307 const HostPortPair
& host_port_pair
,
1308 const SSLConfig
& ssl_config
,
1309 SSLSocketDataProvider
* data
)
1311 // Have to use the right BoundNetLog for LoadTimingInfo regression
1313 transport_socket
->socket()->NetLog()),
1314 transport_(transport_socket
.Pass()),
1316 is_npn_state_set_(false),
1317 new_npn_value_(false),
1318 is_protocol_negotiated_set_(false),
1319 protocol_negotiated_(kProtoUnknown
) {
1321 peer_addr_
= data
->connect
.peer_addr
;
1324 MockSSLClientSocket::~MockSSLClientSocket() {
1328 int MockSSLClientSocket::Read(IOBuffer
* buf
, int buf_len
,
1329 const CompletionCallback
& callback
) {
1330 return transport_
->socket()->Read(buf
, buf_len
, callback
);
1333 int MockSSLClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1334 const CompletionCallback
& callback
) {
1335 return transport_
->socket()->Write(buf
, buf_len
, callback
);
1338 int MockSSLClientSocket::Connect(const CompletionCallback
& callback
) {
1339 int rv
= transport_
->socket()->Connect(
1340 base::Bind(&ConnectCallback
, base::Unretained(this), callback
));
1342 if (data_
->connect
.result
== OK
)
1344 if (data_
->connect
.mode
== ASYNC
) {
1345 RunCallbackAsync(callback
, data_
->connect
.result
);
1346 return ERR_IO_PENDING
;
1348 return data_
->connect
.result
;
1353 void MockSSLClientSocket::Disconnect() {
1354 MockClientSocket::Disconnect();
1355 if (transport_
->socket() != NULL
)
1356 transport_
->socket()->Disconnect();
1359 bool MockSSLClientSocket::IsConnected() const {
1360 return transport_
->socket()->IsConnected();
1363 bool MockSSLClientSocket::WasEverUsed() const {
1364 return transport_
->socket()->WasEverUsed();
1367 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1368 return transport_
->socket()->UsingTCPFastOpen();
1371 int MockSSLClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1372 return transport_
->socket()->GetPeerAddress(address
);
1375 bool MockSSLClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1377 ssl_info
->cert
= data_
->cert
;
1378 ssl_info
->client_cert_sent
= data_
->client_cert_sent
;
1379 ssl_info
->channel_id_sent
= data_
->channel_id_sent
;
1383 void MockSSLClientSocket::GetSSLCertRequestInfo(
1384 SSLCertRequestInfo
* cert_request_info
) {
1385 DCHECK(cert_request_info
);
1386 if (data_
->cert_request_info
) {
1387 cert_request_info
->host_and_port
=
1388 data_
->cert_request_info
->host_and_port
;
1389 cert_request_info
->client_certs
= data_
->cert_request_info
->client_certs
;
1391 cert_request_info
->Reset();
1395 SSLClientSocket::NextProtoStatus
MockSSLClientSocket::GetNextProto(
1396 std::string
* proto
, std::string
* server_protos
) {
1397 *proto
= data_
->next_proto
;
1398 *server_protos
= data_
->server_protos
;
1399 return data_
->next_proto_status
;
1402 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated
) {
1403 is_npn_state_set_
= true;
1404 return new_npn_value_
= negotiated
;
1407 bool MockSSLClientSocket::WasNpnNegotiated() const {
1408 if (is_npn_state_set_
)
1409 return new_npn_value_
;
1410 return data_
->was_npn_negotiated
;
1413 NextProto
MockSSLClientSocket::GetNegotiatedProtocol() const {
1414 if (is_protocol_negotiated_set_
)
1415 return protocol_negotiated_
;
1416 return data_
->protocol_negotiated
;
1419 void MockSSLClientSocket::set_protocol_negotiated(
1420 NextProto protocol_negotiated
) {
1421 is_protocol_negotiated_set_
= true;
1422 protocol_negotiated_
= protocol_negotiated
;
1425 bool MockSSLClientSocket::WasChannelIDSent() const {
1426 return data_
->channel_id_sent
;
1429 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent
) {
1430 data_
->channel_id_sent
= channel_id_sent
;
1433 ServerBoundCertService
* MockSSLClientSocket::GetServerBoundCertService() const {
1434 return data_
->server_bound_cert_service
;
1437 void MockSSLClientSocket::OnReadComplete(const MockRead
& data
) {
1441 void MockSSLClientSocket::OnConnectComplete(const MockConnect
& data
) {
1445 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider
* data
,
1446 net::NetLog
* net_log
)
1447 : connected_(false),
1450 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
1451 need_read_data_(true),
1454 pending_buf_len_(0),
1455 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1456 weak_factory_(this) {
1459 peer_addr_
= data
->connect_data().peer_addr
;
1462 MockUDPClientSocket::~MockUDPClientSocket() {}
1464 int MockUDPClientSocket::Read(IOBuffer
* buf
,
1466 const CompletionCallback
& callback
) {
1468 return ERR_UNEXPECTED
;
1470 // If the buffer is already in use, a read is already in progress!
1471 DCHECK(pending_buf_
== NULL
);
1473 // Store our async IO data.
1475 pending_buf_len_
= buf_len
;
1476 pending_callback_
= callback
;
1478 if (need_read_data_
) {
1479 read_data_
= data_
->GetNextRead();
1480 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1481 // to complete the async IO manually later (via OnReadComplete).
1482 if (read_data_
.result
== ERR_IO_PENDING
) {
1483 // We need to be using async IO in this case.
1484 DCHECK(!callback
.is_null());
1485 return ERR_IO_PENDING
;
1487 need_read_data_
= false;
1490 return CompleteRead();
1493 int MockUDPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1494 const CompletionCallback
& callback
) {
1496 DCHECK_GT(buf_len
, 0);
1499 return ERR_UNEXPECTED
;
1501 std::string
data(buf
->data(), buf_len
);
1502 MockWriteResult write_result
= data_
->OnWrite(data
);
1504 if (write_result
.mode
== ASYNC
) {
1505 RunCallbackAsync(callback
, write_result
.result
);
1506 return ERR_IO_PENDING
;
1508 return write_result
.result
;
1511 int MockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1515 int MockUDPClientSocket::SetSendBufferSize(int32 size
) {
1519 void MockUDPClientSocket::Close() {
1523 int MockUDPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1524 *address
= peer_addr_
;
1528 int MockUDPClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
1530 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1532 *address
= IPEndPoint(ip
, source_port_
);
1536 const BoundNetLog
& MockUDPClientSocket::NetLog() const {
1540 int MockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1542 peer_addr_
= address
;
1543 return data_
->connect_data().result
;
1546 void MockUDPClientSocket::OnReadComplete(const MockRead
& data
) {
1547 // There must be a read pending.
1548 DCHECK(pending_buf_
);
1549 // You can't complete a read with another ERR_IO_PENDING status code.
1550 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
1551 // Since we've been waiting for data, need_read_data_ should be true.
1552 DCHECK(need_read_data_
);
1555 need_read_data_
= false;
1557 // The caller is simulating that this IO completes right now. Don't
1558 // let CompleteRead() schedule a callback.
1559 read_data_
.mode
= SYNCHRONOUS
;
1561 net::CompletionCallback callback
= pending_callback_
;
1562 int rv
= CompleteRead();
1563 RunCallback(callback
, rv
);
1566 void MockUDPClientSocket::OnConnectComplete(const MockConnect
& data
) {
1570 int MockUDPClientSocket::CompleteRead() {
1571 DCHECK(pending_buf_
);
1572 DCHECK(pending_buf_len_
> 0);
1574 // Save the pending async IO data and reset our |pending_| state.
1575 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
1576 int buf_len
= pending_buf_len_
;
1577 CompletionCallback callback
= pending_callback_
;
1578 pending_buf_
= NULL
;
1579 pending_buf_len_
= 0;
1580 pending_callback_
.Reset();
1582 int result
= read_data_
.result
;
1583 DCHECK(result
!= ERR_IO_PENDING
);
1585 if (read_data_
.data
) {
1586 if (read_data_
.data_len
- read_offset_
> 0) {
1587 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
1588 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
1589 read_offset_
+= result
;
1590 if (read_offset_
== read_data_
.data_len
) {
1591 need_read_data_
= true;
1599 if (read_data_
.mode
== ASYNC
) {
1600 DCHECK(!callback
.is_null());
1601 RunCallbackAsync(callback
, result
);
1602 return ERR_IO_PENDING
;
1607 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
1609 base::MessageLoop::current()->PostTask(
1611 base::Bind(&MockUDPClientSocket::RunCallback
,
1612 weak_factory_
.GetWeakPtr(),
1617 void MockUDPClientSocket::RunCallback(const CompletionCallback
& callback
,
1619 if (!callback
.is_null())
1620 callback
.Run(result
);
1623 TestSocketRequest::TestSocketRequest(
1624 std::vector
<TestSocketRequest
*>* request_order
, size_t* completion_count
)
1625 : request_order_(request_order
),
1626 completion_count_(completion_count
),
1627 callback_(base::Bind(&TestSocketRequest::OnComplete
,
1628 base::Unretained(this))) {
1629 DCHECK(request_order
);
1630 DCHECK(completion_count
);
1633 TestSocketRequest::~TestSocketRequest() {
1636 void TestSocketRequest::OnComplete(int result
) {
1638 (*completion_count_
)++;
1639 request_order_
->push_back(this);
1643 const int ClientSocketPoolTest::kIndexOutOfBounds
= -1;
1646 const int ClientSocketPoolTest::kRequestNotFound
= -2;
1648 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1649 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1651 int ClientSocketPoolTest::GetOrderOfRequest(size_t index
) const {
1653 if (index
>= requests_
.size())
1654 return kIndexOutOfBounds
;
1656 for (size_t i
= 0; i
< request_order_
.size(); i
++)
1657 if (requests_
[index
] == request_order_
[i
])
1660 return kRequestNotFound
;
1663 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive
) {
1664 ScopedVector
<TestSocketRequest
>::iterator i
;
1665 for (i
= requests_
.begin(); i
!= requests_
.end(); ++i
) {
1666 if ((*i
)->handle()->is_initialized()) {
1667 if (keep_alive
== NO_KEEP_ALIVE
)
1668 (*i
)->handle()->socket()->Disconnect();
1669 (*i
)->handle()->Reset();
1670 base::RunLoop().RunUntilIdle();
1677 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive
) {
1680 released_one
= ReleaseOneConnection(keep_alive
);
1681 } while (released_one
);
1684 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1685 scoped_ptr
<StreamSocket
> socket
,
1686 ClientSocketHandle
* handle
,
1687 const CompletionCallback
& callback
)
1688 : socket_(socket
.Pass()),
1690 user_callback_(callback
) {
1693 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1695 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1696 int rv
= socket_
->Connect(base::Bind(&MockConnectJob::OnConnect
,
1697 base::Unretained(this)));
1699 user_callback_
.Reset();
1705 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1706 const ClientSocketHandle
* handle
) {
1707 if (handle
!= handle_
)
1711 user_callback_
.Reset();
1715 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv
) {
1719 handle_
->SetSocket(socket_
.Pass());
1721 // Needed for socket pool tests that layer other sockets on top of mock
1723 LoadTimingInfo::ConnectTiming connect_timing
;
1724 base::TimeTicks now
= base::TimeTicks::Now();
1725 connect_timing
.dns_start
= now
;
1726 connect_timing
.dns_end
= now
;
1727 connect_timing
.connect_start
= now
;
1728 connect_timing
.connect_end
= now
;
1729 handle_
->set_connect_timing(connect_timing
);
1736 if (!user_callback_
.is_null()) {
1737 CompletionCallback callback
= user_callback_
;
1738 user_callback_
.Reset();
1743 MockTransportClientSocketPool::MockTransportClientSocketPool(
1745 int max_sockets_per_group
,
1746 ClientSocketPoolHistograms
* histograms
,
1747 ClientSocketFactory
* socket_factory
)
1748 : TransportClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1750 client_socket_factory_(socket_factory
),
1751 last_request_priority_(DEFAULT_PRIORITY
),
1756 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1758 int MockTransportClientSocketPool::RequestSocket(
1759 const std::string
& group_name
, const void* socket_params
,
1760 RequestPriority priority
, ClientSocketHandle
* handle
,
1761 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1762 last_request_priority_
= priority
;
1763 scoped_ptr
<StreamSocket
> socket
=
1764 client_socket_factory_
->CreateTransportClientSocket(
1765 AddressList(), net_log
.net_log(), net::NetLog::Source());
1766 MockConnectJob
* job
= new MockConnectJob(socket
.Pass(), handle
, callback
);
1767 job_list_
.push_back(job
);
1768 handle
->set_pool_id(1);
1769 return job
->Connect();
1772 void MockTransportClientSocketPool::CancelRequest(const std::string
& group_name
,
1773 ClientSocketHandle
* handle
) {
1774 std::vector
<MockConnectJob
*>::iterator i
;
1775 for (i
= job_list_
.begin(); i
!= job_list_
.end(); ++i
) {
1776 if ((*i
)->CancelHandle(handle
)) {
1783 void MockTransportClientSocketPool::ReleaseSocket(
1784 const std::string
& group_name
,
1785 scoped_ptr
<StreamSocket
> socket
,
1791 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1793 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1795 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1796 DeterministicSocketData
* data
) {
1797 mock_data_
.Add(data
);
1800 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1801 SSLSocketDataProvider
* data
) {
1802 mock_ssl_data_
.Add(data
);
1805 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1806 mock_data_
.ResetNextIndex();
1807 mock_ssl_data_
.ResetNextIndex();
1810 MockSSLClientSocket
* DeterministicMockClientSocketFactory::
1811 GetMockSSLClientSocket(size_t index
) const {
1812 DCHECK_LT(index
, ssl_client_sockets_
.size());
1813 return ssl_client_sockets_
[index
];
1816 scoped_ptr
<DatagramClientSocket
>
1817 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1818 DatagramSocket::BindType bind_type
,
1819 const RandIntCallback
& rand_int_cb
,
1820 net::NetLog
* net_log
,
1821 const NetLog::Source
& source
) {
1822 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1823 scoped_ptr
<DeterministicMockUDPClientSocket
> socket(
1824 new DeterministicMockUDPClientSocket(net_log
, data_provider
));
1825 data_provider
->set_delegate(socket
->AsWeakPtr());
1826 udp_client_sockets().push_back(socket
.get());
1827 if (bind_type
== DatagramSocket::RANDOM_BIND
)
1828 socket
->set_source_port(rand_int_cb
.Run(1025, 65535));
1829 return socket
.PassAs
<DatagramClientSocket
>();
1832 scoped_ptr
<StreamSocket
>
1833 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1834 const AddressList
& addresses
,
1835 net::NetLog
* net_log
,
1836 const net::NetLog::Source
& source
) {
1837 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1838 scoped_ptr
<DeterministicMockTCPClientSocket
> socket(
1839 new DeterministicMockTCPClientSocket(net_log
, data_provider
));
1840 data_provider
->set_delegate(socket
->AsWeakPtr());
1841 tcp_client_sockets().push_back(socket
.get());
1842 return socket
.PassAs
<StreamSocket
>();
1845 scoped_ptr
<SSLClientSocket
>
1846 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1847 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1848 const HostPortPair
& host_and_port
,
1849 const SSLConfig
& ssl_config
,
1850 const SSLClientSocketContext
& context
) {
1851 scoped_ptr
<MockSSLClientSocket
> socket(
1852 new MockSSLClientSocket(transport_socket
.Pass(),
1853 host_and_port
, ssl_config
,
1854 mock_ssl_data_
.GetNext()));
1855 ssl_client_sockets_
.push_back(socket
.get());
1856 return socket
.PassAs
<SSLClientSocket
>();
1859 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1862 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1864 int max_sockets_per_group
,
1865 ClientSocketPoolHistograms
* histograms
,
1866 TransportClientSocketPool
* transport_pool
)
1867 : SOCKSClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1868 NULL
, transport_pool
, NULL
),
1869 transport_pool_(transport_pool
) {
1872 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1874 int MockSOCKSClientSocketPool::RequestSocket(
1875 const std::string
& group_name
, const void* socket_params
,
1876 RequestPriority priority
, ClientSocketHandle
* handle
,
1877 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1878 return transport_pool_
->RequestSocket(
1879 group_name
, socket_params
, priority
, handle
, callback
, net_log
);
1882 void MockSOCKSClientSocketPool::CancelRequest(
1883 const std::string
& group_name
,
1884 ClientSocketHandle
* handle
) {
1885 return transport_pool_
->CancelRequest(group_name
, handle
);
1888 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string
& group_name
,
1889 scoped_ptr
<StreamSocket
> socket
,
1891 return transport_pool_
->ReleaseSocket(group_name
, socket
.Pass(), id
);
1894 const char kSOCKS5GreetRequest
[] = { 0x05, 0x01, 0x00 };
1895 const int kSOCKS5GreetRequestLength
= arraysize(kSOCKS5GreetRequest
);
1897 const char kSOCKS5GreetResponse
[] = { 0x05, 0x00 };
1898 const int kSOCKS5GreetResponseLength
= arraysize(kSOCKS5GreetResponse
);
1900 const char kSOCKS5OkRequest
[] =
1901 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1902 const int kSOCKS5OkRequestLength
= arraysize(kSOCKS5OkRequest
);
1904 const char kSOCKS5OkResponse
[] =
1905 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1906 const int kSOCKS5OkResponseLength
= arraysize(kSOCKS5OkResponse
);