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.h"
15 #include "base/run_loop.h"
16 #include "base/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 ALLOW_THIS_IN_INITIALIZER_LIST(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 ALLOW_THIS_IN_INITIALIZER_LIST(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 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), ALLOW_THIS_IN_INITIALIZER_LIST(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), ALLOW_THIS_IN_INITIALIZER_LIST(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 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 (socket_
&& (socket_
->write_pending() || socket_
->read_pending()) &&
486 base::RunLoop().RunUntilIdle();
492 void DeterministicSocketData::RunFor(int steps
) {
497 void DeterministicSocketData::SetStop(int seq
) {
498 DCHECK_LT(sequence_number_
, seq
);
499 stopping_sequence_number_
= seq
;
503 void DeterministicSocketData::StopAfter(int seq
) {
504 SetStop(sequence_number_
+ seq
);
507 MockRead
DeterministicSocketData::GetNextRead() {
508 current_read_
= StaticSocketDataProvider::PeekRead();
510 // Synchronous read while stopped is an error
511 if (stopped() && current_read_
.mode
== SYNCHRONOUS
) {
512 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
513 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
516 // Async read which will be called back in a future step.
517 if (sequence_number_
< current_read_
.sequence_number
) {
518 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
520 MockRead result
= MockRead(SYNCHRONOUS
, ERR_IO_PENDING
);
521 if (current_read_
.mode
== SYNCHRONOUS
) {
522 LOG(ERROR
) << "Unable to perform synchronous read: "
523 << current_read_
.sequence_number
524 << " at stage: " << sequence_number_
;
525 result
= MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
528 DumpMockReadWrite(result
);
532 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
533 << ": Read " << read_index();
535 DumpMockReadWrite(current_read_
);
537 // Increment the sequence number if IO is complete
538 if (current_read_
.mode
== SYNCHRONOUS
)
541 DCHECK_NE(ERR_IO_PENDING
, current_read_
.result
);
542 StaticSocketDataProvider::GetNextRead();
544 return current_read_
;
547 MockWriteResult
DeterministicSocketData::OnWrite(const std::string
& data
) {
548 const MockWrite
& next_write
= StaticSocketDataProvider::PeekWrite();
549 current_write_
= next_write
;
551 // Synchronous write while stopped is an error
552 if (stopped() && next_write
.mode
== SYNCHRONOUS
) {
553 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
554 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
557 // Async write which will be called back in a future step.
558 if (sequence_number_
< next_write
.sequence_number
) {
559 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
561 if (next_write
.mode
== SYNCHRONOUS
) {
562 LOG(ERROR
) << "Unable to perform synchronous write: "
563 << next_write
.sequence_number
<< " at stage: " << sequence_number_
;
564 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
567 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
568 << ": Write " << write_index();
572 DumpMockReadWrite(next_write
);
574 // Move to the next step if I/O is synchronous, since the operation will
575 // complete when this method returns.
576 if (next_write
.mode
== SYNCHRONOUS
)
579 // This is either a sync write for this step, or an async write.
580 return StaticSocketDataProvider::OnWrite(data
);
583 void DeterministicSocketData::Reset() {
584 NET_TRACE(INFO
, " *** ") << "Stage "
585 << sequence_number_
<< ": Reset()";
586 sequence_number_
= 0;
587 StaticSocketDataProvider::Reset();
591 void DeterministicSocketData::InvokeCallbacks() {
592 if (socket_
&& socket_
->write_pending() &&
593 (current_write().sequence_number
== sequence_number())) {
595 socket_
->CompleteWrite();
598 if (socket_
&& socket_
->read_pending() &&
599 (current_read().sequence_number
== sequence_number())) {
601 socket_
->CompleteRead();
606 void DeterministicSocketData::NextStep() {
607 // Invariant: Can never move *past* the stopping step.
608 DCHECK_LT(sequence_number_
, stopping_sequence_number_
);
610 if (sequence_number_
== stopping_sequence_number_
)
614 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
615 MockRead
* reads
, size_t reads_count
,
616 MockWrite
* writes
, size_t writes_count
) {
620 while (read
< reads_count
|| write
< writes_count
) {
621 // Check to see that we have a read or write at the expected
623 if (read
< reads_count
&& reads
[read
].sequence_number
== expected
) {
628 if (write
< writes_count
&& writes
[write
].sequence_number
== expected
) {
633 NOTREACHED() << "Missing sequence number: " << expected
;
636 DCHECK_EQ(read
, reads_count
);
637 DCHECK_EQ(write
, writes_count
);
640 MockClientSocketFactory::MockClientSocketFactory() {}
642 MockClientSocketFactory::~MockClientSocketFactory() {}
644 void MockClientSocketFactory::AddSocketDataProvider(
645 SocketDataProvider
* data
) {
646 mock_data_
.Add(data
);
649 void MockClientSocketFactory::AddSSLSocketDataProvider(
650 SSLSocketDataProvider
* data
) {
651 mock_ssl_data_
.Add(data
);
654 void MockClientSocketFactory::ResetNextMockIndexes() {
655 mock_data_
.ResetNextIndex();
656 mock_ssl_data_
.ResetNextIndex();
659 DatagramClientSocket
* MockClientSocketFactory::CreateDatagramClientSocket(
660 DatagramSocket::BindType bind_type
,
661 const RandIntCallback
& rand_int_cb
,
662 net::NetLog
* net_log
,
663 const net::NetLog::Source
& source
) {
664 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
665 MockUDPClientSocket
* socket
= new MockUDPClientSocket(data_provider
, net_log
);
666 data_provider
->set_socket(socket
);
670 StreamSocket
* MockClientSocketFactory::CreateTransportClientSocket(
671 const AddressList
& addresses
,
672 net::NetLog
* net_log
,
673 const net::NetLog::Source
& source
) {
674 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
675 MockTCPClientSocket
* socket
=
676 new MockTCPClientSocket(addresses
, net_log
, data_provider
);
677 data_provider
->set_socket(socket
);
681 SSLClientSocket
* MockClientSocketFactory::CreateSSLClientSocket(
682 ClientSocketHandle
* transport_socket
,
683 const HostPortPair
& host_and_port
,
684 const SSLConfig
& ssl_config
,
685 const SSLClientSocketContext
& context
) {
686 MockSSLClientSocket
* socket
=
687 new MockSSLClientSocket(transport_socket
, host_and_port
, ssl_config
,
688 mock_ssl_data_
.GetNext());
692 void MockClientSocketFactory::ClearSSLSessionCache() {
695 const char MockClientSocket::kTlsUnique
[] = "MOCK_TLSUNIQ";
697 MockClientSocket::MockClientSocket(const BoundNetLog
& net_log
)
698 : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
702 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
703 peer_addr_
= IPEndPoint(ip
, 0);
706 bool MockClientSocket::SetReceiveBufferSize(int32 size
) {
710 bool MockClientSocket::SetSendBufferSize(int32 size
) {
714 void MockClientSocket::Disconnect() {
718 bool MockClientSocket::IsConnected() const {
722 bool MockClientSocket::IsConnectedAndIdle() const {
726 int MockClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
728 return ERR_SOCKET_NOT_CONNECTED
;
729 *address
= peer_addr_
;
733 int MockClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
735 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
737 *address
= IPEndPoint(ip
, 123);
741 const BoundNetLog
& MockClientSocket::NetLog() const {
745 void MockClientSocket::GetSSLCertRequestInfo(
746 SSLCertRequestInfo
* cert_request_info
) {
749 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece
& label
,
751 const base::StringPiece
& context
,
753 unsigned int outlen
) {
754 memset(out
, 'A', outlen
);
758 int MockClientSocket::GetTLSUniqueChannelBinding(std::string
* out
) {
759 out
->assign(MockClientSocket::kTlsUnique
);
763 ServerBoundCertService
* MockClientSocket::GetServerBoundCertService() const {
768 SSLClientSocket::NextProtoStatus
769 MockClientSocket::GetNextProto(std::string
* proto
, std::string
* server_protos
) {
771 server_protos
->clear();
772 return SSLClientSocket::kNextProtoUnsupported
;
775 MockClientSocket::~MockClientSocket() {}
777 void MockClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
779 MessageLoop::current()->PostTask(FROM_HERE
,
780 base::Bind(&MockClientSocket::RunCallback
, weak_factory_
.GetWeakPtr(),
784 void MockClientSocket::RunCallback(const net::CompletionCallback
& callback
,
786 if (!callback
.is_null())
787 callback
.Run(result
);
790 MockTCPClientSocket::MockTCPClientSocket(const AddressList
& addresses
,
791 net::NetLog
* net_log
,
792 SocketDataProvider
* data
)
793 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
794 addresses_(addresses
),
797 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
798 need_read_data_(true),
799 peer_closed_connection_(false),
802 was_used_to_convey_data_(false) {
804 peer_addr_
= data
->connect_data().peer_addr
;
808 MockTCPClientSocket::~MockTCPClientSocket() {}
810 int MockTCPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
811 const CompletionCallback
& callback
) {
813 return ERR_UNEXPECTED
;
815 // If the buffer is already in use, a read is already in progress!
816 DCHECK(pending_buf_
== NULL
);
818 // Store our async IO data.
820 pending_buf_len_
= buf_len
;
821 pending_callback_
= callback
;
823 if (need_read_data_
) {
824 read_data_
= data_
->GetNextRead();
825 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
826 // This MockRead is just a marker to instruct us to set
827 // peer_closed_connection_.
828 peer_closed_connection_
= true;
830 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
831 // This MockRead is just a marker to instruct us to set
832 // peer_closed_connection_. Skip it and get the next one.
833 read_data_
= data_
->GetNextRead();
834 peer_closed_connection_
= true;
836 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
837 // to complete the async IO manually later (via OnReadComplete).
838 if (read_data_
.result
== ERR_IO_PENDING
) {
839 // We need to be using async IO in this case.
840 DCHECK(!callback
.is_null());
841 return ERR_IO_PENDING
;
843 need_read_data_
= false;
846 return CompleteRead();
849 int MockTCPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
850 const CompletionCallback
& callback
) {
852 DCHECK_GT(buf_len
, 0);
855 return ERR_UNEXPECTED
;
857 std::string
data(buf
->data(), buf_len
);
858 MockWriteResult write_result
= data_
->OnWrite(data
);
860 was_used_to_convey_data_
= true;
862 if (write_result
.mode
== ASYNC
) {
863 RunCallbackAsync(callback
, write_result
.result
);
864 return ERR_IO_PENDING
;
867 return write_result
.result
;
870 int MockTCPClientSocket::Connect(const CompletionCallback
& callback
) {
874 peer_closed_connection_
= false;
875 if (data_
->connect_data().mode
== ASYNC
) {
876 RunCallbackAsync(callback
, data_
->connect_data().result
);
877 return ERR_IO_PENDING
;
879 return data_
->connect_data().result
;
882 void MockTCPClientSocket::Disconnect() {
883 MockClientSocket::Disconnect();
884 pending_callback_
.Reset();
887 bool MockTCPClientSocket::IsConnected() const {
888 return connected_
&& !peer_closed_connection_
;
891 bool MockTCPClientSocket::IsConnectedAndIdle() const {
892 return IsConnected();
895 int MockTCPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
896 if (addresses_
.empty())
897 return MockClientSocket::GetPeerAddress(address
);
899 *address
= addresses_
[0];
903 bool MockTCPClientSocket::WasEverUsed() const {
904 return was_used_to_convey_data_
;
907 bool MockTCPClientSocket::UsingTCPFastOpen() const {
911 bool MockTCPClientSocket::WasNpnNegotiated() const {
915 bool MockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
919 void MockTCPClientSocket::OnReadComplete(const MockRead
& data
) {
920 // There must be a read pending.
921 DCHECK(pending_buf_
);
922 // You can't complete a read with another ERR_IO_PENDING status code.
923 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
924 // Since we've been waiting for data, need_read_data_ should be true.
925 DCHECK(need_read_data_
);
928 need_read_data_
= false;
930 // The caller is simulating that this IO completes right now. Don't
931 // let CompleteRead() schedule a callback.
932 read_data_
.mode
= SYNCHRONOUS
;
934 CompletionCallback callback
= pending_callback_
;
935 int rv
= CompleteRead();
936 RunCallback(callback
, rv
);
939 int MockTCPClientSocket::CompleteRead() {
940 DCHECK(pending_buf_
);
941 DCHECK(pending_buf_len_
> 0);
943 was_used_to_convey_data_
= true;
945 // Save the pending async IO data and reset our |pending_| state.
946 IOBuffer
* buf
= pending_buf_
;
947 int buf_len
= pending_buf_len_
;
948 CompletionCallback callback
= pending_callback_
;
950 pending_buf_len_
= 0;
951 pending_callback_
.Reset();
953 int result
= read_data_
.result
;
954 DCHECK(result
!= ERR_IO_PENDING
);
956 if (read_data_
.data
) {
957 if (read_data_
.data_len
- read_offset_
> 0) {
958 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
959 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
960 read_offset_
+= result
;
961 if (read_offset_
== read_data_
.data_len
) {
962 need_read_data_
= true;
970 if (read_data_
.mode
== ASYNC
) {
971 DCHECK(!callback
.is_null());
972 RunCallbackAsync(callback
, result
);
973 return ERR_IO_PENDING
;
978 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
979 net::NetLog
* net_log
, DeterministicSocketData
* data
)
980 : MockClientSocket(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
981 write_pending_(false),
986 read_pending_(false),
988 was_used_to_convey_data_(false),
989 peer_closed_connection_(false) {
990 peer_addr_
= data
->connect_data().peer_addr
;
993 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
995 void DeterministicMockTCPClientSocket::CompleteWrite() {
996 was_used_to_convey_data_
= true;
997 write_pending_
= false;
998 write_callback_
.Run(write_result_
);
1001 int DeterministicMockTCPClientSocket::CompleteRead() {
1002 DCHECK_GT(read_buf_len_
, 0);
1003 DCHECK_LE(read_data_
.data_len
, read_buf_len_
);
1006 was_used_to_convey_data_
= true;
1008 if (read_data_
.result
== ERR_IO_PENDING
)
1009 read_data_
= data_
->GetNextRead();
1010 DCHECK_NE(ERR_IO_PENDING
, read_data_
.result
);
1011 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1012 // the callback. Therefore we don't even bother to check it.
1013 int result
= read_data_
.result
;
1015 if (read_data_
.data_len
> 0) {
1016 DCHECK(read_data_
.data
);
1017 result
= std::min(read_buf_len_
, read_data_
.data_len
);
1018 memcpy(read_buf_
->data(), read_data_
.data
, result
);
1021 if (read_pending_
) {
1022 read_pending_
= false;
1023 read_callback_
.Run(result
);
1029 int DeterministicMockTCPClientSocket::Write(
1030 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1032 DCHECK_GT(buf_len
, 0);
1035 return ERR_UNEXPECTED
;
1037 std::string
data(buf
->data(), buf_len
);
1038 MockWriteResult write_result
= data_
->OnWrite(data
);
1040 if (write_result
.mode
== ASYNC
) {
1041 write_callback_
= callback
;
1042 write_result_
= write_result
.result
;
1043 DCHECK(!write_callback_
.is_null());
1044 write_pending_
= true;
1045 return ERR_IO_PENDING
;
1048 was_used_to_convey_data_
= true;
1049 write_pending_
= false;
1050 return write_result
.result
;
1053 int DeterministicMockTCPClientSocket::Read(
1054 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1056 return ERR_UNEXPECTED
;
1058 read_data_
= data_
->GetNextRead();
1059 // The buffer should always be big enough to contain all the MockRead data. To
1060 // use small buffers, split the data into multiple MockReads.
1061 DCHECK_LE(read_data_
.data_len
, buf_len
);
1063 if (read_data_
.result
== ERR_CONNECTION_CLOSED
) {
1064 // This MockRead is just a marker to instruct us to set
1065 // peer_closed_connection_.
1066 peer_closed_connection_
= true;
1068 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
1069 // This MockRead is just a marker to instruct us to set
1070 // peer_closed_connection_. Skip it and get the next one.
1071 read_data_
= data_
->GetNextRead();
1072 peer_closed_connection_
= true;
1076 read_buf_len_
= buf_len
;
1077 read_callback_
= callback
;
1079 if (read_data_
.mode
== ASYNC
|| (read_data_
.result
== ERR_IO_PENDING
)) {
1080 read_pending_
= true;
1081 DCHECK(!read_callback_
.is_null());
1082 return ERR_IO_PENDING
;
1085 was_used_to_convey_data_
= true;
1086 return CompleteRead();
1089 // TODO(erikchen): Support connect sequencing.
1090 int DeterministicMockTCPClientSocket::Connect(
1091 const CompletionCallback
& callback
) {
1095 if (data_
->connect_data().mode
== ASYNC
) {
1096 RunCallbackAsync(callback
, data_
->connect_data().result
);
1097 return ERR_IO_PENDING
;
1099 return data_
->connect_data().result
;
1102 void DeterministicMockTCPClientSocket::Disconnect() {
1103 MockClientSocket::Disconnect();
1106 bool DeterministicMockTCPClientSocket::IsConnected() const {
1107 return connected_
&& !peer_closed_connection_
;
1110 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1111 return IsConnected();
1114 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1115 return was_used_to_convey_data_
;
1118 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1122 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1126 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1130 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead
& data
) {}
1133 void MockSSLClientSocket::ConnectCallback(
1134 MockSSLClientSocket
*ssl_client_socket
,
1135 const CompletionCallback
& callback
,
1138 ssl_client_socket
->connected_
= true;
1142 MockSSLClientSocket::MockSSLClientSocket(
1143 ClientSocketHandle
* transport_socket
,
1144 const HostPortPair
& host_port_pair
,
1145 const SSLConfig
& ssl_config
,
1146 SSLSocketDataProvider
* data
)
1148 // Have to use the right BoundNetLog for LoadTimingInfo regression
1150 transport_socket
->socket()->NetLog()),
1151 transport_(transport_socket
),
1153 is_npn_state_set_(false),
1154 new_npn_value_(false),
1155 is_protocol_negotiated_set_(false),
1156 protocol_negotiated_(kProtoUnknown
) {
1158 peer_addr_
= data
->connect
.peer_addr
;
1161 MockSSLClientSocket::~MockSSLClientSocket() {
1165 int MockSSLClientSocket::Read(IOBuffer
* buf
, int buf_len
,
1166 const CompletionCallback
& callback
) {
1167 return transport_
->socket()->Read(buf
, buf_len
, callback
);
1170 int MockSSLClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1171 const CompletionCallback
& callback
) {
1172 return transport_
->socket()->Write(buf
, buf_len
, callback
);
1175 int MockSSLClientSocket::Connect(const CompletionCallback
& callback
) {
1176 int rv
= transport_
->socket()->Connect(
1177 base::Bind(&ConnectCallback
, base::Unretained(this), callback
));
1179 if (data_
->connect
.result
== OK
)
1181 if (data_
->connect
.mode
== ASYNC
) {
1182 RunCallbackAsync(callback
, data_
->connect
.result
);
1183 return ERR_IO_PENDING
;
1185 return data_
->connect
.result
;
1190 void MockSSLClientSocket::Disconnect() {
1191 MockClientSocket::Disconnect();
1192 if (transport_
->socket() != NULL
)
1193 transport_
->socket()->Disconnect();
1196 bool MockSSLClientSocket::IsConnected() const {
1197 return transport_
->socket()->IsConnected();
1200 bool MockSSLClientSocket::WasEverUsed() const {
1201 return transport_
->socket()->WasEverUsed();
1204 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1205 return transport_
->socket()->UsingTCPFastOpen();
1208 int MockSSLClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1209 return transport_
->socket()->GetPeerAddress(address
);
1212 bool MockSSLClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1214 ssl_info
->cert
= data_
->cert
;
1215 ssl_info
->client_cert_sent
= data_
->client_cert_sent
;
1216 ssl_info
->channel_id_sent
= data_
->channel_id_sent
;
1220 void MockSSLClientSocket::GetSSLCertRequestInfo(
1221 SSLCertRequestInfo
* cert_request_info
) {
1222 DCHECK(cert_request_info
);
1223 if (data_
->cert_request_info
) {
1224 cert_request_info
->host_and_port
=
1225 data_
->cert_request_info
->host_and_port
;
1226 cert_request_info
->client_certs
= data_
->cert_request_info
->client_certs
;
1228 cert_request_info
->Reset();
1232 SSLClientSocket::NextProtoStatus
MockSSLClientSocket::GetNextProto(
1233 std::string
* proto
, std::string
* server_protos
) {
1234 *proto
= data_
->next_proto
;
1235 *server_protos
= data_
->server_protos
;
1236 return data_
->next_proto_status
;
1239 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated
) {
1240 is_npn_state_set_
= true;
1241 return new_npn_value_
= negotiated
;
1244 bool MockSSLClientSocket::WasNpnNegotiated() const {
1245 if (is_npn_state_set_
)
1246 return new_npn_value_
;
1247 return data_
->was_npn_negotiated
;
1250 NextProto
MockSSLClientSocket::GetNegotiatedProtocol() const {
1251 if (is_protocol_negotiated_set_
)
1252 return protocol_negotiated_
;
1253 return data_
->protocol_negotiated
;
1256 void MockSSLClientSocket::set_protocol_negotiated(
1257 NextProto protocol_negotiated
) {
1258 is_protocol_negotiated_set_
= true;
1259 protocol_negotiated_
= protocol_negotiated
;
1262 bool MockSSLClientSocket::WasChannelIDSent() const {
1263 return data_
->channel_id_sent
;
1266 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent
) {
1267 data_
->channel_id_sent
= channel_id_sent
;
1270 ServerBoundCertService
* MockSSLClientSocket::GetServerBoundCertService() const {
1271 return data_
->server_bound_cert_service
;
1274 void MockSSLClientSocket::OnReadComplete(const MockRead
& data
) {
1278 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider
* data
,
1279 net::NetLog
* net_log
)
1280 : connected_(false),
1283 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
1284 need_read_data_(true),
1286 pending_buf_len_(0),
1287 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)),
1288 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
1291 peer_addr_
= data
->connect_data().peer_addr
;
1294 MockUDPClientSocket::~MockUDPClientSocket() {}
1296 int MockUDPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
1297 const CompletionCallback
& callback
) {
1299 return ERR_UNEXPECTED
;
1301 // If the buffer is already in use, a read is already in progress!
1302 DCHECK(pending_buf_
== NULL
);
1304 // Store our async IO data.
1306 pending_buf_len_
= buf_len
;
1307 pending_callback_
= callback
;
1309 if (need_read_data_
) {
1310 read_data_
= data_
->GetNextRead();
1311 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1312 // to complete the async IO manually later (via OnReadComplete).
1313 if (read_data_
.result
== ERR_IO_PENDING
) {
1314 // We need to be using async IO in this case.
1315 DCHECK(!callback
.is_null());
1316 return ERR_IO_PENDING
;
1318 need_read_data_
= false;
1321 return CompleteRead();
1324 int MockUDPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1325 const CompletionCallback
& callback
) {
1327 DCHECK_GT(buf_len
, 0);
1330 return ERR_UNEXPECTED
;
1332 std::string
data(buf
->data(), buf_len
);
1333 MockWriteResult write_result
= data_
->OnWrite(data
);
1335 if (write_result
.mode
== ASYNC
) {
1336 RunCallbackAsync(callback
, write_result
.result
);
1337 return ERR_IO_PENDING
;
1339 return write_result
.result
;
1342 bool MockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1346 bool MockUDPClientSocket::SetSendBufferSize(int32 size
) {
1350 void MockUDPClientSocket::Close() {
1354 int MockUDPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1355 *address
= peer_addr_
;
1359 int MockUDPClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
1364 const BoundNetLog
& MockUDPClientSocket::NetLog() const {
1368 int MockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1373 void MockUDPClientSocket::OnReadComplete(const MockRead
& data
) {
1374 // There must be a read pending.
1375 DCHECK(pending_buf_
);
1376 // You can't complete a read with another ERR_IO_PENDING status code.
1377 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
1378 // Since we've been waiting for data, need_read_data_ should be true.
1379 DCHECK(need_read_data_
);
1382 need_read_data_
= false;
1384 // The caller is simulating that this IO completes right now. Don't
1385 // let CompleteRead() schedule a callback.
1386 read_data_
.mode
= SYNCHRONOUS
;
1388 net::CompletionCallback callback
= pending_callback_
;
1389 int rv
= CompleteRead();
1390 RunCallback(callback
, rv
);
1393 int MockUDPClientSocket::CompleteRead() {
1394 DCHECK(pending_buf_
);
1395 DCHECK(pending_buf_len_
> 0);
1397 // Save the pending async IO data and reset our |pending_| state.
1398 IOBuffer
* buf
= pending_buf_
;
1399 int buf_len
= pending_buf_len_
;
1400 CompletionCallback callback
= pending_callback_
;
1401 pending_buf_
= NULL
;
1402 pending_buf_len_
= 0;
1403 pending_callback_
.Reset();
1405 int result
= read_data_
.result
;
1406 DCHECK(result
!= ERR_IO_PENDING
);
1408 if (read_data_
.data
) {
1409 if (read_data_
.data_len
- read_offset_
> 0) {
1410 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
1411 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
1412 read_offset_
+= result
;
1413 if (read_offset_
== read_data_
.data_len
) {
1414 need_read_data_
= true;
1422 if (read_data_
.mode
== ASYNC
) {
1423 DCHECK(!callback
.is_null());
1424 RunCallbackAsync(callback
, result
);
1425 return ERR_IO_PENDING
;
1430 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
1432 MessageLoop::current()->PostTask(
1434 base::Bind(&MockUDPClientSocket::RunCallback
, weak_factory_
.GetWeakPtr(),
1438 void MockUDPClientSocket::RunCallback(const CompletionCallback
& callback
,
1440 if (!callback
.is_null())
1441 callback
.Run(result
);
1444 TestSocketRequest::TestSocketRequest(
1445 std::vector
<TestSocketRequest
*>* request_order
, size_t* completion_count
)
1446 : request_order_(request_order
),
1447 completion_count_(completion_count
),
1448 ALLOW_THIS_IN_INITIALIZER_LIST(callback_(
1449 base::Bind(&TestSocketRequest::OnComplete
, base::Unretained(this)))) {
1450 DCHECK(request_order
);
1451 DCHECK(completion_count
);
1454 TestSocketRequest::~TestSocketRequest() {
1457 void TestSocketRequest::OnComplete(int result
) {
1459 (*completion_count_
)++;
1460 request_order_
->push_back(this);
1464 const int ClientSocketPoolTest::kIndexOutOfBounds
= -1;
1467 const int ClientSocketPoolTest::kRequestNotFound
= -2;
1469 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1470 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1472 int ClientSocketPoolTest::GetOrderOfRequest(size_t index
) const {
1474 if (index
>= requests_
.size())
1475 return kIndexOutOfBounds
;
1477 for (size_t i
= 0; i
< request_order_
.size(); i
++)
1478 if (requests_
[index
] == request_order_
[i
])
1481 return kRequestNotFound
;
1484 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive
) {
1485 ScopedVector
<TestSocketRequest
>::iterator i
;
1486 for (i
= requests_
.begin(); i
!= requests_
.end(); ++i
) {
1487 if ((*i
)->handle()->is_initialized()) {
1488 if (keep_alive
== NO_KEEP_ALIVE
)
1489 (*i
)->handle()->socket()->Disconnect();
1490 (*i
)->handle()->Reset();
1491 base::RunLoop().RunUntilIdle();
1498 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive
) {
1501 released_one
= ReleaseOneConnection(keep_alive
);
1502 } while (released_one
);
1505 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1506 StreamSocket
* socket
,
1507 ClientSocketHandle
* handle
,
1508 const CompletionCallback
& callback
)
1511 user_callback_(callback
) {
1514 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1516 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1517 int rv
= socket_
->Connect(base::Bind(&MockConnectJob::OnConnect
,
1518 base::Unretained(this)));
1520 user_callback_
.Reset();
1526 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1527 const ClientSocketHandle
* handle
) {
1528 if (handle
!= handle_
)
1532 user_callback_
.Reset();
1536 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv
) {
1540 handle_
->set_socket(socket_
.release());
1542 // Needed for socket pool tests that layer other sockets on top of mock
1544 LoadTimingInfo::ConnectTiming connect_timing
;
1545 base::TimeTicks now
= base::TimeTicks::Now();
1546 connect_timing
.dns_start
= now
;
1547 connect_timing
.dns_end
= now
;
1548 connect_timing
.connect_start
= now
;
1549 connect_timing
.connect_end
= now
;
1550 handle_
->set_connect_timing(connect_timing
);
1557 if (!user_callback_
.is_null()) {
1558 CompletionCallback callback
= user_callback_
;
1559 user_callback_
.Reset();
1564 MockTransportClientSocketPool::MockTransportClientSocketPool(
1566 int max_sockets_per_group
,
1567 ClientSocketPoolHistograms
* histograms
,
1568 ClientSocketFactory
* socket_factory
)
1569 : TransportClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1571 client_socket_factory_(socket_factory
),
1576 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1578 int MockTransportClientSocketPool::RequestSocket(
1579 const std::string
& group_name
, const void* socket_params
,
1580 RequestPriority priority
, ClientSocketHandle
* handle
,
1581 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1582 StreamSocket
* socket
= client_socket_factory_
->CreateTransportClientSocket(
1583 AddressList(), net_log
.net_log(), net::NetLog::Source());
1584 MockConnectJob
* job
= new MockConnectJob(socket
, handle
, callback
);
1585 job_list_
.push_back(job
);
1586 handle
->set_pool_id(1);
1587 return job
->Connect();
1590 void MockTransportClientSocketPool::CancelRequest(const std::string
& group_name
,
1591 ClientSocketHandle
* handle
) {
1592 std::vector
<MockConnectJob
*>::iterator i
;
1593 for (i
= job_list_
.begin(); i
!= job_list_
.end(); ++i
) {
1594 if ((*i
)->CancelHandle(handle
)) {
1601 void MockTransportClientSocketPool::ReleaseSocket(const std::string
& group_name
,
1602 StreamSocket
* socket
, int id
) {
1608 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1610 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1612 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1613 DeterministicSocketData
* data
) {
1614 mock_data_
.Add(data
);
1617 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1618 SSLSocketDataProvider
* data
) {
1619 mock_ssl_data_
.Add(data
);
1622 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1623 mock_data_
.ResetNextIndex();
1624 mock_ssl_data_
.ResetNextIndex();
1627 MockSSLClientSocket
* DeterministicMockClientSocketFactory::
1628 GetMockSSLClientSocket(size_t index
) const {
1629 DCHECK_LT(index
, ssl_client_sockets_
.size());
1630 return ssl_client_sockets_
[index
];
1633 DatagramClientSocket
*
1634 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1635 DatagramSocket::BindType bind_type
,
1636 const RandIntCallback
& rand_int_cb
,
1637 net::NetLog
* net_log
,
1638 const NetLog::Source
& source
) {
1643 StreamSocket
* DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1644 const AddressList
& addresses
,
1645 net::NetLog
* net_log
,
1646 const net::NetLog::Source
& source
) {
1647 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1648 DeterministicMockTCPClientSocket
* socket
=
1649 new DeterministicMockTCPClientSocket(net_log
, data_provider
);
1650 data_provider
->set_socket(socket
->AsWeakPtr());
1651 tcp_client_sockets().push_back(socket
);
1655 SSLClientSocket
* DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1656 ClientSocketHandle
* transport_socket
,
1657 const HostPortPair
& host_and_port
,
1658 const SSLConfig
& ssl_config
,
1659 const SSLClientSocketContext
& context
) {
1660 MockSSLClientSocket
* socket
=
1661 new MockSSLClientSocket(transport_socket
, host_and_port
, ssl_config
,
1662 mock_ssl_data_
.GetNext());
1663 ssl_client_sockets_
.push_back(socket
);
1667 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1670 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1672 int max_sockets_per_group
,
1673 ClientSocketPoolHistograms
* histograms
,
1674 TransportClientSocketPool
* transport_pool
)
1675 : SOCKSClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1676 NULL
, transport_pool
, NULL
),
1677 transport_pool_(transport_pool
) {
1680 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1682 int MockSOCKSClientSocketPool::RequestSocket(
1683 const std::string
& group_name
, const void* socket_params
,
1684 RequestPriority priority
, ClientSocketHandle
* handle
,
1685 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1686 return transport_pool_
->RequestSocket(
1687 group_name
, socket_params
, priority
, handle
, callback
, net_log
);
1690 void MockSOCKSClientSocketPool::CancelRequest(
1691 const std::string
& group_name
,
1692 ClientSocketHandle
* handle
) {
1693 return transport_pool_
->CancelRequest(group_name
, handle
);
1696 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string
& group_name
,
1697 StreamSocket
* socket
, int id
) {
1698 return transport_pool_
->ReleaseSocket(group_name
, socket
, id
);
1701 const char kSOCKS5GreetRequest
[] = { 0x05, 0x01, 0x00 };
1702 const int kSOCKS5GreetRequestLength
= arraysize(kSOCKS5GreetRequest
);
1704 const char kSOCKS5GreetResponse
[] = { 0x05, 0x00 };
1705 const int kSOCKS5GreetResponseLength
= arraysize(kSOCKS5GreetResponse
);
1707 const char kSOCKS5OkRequest
[] =
1708 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1709 const int kSOCKS5OkRequestLength
= arraysize(kSOCKS5OkRequest
);
1711 const char kSOCKS5OkResponse
[] =
1712 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1713 const int kSOCKS5OkResponseLength
= arraysize(kSOCKS5OkResponse
);