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/time.h"
16 #include "net/base/address_family.h"
17 #include "net/base/address_list.h"
18 #include "net/base/auth.h"
19 #include "net/base/ssl_cert_request_info.h"
20 #include "net/base/ssl_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 "testing/gtest/include/gtest/gtest.h"
28 // Socket events are easier to debug if you log individual reads and writes.
29 // Enable these if locally debugging, but they are too noisy for the waterfall.
31 #define NET_TRACE(level, s) DLOG(level) << s << __FUNCTION__ << "() "
33 #define NET_TRACE(level, s) EAT_STREAM_PARAMETERS
40 inline char AsciifyHigh(char x
) {
41 char nybble
= static_cast<char>((x
>> 4) & 0x0F);
42 return nybble
+ ((nybble
< 0x0A) ? '0' : 'A' - 10);
45 inline char AsciifyLow(char x
) {
46 char nybble
= static_cast<char>((x
>> 0) & 0x0F);
47 return nybble
+ ((nybble
< 0x0A) ? '0' : 'A' - 10);
50 inline char Asciify(char x
) {
51 if ((x
< 0) || !isprint(x
))
56 void DumpData(const char* data
, int data_len
) {
57 if (logging::LOG_INFO
< logging::GetMinLogLevel())
59 DVLOG(1) << "Length: " << data_len
;
60 const char* pfx
= "Data: ";
61 if (!data
|| (data_len
<= 0)) {
62 DVLOG(1) << pfx
<< "<None>";
65 for (i
= 0; i
<= (data_len
- 4); i
+= 4) {
67 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
68 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
69 << AsciifyHigh(data
[i
+ 2]) << AsciifyLow(data
[i
+ 2])
70 << AsciifyHigh(data
[i
+ 3]) << AsciifyLow(data
[i
+ 3])
72 << Asciify(data
[i
+ 0])
73 << Asciify(data
[i
+ 1])
74 << Asciify(data
[i
+ 2])
75 << Asciify(data
[i
+ 3])
79 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
80 switch (data_len
- i
) {
83 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
84 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
85 << AsciifyHigh(data
[i
+ 2]) << AsciifyLow(data
[i
+ 2])
87 << Asciify(data
[i
+ 0])
88 << Asciify(data
[i
+ 1])
89 << Asciify(data
[i
+ 2])
94 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
95 << AsciifyHigh(data
[i
+ 1]) << AsciifyLow(data
[i
+ 1])
97 << Asciify(data
[i
+ 0])
98 << Asciify(data
[i
+ 1])
103 << AsciifyHigh(data
[i
+ 0]) << AsciifyLow(data
[i
+ 0])
105 << Asciify(data
[i
+ 0])
112 template <MockReadWriteType type
>
113 void DumpMockReadWrite(const MockReadWrite
<type
>& r
) {
114 if (logging::LOG_INFO
< logging::GetMinLogLevel())
116 DVLOG(1) << "Async: " << (r
.mode
== ASYNC
)
117 << "\nResult: " << r
.result
;
118 DumpData(r
.data
, r
.data_len
);
119 const char* stop
= (r
.sequence_number
& MockRead::STOPLOOP
) ? " (STOP)" : "";
120 DVLOG(1) << "Stage: " << (r
.sequence_number
& ~MockRead::STOPLOOP
) << stop
121 << "\nTime: " << r
.time_stamp
.ToInternalValue();
126 MockConnect::MockConnect() : mode(ASYNC
), result(OK
) {
128 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
129 peer_addr
= IPEndPoint(ip
, 0);
132 MockConnect::MockConnect(IoMode io_mode
, int r
) : mode(io_mode
), result(r
) {
134 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
135 peer_addr
= IPEndPoint(ip
, 0);
138 MockConnect::MockConnect(IoMode io_mode
, int r
, IPEndPoint addr
) :
144 MockConnect::~MockConnect() {}
146 StaticSocketDataProvider::StaticSocketDataProvider()
155 StaticSocketDataProvider::StaticSocketDataProvider(MockRead
* reads
,
161 read_count_(reads_count
),
164 write_count_(writes_count
) {
167 StaticSocketDataProvider::~StaticSocketDataProvider() {}
169 const MockRead
& StaticSocketDataProvider::PeekRead() const {
170 DCHECK(!at_read_eof());
171 return reads_
[read_index_
];
174 const MockWrite
& StaticSocketDataProvider::PeekWrite() const {
175 DCHECK(!at_write_eof());
176 return writes_
[write_index_
];
179 const MockRead
& StaticSocketDataProvider::PeekRead(size_t index
) const {
180 DCHECK_LT(index
, read_count_
);
181 return reads_
[index
];
184 const MockWrite
& StaticSocketDataProvider::PeekWrite(size_t index
) const {
185 DCHECK_LT(index
, write_count_
);
186 return writes_
[index
];
189 MockRead
StaticSocketDataProvider::GetNextRead() {
190 DCHECK(!at_read_eof());
191 reads_
[read_index_
].time_stamp
= base::Time::Now();
192 return reads_
[read_index_
++];
195 MockWriteResult
StaticSocketDataProvider::OnWrite(const std::string
& data
) {
197 // Not using mock writes; succeed synchronously.
198 return MockWriteResult(SYNCHRONOUS
, data
.length());
200 DCHECK(!at_write_eof());
202 // Check that what we are writing matches the expectation.
203 // Then give the mocked return value.
204 MockWrite
* w
= &writes_
[write_index_
++];
205 w
->time_stamp
= base::Time::Now();
206 int result
= w
->result
;
208 // Note - we can simulate a partial write here. If the expected data
209 // is a match, but shorter than the write actually written, that is legal.
211 // Application writes "foobarbaz" (9 bytes)
212 // Expected write was "foo" (3 bytes)
213 // This is a success, and we return 3 to the application.
214 std::string
expected_data(w
->data
, w
->data_len
);
215 EXPECT_GE(data
.length(), expected_data
.length());
216 std::string
actual_data(data
.substr(0, w
->data_len
));
217 EXPECT_EQ(expected_data
, actual_data
);
218 if (expected_data
!= actual_data
)
219 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
221 result
= w
->data_len
;
223 return MockWriteResult(w
->mode
, result
);
226 void StaticSocketDataProvider::Reset() {
231 DynamicSocketDataProvider::DynamicSocketDataProvider()
232 : short_read_limit_(0),
233 allow_unconsumed_reads_(false) {
236 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
238 MockRead
DynamicSocketDataProvider::GetNextRead() {
240 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
241 MockRead result
= reads_
.front();
242 if (short_read_limit_
== 0 || result
.data_len
<= short_read_limit_
) {
245 result
.data_len
= short_read_limit_
;
246 reads_
.front().data
+= result
.data_len
;
247 reads_
.front().data_len
-= result
.data_len
;
252 void DynamicSocketDataProvider::Reset() {
256 void DynamicSocketDataProvider::SimulateRead(const char* data
,
257 const size_t length
) {
258 if (!allow_unconsumed_reads_
) {
259 EXPECT_TRUE(reads_
.empty()) << "Unconsumed read: " << reads_
.front().data
;
261 reads_
.push_back(MockRead(ASYNC
, data
, length
));
264 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode
, int result
)
265 : connect(mode
, result
),
266 next_proto_status(SSLClientSocket::kNextProtoUnsupported
),
267 was_npn_negotiated(false),
268 protocol_negotiated(kProtoUnknown
),
269 client_cert_sent(false),
270 cert_request_info(NULL
),
271 channel_id_sent(false) {
274 SSLSocketDataProvider::~SSLSocketDataProvider() {
277 void SSLSocketDataProvider::SetNextProto(NextProto proto
) {
278 was_npn_negotiated
= true;
279 next_proto_status
= SSLClientSocket::kNextProtoNegotiated
;
280 protocol_negotiated
= proto
;
281 next_proto
= SSLClientSocket::NextProtoToString(proto
);
284 DelayedSocketData::DelayedSocketData(
285 int write_delay
, MockRead
* reads
, size_t reads_count
,
286 MockWrite
* writes
, size_t writes_count
)
287 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
288 write_delay_(write_delay
),
289 read_in_progress_(false),
290 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
291 DCHECK_GE(write_delay_
, 0);
294 DelayedSocketData::DelayedSocketData(
295 const MockConnect
& connect
, int write_delay
, MockRead
* reads
,
296 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
297 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
298 write_delay_(write_delay
),
299 read_in_progress_(false),
300 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
301 DCHECK_GE(write_delay_
, 0);
302 set_connect_data(connect
);
305 DelayedSocketData::~DelayedSocketData() {
308 void DelayedSocketData::ForceNextRead() {
309 DCHECK(read_in_progress_
);
314 MockRead
DelayedSocketData::GetNextRead() {
315 MockRead out
= MockRead(ASYNC
, ERR_IO_PENDING
);
316 if (write_delay_
<= 0)
317 out
= StaticSocketDataProvider::GetNextRead();
318 read_in_progress_
= (out
.result
== ERR_IO_PENDING
);
322 MockWriteResult
DelayedSocketData::OnWrite(const std::string
& data
) {
323 MockWriteResult rv
= StaticSocketDataProvider::OnWrite(data
);
324 // Now that our write has completed, we can allow reads to continue.
325 if (!--write_delay_
&& read_in_progress_
)
326 MessageLoop::current()->PostDelayedTask(
328 base::Bind(&DelayedSocketData::CompleteRead
,
329 weak_factory_
.GetWeakPtr()),
330 base::TimeDelta::FromMilliseconds(100));
334 void DelayedSocketData::Reset() {
336 read_in_progress_
= false;
337 weak_factory_
.InvalidateWeakPtrs();
338 StaticSocketDataProvider::Reset();
341 void DelayedSocketData::CompleteRead() {
342 if (socket() && read_in_progress_
)
343 socket()->OnReadComplete(GetNextRead());
346 OrderedSocketData::OrderedSocketData(
347 MockRead
* reads
, size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
348 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
349 sequence_number_(0), loop_stop_stage_(0),
350 blocked_(false), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
353 OrderedSocketData::OrderedSocketData(
354 const MockConnect
& connect
,
355 MockRead
* reads
, size_t reads_count
,
356 MockWrite
* writes
, size_t writes_count
)
357 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
358 sequence_number_(0), loop_stop_stage_(0),
359 blocked_(false), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
360 set_connect_data(connect
);
363 void OrderedSocketData::EndLoop() {
364 // If we've already stopped the loop, don't do it again until we've advanced
365 // to the next sequence_number.
366 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
<< ": EndLoop()";
367 if (loop_stop_stage_
> 0) {
368 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
369 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) >
371 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
372 << ": Clearing stop index";
373 loop_stop_stage_
= 0;
378 // Record the sequence_number at which we stopped the loop.
379 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
380 << ": Posting Quit at read " << read_index();
381 loop_stop_stage_
= sequence_number_
;
384 MockRead
OrderedSocketData::GetNextRead() {
385 weak_factory_
.InvalidateWeakPtrs();
387 const MockRead
& next_read
= StaticSocketDataProvider::PeekRead();
388 if (next_read
.sequence_number
& MockRead::STOPLOOP
)
390 if ((next_read
.sequence_number
& ~MockRead::STOPLOOP
) <=
391 sequence_number_
++) {
392 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
393 << ": Read " << read_index();
394 DumpMockReadWrite(next_read
);
395 blocked_
= (next_read
.result
== ERR_IO_PENDING
);
396 return StaticSocketDataProvider::GetNextRead();
398 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
- 1
400 MockRead result
= MockRead(ASYNC
, ERR_IO_PENDING
);
401 DumpMockReadWrite(result
);
406 MockWriteResult
OrderedSocketData::OnWrite(const std::string
& data
) {
407 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
408 << ": Write " << write_index();
409 DumpMockReadWrite(PeekWrite());
412 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
413 // should probably fix the weirdness. One example is in SpdyStream,
414 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
415 // SYN_REPLY causes OnResponseReceived() to get called before
416 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
417 MessageLoop::current()->PostDelayedTask(
419 base::Bind(&OrderedSocketData::CompleteRead
,
420 weak_factory_
.GetWeakPtr()),
421 base::TimeDelta::FromMilliseconds(100));
423 return StaticSocketDataProvider::OnWrite(data
);
426 void OrderedSocketData::Reset() {
427 NET_TRACE(INFO
, " *** ") << "Stage "
428 << sequence_number_
<< ": Reset()";
429 sequence_number_
= 0;
430 loop_stop_stage_
= 0;
432 weak_factory_
.InvalidateWeakPtrs();
433 StaticSocketDataProvider::Reset();
436 void OrderedSocketData::CompleteRead() {
437 if (socket() && blocked_
) {
438 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
;
439 socket()->OnReadComplete(GetNextRead());
443 OrderedSocketData::~OrderedSocketData() {}
445 DeterministicSocketData::DeterministicSocketData(MockRead
* reads
,
446 size_t reads_count
, MockWrite
* writes
, size_t writes_count
)
447 : StaticSocketDataProvider(reads
, reads_count
, writes
, writes_count
),
451 stopping_sequence_number_(0),
453 print_debug_(false) {
454 VerifyCorrectSequenceNumbers(reads
, reads_count
, writes
, writes_count
);
457 DeterministicSocketData::~DeterministicSocketData() {}
459 void DeterministicSocketData::Run() {
462 // Continue to consume data until all data has run out, or the stopped_ flag
463 // has been set. Consuming data requires two separate operations -- running
464 // the tasks in the message loop, and explicitly invoking the read/write
465 // callbacks (simulating network I/O). We check our conditions between each,
466 // since they can change in either.
467 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
468 if (counter
% 2 == 0)
469 MessageLoop::current()->RunUntilIdle();
470 if (counter
% 2 == 1) {
475 // We're done consuming new data, but it is possible there are still some
476 // pending callbacks which we expect to complete before returning.
477 while (socket_
&& (socket_
->write_pending() || socket_
->read_pending()) &&
480 MessageLoop::current()->RunUntilIdle();
485 void DeterministicSocketData::RunFor(int steps
) {
490 void DeterministicSocketData::SetStop(int seq
) {
491 DCHECK_LT(sequence_number_
, seq
);
492 stopping_sequence_number_
= seq
;
496 void DeterministicSocketData::StopAfter(int seq
) {
497 SetStop(sequence_number_
+ seq
);
500 MockRead
DeterministicSocketData::GetNextRead() {
501 current_read_
= StaticSocketDataProvider::PeekRead();
502 EXPECT_LE(sequence_number_
, current_read_
.sequence_number
);
504 // Synchronous read while stopped is an error
505 if (stopped() && current_read_
.mode
== SYNCHRONOUS
) {
506 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
507 return MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
510 // Async read which will be called back in a future step.
511 if (sequence_number_
< current_read_
.sequence_number
) {
512 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
514 MockRead result
= MockRead(SYNCHRONOUS
, ERR_IO_PENDING
);
515 if (current_read_
.mode
== SYNCHRONOUS
) {
516 LOG(ERROR
) << "Unable to perform synchronous read: "
517 << current_read_
.sequence_number
518 << " at stage: " << sequence_number_
;
519 result
= MockRead(SYNCHRONOUS
, ERR_UNEXPECTED
);
522 DumpMockReadWrite(result
);
526 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
527 << ": Read " << read_index();
529 DumpMockReadWrite(current_read_
);
531 // Increment the sequence number if IO is complete
532 if (current_read_
.mode
== SYNCHRONOUS
)
535 DCHECK_NE(ERR_IO_PENDING
, current_read_
.result
);
536 StaticSocketDataProvider::GetNextRead();
538 return current_read_
;
541 MockWriteResult
DeterministicSocketData::OnWrite(const std::string
& data
) {
542 const MockWrite
& next_write
= StaticSocketDataProvider::PeekWrite();
543 current_write_
= next_write
;
545 // Synchronous write while stopped is an error
546 if (stopped() && next_write
.mode
== SYNCHRONOUS
) {
547 LOG(ERROR
) << "Unable to perform synchronous IO while stopped";
548 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
551 // Async write which will be called back in a future step.
552 if (sequence_number_
< next_write
.sequence_number
) {
553 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
555 if (next_write
.mode
== SYNCHRONOUS
) {
556 LOG(ERROR
) << "Unable to perform synchronous write: "
557 << next_write
.sequence_number
<< " at stage: " << sequence_number_
;
558 return MockWriteResult(SYNCHRONOUS
, ERR_UNEXPECTED
);
561 NET_TRACE(INFO
, " *** ") << "Stage " << sequence_number_
562 << ": Write " << write_index();
566 DumpMockReadWrite(next_write
);
568 // Move to the next step if I/O is synchronous, since the operation will
569 // complete when this method returns.
570 if (next_write
.mode
== SYNCHRONOUS
)
573 // This is either a sync write for this step, or an async write.
574 return StaticSocketDataProvider::OnWrite(data
);
577 void DeterministicSocketData::Reset() {
578 NET_TRACE(INFO
, " *** ") << "Stage "
579 << sequence_number_
<< ": Reset()";
580 sequence_number_
= 0;
581 StaticSocketDataProvider::Reset();
585 void DeterministicSocketData::InvokeCallbacks() {
586 if (socket_
&& socket_
->write_pending() &&
587 (current_write().sequence_number
== sequence_number())) {
588 socket_
->CompleteWrite();
592 if (socket_
&& socket_
->read_pending() &&
593 (current_read().sequence_number
== sequence_number())) {
594 socket_
->CompleteRead();
600 void DeterministicSocketData::NextStep() {
601 // Invariant: Can never move *past* the stopping step.
602 DCHECK_LT(sequence_number_
, stopping_sequence_number_
);
604 if (sequence_number_
== stopping_sequence_number_
)
608 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
609 MockRead
* reads
, size_t reads_count
,
610 MockWrite
* writes
, size_t writes_count
) {
614 while (read
< reads_count
|| write
< writes_count
) {
615 // Check to see that we have a read or write at the expected
617 if (read
< reads_count
&& reads
[read
].sequence_number
== expected
) {
622 if (write
< writes_count
&& writes
[write
].sequence_number
== expected
) {
627 NOTREACHED() << "Missing sequence number: " << expected
;
630 DCHECK_EQ(read
, reads_count
);
631 DCHECK_EQ(write
, writes_count
);
634 MockClientSocketFactory::MockClientSocketFactory() {}
636 MockClientSocketFactory::~MockClientSocketFactory() {}
638 void MockClientSocketFactory::AddSocketDataProvider(
639 SocketDataProvider
* data
) {
640 mock_data_
.Add(data
);
643 void MockClientSocketFactory::AddSSLSocketDataProvider(
644 SSLSocketDataProvider
* data
) {
645 mock_ssl_data_
.Add(data
);
648 void MockClientSocketFactory::ResetNextMockIndexes() {
649 mock_data_
.ResetNextIndex();
650 mock_ssl_data_
.ResetNextIndex();
653 DatagramClientSocket
* MockClientSocketFactory::CreateDatagramClientSocket(
654 DatagramSocket::BindType bind_type
,
655 const RandIntCallback
& rand_int_cb
,
656 net::NetLog
* net_log
,
657 const net::NetLog::Source
& source
) {
658 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
659 MockUDPClientSocket
* socket
= new MockUDPClientSocket(data_provider
, net_log
);
660 data_provider
->set_socket(socket
);
664 StreamSocket
* MockClientSocketFactory::CreateTransportClientSocket(
665 const AddressList
& addresses
,
666 net::NetLog
* net_log
,
667 const net::NetLog::Source
& source
) {
668 SocketDataProvider
* data_provider
= mock_data_
.GetNext();
669 MockTCPClientSocket
* socket
=
670 new MockTCPClientSocket(addresses
, net_log
, data_provider
);
671 data_provider
->set_socket(socket
);
675 SSLClientSocket
* MockClientSocketFactory::CreateSSLClientSocket(
676 ClientSocketHandle
* transport_socket
,
677 const HostPortPair
& host_and_port
,
678 const SSLConfig
& ssl_config
,
679 const SSLClientSocketContext
& context
) {
680 MockSSLClientSocket
* socket
=
681 new MockSSLClientSocket(transport_socket
, host_and_port
, ssl_config
,
682 mock_ssl_data_
.GetNext());
686 void MockClientSocketFactory::ClearSSLSessionCache() {
689 const char MockClientSocket::kTlsUnique
[] = "MOCK_TLSUNIQ";
691 MockClientSocket::MockClientSocket(net::NetLog
* net_log
)
692 : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
694 net_log_(BoundNetLog::Make(net_log
, net::NetLog::SOURCE_NONE
)) {
696 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip
));
697 peer_addr_
= IPEndPoint(ip
, 0);
700 bool MockClientSocket::SetReceiveBufferSize(int32 size
) {
704 bool MockClientSocket::SetSendBufferSize(int32 size
) {
708 void MockClientSocket::Disconnect() {
712 bool MockClientSocket::IsConnected() const {
716 bool MockClientSocket::IsConnectedAndIdle() const {
720 int MockClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
721 *address
= peer_addr_
;
725 int MockClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
727 bool rv
= ParseIPLiteralToNumber("192.0.2.33", &ip
);
729 *address
= IPEndPoint(ip
, 123);
733 const BoundNetLog
& MockClientSocket::NetLog() const {
737 void MockClientSocket::GetSSLCertRequestInfo(
738 SSLCertRequestInfo
* cert_request_info
) {
741 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece
& label
,
743 const base::StringPiece
& context
,
745 unsigned int outlen
) {
746 memset(out
, 'A', outlen
);
750 int MockClientSocket::GetTLSUniqueChannelBinding(std::string
* out
) {
751 out
->assign(MockClientSocket::kTlsUnique
);
755 ServerBoundCertService
* MockClientSocket::GetServerBoundCertService() const {
760 SSLClientSocket::NextProtoStatus
761 MockClientSocket::GetNextProto(std::string
* proto
, std::string
* server_protos
) {
763 server_protos
->clear();
764 return SSLClientSocket::kNextProtoUnsupported
;
767 MockClientSocket::~MockClientSocket() {}
769 void MockClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
771 MessageLoop::current()->PostTask(FROM_HERE
,
772 base::Bind(&MockClientSocket::RunCallback
, weak_factory_
.GetWeakPtr(),
776 void MockClientSocket::RunCallback(const net::CompletionCallback
& callback
,
778 if (!callback
.is_null())
779 callback
.Run(result
);
782 MockTCPClientSocket::MockTCPClientSocket(const AddressList
& addresses
,
783 net::NetLog
* net_log
,
784 SocketDataProvider
* data
)
785 : MockClientSocket(net_log
),
786 addresses_(addresses
),
790 read_data_(SYNCHRONOUS
, ERR_UNEXPECTED
),
791 need_read_data_(true),
792 peer_closed_connection_(false),
795 was_used_to_convey_data_(false) {
797 peer_addr_
= data
->connect_data().peer_addr
;
801 MockTCPClientSocket::~MockTCPClientSocket() {}
803 int MockTCPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
804 const CompletionCallback
& callback
) {
806 return ERR_UNEXPECTED
;
808 // If the buffer is already in use, a read is already in progress!
809 DCHECK(pending_buf_
== NULL
);
811 // Store our async IO data.
813 pending_buf_len_
= buf_len
;
814 pending_callback_
= callback
;
816 if (need_read_data_
) {
817 read_data_
= data_
->GetNextRead();
818 if (read_data_
.result
== ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
) {
819 // This MockRead is just a marker to instruct us to set
820 // peer_closed_connection_. Skip it and get the next one.
821 read_data_
= data_
->GetNextRead();
822 peer_closed_connection_
= true;
824 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
825 // to complete the async IO manually later (via OnReadComplete).
826 if (read_data_
.result
== ERR_IO_PENDING
) {
827 // We need to be using async IO in this case.
828 DCHECK(!callback
.is_null());
829 return ERR_IO_PENDING
;
831 need_read_data_
= false;
834 return CompleteRead();
837 int MockTCPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
838 const CompletionCallback
& callback
) {
840 DCHECK_GT(buf_len
, 0);
843 return ERR_UNEXPECTED
;
845 std::string
data(buf
->data(), buf_len
);
846 MockWriteResult write_result
= data_
->OnWrite(data
);
848 was_used_to_convey_data_
= true;
850 if (write_result
.mode
== ASYNC
) {
851 RunCallbackAsync(callback
, write_result
.result
);
852 return ERR_IO_PENDING
;
855 return write_result
.result
;
858 int MockTCPClientSocket::Connect(const CompletionCallback
& callback
) {
862 peer_closed_connection_
= false;
863 if (data_
->connect_data().mode
== ASYNC
) {
864 RunCallbackAsync(callback
, data_
->connect_data().result
);
865 return ERR_IO_PENDING
;
867 return data_
->connect_data().result
;
870 void MockTCPClientSocket::Disconnect() {
871 MockClientSocket::Disconnect();
872 pending_callback_
.Reset();
875 bool MockTCPClientSocket::IsConnected() const {
876 return connected_
&& !peer_closed_connection_
;
879 bool MockTCPClientSocket::IsConnectedAndIdle() const {
880 return IsConnected();
883 int MockTCPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
884 if (addresses_
.empty())
885 return MockClientSocket::GetPeerAddress(address
);
887 *address
= addresses_
[0];
891 bool MockTCPClientSocket::WasEverUsed() const {
892 return was_used_to_convey_data_
;
895 bool MockTCPClientSocket::UsingTCPFastOpen() const {
899 int64
MockTCPClientSocket::NumBytesRead() const {
900 return num_bytes_read_
;
903 base::TimeDelta
MockTCPClientSocket::GetConnectTimeMicros() const {
905 static const base::TimeDelta kTestingConnectTimeMicros
=
906 base::TimeDelta::FromMicroseconds(20);
907 return kTestingConnectTimeMicros
;
910 bool MockTCPClientSocket::WasNpnNegotiated() const {
914 bool MockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
918 void MockTCPClientSocket::OnReadComplete(const MockRead
& data
) {
919 // There must be a read pending.
920 DCHECK(pending_buf_
);
921 // You can't complete a read with another ERR_IO_PENDING status code.
922 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
923 // Since we've been waiting for data, need_read_data_ should be true.
924 DCHECK(need_read_data_
);
927 need_read_data_
= false;
929 // The caller is simulating that this IO completes right now. Don't
930 // let CompleteRead() schedule a callback.
931 read_data_
.mode
= SYNCHRONOUS
;
933 CompletionCallback callback
= pending_callback_
;
934 int rv
= CompleteRead();
935 RunCallback(callback
, rv
);
938 int MockTCPClientSocket::CompleteRead() {
939 DCHECK(pending_buf_
);
940 DCHECK(pending_buf_len_
> 0);
942 was_used_to_convey_data_
= true;
944 // Save the pending async IO data and reset our |pending_| state.
945 IOBuffer
* buf
= pending_buf_
;
946 int buf_len
= pending_buf_len_
;
947 CompletionCallback callback
= pending_callback_
;
949 pending_buf_len_
= 0;
950 pending_callback_
.Reset();
952 int result
= read_data_
.result
;
953 DCHECK(result
!= ERR_IO_PENDING
);
955 if (read_data_
.data
) {
956 if (read_data_
.data_len
- read_offset_
> 0) {
957 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
958 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
959 read_offset_
+= result
;
960 num_bytes_read_
+= 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(net_log
),
981 write_pending_(false),
986 read_pending_(false),
988 was_used_to_convey_data_(false) {
989 peer_addr_
= data
->connect_data().peer_addr
;
992 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
994 void DeterministicMockTCPClientSocket::CompleteWrite() {
995 was_used_to_convey_data_
= true;
996 write_pending_
= false;
997 write_callback_
.Run(write_result_
);
1000 int DeterministicMockTCPClientSocket::CompleteRead() {
1001 DCHECK_GT(read_buf_len_
, 0);
1002 DCHECK_LE(read_data_
.data_len
, read_buf_len_
);
1005 was_used_to_convey_data_
= true;
1007 if (read_data_
.result
== ERR_IO_PENDING
)
1008 read_data_
= data_
->GetNextRead();
1009 DCHECK_NE(ERR_IO_PENDING
, read_data_
.result
);
1010 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1011 // the callback. Therefore we don't even bother to check it.
1012 int result
= read_data_
.result
;
1014 if (read_data_
.data_len
> 0) {
1015 DCHECK(read_data_
.data
);
1016 result
= std::min(read_buf_len_
, read_data_
.data_len
);
1017 memcpy(read_buf_
->data(), read_data_
.data
, result
);
1020 if (read_pending_
) {
1021 read_pending_
= false;
1022 read_callback_
.Run(result
);
1028 int DeterministicMockTCPClientSocket::Write(
1029 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1031 DCHECK_GT(buf_len
, 0);
1034 return ERR_UNEXPECTED
;
1036 std::string
data(buf
->data(), buf_len
);
1037 MockWriteResult write_result
= data_
->OnWrite(data
);
1039 if (write_result
.mode
== ASYNC
) {
1040 write_callback_
= callback
;
1041 write_result_
= write_result
.result
;
1042 DCHECK(!write_callback_
.is_null());
1043 write_pending_
= true;
1044 return ERR_IO_PENDING
;
1047 was_used_to_convey_data_
= true;
1048 write_pending_
= false;
1049 return write_result
.result
;
1052 int DeterministicMockTCPClientSocket::Read(
1053 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
1055 return ERR_UNEXPECTED
;
1057 read_data_
= data_
->GetNextRead();
1058 // The buffer should always be big enough to contain all the MockRead data. To
1059 // use small buffers, split the data into multiple MockReads.
1060 DCHECK_LE(read_data_
.data_len
, buf_len
);
1063 read_buf_len_
= buf_len
;
1064 read_callback_
= callback
;
1066 if (read_data_
.mode
== ASYNC
|| (read_data_
.result
== ERR_IO_PENDING
)) {
1067 read_pending_
= true;
1068 DCHECK(!read_callback_
.is_null());
1069 return ERR_IO_PENDING
;
1072 was_used_to_convey_data_
= true;
1073 return CompleteRead();
1076 // TODO(erikchen): Support connect sequencing.
1077 int DeterministicMockTCPClientSocket::Connect(
1078 const CompletionCallback
& callback
) {
1082 if (data_
->connect_data().mode
== ASYNC
) {
1083 RunCallbackAsync(callback
, data_
->connect_data().result
);
1084 return ERR_IO_PENDING
;
1086 return data_
->connect_data().result
;
1089 void DeterministicMockTCPClientSocket::Disconnect() {
1090 MockClientSocket::Disconnect();
1093 bool DeterministicMockTCPClientSocket::IsConnected() const {
1097 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1098 return IsConnected();
1101 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1102 return was_used_to_convey_data_
;
1105 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1109 int64
DeterministicMockTCPClientSocket::NumBytesRead() const {
1113 base::TimeDelta
DeterministicMockTCPClientSocket::GetConnectTimeMicros() const {
1114 return base::TimeDelta::FromMicroseconds(-1);
1117 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1121 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
1125 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead
& data
) {}
1128 void MockSSLClientSocket::ConnectCallback(
1129 MockSSLClientSocket
*ssl_client_socket
,
1130 const CompletionCallback
& callback
,
1133 ssl_client_socket
->connected_
= true;
1137 MockSSLClientSocket::MockSSLClientSocket(
1138 ClientSocketHandle
* transport_socket
,
1139 const HostPortPair
& host_port_pair
,
1140 const SSLConfig
& ssl_config
,
1141 SSLSocketDataProvider
* data
)
1142 : MockClientSocket(transport_socket
->socket()->NetLog().net_log()),
1143 transport_(transport_socket
),
1145 is_npn_state_set_(false),
1146 new_npn_value_(false),
1147 is_protocol_negotiated_set_(false),
1148 protocol_negotiated_(kProtoUnknown
) {
1150 peer_addr_
= data
->connect
.peer_addr
;
1153 MockSSLClientSocket::~MockSSLClientSocket() {
1157 int MockSSLClientSocket::Read(IOBuffer
* buf
, int buf_len
,
1158 const CompletionCallback
& callback
) {
1159 return transport_
->socket()->Read(buf
, buf_len
, callback
);
1162 int MockSSLClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1163 const CompletionCallback
& callback
) {
1164 return transport_
->socket()->Write(buf
, buf_len
, callback
);
1167 int MockSSLClientSocket::Connect(const CompletionCallback
& callback
) {
1168 int rv
= transport_
->socket()->Connect(
1169 base::Bind(&ConnectCallback
, base::Unretained(this), callback
));
1171 if (data_
->connect
.result
== OK
)
1173 if (data_
->connect
.mode
== ASYNC
) {
1174 RunCallbackAsync(callback
, data_
->connect
.result
);
1175 return ERR_IO_PENDING
;
1177 return data_
->connect
.result
;
1182 void MockSSLClientSocket::Disconnect() {
1183 MockClientSocket::Disconnect();
1184 if (transport_
->socket() != NULL
)
1185 transport_
->socket()->Disconnect();
1188 bool MockSSLClientSocket::IsConnected() const {
1189 return transport_
->socket()->IsConnected();
1192 bool MockSSLClientSocket::WasEverUsed() const {
1193 return transport_
->socket()->WasEverUsed();
1196 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1197 return transport_
->socket()->UsingTCPFastOpen();
1200 int64
MockSSLClientSocket::NumBytesRead() const {
1204 int MockSSLClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1205 return transport_
->socket()->GetPeerAddress(address
);
1208 base::TimeDelta
MockSSLClientSocket::GetConnectTimeMicros() const {
1209 return base::TimeDelta::FromMicroseconds(-1);
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)) {
1293 MockUDPClientSocket::~MockUDPClientSocket() {}
1295 int MockUDPClientSocket::Read(IOBuffer
* buf
, int buf_len
,
1296 const CompletionCallback
& callback
) {
1298 return ERR_UNEXPECTED
;
1300 // If the buffer is already in use, a read is already in progress!
1301 DCHECK(pending_buf_
== NULL
);
1303 // Store our async IO data.
1305 pending_buf_len_
= buf_len
;
1306 pending_callback_
= callback
;
1308 if (need_read_data_
) {
1309 read_data_
= data_
->GetNextRead();
1310 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1311 // to complete the async IO manually later (via OnReadComplete).
1312 if (read_data_
.result
== ERR_IO_PENDING
) {
1313 // We need to be using async IO in this case.
1314 DCHECK(!callback
.is_null());
1315 return ERR_IO_PENDING
;
1317 need_read_data_
= false;
1320 return CompleteRead();
1323 int MockUDPClientSocket::Write(IOBuffer
* buf
, int buf_len
,
1324 const CompletionCallback
& callback
) {
1326 DCHECK_GT(buf_len
, 0);
1329 return ERR_UNEXPECTED
;
1331 std::string
data(buf
->data(), buf_len
);
1332 MockWriteResult write_result
= data_
->OnWrite(data
);
1334 if (write_result
.mode
== ASYNC
) {
1335 RunCallbackAsync(callback
, write_result
.result
);
1336 return ERR_IO_PENDING
;
1338 return write_result
.result
;
1341 bool MockUDPClientSocket::SetReceiveBufferSize(int32 size
) {
1345 bool MockUDPClientSocket::SetSendBufferSize(int32 size
) {
1349 void MockUDPClientSocket::Close() {
1353 int MockUDPClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
1358 int MockUDPClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
1363 const BoundNetLog
& MockUDPClientSocket::NetLog() const {
1367 int MockUDPClientSocket::Connect(const IPEndPoint
& address
) {
1372 void MockUDPClientSocket::OnReadComplete(const MockRead
& data
) {
1373 // There must be a read pending.
1374 DCHECK(pending_buf_
);
1375 // You can't complete a read with another ERR_IO_PENDING status code.
1376 DCHECK_NE(ERR_IO_PENDING
, data
.result
);
1377 // Since we've been waiting for data, need_read_data_ should be true.
1378 DCHECK(need_read_data_
);
1381 need_read_data_
= false;
1383 // The caller is simulating that this IO completes right now. Don't
1384 // let CompleteRead() schedule a callback.
1385 read_data_
.mode
= SYNCHRONOUS
;
1387 net::CompletionCallback callback
= pending_callback_
;
1388 int rv
= CompleteRead();
1389 RunCallback(callback
, rv
);
1392 int MockUDPClientSocket::CompleteRead() {
1393 DCHECK(pending_buf_
);
1394 DCHECK(pending_buf_len_
> 0);
1396 // Save the pending async IO data and reset our |pending_| state.
1397 IOBuffer
* buf
= pending_buf_
;
1398 int buf_len
= pending_buf_len_
;
1399 CompletionCallback callback
= pending_callback_
;
1400 pending_buf_
= NULL
;
1401 pending_buf_len_
= 0;
1402 pending_callback_
.Reset();
1404 int result
= read_data_
.result
;
1405 DCHECK(result
!= ERR_IO_PENDING
);
1407 if (read_data_
.data
) {
1408 if (read_data_
.data_len
- read_offset_
> 0) {
1409 result
= std::min(buf_len
, read_data_
.data_len
- read_offset_
);
1410 memcpy(buf
->data(), read_data_
.data
+ read_offset_
, result
);
1411 read_offset_
+= result
;
1412 if (read_offset_
== read_data_
.data_len
) {
1413 need_read_data_
= true;
1421 if (read_data_
.mode
== ASYNC
) {
1422 DCHECK(!callback
.is_null());
1423 RunCallbackAsync(callback
, result
);
1424 return ERR_IO_PENDING
;
1429 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback
& callback
,
1431 MessageLoop::current()->PostTask(
1433 base::Bind(&MockUDPClientSocket::RunCallback
, weak_factory_
.GetWeakPtr(),
1437 void MockUDPClientSocket::RunCallback(const CompletionCallback
& callback
,
1439 if (!callback
.is_null())
1440 callback
.Run(result
);
1443 TestSocketRequest::TestSocketRequest(
1444 std::vector
<TestSocketRequest
*>* request_order
, size_t* completion_count
)
1445 : request_order_(request_order
),
1446 completion_count_(completion_count
),
1447 ALLOW_THIS_IN_INITIALIZER_LIST(callback_(
1448 base::Bind(&TestSocketRequest::OnComplete
, base::Unretained(this)))) {
1449 DCHECK(request_order
);
1450 DCHECK(completion_count
);
1453 TestSocketRequest::~TestSocketRequest() {
1456 void TestSocketRequest::OnComplete(int result
) {
1458 (*completion_count_
)++;
1459 request_order_
->push_back(this);
1463 const int ClientSocketPoolTest::kIndexOutOfBounds
= -1;
1466 const int ClientSocketPoolTest::kRequestNotFound
= -2;
1468 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1469 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1471 int ClientSocketPoolTest::GetOrderOfRequest(size_t index
) const {
1473 if (index
>= requests_
.size())
1474 return kIndexOutOfBounds
;
1476 for (size_t i
= 0; i
< request_order_
.size(); i
++)
1477 if (requests_
[index
] == request_order_
[i
])
1480 return kRequestNotFound
;
1483 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive
) {
1484 ScopedVector
<TestSocketRequest
>::iterator i
;
1485 for (i
= requests_
.begin(); i
!= requests_
.end(); ++i
) {
1486 if ((*i
)->handle()->is_initialized()) {
1487 if (keep_alive
== NO_KEEP_ALIVE
)
1488 (*i
)->handle()->socket()->Disconnect();
1489 (*i
)->handle()->Reset();
1490 MessageLoop::current()->RunUntilIdle();
1497 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive
) {
1500 released_one
= ReleaseOneConnection(keep_alive
);
1501 } while (released_one
);
1504 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1505 StreamSocket
* socket
,
1506 ClientSocketHandle
* handle
,
1507 const CompletionCallback
& callback
)
1510 user_callback_(callback
) {
1513 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1515 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1516 int rv
= socket_
->Connect(base::Bind(&MockConnectJob::OnConnect
,
1517 base::Unretained(this)));
1519 user_callback_
.Reset();
1525 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1526 const ClientSocketHandle
* handle
) {
1527 if (handle
!= handle_
)
1531 user_callback_
.Reset();
1535 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv
) {
1539 handle_
->set_socket(socket_
.release());
1546 if (!user_callback_
.is_null()) {
1547 CompletionCallback callback
= user_callback_
;
1548 user_callback_
.Reset();
1553 MockTransportClientSocketPool::MockTransportClientSocketPool(
1555 int max_sockets_per_group
,
1556 ClientSocketPoolHistograms
* histograms
,
1557 ClientSocketFactory
* socket_factory
)
1558 : TransportClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1560 client_socket_factory_(socket_factory
),
1565 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1567 int MockTransportClientSocketPool::RequestSocket(
1568 const std::string
& group_name
, const void* socket_params
,
1569 RequestPriority priority
, ClientSocketHandle
* handle
,
1570 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1571 StreamSocket
* socket
= client_socket_factory_
->CreateTransportClientSocket(
1572 AddressList(), net_log
.net_log(), net::NetLog::Source());
1573 MockConnectJob
* job
= new MockConnectJob(socket
, handle
, callback
);
1574 job_list_
.push_back(job
);
1575 handle
->set_pool_id(1);
1576 return job
->Connect();
1579 void MockTransportClientSocketPool::CancelRequest(const std::string
& group_name
,
1580 ClientSocketHandle
* handle
) {
1581 std::vector
<MockConnectJob
*>::iterator i
;
1582 for (i
= job_list_
.begin(); i
!= job_list_
.end(); ++i
) {
1583 if ((*i
)->CancelHandle(handle
)) {
1590 void MockTransportClientSocketPool::ReleaseSocket(const std::string
& group_name
,
1591 StreamSocket
* socket
, int id
) {
1597 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1599 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1601 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1602 DeterministicSocketData
* data
) {
1603 mock_data_
.Add(data
);
1606 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1607 SSLSocketDataProvider
* data
) {
1608 mock_ssl_data_
.Add(data
);
1611 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1612 mock_data_
.ResetNextIndex();
1613 mock_ssl_data_
.ResetNextIndex();
1616 MockSSLClientSocket
* DeterministicMockClientSocketFactory::
1617 GetMockSSLClientSocket(size_t index
) const {
1618 DCHECK_LT(index
, ssl_client_sockets_
.size());
1619 return ssl_client_sockets_
[index
];
1622 DatagramClientSocket
*
1623 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1624 DatagramSocket::BindType bind_type
,
1625 const RandIntCallback
& rand_int_cb
,
1626 net::NetLog
* net_log
,
1627 const NetLog::Source
& source
) {
1632 StreamSocket
* DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1633 const AddressList
& addresses
,
1634 net::NetLog
* net_log
,
1635 const net::NetLog::Source
& source
) {
1636 DeterministicSocketData
* data_provider
= mock_data().GetNext();
1637 DeterministicMockTCPClientSocket
* socket
=
1638 new DeterministicMockTCPClientSocket(net_log
, data_provider
);
1639 data_provider
->set_socket(socket
->AsWeakPtr());
1640 tcp_client_sockets().push_back(socket
);
1644 SSLClientSocket
* DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1645 ClientSocketHandle
* transport_socket
,
1646 const HostPortPair
& host_and_port
,
1647 const SSLConfig
& ssl_config
,
1648 const SSLClientSocketContext
& context
) {
1649 MockSSLClientSocket
* socket
=
1650 new MockSSLClientSocket(transport_socket
, host_and_port
, ssl_config
,
1651 mock_ssl_data_
.GetNext());
1652 ssl_client_sockets_
.push_back(socket
);
1656 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1659 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1661 int max_sockets_per_group
,
1662 ClientSocketPoolHistograms
* histograms
,
1663 TransportClientSocketPool
* transport_pool
)
1664 : SOCKSClientSocketPool(max_sockets
, max_sockets_per_group
, histograms
,
1665 NULL
, transport_pool
, NULL
),
1666 transport_pool_(transport_pool
) {
1669 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1671 int MockSOCKSClientSocketPool::RequestSocket(
1672 const std::string
& group_name
, const void* socket_params
,
1673 RequestPriority priority
, ClientSocketHandle
* handle
,
1674 const CompletionCallback
& callback
, const BoundNetLog
& net_log
) {
1675 return transport_pool_
->RequestSocket(
1676 group_name
, socket_params
, priority
, handle
, callback
, net_log
);
1679 void MockSOCKSClientSocketPool::CancelRequest(
1680 const std::string
& group_name
,
1681 ClientSocketHandle
* handle
) {
1682 return transport_pool_
->CancelRequest(group_name
, handle
);
1685 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string
& group_name
,
1686 StreamSocket
* socket
, int id
) {
1687 return transport_pool_
->ReleaseSocket(group_name
, socket
, id
);
1690 const char kSOCKS5GreetRequest
[] = { 0x05, 0x01, 0x00 };
1691 const int kSOCKS5GreetRequestLength
= arraysize(kSOCKS5GreetRequest
);
1693 const char kSOCKS5GreetResponse
[] = { 0x05, 0x00 };
1694 const int kSOCKS5GreetResponseLength
= arraysize(kSOCKS5GreetResponse
);
1696 const char kSOCKS5OkRequest
[] =
1697 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1698 const int kSOCKS5OkRequestLength
= arraysize(kSOCKS5OkRequest
);
1700 const char kSOCKS5OkResponse
[] =
1701 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1702 const int kSOCKS5OkResponseLength
= arraysize(kSOCKS5OkResponse
);