move SK_DISABLE_DITHER_32BIT_GRADIENT from SkUserConfig.h to skia.gyp, so we can...
[chromium-blink-merge.git] / net / socket / socket_test_util.cc
blob590a56d34700309083e09f13951b50c708a9934a
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"
7 #include <algorithm>
8 #include <vector>
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.
30 #if 0
31 #define NET_TRACE(level, s) DLOG(level) << s << __FUNCTION__ << "() "
32 #else
33 #define NET_TRACE(level, s) EAT_STREAM_PARAMETERS
34 #endif
36 namespace net {
38 namespace {
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))
52 return '.';
53 return x;
56 void DumpData(const char* data, int data_len) {
57 if (logging::LOG_INFO < logging::GetMinLogLevel())
58 return;
59 DVLOG(1) << "Length: " << data_len;
60 const char* pfx = "Data: ";
61 if (!data || (data_len <= 0)) {
62 DVLOG(1) << pfx << "<None>";
63 } else {
64 int i;
65 for (i = 0; i <= (data_len - 4); i += 4) {
66 DVLOG(1) << pfx
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])
71 << " '"
72 << Asciify(data[i + 0])
73 << Asciify(data[i + 1])
74 << Asciify(data[i + 2])
75 << Asciify(data[i + 3])
76 << "'";
77 pfx = " ";
79 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
80 switch (data_len - i) {
81 case 3:
82 DVLOG(1) << pfx
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])
86 << " '"
87 << Asciify(data[i + 0])
88 << Asciify(data[i + 1])
89 << Asciify(data[i + 2])
90 << " '";
91 break;
92 case 2:
93 DVLOG(1) << pfx
94 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
95 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
96 << " '"
97 << Asciify(data[i + 0])
98 << Asciify(data[i + 1])
99 << " '";
100 break;
101 case 1:
102 DVLOG(1) << pfx
103 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
104 << " '"
105 << Asciify(data[i + 0])
106 << " '";
107 break;
112 template <MockReadWriteType type>
113 void DumpMockReadWrite(const MockReadWrite<type>& r) {
114 if (logging::LOG_INFO < logging::GetMinLogLevel())
115 return;
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();
124 } // namespace
126 MockConnect::MockConnect() : mode(ASYNC), result(OK) {
127 IPAddressNumber ip;
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) {
133 IPAddressNumber ip;
134 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
135 peer_addr = IPEndPoint(ip, 0);
138 MockConnect::MockConnect(IoMode io_mode, int r, IPEndPoint addr) :
139 mode(io_mode),
140 result(r),
141 peer_addr(addr) {
144 MockConnect::~MockConnect() {}
146 StaticSocketDataProvider::StaticSocketDataProvider()
147 : reads_(NULL),
148 read_index_(0),
149 read_count_(0),
150 writes_(NULL),
151 write_index_(0),
152 write_count_(0) {
155 StaticSocketDataProvider::StaticSocketDataProvider(MockRead* reads,
156 size_t reads_count,
157 MockWrite* writes,
158 size_t writes_count)
159 : reads_(reads),
160 read_index_(0),
161 read_count_(reads_count),
162 writes_(writes),
163 write_index_(0),
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) {
196 if (!writes_) {
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;
207 if (w->data) {
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.
210 // Example:
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);
220 if (result == OK)
221 result = w->data_len;
223 return MockWriteResult(w->mode, result);
226 void StaticSocketDataProvider::Reset() {
227 read_index_ = 0;
228 write_index_ = 0;
231 DynamicSocketDataProvider::DynamicSocketDataProvider()
232 : short_read_limit_(0),
233 allow_unconsumed_reads_(false) {
236 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
238 MockRead DynamicSocketDataProvider::GetNextRead() {
239 if (reads_.empty())
240 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
241 MockRead result = reads_.front();
242 if (short_read_limit_ == 0 || result.data_len <= short_read_limit_) {
243 reads_.pop_front();
244 } else {
245 result.data_len = short_read_limit_;
246 reads_.front().data += result.data_len;
247 reads_.front().data_len -= result.data_len;
249 return result;
252 void DynamicSocketDataProvider::Reset() {
253 reads_.clear();
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_);
310 write_delay_ = 0;
311 CompleteRead();
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);
319 return out;
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(
327 FROM_HERE,
328 base::Bind(&DelayedSocketData::CompleteRead,
329 weak_factory_.GetWeakPtr()),
330 base::TimeDelta::FromMilliseconds(100));
331 return rv;
334 void DelayedSocketData::Reset() {
335 set_socket(NULL);
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) >
370 loop_stop_stage_) {
371 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
372 << ": Clearing stop index";
373 loop_stop_stage_ = 0;
374 } else {
375 return;
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();
386 blocked_ = false;
387 const MockRead& next_read = StaticSocketDataProvider::PeekRead();
388 if (next_read.sequence_number & MockRead::STOPLOOP)
389 EndLoop();
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
399 << ": I/O Pending";
400 MockRead result = MockRead(ASYNC, ERR_IO_PENDING);
401 DumpMockReadWrite(result);
402 blocked_ = true;
403 return result;
406 MockWriteResult OrderedSocketData::OnWrite(const std::string& data) {
407 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
408 << ": Write " << write_index();
409 DumpMockReadWrite(PeekWrite());
410 ++sequence_number_;
411 if (blocked_) {
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(
418 FROM_HERE,
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;
431 set_socket(NULL);
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),
448 sequence_number_(0),
449 current_read_(),
450 current_write_(),
451 stopping_sequence_number_(0),
452 stopped_(false),
453 print_debug_(false) {
454 VerifyCorrectSequenceNumbers(reads, reads_count, writes, writes_count);
457 DeterministicSocketData::~DeterministicSocketData() {}
459 void DeterministicSocketData::Run() {
460 SetStopped(false);
461 int counter = 0;
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) {
471 InvokeCallbacks();
473 counter++;
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()) &&
478 !stopped()) {
479 InvokeCallbacks();
480 MessageLoop::current()->RunUntilIdle();
482 SetStopped(false);
485 void DeterministicSocketData::RunFor(int steps) {
486 StopAfter(steps);
487 Run();
490 void DeterministicSocketData::SetStop(int seq) {
491 DCHECK_LT(sequence_number_, seq);
492 stopping_sequence_number_ = seq;
493 stopped_ = false;
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_
513 << ": I/O Pending";
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);
521 if (print_debug_)
522 DumpMockReadWrite(result);
523 return result;
526 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
527 << ": Read " << read_index();
528 if (print_debug_)
529 DumpMockReadWrite(current_read_);
531 // Increment the sequence number if IO is complete
532 if (current_read_.mode == SYNCHRONOUS)
533 NextStep();
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_
554 << ": I/O Pending";
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);
560 } else {
561 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
562 << ": Write " << write_index();
565 if (print_debug_)
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)
571 NextStep();
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();
582 NOTREACHED();
585 void DeterministicSocketData::InvokeCallbacks() {
586 if (socket_ && socket_->write_pending() &&
587 (current_write().sequence_number == sequence_number())) {
588 socket_->CompleteWrite();
589 NextStep();
590 return;
592 if (socket_ && socket_->read_pending() &&
593 (current_read().sequence_number == sequence_number())) {
594 socket_->CompleteRead();
595 NextStep();
596 return;
600 void DeterministicSocketData::NextStep() {
601 // Invariant: Can never move *past* the stopping step.
602 DCHECK_LT(sequence_number_, stopping_sequence_number_);
603 sequence_number_++;
604 if (sequence_number_ == stopping_sequence_number_)
605 SetStopped(true);
608 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
609 MockRead* reads, size_t reads_count,
610 MockWrite* writes, size_t writes_count) {
611 size_t read = 0;
612 size_t write = 0;
613 int expected = 0;
614 while (read < reads_count || write < writes_count) {
615 // Check to see that we have a read or write at the expected
616 // state.
617 if (read < reads_count && reads[read].sequence_number == expected) {
618 ++read;
619 ++expected;
620 continue;
622 if (write < writes_count && writes[write].sequence_number == expected) {
623 ++write;
624 ++expected;
625 continue;
627 NOTREACHED() << "Missing sequence number: " << expected;
628 return;
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);
661 return 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);
672 return 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());
683 return socket;
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)),
693 connected_(false),
694 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)) {
695 IPAddressNumber ip;
696 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
697 peer_addr_ = IPEndPoint(ip, 0);
700 bool MockClientSocket::SetReceiveBufferSize(int32 size) {
701 return true;
704 bool MockClientSocket::SetSendBufferSize(int32 size) {
705 return true;
708 void MockClientSocket::Disconnect() {
709 connected_ = false;
712 bool MockClientSocket::IsConnected() const {
713 return connected_;
716 bool MockClientSocket::IsConnectedAndIdle() const {
717 return connected_;
720 int MockClientSocket::GetPeerAddress(IPEndPoint* address) const {
721 *address = peer_addr_;
722 return OK;
725 int MockClientSocket::GetLocalAddress(IPEndPoint* address) const {
726 IPAddressNumber ip;
727 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
728 CHECK(rv);
729 *address = IPEndPoint(ip, 123);
730 return OK;
733 const BoundNetLog& MockClientSocket::NetLog() const {
734 return net_log_;
737 void MockClientSocket::GetSSLCertRequestInfo(
738 SSLCertRequestInfo* cert_request_info) {
741 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece& label,
742 bool has_context,
743 const base::StringPiece& context,
744 unsigned char* out,
745 unsigned int outlen) {
746 memset(out, 'A', outlen);
747 return OK;
750 int MockClientSocket::GetTLSUniqueChannelBinding(std::string* out) {
751 out->assign(MockClientSocket::kTlsUnique);
752 return OK;
755 ServerBoundCertService* MockClientSocket::GetServerBoundCertService() const {
756 NOTREACHED();
757 return NULL;
760 SSLClientSocket::NextProtoStatus
761 MockClientSocket::GetNextProto(std::string* proto, std::string* server_protos) {
762 proto->clear();
763 server_protos->clear();
764 return SSLClientSocket::kNextProtoUnsupported;
767 MockClientSocket::~MockClientSocket() {}
769 void MockClientSocket::RunCallbackAsync(const CompletionCallback& callback,
770 int result) {
771 MessageLoop::current()->PostTask(FROM_HERE,
772 base::Bind(&MockClientSocket::RunCallback, weak_factory_.GetWeakPtr(),
773 callback, result));
776 void MockClientSocket::RunCallback(const net::CompletionCallback& callback,
777 int result) {
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),
787 data_(data),
788 read_offset_(0),
789 num_bytes_read_(0),
790 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
791 need_read_data_(true),
792 peer_closed_connection_(false),
793 pending_buf_(NULL),
794 pending_buf_len_(0),
795 was_used_to_convey_data_(false) {
796 DCHECK(data_);
797 peer_addr_ = data->connect_data().peer_addr;
798 data_->Reset();
801 MockTCPClientSocket::~MockTCPClientSocket() {}
803 int MockTCPClientSocket::Read(IOBuffer* buf, int buf_len,
804 const CompletionCallback& callback) {
805 if (!connected_)
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.
812 pending_buf_ = buf;
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) {
839 DCHECK(buf);
840 DCHECK_GT(buf_len, 0);
842 if (!connected_)
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) {
859 if (connected_)
860 return OK;
861 connected_ = true;
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];
888 return OK;
891 bool MockTCPClientSocket::WasEverUsed() const {
892 return was_used_to_convey_data_;
895 bool MockTCPClientSocket::UsingTCPFastOpen() const {
896 return false;
899 int64 MockTCPClientSocket::NumBytesRead() const {
900 return num_bytes_read_;
903 base::TimeDelta MockTCPClientSocket::GetConnectTimeMicros() const {
904 // Dummy value.
905 static const base::TimeDelta kTestingConnectTimeMicros =
906 base::TimeDelta::FromMicroseconds(20);
907 return kTestingConnectTimeMicros;
910 bool MockTCPClientSocket::WasNpnNegotiated() const {
911 return false;
914 bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
915 return false;
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_);
926 read_data_ = 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_;
948 pending_buf_ = NULL;
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;
963 read_offset_ = 0;
965 } else {
966 result = 0; // EOF
970 if (read_data_.mode == ASYNC) {
971 DCHECK(!callback.is_null());
972 RunCallbackAsync(callback, result);
973 return ERR_IO_PENDING;
975 return result;
978 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
979 net::NetLog* net_log, DeterministicSocketData* data)
980 : MockClientSocket(net_log),
981 write_pending_(false),
982 write_result_(0),
983 read_data_(),
984 read_buf_(NULL),
985 read_buf_len_(0),
986 read_pending_(false),
987 data_(data),
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_);
1003 DCHECK(read_buf_);
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);
1025 return result;
1028 int DeterministicMockTCPClientSocket::Write(
1029 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1030 DCHECK(buf);
1031 DCHECK_GT(buf_len, 0);
1033 if (!connected_)
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) {
1054 if (!connected_)
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);
1062 read_buf_ = buf;
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) {
1079 if (connected_)
1080 return OK;
1081 connected_ = true;
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 {
1094 return connected_;
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 {
1106 return false;
1109 int64 DeterministicMockTCPClientSocket::NumBytesRead() const {
1110 return -1;
1113 base::TimeDelta DeterministicMockTCPClientSocket::GetConnectTimeMicros() const {
1114 return base::TimeDelta::FromMicroseconds(-1);
1117 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1118 return false;
1121 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1122 return false;
1125 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead& data) {}
1127 // static
1128 void MockSSLClientSocket::ConnectCallback(
1129 MockSSLClientSocket *ssl_client_socket,
1130 const CompletionCallback& callback,
1131 int rv) {
1132 if (rv == OK)
1133 ssl_client_socket->connected_ = true;
1134 callback.Run(rv);
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),
1144 data_(data),
1145 is_npn_state_set_(false),
1146 new_npn_value_(false),
1147 is_protocol_negotiated_set_(false),
1148 protocol_negotiated_(kProtoUnknown) {
1149 DCHECK(data_);
1150 peer_addr_ = data->connect.peer_addr;
1153 MockSSLClientSocket::~MockSSLClientSocket() {
1154 Disconnect();
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));
1170 if (rv == OK) {
1171 if (data_->connect.result == OK)
1172 connected_ = true;
1173 if (data_->connect.mode == ASYNC) {
1174 RunCallbackAsync(callback, data_->connect.result);
1175 return ERR_IO_PENDING;
1177 return data_->connect.result;
1179 return rv;
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 {
1201 return -1;
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) {
1213 ssl_info->Reset();
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;
1217 return true;
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;
1227 } else {
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) {
1275 NOTIMPLEMENTED();
1278 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data,
1279 net::NetLog* net_log)
1280 : connected_(false),
1281 data_(data),
1282 read_offset_(0),
1283 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
1284 need_read_data_(true),
1285 pending_buf_(NULL),
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)) {
1289 DCHECK(data_);
1290 data_->Reset();
1293 MockUDPClientSocket::~MockUDPClientSocket() {}
1295 int MockUDPClientSocket::Read(IOBuffer* buf, int buf_len,
1296 const CompletionCallback& callback) {
1297 if (!connected_)
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.
1304 pending_buf_ = buf;
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) {
1325 DCHECK(buf);
1326 DCHECK_GT(buf_len, 0);
1328 if (!connected_)
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) {
1342 return true;
1345 bool MockUDPClientSocket::SetSendBufferSize(int32 size) {
1346 return true;
1349 void MockUDPClientSocket::Close() {
1350 connected_ = false;
1353 int MockUDPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1354 NOTIMPLEMENTED();
1355 return OK;
1358 int MockUDPClientSocket::GetLocalAddress(IPEndPoint* address) const {
1359 NOTIMPLEMENTED();
1360 return OK;
1363 const BoundNetLog& MockUDPClientSocket::NetLog() const {
1364 return net_log_;
1367 int MockUDPClientSocket::Connect(const IPEndPoint& address) {
1368 connected_ = true;
1369 return OK;
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_);
1380 read_data_ = 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;
1414 read_offset_ = 0;
1416 } else {
1417 result = 0; // EOF
1421 if (read_data_.mode == ASYNC) {
1422 DCHECK(!callback.is_null());
1423 RunCallbackAsync(callback, result);
1424 return ERR_IO_PENDING;
1426 return result;
1429 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback& callback,
1430 int result) {
1431 MessageLoop::current()->PostTask(
1432 FROM_HERE,
1433 base::Bind(&MockUDPClientSocket::RunCallback, weak_factory_.GetWeakPtr(),
1434 callback, result));
1437 void MockUDPClientSocket::RunCallback(const CompletionCallback& callback,
1438 int result) {
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) {
1457 SetResult(result);
1458 (*completion_count_)++;
1459 request_order_->push_back(this);
1462 // static
1463 const int ClientSocketPoolTest::kIndexOutOfBounds = -1;
1465 // static
1466 const int ClientSocketPoolTest::kRequestNotFound = -2;
1468 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1469 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1471 int ClientSocketPoolTest::GetOrderOfRequest(size_t index) const {
1472 index--;
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])
1478 return i + 1;
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();
1491 return true;
1494 return false;
1497 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
1498 bool released_one;
1499 do {
1500 released_one = ReleaseOneConnection(keep_alive);
1501 } while (released_one);
1504 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1505 StreamSocket* socket,
1506 ClientSocketHandle* handle,
1507 const CompletionCallback& callback)
1508 : socket_(socket),
1509 handle_(handle),
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)));
1518 if (rv == OK) {
1519 user_callback_.Reset();
1520 OnConnect(OK);
1522 return rv;
1525 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1526 const ClientSocketHandle* handle) {
1527 if (handle != handle_)
1528 return false;
1529 socket_.reset();
1530 handle_ = NULL;
1531 user_callback_.Reset();
1532 return true;
1535 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) {
1536 if (!socket_.get())
1537 return;
1538 if (rv == OK) {
1539 handle_->set_socket(socket_.release());
1540 } else {
1541 socket_.reset();
1544 handle_ = NULL;
1546 if (!user_callback_.is_null()) {
1547 CompletionCallback callback = user_callback_;
1548 user_callback_.Reset();
1549 callback.Run(rv);
1553 MockTransportClientSocketPool::MockTransportClientSocketPool(
1554 int max_sockets,
1555 int max_sockets_per_group,
1556 ClientSocketPoolHistograms* histograms,
1557 ClientSocketFactory* socket_factory)
1558 : TransportClientSocketPool(max_sockets, max_sockets_per_group, histograms,
1559 NULL, NULL, NULL),
1560 client_socket_factory_(socket_factory),
1561 release_count_(0),
1562 cancel_count_(0) {
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)) {
1584 cancel_count_++;
1585 break;
1590 void MockTransportClientSocketPool::ReleaseSocket(const std::string& group_name,
1591 StreamSocket* socket, int id) {
1592 EXPECT_EQ(1, id);
1593 release_count_++;
1594 delete socket;
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) {
1628 NOTREACHED();
1629 return NULL;
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);
1641 return 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);
1653 return socket;
1656 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1659 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1660 int max_sockets,
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);
1704 } // namespace net