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 DCHECK(!at_read_eof());
173 return reads_
[read_index_
];
176 const MockWrite
& StaticSocketDataProvider::PeekWrite() const {
177 DCHECK(!at_write_eof());
178 return writes_
[write_index_
];
181 const MockRead
& StaticSocketDataProvider::PeekRead(size_t index
) const {
182 DCHECK_LT(index
, read_count_
);
183 return reads_
[index
];
186 const MockWrite
& StaticSocketDataProvider::PeekWrite(size_t index
) const {
187 DCHECK_LT(index
, write_count_
);
188 return writes_
[index
];
191 MockRead
StaticSocketDataProvider::GetNextRead() {
192 DCHECK(!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 DCHECK(!at_write_eof());
204 // Check that what we are writing matches the expectation.
205 // Then give the mocked return value.
206 MockWrite
* w
= &writes_
[write_index_
++];
207 w
->time_stamp
= base::Time::Now();
208 int result
= w
->result
;
210 // Note - we can simulate a partial write here. If the expected data
211 // is a match, but shorter than the write actually written, that is legal.
213 // Application writes "foobarbaz" (9 bytes)
214 // Expected write was "foo" (3 bytes)
215 // This is a success, and we return 3 to the application.
216 std::string
expected_data(w
->data
, w
->data_len
);
217 EXPECT_GE(data
.length(), expected_data
.length());
218 std::string
actual_data(data
.substr(0, w
->data_len
));
219 EXPECT_EQ(expected_data
, actual_data
);
220 if (expected_data
!= actual_data
)
221 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
223 result
= w
->data_len
;
225 return MockWriteResult(w
->mode
, result
);
228 void StaticSocketDataProvider::Reset() {
233 DynamicSocketDataProvider::DynamicSocketDataProvider()
234 : short_read_limit_(0),
235 allow_unconsumed_reads_(false) {
238 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
240 MockRead
DynamicSocketDataProvider::GetNextRead() {
242 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
243 MockRead result
= reads_
.front();
244 if (short_read_limit_
== 0 || result
.data_len
<= short_read_limit_
) {
247 result
.data_len
= short_read_limit_
;
248 reads_
.front().data
+= result
.data_len
;
249 reads_
.front().data_len
-= result
.data_len
;
254 void DynamicSocketDataProvider::Reset() {
258 void DynamicSocketDataProvider::SimulateRead(const char* data
,
259 const size_t length
) {
260 if (!allow_unconsumed_reads_
) {
261 EXPECT_TRUE(reads_
.empty()) << "Unconsumed read: " << reads_
.front().data
;
263 reads_
.push_back(MockRead(ASYNC
, data
, length
));
266 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode
, int result
)
267 : connect(mode
, result
),
268 next_proto_status(SSLClientSocket::kNextProtoUnsupported
),
269 was_npn_negotiated(false),
270 protocol_negotiated(kProtoUnknown
),
271 client_cert_sent(false),
272 cert_request_info(NULL
),
273 channel_id_sent(false) {
276 SSLSocketDataProvider::~SSLSocketDataProvider() {
279 void SSLSocketDataProvider::SetNextProto(NextProto proto
) {
280 was_npn_negotiated
= true;
281 next_proto_status
= SSLClientSocket::kNextProtoNegotiated
;
282 protocol_negotiated
= proto
;
283 next_proto
= SSLClientSocket::NextProtoToString(proto
);
286 DelayedSocketData::DelayedSocketData(
287 int write_delay
, MockRead
* reads
, size_t reads_count
,
288 MockWrite
* writes
, size_t writes_count
)
289 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
290 write_delay_(write_delay
),
291 read_in_progress_(false),
292 weak_factory_(this) {
293 DCHECK_GE(write_delay_
, 0);
296 DelayedSocketData::DelayedSocketData(
297 const MockConnect
& connect
, int write_delay
, MockRead
* reads
,
298 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
299 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
300 write_delay_(write_delay
),
301 read_in_progress_(false),
302 weak_factory_(this) {
303 DCHECK_GE(write_delay_
, 0);
304 set_connect_data(connect
);
307 DelayedSocketData::~DelayedSocketData() {
310 void DelayedSocketData::ForceNextRead() {
311 DCHECK(read_in_progress_
);
316 MockRead
DelayedSocketData::GetNextRead() {
317 MockRead out
= MockRead(ASYNC
, ERR_IO_PENDING
);
318 if (write_delay_
<= 0)
319 out
= StaticSocketDataProvider::GetNextRead();
320 read_in_progress_
= (out
.result
== ERR_IO_PENDING
);
324 MockWriteResult
DelayedSocketData::OnWrite(const std::string
& data
) {
325 MockWriteResult rv
= StaticSocketDataProvider::OnWrite(data
);
326 // Now that our write has completed, we can allow reads to continue.
327 if (!--write_delay_
&& read_in_progress_
)
328 base::MessageLoop::current()->PostDelayedTask(
330 base::Bind(&DelayedSocketData::CompleteRead
,
331 weak_factory_
.GetWeakPtr()),
332 base::TimeDelta::FromMilliseconds(100));
336 void DelayedSocketData::Reset() {
338 read_in_progress_
= false;
339 weak_factory_
.InvalidateWeakPtrs();
340 StaticSocketDataProvider::Reset();
343 void DelayedSocketData::CompleteRead() {
344 if (socket() && read_in_progress_
)
345 socket()->OnReadComplete(GetNextRead());
348 OrderedSocketData::OrderedSocketData(
349 MockRead
* reads
, size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
350 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
351 sequence_number_(0), loop_stop_stage_(0),
352 blocked_(false), weak_factory_(this) {
355 OrderedSocketData::OrderedSocketData(
356 const MockConnect
& connect
,
357 MockRead
* reads
, size_t reads_count
,
358 MockWrite
* writes
, size_t writes_count
)
359 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
360 sequence_number_(0), loop_stop_stage_(0),
361 blocked_(false), weak_factory_(this) {
362 set_connect_data(connect
);
365 void OrderedSocketData::EndLoop() {
366 // If we've already stopped the loop, don't do it again until we've advanced
367 // to the next sequence_number.
368 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
<< ": EndLoop()";
369 if (loop_stop_stage_
> 0) {
370 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
371 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) >
373 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
374 << ": Clearing stop index";
375 loop_stop_stage_
= 0;
380 // Record the sequence_number at which we stopped the loop.
381 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
382 << ": Posting Quit at read " << read_index();
383 loop_stop_stage_
= sequence_number_
;
386 MockRead
OrderedSocketData::GetNextRead() {
387 weak_factory_
.InvalidateWeakPtrs();
389 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
390 if (next_read
.sequence_number
& MockRead::STOPLOOP
)
392 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) <=
393 sequence_number_
++) {
394 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
395 << ": Read " << read_index();
396 DumpMockReadWrite(next_read
);
397 blocked_
= (next_read
.result
== ERR_IO_PENDING
);
398 return StaticSocketDataProvider::GetNextRead();
400 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
402 MockRead result
= MockRead(ASYNC
, ERR_IO_PENDING
);
403 DumpMockReadWrite(result
);
408 MockWriteResult
OrderedSocketData::OnWrite(const std::string
& data
) {
409 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
410 << ": Write " << write_index();
411 DumpMockReadWrite(PeekWrite());
414 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
415 // should probably fix the weirdness. One example is in SpdyStream,
416 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
417 // SYN_REPLY causes OnResponseReceived() to get called before
418 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
419 base::MessageLoop::current()->PostDelayedTask(
421 base::Bind(&OrderedSocketData::CompleteRead
,
422 weak_factory_
.GetWeakPtr()),
423 base::TimeDelta::FromMilliseconds(100));
425 return StaticSocketDataProvider::OnWrite(data
);
428 void OrderedSocketData::Reset() {
429 NET_TRACE(INFO
, " *** ") << "Stage "
430 << sequence_number_
<< ": Reset()";
431 sequence_number_
= 0;
432 loop_stop_stage_
= 0;
434 weak_factory_
.InvalidateWeakPtrs();
435 StaticSocketDataProvider::Reset();
438 void OrderedSocketData::CompleteRead() {
439 if (socket() && blocked_
) {
440 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
;
441 socket()->OnReadComplete(GetNextRead());
445 OrderedSocketData::~OrderedSocketData() {}
447 DeterministicSocketData::DeterministicSocketData(MockRead
* reads
,
448 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
449 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
453 stopping_sequence_number_(0),
457 VerifyCorrectSequenceNumbers(reads
, reads_count
, writes
, writes_count
);
460 DeterministicSocketData::~DeterministicSocketData() {}
462 void DeterministicSocketData::Run() {
463 DCHECK(!is_running_
);
468 // Continue to consume data until all data has run out, or the stopped_ flag
469 // has been set. Consuming data requires two separate operations -- running
470 // the tasks in the message loop, and explicitly invoking the read/write
471 // callbacks (simulating network I/O). We check our conditions between each,
472 // since they can change in either.
473 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
474 if (counter
% 2 == 0)
475 base::RunLoop().RunUntilIdle();
476 if (counter
% 2 == 1) {
481 // We're done consuming new data, but it is possible there are still some
482 // pending callbacks which we expect to complete before returning.
483 while (delegate_
.get() &&
484 (delegate_
->WritePending() || delegate_
->ReadPending()) &&
487 base::RunLoop().RunUntilIdle();
493 void DeterministicSocketData::RunFor(int steps
) {
498 void DeterministicSocketData::SetStop(int seq
) {
499 DCHECK_LT(sequence_number_
, seq
);
500 stopping_sequence_number_
= seq
;
504 void DeterministicSocketData::StopAfter(int seq
) {
505 SetStop(sequence_number_
+ seq
);
508 MockRead
DeterministicSocketData::GetNextRead() {
509 current_read_
= StaticSocketDataProvider::PeekRead();
511 // Synchronous read while stopped is an error
512 if (stopped() && current_read_
.mode
== SYNCHRONOUS
) {
513 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
514 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
517 // Async read which will be called back in a future step.
518 if (sequence_number_
< current_read_
.sequence_number
) {
519 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
521 MockRead result
= MockRead(SYNCHRONOUS
, ERR_IO_PENDING
);
522 if (current_read_
.mode
== SYNCHRONOUS
) {
523 LOG(ERROR
) << "Unable to perform synchronous read: "
524 << current_read_
.sequence_number
525 << " at stage: " << sequence_number_
;
526 result
= MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
529 DumpMockReadWrite(result
);
533 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
534 << ": Read " << read_index();
536 DumpMockReadWrite(current_read_
);
538 // Increment the sequence number if IO is complete
539 if (current_read_
.mode
== SYNCHRONOUS
)
542 DCHECK_NE(ERR_IO_PENDING
, current_read_
.result
);
543 StaticSocketDataProvider::GetNextRead();
545 return current_read_
;
548 MockWriteResult
DeterministicSocketData::OnWrite(const std::string
& data
) {
549 const MockWrite
& next_write
= StaticSocketDataProvider::PeekWrite();
550 current_write_
= next_write
;
552 // Synchronous write while stopped is an error
553 if (stopped() && next_write
.mode
== SYNCHRONOUS
) {
554 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
555 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
558 // Async write which will be called back in a future step.
559 if (sequence_number_
< next_write
.sequence_number
) {
560 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
562 if (next_write
.mode
== SYNCHRONOUS
) {
563 LOG(ERROR
) << "Unable to perform synchronous write: "
564 << next_write
.sequence_number
<< " at stage: " << sequence_number_
;
565 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
568 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
569 << ": Write " << write_index();
573 DumpMockReadWrite(next_write
);
575 // Move to the next step if I/O is synchronous, since the operation will
576 // complete when this method returns.
577 if (next_write
.mode
== SYNCHRONOUS
)
580 // This is either a sync write for this step, or an async write.
581 return StaticSocketDataProvider::OnWrite(data
);
584 void DeterministicSocketData::Reset() {
585 NET_TRACE(INFO
, " *** ") << "Stage "
586 << sequence_number_
<< ": Reset()";
587 sequence_number_
= 0;
588 StaticSocketDataProvider::Reset();
592 void DeterministicSocketData::InvokeCallbacks() {
593 if (delegate_
.get() && delegate_
->WritePending() &&
594 (current_write().sequence_number
== sequence_number())) {
596 delegate_
->CompleteWrite();
599 if (delegate_
.get() && delegate_
->ReadPending() &&
600 (current_read().sequence_number
== sequence_number())) {
602 delegate_
->CompleteRead();
607 void DeterministicSocketData::NextStep() {
608 // Invariant: Can never move *past* the stopping step.
609 DCHECK_LT(sequence_number_
, stopping_sequence_number_
);
611 if (sequence_number_
== stopping_sequence_number_
)
615 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
616 MockRead
* reads
, size_t reads_count
,
617 MockWrite
* writes
, size_t writes_count
) {
621 while (read
< reads_count
|| write
< writes_count
) {
622 // Check to see that we have a read or write at the expected
624 if (read
< reads_count
&& reads
[read
].sequence_number
== expected
) {
629 if (write
< writes_count
&& writes
[write
].sequence_number
== expected
) {
634 NOTREACHED() << "Missing sequence number: " << expected
;
637 DCHECK_EQ(read
, reads_count
);
638 DCHECK_EQ(write
, writes_count
);
641 MockClientSocketFactory::MockClientSocketFactory() {}
643 MockClientSocketFactory::~MockClientSocketFactory() {}
645 void MockClientSocketFactory::AddSocketDataProvider(
646 SocketDataProvider
* data
) {
647 mock_data_
.Add(data
);
650 void MockClientSocketFactory::AddSSLSocketDataProvider(
651 SSLSocketDataProvider
* data
) {
652 mock_ssl_data_
.Add(data
);
655 void MockClientSocketFactory::ResetNextMockIndexes() {
656 mock_data_
.ResetNextIndex();
657 mock_ssl_data_
.ResetNextIndex();
660 scoped_ptr
<DatagramClientSocket
>
661 MockClientSocketFactory::CreateDatagramClientSocket(
662 DatagramSocket::BindType bind_type
,
663 const RandIntCallback
& rand_int_cb
,
664 net::NetLog
* net_log
,
665 const net::NetLog::Source
& source
) {
666 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
667 scoped_ptr
<MockUDPClientSocket
> socket(
668 new MockUDPClientSocket(data_provider
, net_log
));
669 data_provider
->set_socket(socket
.get());
670 return socket
.PassAs
<DatagramClientSocket
>();
673 scoped_ptr
<StreamSocket
> MockClientSocketFactory::CreateTransportClientSocket(
674 const AddressList
& addresses
,
675 net::NetLog
* net_log
,
676 const net::NetLog::Source
& source
) {
677 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
678 scoped_ptr
<MockTCPClientSocket
> socket(
679 new MockTCPClientSocket(addresses
, net_log
, data_provider
));
680 data_provider
->set_socket(socket
.get());
681 return socket
.PassAs
<StreamSocket
>();
684 scoped_ptr
<SSLClientSocket
> MockClientSocketFactory::CreateSSLClientSocket(
685 scoped_ptr
<ClientSocketHandle
> transport_socket
,
686 const HostPortPair
& host_and_port
,
687 const SSLConfig
& ssl_config
,
688 const SSLClientSocketContext
& context
) {
689 return scoped_ptr
<SSLClientSocket
>(
690 new MockSSLClientSocket(transport_socket
.Pass(),
691 host_and_port
, ssl_config
,
692 mock_ssl_data_
.GetNext()));
695 void MockClientSocketFactory::ClearSSLSessionCache() {
698 const char MockClientSocket::kTlsUnique
[] = "MOCK_TLSUNIQ";
700 MockClientSocket::MockClientSocket(const BoundNetLog
& net_log
)
703 weak_factory_(this) {
705 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
706 peer_addr_
= IPEndPoint(ip
, 0);
709 bool MockClientSocket::SetReceiveBufferSize(int32 size
) {
713 bool MockClientSocket::SetSendBufferSize(int32 size
) {
717 void MockClientSocket::Disconnect() {
721 bool MockClientSocket::IsConnected() const {
725 bool MockClientSocket::IsConnectedAndIdle() const {
729 int MockClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
731 return ERR_SOCKET_NOT_CONNECTED
;
732 *address
= peer_addr_
;
736 int MockClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
738 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
740 *address
= IPEndPoint(ip
, 123);
744 const BoundNetLog
& MockClientSocket::NetLog() const {
748 void MockClientSocket::GetSSLCertRequestInfo(
749 SSLCertRequestInfo
* cert_request_info
) {
752 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece
& label
,
754 const base::StringPiece
& context
,
756 unsigned int outlen
) {
757 memset(out
, 'A', outlen
);
761 int MockClientSocket::GetTLSUniqueChannelBinding(std::string
* out
) {
762 out
->assign(MockClientSocket::kTlsUnique
);
766 ServerBoundCertService
* MockClientSocket::GetServerBoundCertService() const {
771 SSLClientSocket::NextProtoStatus
772 MockClientSocket::GetNextProto(std::string
* proto
, std::string
* server_protos
) {
774 server_protos
->clear();
775 return SSLClientSocket::kNextProtoUnsupported
;
778 MockClientSocket::~MockClientSocket() {}
780 void MockClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
782 base::MessageLoop::current()->PostTask(
784 base::Bind(&MockClientSocket::RunCallback
,
785 weak_factory_
.GetWeakPtr(),
790 void MockClientSocket::RunCallback(const net::CompletionCallback
& callback
,
792 if (!callback
.is_null())
793 callback
.Run(result
);
796 MockTCPClientSocket::MockTCPClientSocket(const AddressList
& addresses
,
797 net::NetLog
* net_log
,
798 SocketDataProvider
* data
)
799 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
800 addresses_(addresses
),
803 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
804 need_read_data_(true),
805 peer_closed_connection_(false),
808 was_used_to_convey_data_(false) {
810 peer_addr_
= data
->connect_data().peer_addr
;
814 MockTCPClientSocket::~MockTCPClientSocket() {}
816 int MockTCPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
817 const CompletionCallback
& callback
) {
819 return ERR_UNEXPECTED
;
821 // If the buffer is already in use, a read is already in progress!
822 DCHECK(pending_buf_
== NULL
);
824 // Store our async IO data.
826 pending_buf_len_
= buf_len
;
827 pending_callback_
= callback
;
829 if (need_read_data_
) {
830 read_data_
= data_
->GetNextRead();
831 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
832 // This MockRead is just a marker to instruct us to set
833 // peer_closed_connection_.
834 peer_closed_connection_
= true;
836 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
837 // This MockRead is just a marker to instruct us to set
838 // peer_closed_connection_. Skip it and get the next one.
839 read_data_
= data_
->GetNextRead();
840 peer_closed_connection_
= true;
842 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
843 // to complete the async IO manually later (via OnReadComplete).
844 if (read_data_
.result
== ERR_IO_PENDING
) {
845 // We need to be using async IO in this case.
846 DCHECK(!callback
.is_null());
847 return ERR_IO_PENDING
;
849 need_read_data_
= false;
852 return CompleteRead();
855 int MockTCPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
856 const CompletionCallback
& callback
) {
858 DCHECK_GT(buf_len
, 0);
861 return ERR_UNEXPECTED
;
863 std::string
data(buf
->data(), buf_len
);
864 MockWriteResult write_result
= data_
->OnWrite(data
);
866 was_used_to_convey_data_
= true;
868 if (write_result
.mode
== ASYNC
) {
869 RunCallbackAsync(callback
, write_result
.result
);
870 return ERR_IO_PENDING
;
873 return write_result
.result
;
876 int MockTCPClientSocket::Connect(const CompletionCallback
& callback
) {
880 peer_closed_connection_
= false;
881 if (data_
->connect_data().mode
== ASYNC
) {
882 if (data_
->connect_data().result
== ERR_IO_PENDING
)
883 pending_callback_
= callback
;
885 RunCallbackAsync(callback
, data_
->connect_data().result
);
886 return ERR_IO_PENDING
;
888 return data_
->connect_data().result
;
891 void MockTCPClientSocket::Disconnect() {
892 MockClientSocket::Disconnect();
893 pending_callback_
.Reset();
896 bool MockTCPClientSocket::IsConnected() const {
897 return connected_
&& !peer_closed_connection_
;
900 bool MockTCPClientSocket::IsConnectedAndIdle() const {
901 return IsConnected();
904 int MockTCPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
905 if (addresses_
.empty())
906 return MockClientSocket::GetPeerAddress(address
);
908 *address
= addresses_
[0];
912 bool MockTCPClientSocket::WasEverUsed() const {
913 return was_used_to_convey_data_
;
916 bool MockTCPClientSocket::UsingTCPFastOpen() const {
920 bool MockTCPClientSocket::WasNpnNegotiated() const {
924 bool MockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
928 void MockTCPClientSocket::OnReadComplete(const MockRead
& data
) {
929 // There must be a read pending.
930 DCHECK(pending_buf_
);
931 // You can't complete a read with another ERR_IO_PENDING status code.
932 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
933 // Since we've been waiting for data, need_read_data_ should be true.
934 DCHECK(need_read_data_
);
937 need_read_data_
= false;
939 // The caller is simulating that this IO completes right now. Don't
940 // let CompleteRead() schedule a callback.
941 read_data_
.mode
= SYNCHRONOUS
;
943 CompletionCallback callback
= pending_callback_
;
944 int rv
= CompleteRead();
945 RunCallback(callback
, rv
);
948 void MockTCPClientSocket::OnConnectComplete(const MockConnect
& data
) {
949 CompletionCallback callback
= pending_callback_
;
950 RunCallback(callback
, data
.result
);
953 int MockTCPClientSocket::CompleteRead() {
954 DCHECK(pending_buf_
);
955 DCHECK(pending_buf_len_
> 0);
957 was_used_to_convey_data_
= true;
959 // Save the pending async IO data and reset our |pending_| state.
960 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
961 int buf_len
= pending_buf_len_
;
962 CompletionCallback callback
= pending_callback_
;
964 pending_buf_len_
= 0;
965 pending_callback_
.Reset();
967 int result
= read_data_
.result
;
968 DCHECK(result
!= ERR_IO_PENDING
);
970 if (read_data_
.data
) {
971 if (read_data_
.data_len
- read_offset_
> 0) {
972 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
973 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
974 read_offset_
+= result
;
975 if (read_offset_
== read_data_
.data_len
) {
976 need_read_data_
= true;
984 if (read_data_
.mode
== ASYNC
) {
985 DCHECK(!callback
.is_null());
986 RunCallbackAsync(callback
, result
);
987 return ERR_IO_PENDING
;
992 DeterministicSocketHelper::DeterministicSocketHelper(
993 net::NetLog
* net_log
,
994 DeterministicSocketData
* data
)
995 : write_pending_(false),
1000 read_pending_(false),
1002 was_used_to_convey_data_(false),
1003 peer_closed_connection_(false),
1004 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)) {
1007 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1009 void DeterministicSocketHelper::CompleteWrite() {
1010 was_used_to_convey_data_
= true;
1011 write_pending_
= false;
1012 write_callback_
.Run(write_result_
);
1015 int DeterministicSocketHelper::CompleteRead() {
1016 DCHECK_GT(read_buf_len_
, 0);
1017 DCHECK_LE(read_data_
.data_len
, read_buf_len_
);
1020 was_used_to_convey_data_
= true;
1022 if (read_data_
.result
== ERR_IO_PENDING
)
1023 read_data_
= data_
->GetNextRead();
1024 DCHECK_NE(ERR_IO_PENDING
, read_data_
.result
);
1025 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1026 // the callback. Therefore we don't even bother to check it.
1027 int result
= read_data_
.result
;
1029 if (read_data_
.data_len
> 0) {
1030 DCHECK(read_data_
.data
);
1031 result
= std::min(read_buf_len_
, read_data_
.data_len
);
1032 memcpy(read_buf_
->data(), read_data_
.data
, result
);
1035 if (read_pending_
) {
1036 read_pending_
= false;
1037 read_callback_
.Run(result
);
1043 int DeterministicSocketHelper::Write(
1044 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1046 DCHECK_GT(buf_len
, 0);
1048 std::string
data(buf
->data(), buf_len
);
1049 MockWriteResult write_result
= data_
->OnWrite(data
);
1051 if (write_result
.mode
== ASYNC
) {
1052 write_callback_
= callback
;
1053 write_result_
= write_result
.result
;
1054 DCHECK(!write_callback_
.is_null());
1055 write_pending_
= true;
1056 return ERR_IO_PENDING
;
1059 was_used_to_convey_data_
= true;
1060 write_pending_
= false;
1061 return write_result
.result
;
1064 int DeterministicSocketHelper::Read(
1065 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1067 read_data_
= data_
->GetNextRead();
1068 // The buffer should always be big enough to contain all the MockRead data. To
1069 // use small buffers, split the data into multiple MockReads.
1070 DCHECK_LE(read_data_
.data_len
, buf_len
);
1072 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
1073 // This MockRead is just a marker to instruct us to set
1074 // peer_closed_connection_.
1075 peer_closed_connection_
= true;
1077 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
1078 // This MockRead is just a marker to instruct us to set
1079 // peer_closed_connection_. Skip it and get the next one.
1080 read_data_
= data_
->GetNextRead();
1081 peer_closed_connection_
= true;
1085 read_buf_len_
= buf_len
;
1086 read_callback_
= callback
;
1088 if (read_data_
.mode
== ASYNC
|| (read_data_
.result
== ERR_IO_PENDING
)) {
1089 read_pending_
= true;
1090 DCHECK(!read_callback_
.is_null());
1091 return ERR_IO_PENDING
;
1094 was_used_to_convey_data_
= true;
1095 return CompleteRead();
1098 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1099 net::NetLog
* net_log
,
1100 DeterministicSocketData
* data
)
1101 : connected_(false),
1102 helper_(net_log
, data
) {
1105 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1107 bool DeterministicMockUDPClientSocket::WritePending() const {
1108 return helper_
.write_pending();
1111 bool DeterministicMockUDPClientSocket::ReadPending() const {
1112 return helper_
.read_pending();
1115 void DeterministicMockUDPClientSocket::CompleteWrite() {
1116 helper_
.CompleteWrite();
1119 int DeterministicMockUDPClientSocket::CompleteRead() {
1120 return helper_
.CompleteRead();
1123 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1127 peer_address_
= address
;
1128 return helper_
.data()->connect_data().result
;
1131 int DeterministicMockUDPClientSocket::Write(
1134 const CompletionCallback
& callback
) {
1136 return ERR_UNEXPECTED
;
1138 return helper_
.Write(buf
, buf_len
, callback
);
1141 int DeterministicMockUDPClientSocket::Read(
1144 const CompletionCallback
& callback
) {
1146 return ERR_UNEXPECTED
;
1148 return helper_
.Read(buf
, buf_len
, callback
);
1151 bool DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1155 bool DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size
) {
1159 void DeterministicMockUDPClientSocket::Close() {
1163 int DeterministicMockUDPClientSocket::GetPeerAddress(
1164 IPEndPoint
* address
) const {
1165 *address
= peer_address_
;
1169 int DeterministicMockUDPClientSocket::GetLocalAddress(
1170 IPEndPoint
* address
) const {
1172 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1174 *address
= IPEndPoint(ip
, 123);
1178 const BoundNetLog
& DeterministicMockUDPClientSocket::NetLog() const {
1179 return helper_
.net_log();
1182 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead
& data
) {}
1184 void DeterministicMockUDPClientSocket::OnConnectComplete(
1185 const MockConnect
& data
) {
1189 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1190 net::NetLog
* net_log
,
1191 DeterministicSocketData
* data
)
1192 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1193 helper_(net_log
, data
) {
1194 peer_addr_
= data
->connect_data().peer_addr
;
1197 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1199 bool DeterministicMockTCPClientSocket::WritePending() const {
1200 return helper_
.write_pending();
1203 bool DeterministicMockTCPClientSocket::ReadPending() const {
1204 return helper_
.read_pending();
1207 void DeterministicMockTCPClientSocket::CompleteWrite() {
1208 helper_
.CompleteWrite();
1211 int DeterministicMockTCPClientSocket::CompleteRead() {
1212 return helper_
.CompleteRead();
1215 int DeterministicMockTCPClientSocket::Write(
1218 const CompletionCallback
& callback
) {
1220 return ERR_UNEXPECTED
;
1222 return helper_
.Write(buf
, buf_len
, callback
);
1225 int DeterministicMockTCPClientSocket::Read(
1228 const CompletionCallback
& callback
) {
1230 return ERR_UNEXPECTED
;
1232 return helper_
.Read(buf
, buf_len
, callback
);
1235 // TODO(erikchen): Support connect sequencing.
1236 int DeterministicMockTCPClientSocket::Connect(
1237 const CompletionCallback
& callback
) {
1241 if (helper_
.data()->connect_data().mode
== ASYNC
) {
1242 RunCallbackAsync(callback
, helper_
.data()->connect_data().result
);
1243 return ERR_IO_PENDING
;
1245 return helper_
.data()->connect_data().result
;
1248 void DeterministicMockTCPClientSocket::Disconnect() {
1249 MockClientSocket::Disconnect();
1252 bool DeterministicMockTCPClientSocket::IsConnected() const {
1253 return connected_
&& !helper_
.peer_closed_connection();
1256 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1257 return IsConnected();
1260 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1261 return helper_
.was_used_to_convey_data();
1264 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1268 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1272 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1276 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead
& data
) {}
1278 void DeterministicMockTCPClientSocket::OnConnectComplete(
1279 const MockConnect
& data
) {}
1282 void MockSSLClientSocket::ConnectCallback(
1283 MockSSLClientSocket
* ssl_client_socket
,
1284 const CompletionCallback
& callback
,
1287 ssl_client_socket
->connected_
= true;
1291 MockSSLClientSocket::MockSSLClientSocket(
1292 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1293 const HostPortPair
& host_port_pair
,
1294 const SSLConfig
& ssl_config
,
1295 SSLSocketDataProvider
* data
)
1297 // Have to use the right BoundNetLog for LoadTimingInfo regression
1299 transport_socket
->socket()->NetLog()),
1300 transport_(transport_socket
.Pass()),
1302 is_npn_state_set_(false),
1303 new_npn_value_(false),
1304 is_protocol_negotiated_set_(false),
1305 protocol_negotiated_(kProtoUnknown
) {
1307 peer_addr_
= data
->connect
.peer_addr
;
1310 MockSSLClientSocket::~MockSSLClientSocket() {
1314 int MockSSLClientSocket::Read(IOBuffer
* buf
, int buf_len
,
1315 const CompletionCallback
& callback
) {
1316 return transport_
->socket()->Read(buf
, buf_len
, callback
);
1319 int MockSSLClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1320 const CompletionCallback
& callback
) {
1321 return transport_
->socket()->Write(buf
, buf_len
, callback
);
1324 int MockSSLClientSocket::Connect(const CompletionCallback
& callback
) {
1325 int rv
= transport_
->socket()->Connect(
1326 base::Bind(&ConnectCallback
, base::Unretained(this), callback
));
1328 if (data_
->connect
.result
== OK
)
1330 if (data_
->connect
.mode
== ASYNC
) {
1331 RunCallbackAsync(callback
, data_
->connect
.result
);
1332 return ERR_IO_PENDING
;
1334 return data_
->connect
.result
;
1339 void MockSSLClientSocket::Disconnect() {
1340 MockClientSocket::Disconnect();
1341 if (transport_
->socket() != NULL
)
1342 transport_
->socket()->Disconnect();
1345 bool MockSSLClientSocket::IsConnected() const {
1346 return transport_
->socket()->IsConnected();
1349 bool MockSSLClientSocket::WasEverUsed() const {
1350 return transport_
->socket()->WasEverUsed();
1353 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1354 return transport_
->socket()->UsingTCPFastOpen();
1357 int MockSSLClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1358 return transport_
->socket()->GetPeerAddress(address
);
1361 bool MockSSLClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1363 ssl_info
->cert
= data_
->cert
;
1364 ssl_info
->client_cert_sent
= data_
->client_cert_sent
;
1365 ssl_info
->channel_id_sent
= data_
->channel_id_sent
;
1369 void MockSSLClientSocket::GetSSLCertRequestInfo(
1370 SSLCertRequestInfo
* cert_request_info
) {
1371 DCHECK(cert_request_info
);
1372 if (data_
->cert_request_info
) {
1373 cert_request_info
->host_and_port
=
1374 data_
->cert_request_info
->host_and_port
;
1375 cert_request_info
->client_certs
= data_
->cert_request_info
->client_certs
;
1377 cert_request_info
->Reset();
1381 SSLClientSocket::NextProtoStatus
MockSSLClientSocket::GetNextProto(
1382 std::string
* proto
, std::string
* server_protos
) {
1383 *proto
= data_
->next_proto
;
1384 *server_protos
= data_
->server_protos
;
1385 return data_
->next_proto_status
;
1388 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated
) {
1389 is_npn_state_set_
= true;
1390 return new_npn_value_
= negotiated
;
1393 bool MockSSLClientSocket::WasNpnNegotiated() const {
1394 if (is_npn_state_set_
)
1395 return new_npn_value_
;
1396 return data_
->was_npn_negotiated
;
1399 NextProto
MockSSLClientSocket::GetNegotiatedProtocol() const {
1400 if (is_protocol_negotiated_set_
)
1401 return protocol_negotiated_
;
1402 return data_
->protocol_negotiated
;
1405 void MockSSLClientSocket::set_protocol_negotiated(
1406 NextProto protocol_negotiated
) {
1407 is_protocol_negotiated_set_
= true;
1408 protocol_negotiated_
= protocol_negotiated
;
1411 bool MockSSLClientSocket::WasChannelIDSent() const {
1412 return data_
->channel_id_sent
;
1415 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent
) {
1416 data_
->channel_id_sent
= channel_id_sent
;
1419 ServerBoundCertService
* MockSSLClientSocket::GetServerBoundCertService() const {
1420 return data_
->server_bound_cert_service
;
1423 void MockSSLClientSocket::OnReadComplete(const MockRead
& data
) {
1427 void MockSSLClientSocket::OnConnectComplete(const MockConnect
& data
) {
1431 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider
* data
,
1432 net::NetLog
* net_log
)
1433 : connected_(false),
1436 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
1437 need_read_data_(true),
1439 pending_buf_len_(0),
1440 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1441 weak_factory_(this) {
1444 peer_addr_
= data
->connect_data().peer_addr
;
1447 MockUDPClientSocket::~MockUDPClientSocket() {}
1449 int MockUDPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
1450 const CompletionCallback
& callback
) {
1452 return ERR_UNEXPECTED
;
1454 // If the buffer is already in use, a read is already in progress!
1455 DCHECK(pending_buf_
== NULL
);
1457 // Store our async IO data.
1459 pending_buf_len_
= buf_len
;
1460 pending_callback_
= callback
;
1462 if (need_read_data_
) {
1463 read_data_
= data_
->GetNextRead();
1464 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1465 // to complete the async IO manually later (via OnReadComplete).
1466 if (read_data_
.result
== ERR_IO_PENDING
) {
1467 // We need to be using async IO in this case.
1468 DCHECK(!callback
.is_null());
1469 return ERR_IO_PENDING
;
1471 need_read_data_
= false;
1474 return CompleteRead();
1477 int MockUDPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1478 const CompletionCallback
& callback
) {
1480 DCHECK_GT(buf_len
, 0);
1483 return ERR_UNEXPECTED
;
1485 std::string
data(buf
->data(), buf_len
);
1486 MockWriteResult write_result
= data_
->OnWrite(data
);
1488 if (write_result
.mode
== ASYNC
) {
1489 RunCallbackAsync(callback
, write_result
.result
);
1490 return ERR_IO_PENDING
;
1492 return write_result
.result
;
1495 bool MockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1499 bool MockUDPClientSocket::SetSendBufferSize(int32 size
) {
1503 void MockUDPClientSocket::Close() {
1507 int MockUDPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1508 *address
= peer_addr_
;
1512 int MockUDPClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
1514 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
1516 *address
= IPEndPoint(ip
, 123);
1520 const BoundNetLog
& MockUDPClientSocket::NetLog() const {
1524 int MockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1526 peer_addr_
= address
;
1530 void MockUDPClientSocket::OnReadComplete(const MockRead
& data
) {
1531 // There must be a read pending.
1532 DCHECK(pending_buf_
);
1533 // You can't complete a read with another ERR_IO_PENDING status code.
1534 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
1535 // Since we've been waiting for data, need_read_data_ should be true.
1536 DCHECK(need_read_data_
);
1539 need_read_data_
= false;
1541 // The caller is simulating that this IO completes right now. Don't
1542 // let CompleteRead() schedule a callback.
1543 read_data_
.mode
= SYNCHRONOUS
;
1545 net::CompletionCallback callback
= pending_callback_
;
1546 int rv
= CompleteRead();
1547 RunCallback(callback
, rv
);
1550 void MockUDPClientSocket::OnConnectComplete(const MockConnect
& data
) {
1554 int MockUDPClientSocket::CompleteRead() {
1555 DCHECK(pending_buf_
);
1556 DCHECK(pending_buf_len_
> 0);
1558 // Save the pending async IO data and reset our |pending_| state.
1559 scoped_refptr
<IOBuffer
> buf
= pending_buf_
;
1560 int buf_len
= pending_buf_len_
;
1561 CompletionCallback callback
= pending_callback_
;
1562 pending_buf_
= NULL
;
1563 pending_buf_len_
= 0;
1564 pending_callback_
.Reset();
1566 int result
= read_data_
.result
;
1567 DCHECK(result
!= ERR_IO_PENDING
);
1569 if (read_data_
.data
) {
1570 if (read_data_
.data_len
- read_offset_
> 0) {
1571 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
1572 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
1573 read_offset_
+= result
;
1574 if (read_offset_
== read_data_
.data_len
) {
1575 need_read_data_
= true;
1583 if (read_data_
.mode
== ASYNC
) {
1584 DCHECK(!callback
.is_null());
1585 RunCallbackAsync(callback
, result
);
1586 return ERR_IO_PENDING
;
1591 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
1593 base::MessageLoop::current()->PostTask(
1595 base::Bind(&MockUDPClientSocket::RunCallback
,
1596 weak_factory_
.GetWeakPtr(),
1601 void MockUDPClientSocket::RunCallback(const CompletionCallback
& callback
,
1603 if (!callback
.is_null())
1604 callback
.Run(result
);
1607 TestSocketRequest::TestSocketRequest(
1608 std::vector
<TestSocketRequest
*>* request_order
, size_t* completion_count
)
1609 : request_order_(request_order
),
1610 completion_count_(completion_count
),
1611 callback_(base::Bind(&TestSocketRequest::OnComplete
,
1612 base::Unretained(this))) {
1613 DCHECK(request_order
);
1614 DCHECK(completion_count
);
1617 TestSocketRequest::~TestSocketRequest() {
1620 void TestSocketRequest::OnComplete(int result
) {
1622 (*completion_count_
)++;
1623 request_order_
->push_back(this);
1627 const int ClientSocketPoolTest::kIndexOutOfBounds
= -1;
1630 const int ClientSocketPoolTest::kRequestNotFound
= -2;
1632 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1633 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1635 int ClientSocketPoolTest::GetOrderOfRequest(size_t index
) const {
1637 if (index
>= requests_
.size())
1638 return kIndexOutOfBounds
;
1640 for (size_t i
= 0; i
< request_order_
.size(); i
++)
1641 if (requests_
[index
] == request_order_
[i
])
1644 return kRequestNotFound
;
1647 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive
) {
1648 ScopedVector
<TestSocketRequest
>::iterator i
;
1649 for (i
= requests_
.begin(); i
!= requests_
.end(); ++i
) {
1650 if ((*i
)->handle()->is_initialized()) {
1651 if (keep_alive
== NO_KEEP_ALIVE
)
1652 (*i
)->handle()->socket()->Disconnect();
1653 (*i
)->handle()->Reset();
1654 base::RunLoop().RunUntilIdle();
1661 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive
) {
1664 released_one
= ReleaseOneConnection(keep_alive
);
1665 } while (released_one
);
1668 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1669 scoped_ptr
<StreamSocket
> socket
,
1670 ClientSocketHandle
* handle
,
1671 const CompletionCallback
& callback
)
1672 : socket_(socket
.Pass()),
1674 user_callback_(callback
) {
1677 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1679 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1680 int rv
= socket_
->Connect(base::Bind(&MockConnectJob::OnConnect
,
1681 base::Unretained(this)));
1683 user_callback_
.Reset();
1689 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1690 const ClientSocketHandle
* handle
) {
1691 if (handle
!= handle_
)
1695 user_callback_
.Reset();
1699 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv
) {
1703 handle_
->SetSocket(socket_
.Pass());
1705 // Needed for socket pool tests that layer other sockets on top of mock
1707 LoadTimingInfo::ConnectTiming connect_timing
;
1708 base::TimeTicks now
= base::TimeTicks::Now();
1709 connect_timing
.dns_start
= now
;
1710 connect_timing
.dns_end
= now
;
1711 connect_timing
.connect_start
= now
;
1712 connect_timing
.connect_end
= now
;
1713 handle_
->set_connect_timing(connect_timing
);
1720 if (!user_callback_
.is_null()) {
1721 CompletionCallback callback
= user_callback_
;
1722 user_callback_
.Reset();
1727 MockTransportClientSocketPool::MockTransportClientSocketPool(
1729 int max_sockets_per_group
,
1730 ClientSocketPoolHistograms
* histograms
,
1731 ClientSocketFactory
* socket_factory
)
1732 : TransportClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1734 client_socket_factory_(socket_factory
),
1735 last_request_priority_(DEFAULT_PRIORITY
),
1740 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1742 int MockTransportClientSocketPool::RequestSocket(
1743 const std::string
& group_name
, const void* socket_params
,
1744 RequestPriority priority
, ClientSocketHandle
* handle
,
1745 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1746 last_request_priority_
= priority
;
1747 scoped_ptr
<StreamSocket
> socket
=
1748 client_socket_factory_
->CreateTransportClientSocket(
1749 AddressList(), net_log
.net_log(), net::NetLog::Source());
1750 MockConnectJob
* job
= new MockConnectJob(socket
.Pass(), handle
, callback
);
1751 job_list_
.push_back(job
);
1752 handle
->set_pool_id(1);
1753 return job
->Connect();
1756 void MockTransportClientSocketPool::CancelRequest(const std::string
& group_name
,
1757 ClientSocketHandle
* handle
) {
1758 std::vector
<MockConnectJob
*>::iterator i
;
1759 for (i
= job_list_
.begin(); i
!= job_list_
.end(); ++i
) {
1760 if ((*i
)->CancelHandle(handle
)) {
1767 void MockTransportClientSocketPool::ReleaseSocket(
1768 const std::string
& group_name
,
1769 scoped_ptr
<StreamSocket
> socket
,
1775 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1777 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1779 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1780 DeterministicSocketData
* data
) {
1781 mock_data_
.Add(data
);
1784 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1785 SSLSocketDataProvider
* data
) {
1786 mock_ssl_data_
.Add(data
);
1789 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1790 mock_data_
.ResetNextIndex();
1791 mock_ssl_data_
.ResetNextIndex();
1794 MockSSLClientSocket
* DeterministicMockClientSocketFactory::
1795 GetMockSSLClientSocket(size_t index
) const {
1796 DCHECK_LT(index
, ssl_client_sockets_
.size());
1797 return ssl_client_sockets_
[index
];
1800 scoped_ptr
<DatagramClientSocket
>
1801 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1802 DatagramSocket::BindType bind_type
,
1803 const RandIntCallback
& rand_int_cb
,
1804 net::NetLog
* net_log
,
1805 const NetLog::Source
& source
) {
1806 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1807 scoped_ptr
<DeterministicMockUDPClientSocket
> socket(
1808 new DeterministicMockUDPClientSocket(net_log
, data_provider
));
1809 data_provider
->set_delegate(socket
->AsWeakPtr());
1810 udp_client_sockets().push_back(socket
.get());
1811 return socket
.PassAs
<DatagramClientSocket
>();
1814 scoped_ptr
<StreamSocket
>
1815 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1816 const AddressList
& addresses
,
1817 net::NetLog
* net_log
,
1818 const net::NetLog::Source
& source
) {
1819 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1820 scoped_ptr
<DeterministicMockTCPClientSocket
> socket(
1821 new DeterministicMockTCPClientSocket(net_log
, data_provider
));
1822 data_provider
->set_delegate(socket
->AsWeakPtr());
1823 tcp_client_sockets().push_back(socket
.get());
1824 return socket
.PassAs
<StreamSocket
>();
1827 scoped_ptr
<SSLClientSocket
>
1828 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1829 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1830 const HostPortPair
& host_and_port
,
1831 const SSLConfig
& ssl_config
,
1832 const SSLClientSocketContext
& context
) {
1833 scoped_ptr
<MockSSLClientSocket
> socket(
1834 new MockSSLClientSocket(transport_socket
.Pass(),
1835 host_and_port
, ssl_config
,
1836 mock_ssl_data_
.GetNext()));
1837 ssl_client_sockets_
.push_back(socket
.get());
1838 return socket
.PassAs
<SSLClientSocket
>();
1841 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1844 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1846 int max_sockets_per_group
,
1847 ClientSocketPoolHistograms
* histograms
,
1848 TransportClientSocketPool
* transport_pool
)
1849 : SOCKSClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1850 NULL
, transport_pool
, NULL
),
1851 transport_pool_(transport_pool
) {
1854 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1856 int MockSOCKSClientSocketPool::RequestSocket(
1857 const std::string
& group_name
, const void* socket_params
,
1858 RequestPriority priority
, ClientSocketHandle
* handle
,
1859 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1860 return transport_pool_
->RequestSocket(
1861 group_name
, socket_params
, priority
, handle
, callback
, net_log
);
1864 void MockSOCKSClientSocketPool::CancelRequest(
1865 const std::string
& group_name
,
1866 ClientSocketHandle
* handle
) {
1867 return transport_pool_
->CancelRequest(group_name
, handle
);
1870 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string
& group_name
,
1871 scoped_ptr
<StreamSocket
> socket
,
1873 return transport_pool_
->ReleaseSocket(group_name
, socket
.Pass(), id
);
1876 const char kSOCKS5GreetRequest
[] = { 0x05, 0x01, 0x00 };
1877 const int kSOCKS5GreetRequestLength
= arraysize(kSOCKS5GreetRequest
);
1879 const char kSOCKS5GreetResponse
[] = { 0x05, 0x00 };
1880 const int kSOCKS5GreetResponseLength
= arraysize(kSOCKS5GreetResponse
);
1882 const char kSOCKS5OkRequest
[] =
1883 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1884 const int kSOCKS5OkRequestLength
= arraysize(kSOCKS5OkRequest
);
1886 const char kSOCKS5OkResponse
[] =
1887 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1888 const int kSOCKS5OkResponseLength
= arraysize(kSOCKS5OkResponse
);