Patch 3/3 to get WebScheduler via WebThread
[chromium-blink-merge.git] / net / socket / socket_test_util.cc
blobb905597a2aa2d5d079586126684c6adbf53d19a3
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/message_loop.h"
15 #include "base/run_loop.h"
16 #include "base/time/time.h"
17 #include "net/base/address_family.h"
18 #include "net/base/address_list.h"
19 #include "net/base/auth.h"
20 #include "net/base/load_timing_info.h"
21 #include "net/http/http_network_session.h"
22 #include "net/http/http_request_headers.h"
23 #include "net/http/http_response_headers.h"
24 #include "net/socket/socket.h"
25 #include "net/socket/websocket_endpoint_lock_manager.h"
26 #include "net/ssl/ssl_cert_request_info.h"
27 #include "net/ssl/ssl_connection_status_flags.h"
28 #include "net/ssl/ssl_info.h"
29 #include "testing/gtest/include/gtest/gtest.h"
31 #define NET_TRACE(level, s) VLOG(level) << s << __FUNCTION__ << "() "
33 namespace net {
35 namespace {
37 inline char AsciifyHigh(char x) {
38 char nybble = static_cast<char>((x >> 4) & 0x0F);
39 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
42 inline char AsciifyLow(char x) {
43 char nybble = static_cast<char>((x >> 0) & 0x0F);
44 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
47 inline char Asciify(char x) {
48 if ((x < 0) || !isprint(x))
49 return '.';
50 return x;
53 void DumpData(const char* data, int data_len) {
54 if (logging::LOG_INFO < logging::GetMinLogLevel())
55 return;
56 DVLOG(1) << "Length: " << data_len;
57 const char* pfx = "Data: ";
58 if (!data || (data_len <= 0)) {
59 DVLOG(1) << pfx << "<None>";
60 } else {
61 int i;
62 for (i = 0; i <= (data_len - 4); i += 4) {
63 DVLOG(1) << pfx
64 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
65 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
66 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
67 << AsciifyHigh(data[i + 3]) << AsciifyLow(data[i + 3])
68 << " '"
69 << Asciify(data[i + 0])
70 << Asciify(data[i + 1])
71 << Asciify(data[i + 2])
72 << Asciify(data[i + 3])
73 << "'";
74 pfx = " ";
76 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
77 switch (data_len - i) {
78 case 3:
79 DVLOG(1) << pfx
80 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
81 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
82 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
83 << " '"
84 << Asciify(data[i + 0])
85 << Asciify(data[i + 1])
86 << Asciify(data[i + 2])
87 << " '";
88 break;
89 case 2:
90 DVLOG(1) << pfx
91 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
92 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
93 << " '"
94 << Asciify(data[i + 0])
95 << Asciify(data[i + 1])
96 << " '";
97 break;
98 case 1:
99 DVLOG(1) << pfx
100 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
101 << " '"
102 << Asciify(data[i + 0])
103 << " '";
104 break;
109 template <MockReadWriteType type>
110 void DumpMockReadWrite(const MockReadWrite<type>& r) {
111 if (logging::LOG_INFO < logging::GetMinLogLevel())
112 return;
113 DVLOG(1) << "Async: " << (r.mode == ASYNC)
114 << "\nResult: " << r.result;
115 DumpData(r.data, r.data_len);
116 const char* stop = (r.sequence_number & MockRead::STOPLOOP) ? " (STOP)" : "";
117 DVLOG(1) << "Stage: " << (r.sequence_number & ~MockRead::STOPLOOP) << stop;
120 } // namespace
122 MockConnect::MockConnect() : mode(ASYNC), result(OK) {
123 IPAddressNumber ip;
124 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
125 peer_addr = IPEndPoint(ip, 0);
128 MockConnect::MockConnect(IoMode io_mode, int r) : mode(io_mode), result(r) {
129 IPAddressNumber ip;
130 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
131 peer_addr = IPEndPoint(ip, 0);
134 MockConnect::MockConnect(IoMode io_mode, int r, IPEndPoint addr) :
135 mode(io_mode),
136 result(r),
137 peer_addr(addr) {
140 MockConnect::~MockConnect() {}
142 StaticSocketDataHelper::StaticSocketDataHelper(MockRead* reads,
143 size_t reads_count,
144 MockWrite* writes,
145 size_t writes_count)
146 : reads_(reads),
147 read_index_(0),
148 read_count_(reads_count),
149 writes_(writes),
150 write_index_(0),
151 write_count_(writes_count) {
154 StaticSocketDataHelper::~StaticSocketDataHelper() {
157 const MockRead& StaticSocketDataHelper::PeekRead() const {
158 CHECK(!at_read_eof());
159 return reads_[read_index_];
162 const MockWrite& StaticSocketDataHelper::PeekWrite() const {
163 CHECK(!at_write_eof());
164 return writes_[write_index_];
167 const MockRead& StaticSocketDataHelper::AdvanceRead() {
168 CHECK(!at_read_eof());
169 return reads_[read_index_++];
172 const MockWrite& StaticSocketDataHelper::AdvanceWrite() {
173 CHECK(!at_write_eof());
174 return writes_[write_index_++];
177 void StaticSocketDataHelper::Reset() {
178 read_index_ = 0;
179 write_index_ = 0;
182 StaticSocketDataProvider::StaticSocketDataProvider()
183 : StaticSocketDataProvider(nullptr, 0, nullptr, 0) {
186 StaticSocketDataProvider::StaticSocketDataProvider(MockRead* reads,
187 size_t reads_count,
188 MockWrite* writes,
189 size_t writes_count)
190 : helper_(reads, reads_count, writes, writes_count) {
193 StaticSocketDataProvider::~StaticSocketDataProvider() {
196 MockRead StaticSocketDataProvider::OnRead() {
197 CHECK(!helper_.at_read_eof());
198 return helper_.AdvanceRead();
201 MockWriteResult StaticSocketDataProvider::OnWrite(const std::string& data) {
202 if (helper_.write_count() == 0) {
203 // Not using mock writes; succeed synchronously.
204 return MockWriteResult(SYNCHRONOUS, data.length());
206 EXPECT_FALSE(helper_.at_write_eof());
207 if (helper_.at_write_eof()) {
208 // Show what the extra write actually consists of.
209 EXPECT_EQ("<unexpected write>", data);
210 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
213 // Check that what we are writing matches the expectation.
214 // Then give the mocked return value.
215 const MockWrite& w = helper_.AdvanceWrite();
216 int result = w.result;
217 if (w.data) {
218 // Note - we can simulate a partial write here. If the expected data
219 // is a match, but shorter than the write actually written, that is legal.
220 // Example:
221 // Application writes "foobarbaz" (9 bytes)
222 // Expected write was "foo" (3 bytes)
223 // This is a success, and we return 3 to the application.
224 std::string expected_data(w.data, w.data_len);
225 EXPECT_GE(data.length(), expected_data.length());
226 std::string actual_data(data.substr(0, w.data_len));
227 EXPECT_EQ(expected_data, actual_data);
228 if (expected_data != actual_data)
229 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
230 if (result == OK)
231 result = w.data_len;
233 return MockWriteResult(w.mode, result);
236 void StaticSocketDataProvider::Reset() {
237 helper_.Reset();
240 DynamicSocketDataProvider::DynamicSocketDataProvider()
241 : short_read_limit_(0),
242 allow_unconsumed_reads_(false) {
245 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
247 MockRead DynamicSocketDataProvider::OnRead() {
248 if (reads_.empty())
249 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
250 MockRead result = reads_.front();
251 if (short_read_limit_ == 0 || result.data_len <= short_read_limit_) {
252 reads_.pop_front();
253 } else {
254 result.data_len = short_read_limit_;
255 reads_.front().data += result.data_len;
256 reads_.front().data_len -= result.data_len;
258 return result;
261 void DynamicSocketDataProvider::Reset() {
262 reads_.clear();
265 void DynamicSocketDataProvider::SimulateRead(const char* data,
266 const size_t length) {
267 if (!allow_unconsumed_reads_) {
268 EXPECT_TRUE(reads_.empty()) << "Unconsumed read: " << reads_.front().data;
270 reads_.push_back(MockRead(ASYNC, data, length));
273 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode, int result)
274 : connect(mode, result),
275 next_proto_status(SSLClientSocket::kNextProtoUnsupported),
276 was_npn_negotiated(false),
277 protocol_negotiated(kProtoUnknown),
278 client_cert_sent(false),
279 cert_request_info(NULL),
280 channel_id_sent(false),
281 connection_status(0) {
282 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2,
283 &connection_status);
284 // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
285 SSLConnectionStatusSetCipherSuite(0xcc14, &connection_status);
288 SSLSocketDataProvider::~SSLSocketDataProvider() {
291 void SSLSocketDataProvider::SetNextProto(NextProto proto) {
292 was_npn_negotiated = true;
293 next_proto_status = SSLClientSocket::kNextProtoNegotiated;
294 protocol_negotiated = proto;
295 next_proto = SSLClientSocket::NextProtoToString(proto);
298 DelayedSocketData::DelayedSocketData(
299 int write_delay, MockRead* reads, size_t reads_count,
300 MockWrite* writes, size_t writes_count)
301 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
302 write_delay_(write_delay),
303 read_in_progress_(false),
304 weak_factory_(this) {
305 DCHECK_GE(write_delay_, 0);
308 DelayedSocketData::DelayedSocketData(
309 const MockConnect& connect, int write_delay, MockRead* reads,
310 size_t reads_count, MockWrite* writes, size_t writes_count)
311 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
312 write_delay_(write_delay),
313 read_in_progress_(false),
314 weak_factory_(this) {
315 DCHECK_GE(write_delay_, 0);
316 set_connect_data(connect);
319 DelayedSocketData::~DelayedSocketData() {
322 void DelayedSocketData::ForceNextRead() {
323 DCHECK(read_in_progress_);
324 write_delay_ = 0;
325 CompleteRead();
328 MockRead DelayedSocketData::OnRead() {
329 MockRead out = MockRead(ASYNC, ERR_IO_PENDING);
330 if (write_delay_ <= 0)
331 out = StaticSocketDataProvider::OnRead();
332 read_in_progress_ = (out.result == ERR_IO_PENDING);
333 return out;
336 MockWriteResult DelayedSocketData::OnWrite(const std::string& data) {
337 MockWriteResult rv = StaticSocketDataProvider::OnWrite(data);
338 // Now that our write has completed, we can allow reads to continue.
339 if (!--write_delay_ && read_in_progress_)
340 base::MessageLoop::current()->PostDelayedTask(
341 FROM_HERE,
342 base::Bind(&DelayedSocketData::CompleteRead,
343 weak_factory_.GetWeakPtr()),
344 base::TimeDelta::FromMilliseconds(100));
345 return rv;
348 void DelayedSocketData::Reset() {
349 set_socket(NULL);
350 read_in_progress_ = false;
351 weak_factory_.InvalidateWeakPtrs();
352 StaticSocketDataProvider::Reset();
355 void DelayedSocketData::CompleteRead() {
356 if (socket() && read_in_progress_)
357 socket()->OnReadComplete(OnRead());
360 OrderedSocketData::OrderedSocketData(
361 MockRead* reads, size_t reads_count, MockWrite* writes, size_t writes_count)
362 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
363 sequence_number_(0), loop_stop_stage_(0),
364 blocked_(false), weak_factory_(this) {
367 OrderedSocketData::OrderedSocketData(
368 const MockConnect& connect,
369 MockRead* reads, size_t reads_count,
370 MockWrite* writes, size_t writes_count)
371 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
372 sequence_number_(0), loop_stop_stage_(0),
373 blocked_(false), weak_factory_(this) {
374 set_connect_data(connect);
377 void OrderedSocketData::EndLoop() {
378 // If we've already stopped the loop, don't do it again until we've advanced
379 // to the next sequence_number.
380 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": EndLoop()";
381 if (loop_stop_stage_ > 0) {
382 const MockRead& next_read = helper()->PeekRead();
383 if ((next_read.sequence_number & ~MockRead::STOPLOOP) >
384 loop_stop_stage_) {
385 NET_TRACE(1, " *** ") << "Stage " << sequence_number_
386 << ": Clearing stop index";
387 loop_stop_stage_ = 0;
388 } else {
389 return;
392 // Record the sequence_number at which we stopped the loop.
393 NET_TRACE(1, " *** ") << "Stage " << sequence_number_
394 << ": Posting Quit at read " << read_index();
395 loop_stop_stage_ = sequence_number_;
398 MockRead OrderedSocketData::OnRead() {
399 weak_factory_.InvalidateWeakPtrs();
400 blocked_ = false;
401 const MockRead& next_read = helper()->PeekRead();
402 if (next_read.sequence_number & MockRead::STOPLOOP)
403 EndLoop();
404 if ((next_read.sequence_number & ~MockRead::STOPLOOP) <=
405 sequence_number_++) {
406 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ - 1 << ": Read "
407 << read_index();
408 DumpMockReadWrite(next_read);
409 blocked_ = (next_read.result == ERR_IO_PENDING);
410 return StaticSocketDataProvider::OnRead();
412 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ - 1 << ": I/O Pending";
413 MockRead result = MockRead(ASYNC, ERR_IO_PENDING);
414 DumpMockReadWrite(result);
415 blocked_ = true;
416 return result;
419 MockWriteResult OrderedSocketData::OnWrite(const std::string& data) {
420 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Write "
421 << write_index();
422 DumpMockReadWrite(helper()->PeekWrite());
423 ++sequence_number_;
424 if (blocked_) {
425 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
426 // should probably fix the weirdness. One example is in SpdyStream,
427 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
428 // SYN_REPLY causes OnResponseReceived() to get called before
429 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
430 base::MessageLoop::current()->PostDelayedTask(
431 FROM_HERE,
432 base::Bind(&OrderedSocketData::CompleteRead,
433 weak_factory_.GetWeakPtr()),
434 base::TimeDelta::FromMilliseconds(100));
436 return StaticSocketDataProvider::OnWrite(data);
439 void OrderedSocketData::Reset() {
440 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Reset()";
441 sequence_number_ = 0;
442 loop_stop_stage_ = 0;
443 set_socket(NULL);
444 weak_factory_.InvalidateWeakPtrs();
445 StaticSocketDataProvider::Reset();
448 void OrderedSocketData::CompleteRead() {
449 if (socket() && blocked_) {
450 NET_TRACE(1, " *** ") << "Stage " << sequence_number_;
451 socket()->OnReadComplete(OnRead());
455 OrderedSocketData::~OrderedSocketData() {}
457 DeterministicSocketData::DeterministicSocketData(MockRead* reads,
458 size_t reads_count, MockWrite* writes, size_t writes_count)
459 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
460 sequence_number_(0),
461 current_read_(),
462 current_write_(),
463 stopping_sequence_number_(0),
464 stopped_(false),
465 print_debug_(false),
466 is_running_(false) {
467 VerifyCorrectSequenceNumbers(reads, reads_count, writes, writes_count);
470 DeterministicSocketData::~DeterministicSocketData() {}
472 void DeterministicSocketData::Run() {
473 DCHECK(!is_running_);
474 is_running_ = true;
476 SetStopped(false);
477 int counter = 0;
478 // Continue to consume data until all data has run out, or the stopped_ flag
479 // has been set. Consuming data requires two separate operations -- running
480 // the tasks in the message loop, and explicitly invoking the read/write
481 // callbacks (simulating network I/O). We check our conditions between each,
482 // since they can change in either.
483 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
484 if (counter % 2 == 0)
485 base::RunLoop().RunUntilIdle();
486 if (counter % 2 == 1) {
487 InvokeCallbacks();
489 counter++;
491 // We're done consuming new data, but it is possible there are still some
492 // pending callbacks which we expect to complete before returning.
493 while (delegate_.get() &&
494 (delegate_->WritePending() || delegate_->ReadPending()) &&
495 !stopped()) {
496 InvokeCallbacks();
497 base::RunLoop().RunUntilIdle();
499 SetStopped(false);
500 is_running_ = false;
503 void DeterministicSocketData::RunFor(int steps) {
504 StopAfter(steps);
505 Run();
508 void DeterministicSocketData::SetStop(int seq) {
509 DCHECK_LT(sequence_number_, seq);
510 stopping_sequence_number_ = seq;
511 stopped_ = false;
514 void DeterministicSocketData::StopAfter(int seq) {
515 SetStop(sequence_number_ + seq);
518 MockRead DeterministicSocketData::OnRead() {
519 current_read_ = helper()->PeekRead();
521 // Synchronous read while stopped is an error
522 if (stopped() && current_read_.mode == SYNCHRONOUS) {
523 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
524 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
527 // Async read which will be called back in a future step.
528 if (sequence_number_ < current_read_.sequence_number) {
529 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": I/O Pending";
530 MockRead result = MockRead(SYNCHRONOUS, ERR_IO_PENDING);
531 if (current_read_.mode == SYNCHRONOUS) {
532 LOG(ERROR) << "Unable to perform synchronous read: "
533 << current_read_.sequence_number
534 << " at stage: " << sequence_number_;
535 result = MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
537 if (print_debug_)
538 DumpMockReadWrite(result);
539 return result;
542 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Read "
543 << read_index();
544 if (print_debug_)
545 DumpMockReadWrite(current_read_);
547 // Increment the sequence number if IO is complete
548 if (current_read_.mode == SYNCHRONOUS)
549 NextStep();
551 DCHECK_NE(ERR_IO_PENDING, current_read_.result);
552 StaticSocketDataProvider::OnRead();
554 return current_read_;
557 MockWriteResult DeterministicSocketData::OnWrite(const std::string& data) {
558 const MockWrite& next_write = helper()->PeekWrite();
559 current_write_ = next_write;
561 // Synchronous write while stopped is an error
562 if (stopped() && next_write.mode == SYNCHRONOUS) {
563 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
564 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
567 // Async write which will be called back in a future step.
568 if (sequence_number_ < next_write.sequence_number) {
569 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": I/O Pending";
570 if (next_write.mode == SYNCHRONOUS) {
571 LOG(ERROR) << "Unable to perform synchronous write: "
572 << next_write.sequence_number << " at stage: " << sequence_number_;
573 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
575 } else {
576 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Write "
577 << write_index();
580 if (print_debug_)
581 DumpMockReadWrite(next_write);
583 // Move to the next step if I/O is synchronous, since the operation will
584 // complete when this method returns.
585 if (next_write.mode == SYNCHRONOUS)
586 NextStep();
588 // This is either a sync write for this step, or an async write.
589 return StaticSocketDataProvider::OnWrite(data);
592 void DeterministicSocketData::Reset() {
593 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Reset()";
594 sequence_number_ = 0;
595 StaticSocketDataProvider::Reset();
596 NOTREACHED();
599 void DeterministicSocketData::InvokeCallbacks() {
600 if (delegate_.get() && delegate_->WritePending() &&
601 (current_write().sequence_number == sequence_number())) {
602 NextStep();
603 delegate_->CompleteWrite();
604 return;
606 if (delegate_.get() && delegate_->ReadPending() &&
607 (current_read().sequence_number == sequence_number())) {
608 NextStep();
609 delegate_->CompleteRead();
610 return;
614 void DeterministicSocketData::NextStep() {
615 // Invariant: Can never move *past* the stopping step.
616 DCHECK_LT(sequence_number_, stopping_sequence_number_);
617 sequence_number_++;
618 if (sequence_number_ == stopping_sequence_number_)
619 SetStopped(true);
622 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
623 MockRead* reads, size_t reads_count,
624 MockWrite* writes, size_t writes_count) {
625 size_t read = 0;
626 size_t write = 0;
627 int expected = 0;
628 while (read < reads_count || write < writes_count) {
629 // Check to see that we have a read or write at the expected
630 // state.
631 if (read < reads_count && reads[read].sequence_number == expected) {
632 ++read;
633 ++expected;
634 continue;
636 if (write < writes_count && writes[write].sequence_number == expected) {
637 ++write;
638 ++expected;
639 continue;
641 NOTREACHED() << "Missing sequence number: " << expected;
642 return;
644 DCHECK_EQ(read, reads_count);
645 DCHECK_EQ(write, writes_count);
648 MockClientSocketFactory::MockClientSocketFactory() {}
650 MockClientSocketFactory::~MockClientSocketFactory() {}
652 void MockClientSocketFactory::AddSocketDataProvider(
653 SocketDataProvider* data) {
654 mock_data_.Add(data);
657 void MockClientSocketFactory::AddSSLSocketDataProvider(
658 SSLSocketDataProvider* data) {
659 mock_ssl_data_.Add(data);
662 void MockClientSocketFactory::ResetNextMockIndexes() {
663 mock_data_.ResetNextIndex();
664 mock_ssl_data_.ResetNextIndex();
667 scoped_ptr<DatagramClientSocket>
668 MockClientSocketFactory::CreateDatagramClientSocket(
669 DatagramSocket::BindType bind_type,
670 const RandIntCallback& rand_int_cb,
671 net::NetLog* net_log,
672 const net::NetLog::Source& source) {
673 SocketDataProvider* data_provider = mock_data_.GetNext();
674 scoped_ptr<MockUDPClientSocket> socket(
675 new MockUDPClientSocket(data_provider, net_log));
676 data_provider->set_socket(socket.get());
677 if (bind_type == DatagramSocket::RANDOM_BIND)
678 socket->set_source_port(static_cast<uint16>(rand_int_cb.Run(1025, 65535)));
679 return socket.Pass();
682 scoped_ptr<StreamSocket> MockClientSocketFactory::CreateTransportClientSocket(
683 const AddressList& addresses,
684 net::NetLog* net_log,
685 const net::NetLog::Source& source) {
686 SocketDataProvider* data_provider = mock_data_.GetNext();
687 scoped_ptr<MockTCPClientSocket> socket(
688 new MockTCPClientSocket(addresses, net_log, data_provider));
689 data_provider->set_socket(socket.get());
690 return socket.Pass();
693 scoped_ptr<SSLClientSocket> MockClientSocketFactory::CreateSSLClientSocket(
694 scoped_ptr<ClientSocketHandle> transport_socket,
695 const HostPortPair& host_and_port,
696 const SSLConfig& ssl_config,
697 const SSLClientSocketContext& context) {
698 SSLSocketDataProvider* next_ssl_data = mock_ssl_data_.GetNext();
699 if (!next_ssl_data->next_protos_expected_in_ssl_config.empty()) {
700 EXPECT_EQ(next_ssl_data->next_protos_expected_in_ssl_config.size(),
701 ssl_config.next_protos.size());
702 EXPECT_TRUE(
703 std::equal(next_ssl_data->next_protos_expected_in_ssl_config.begin(),
704 next_ssl_data->next_protos_expected_in_ssl_config.end(),
705 ssl_config.next_protos.begin()));
707 return scoped_ptr<SSLClientSocket>(new MockSSLClientSocket(
708 transport_socket.Pass(), host_and_port, ssl_config, next_ssl_data));
711 void MockClientSocketFactory::ClearSSLSessionCache() {
714 const char MockClientSocket::kTlsUnique[] = "MOCK_TLSUNIQ";
716 MockClientSocket::MockClientSocket(const BoundNetLog& net_log)
717 : connected_(false),
718 net_log_(net_log),
719 weak_factory_(this) {
720 IPAddressNumber ip;
721 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
722 peer_addr_ = IPEndPoint(ip, 0);
725 int MockClientSocket::SetReceiveBufferSize(int32 size) {
726 return OK;
729 int MockClientSocket::SetSendBufferSize(int32 size) {
730 return OK;
733 void MockClientSocket::Disconnect() {
734 connected_ = false;
737 bool MockClientSocket::IsConnected() const {
738 return connected_;
741 bool MockClientSocket::IsConnectedAndIdle() const {
742 return connected_;
745 int MockClientSocket::GetPeerAddress(IPEndPoint* address) const {
746 if (!IsConnected())
747 return ERR_SOCKET_NOT_CONNECTED;
748 *address = peer_addr_;
749 return OK;
752 int MockClientSocket::GetLocalAddress(IPEndPoint* address) const {
753 IPAddressNumber ip;
754 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
755 CHECK(rv);
756 *address = IPEndPoint(ip, 123);
757 return OK;
760 const BoundNetLog& MockClientSocket::NetLog() const {
761 return net_log_;
764 void MockClientSocket::GetSSLCertRequestInfo(
765 SSLCertRequestInfo* cert_request_info) {
768 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece& label,
769 bool has_context,
770 const base::StringPiece& context,
771 unsigned char* out,
772 unsigned int outlen) {
773 memset(out, 'A', outlen);
774 return OK;
777 int MockClientSocket::GetTLSUniqueChannelBinding(std::string* out) {
778 out->assign(MockClientSocket::kTlsUnique);
779 return OK;
782 ChannelIDService* MockClientSocket::GetChannelIDService() const {
783 NOTREACHED();
784 return NULL;
787 SSLClientSocket::NextProtoStatus
788 MockClientSocket::GetNextProto(std::string* proto) {
789 proto->clear();
790 return SSLClientSocket::kNextProtoUnsupported;
793 scoped_refptr<X509Certificate>
794 MockClientSocket::GetUnverifiedServerCertificateChain() const {
795 NOTREACHED();
796 return NULL;
799 MockClientSocket::~MockClientSocket() {}
801 void MockClientSocket::RunCallbackAsync(const CompletionCallback& callback,
802 int result) {
803 base::MessageLoop::current()->PostTask(
804 FROM_HERE,
805 base::Bind(&MockClientSocket::RunCallback,
806 weak_factory_.GetWeakPtr(),
807 callback,
808 result));
811 void MockClientSocket::RunCallback(const net::CompletionCallback& callback,
812 int result) {
813 if (!callback.is_null())
814 callback.Run(result);
817 MockTCPClientSocket::MockTCPClientSocket(const AddressList& addresses,
818 net::NetLog* net_log,
819 SocketDataProvider* data)
820 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
821 addresses_(addresses),
822 data_(data),
823 read_offset_(0),
824 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
825 need_read_data_(true),
826 peer_closed_connection_(false),
827 pending_buf_(NULL),
828 pending_buf_len_(0),
829 was_used_to_convey_data_(false) {
830 DCHECK(data_);
831 peer_addr_ = data->connect_data().peer_addr;
832 data_->Reset();
835 MockTCPClientSocket::~MockTCPClientSocket() {}
837 int MockTCPClientSocket::Read(IOBuffer* buf, int buf_len,
838 const CompletionCallback& callback) {
839 if (!connected_)
840 return ERR_UNEXPECTED;
842 // If the buffer is already in use, a read is already in progress!
843 DCHECK(pending_buf_.get() == NULL);
845 // Store our async IO data.
846 pending_buf_ = buf;
847 pending_buf_len_ = buf_len;
848 pending_callback_ = callback;
850 if (need_read_data_) {
851 read_data_ = data_->OnRead();
852 if (read_data_.result == ERR_CONNECTION_CLOSED) {
853 // This MockRead is just a marker to instruct us to set
854 // peer_closed_connection_.
855 peer_closed_connection_ = true;
857 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
858 // This MockRead is just a marker to instruct us to set
859 // peer_closed_connection_. Skip it and get the next one.
860 read_data_ = data_->OnRead();
861 peer_closed_connection_ = true;
863 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
864 // to complete the async IO manually later (via OnReadComplete).
865 if (read_data_.result == ERR_IO_PENDING) {
866 // We need to be using async IO in this case.
867 DCHECK(!callback.is_null());
868 return ERR_IO_PENDING;
870 need_read_data_ = false;
873 return CompleteRead();
876 int MockTCPClientSocket::Write(IOBuffer* buf, int buf_len,
877 const CompletionCallback& callback) {
878 DCHECK(buf);
879 DCHECK_GT(buf_len, 0);
881 if (!connected_)
882 return ERR_UNEXPECTED;
884 std::string data(buf->data(), buf_len);
885 MockWriteResult write_result = data_->OnWrite(data);
887 was_used_to_convey_data_ = true;
889 if (write_result.mode == ASYNC) {
890 RunCallbackAsync(callback, write_result.result);
891 return ERR_IO_PENDING;
894 return write_result.result;
897 int MockTCPClientSocket::Connect(const CompletionCallback& callback) {
898 if (connected_)
899 return OK;
900 connected_ = true;
901 peer_closed_connection_ = false;
902 if (data_->connect_data().mode == ASYNC) {
903 if (data_->connect_data().result == ERR_IO_PENDING)
904 pending_callback_ = callback;
905 else
906 RunCallbackAsync(callback, data_->connect_data().result);
907 return ERR_IO_PENDING;
909 return data_->connect_data().result;
912 void MockTCPClientSocket::Disconnect() {
913 MockClientSocket::Disconnect();
914 pending_callback_.Reset();
917 bool MockTCPClientSocket::IsConnected() const {
918 return connected_ && !peer_closed_connection_;
921 bool MockTCPClientSocket::IsConnectedAndIdle() const {
922 return IsConnected();
925 int MockTCPClientSocket::GetPeerAddress(IPEndPoint* address) const {
926 if (addresses_.empty())
927 return MockClientSocket::GetPeerAddress(address);
929 *address = addresses_[0];
930 return OK;
933 bool MockTCPClientSocket::WasEverUsed() const {
934 return was_used_to_convey_data_;
937 bool MockTCPClientSocket::UsingTCPFastOpen() const {
938 return false;
941 bool MockTCPClientSocket::WasNpnNegotiated() const {
942 return false;
945 bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
946 return false;
949 void MockTCPClientSocket::OnReadComplete(const MockRead& data) {
950 // There must be a read pending.
951 DCHECK(pending_buf_.get());
952 // You can't complete a read with another ERR_IO_PENDING status code.
953 DCHECK_NE(ERR_IO_PENDING, data.result);
954 // Since we've been waiting for data, need_read_data_ should be true.
955 DCHECK(need_read_data_);
957 read_data_ = data;
958 need_read_data_ = false;
960 // The caller is simulating that this IO completes right now. Don't
961 // let CompleteRead() schedule a callback.
962 read_data_.mode = SYNCHRONOUS;
964 CompletionCallback callback = pending_callback_;
965 int rv = CompleteRead();
966 RunCallback(callback, rv);
969 void MockTCPClientSocket::OnConnectComplete(const MockConnect& data) {
970 CompletionCallback callback = pending_callback_;
971 RunCallback(callback, data.result);
974 int MockTCPClientSocket::CompleteRead() {
975 DCHECK(pending_buf_.get());
976 DCHECK(pending_buf_len_ > 0);
978 was_used_to_convey_data_ = true;
980 // Save the pending async IO data and reset our |pending_| state.
981 scoped_refptr<IOBuffer> buf = pending_buf_;
982 int buf_len = pending_buf_len_;
983 CompletionCallback callback = pending_callback_;
984 pending_buf_ = NULL;
985 pending_buf_len_ = 0;
986 pending_callback_.Reset();
988 int result = read_data_.result;
989 DCHECK(result != ERR_IO_PENDING);
991 if (read_data_.data) {
992 if (read_data_.data_len - read_offset_ > 0) {
993 result = std::min(buf_len, read_data_.data_len - read_offset_);
994 memcpy(buf->data(), read_data_.data + read_offset_, result);
995 read_offset_ += result;
996 if (read_offset_ == read_data_.data_len) {
997 need_read_data_ = true;
998 read_offset_ = 0;
1000 } else {
1001 result = 0; // EOF
1005 if (read_data_.mode == ASYNC) {
1006 DCHECK(!callback.is_null());
1007 RunCallbackAsync(callback, result);
1008 return ERR_IO_PENDING;
1010 return result;
1013 DeterministicSocketHelper::DeterministicSocketHelper(
1014 net::NetLog* net_log,
1015 DeterministicSocketData* data)
1016 : write_pending_(false),
1017 write_result_(0),
1018 read_data_(),
1019 read_buf_(NULL),
1020 read_buf_len_(0),
1021 read_pending_(false),
1022 data_(data),
1023 was_used_to_convey_data_(false),
1024 peer_closed_connection_(false),
1025 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)) {
1028 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1030 void DeterministicSocketHelper::CompleteWrite() {
1031 was_used_to_convey_data_ = true;
1032 write_pending_ = false;
1033 write_callback_.Run(write_result_);
1036 int DeterministicSocketHelper::CompleteRead() {
1037 DCHECK_GT(read_buf_len_, 0);
1038 DCHECK_LE(read_data_.data_len, read_buf_len_);
1039 DCHECK(read_buf_);
1041 was_used_to_convey_data_ = true;
1043 if (read_data_.result == ERR_IO_PENDING)
1044 read_data_ = data_->OnRead();
1045 DCHECK_NE(ERR_IO_PENDING, read_data_.result);
1046 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1047 // the callback. Therefore we don't even bother to check it.
1048 int result = read_data_.result;
1050 if (read_data_.data_len > 0) {
1051 DCHECK(read_data_.data);
1052 result = std::min(read_buf_len_, read_data_.data_len);
1053 memcpy(read_buf_->data(), read_data_.data, result);
1056 if (read_pending_) {
1057 read_pending_ = false;
1058 read_callback_.Run(result);
1061 return result;
1064 int DeterministicSocketHelper::Write(
1065 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1066 DCHECK(buf);
1067 DCHECK_GT(buf_len, 0);
1069 std::string data(buf->data(), buf_len);
1070 MockWriteResult write_result = data_->OnWrite(data);
1072 if (write_result.mode == ASYNC) {
1073 write_callback_ = callback;
1074 write_result_ = write_result.result;
1075 DCHECK(!write_callback_.is_null());
1076 write_pending_ = true;
1077 return ERR_IO_PENDING;
1080 was_used_to_convey_data_ = true;
1081 write_pending_ = false;
1082 return write_result.result;
1085 int DeterministicSocketHelper::Read(
1086 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1087 read_data_ = data_->OnRead();
1088 // The buffer should always be big enough to contain all the MockRead data. To
1089 // use small buffers, split the data into multiple MockReads.
1090 DCHECK_LE(read_data_.data_len, buf_len);
1092 if (read_data_.result == ERR_CONNECTION_CLOSED) {
1093 // This MockRead is just a marker to instruct us to set
1094 // peer_closed_connection_.
1095 peer_closed_connection_ = true;
1097 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
1098 // This MockRead is just a marker to instruct us to set
1099 // peer_closed_connection_. Skip it and get the next one.
1100 read_data_ = data_->OnRead();
1101 peer_closed_connection_ = true;
1104 read_buf_ = buf;
1105 read_buf_len_ = buf_len;
1106 read_callback_ = callback;
1108 if (read_data_.mode == ASYNC || (read_data_.result == ERR_IO_PENDING)) {
1109 read_pending_ = true;
1110 DCHECK(!read_callback_.is_null());
1111 return ERR_IO_PENDING;
1114 was_used_to_convey_data_ = true;
1115 return CompleteRead();
1118 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1119 net::NetLog* net_log,
1120 DeterministicSocketData* data)
1121 : connected_(false),
1122 helper_(net_log, data),
1123 source_port_(123) {
1126 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1128 bool DeterministicMockUDPClientSocket::WritePending() const {
1129 return helper_.write_pending();
1132 bool DeterministicMockUDPClientSocket::ReadPending() const {
1133 return helper_.read_pending();
1136 void DeterministicMockUDPClientSocket::CompleteWrite() {
1137 helper_.CompleteWrite();
1140 int DeterministicMockUDPClientSocket::CompleteRead() {
1141 return helper_.CompleteRead();
1144 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint& address) {
1145 if (connected_)
1146 return OK;
1147 connected_ = true;
1148 peer_address_ = address;
1149 return helper_.data()->connect_data().result;
1152 int DeterministicMockUDPClientSocket::Write(
1153 IOBuffer* buf,
1154 int buf_len,
1155 const CompletionCallback& callback) {
1156 if (!connected_)
1157 return ERR_UNEXPECTED;
1159 return helper_.Write(buf, buf_len, callback);
1162 int DeterministicMockUDPClientSocket::Read(
1163 IOBuffer* buf,
1164 int buf_len,
1165 const CompletionCallback& callback) {
1166 if (!connected_)
1167 return ERR_UNEXPECTED;
1169 return helper_.Read(buf, buf_len, callback);
1172 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1173 return OK;
1176 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size) {
1177 return OK;
1180 void DeterministicMockUDPClientSocket::Close() {
1181 connected_ = false;
1184 int DeterministicMockUDPClientSocket::GetPeerAddress(
1185 IPEndPoint* address) const {
1186 *address = peer_address_;
1187 return OK;
1190 int DeterministicMockUDPClientSocket::GetLocalAddress(
1191 IPEndPoint* address) const {
1192 IPAddressNumber ip;
1193 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1194 CHECK(rv);
1195 *address = IPEndPoint(ip, source_port_);
1196 return OK;
1199 const BoundNetLog& DeterministicMockUDPClientSocket::NetLog() const {
1200 return helper_.net_log();
1203 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead& data) {}
1205 void DeterministicMockUDPClientSocket::OnConnectComplete(
1206 const MockConnect& data) {
1207 NOTIMPLEMENTED();
1210 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1211 net::NetLog* net_log,
1212 DeterministicSocketData* data)
1213 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1214 helper_(net_log, data) {
1215 peer_addr_ = data->connect_data().peer_addr;
1218 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1220 bool DeterministicMockTCPClientSocket::WritePending() const {
1221 return helper_.write_pending();
1224 bool DeterministicMockTCPClientSocket::ReadPending() const {
1225 return helper_.read_pending();
1228 void DeterministicMockTCPClientSocket::CompleteWrite() {
1229 helper_.CompleteWrite();
1232 int DeterministicMockTCPClientSocket::CompleteRead() {
1233 return helper_.CompleteRead();
1236 int DeterministicMockTCPClientSocket::Write(
1237 IOBuffer* buf,
1238 int buf_len,
1239 const CompletionCallback& callback) {
1240 if (!connected_)
1241 return ERR_UNEXPECTED;
1243 return helper_.Write(buf, buf_len, callback);
1246 int DeterministicMockTCPClientSocket::Read(
1247 IOBuffer* buf,
1248 int buf_len,
1249 const CompletionCallback& callback) {
1250 if (!connected_)
1251 return ERR_UNEXPECTED;
1253 return helper_.Read(buf, buf_len, callback);
1256 // TODO(erikchen): Support connect sequencing.
1257 int DeterministicMockTCPClientSocket::Connect(
1258 const CompletionCallback& callback) {
1259 if (connected_)
1260 return OK;
1261 connected_ = true;
1262 if (helper_.data()->connect_data().mode == ASYNC) {
1263 RunCallbackAsync(callback, helper_.data()->connect_data().result);
1264 return ERR_IO_PENDING;
1266 return helper_.data()->connect_data().result;
1269 void DeterministicMockTCPClientSocket::Disconnect() {
1270 MockClientSocket::Disconnect();
1273 bool DeterministicMockTCPClientSocket::IsConnected() const {
1274 return connected_ && !helper_.peer_closed_connection();
1277 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1278 return IsConnected();
1281 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1282 return helper_.was_used_to_convey_data();
1285 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1286 return false;
1289 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1290 return false;
1293 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1294 return false;
1297 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead& data) {}
1299 void DeterministicMockTCPClientSocket::OnConnectComplete(
1300 const MockConnect& data) {}
1302 // static
1303 void MockSSLClientSocket::ConnectCallback(
1304 MockSSLClientSocket* ssl_client_socket,
1305 const CompletionCallback& callback,
1306 int rv) {
1307 if (rv == OK)
1308 ssl_client_socket->connected_ = true;
1309 callback.Run(rv);
1312 MockSSLClientSocket::MockSSLClientSocket(
1313 scoped_ptr<ClientSocketHandle> transport_socket,
1314 const HostPortPair& host_port_pair,
1315 const SSLConfig& ssl_config,
1316 SSLSocketDataProvider* data)
1317 : MockClientSocket(
1318 // Have to use the right BoundNetLog for LoadTimingInfo regression
1319 // tests.
1320 transport_socket->socket()->NetLog()),
1321 transport_(transport_socket.Pass()),
1322 data_(data),
1323 is_npn_state_set_(false),
1324 new_npn_value_(false),
1325 is_protocol_negotiated_set_(false),
1326 protocol_negotiated_(kProtoUnknown) {
1327 DCHECK(data_);
1328 peer_addr_ = data->connect.peer_addr;
1331 MockSSLClientSocket::~MockSSLClientSocket() {
1332 Disconnect();
1335 int MockSSLClientSocket::Read(IOBuffer* buf, int buf_len,
1336 const CompletionCallback& callback) {
1337 return transport_->socket()->Read(buf, buf_len, callback);
1340 int MockSSLClientSocket::Write(IOBuffer* buf, int buf_len,
1341 const CompletionCallback& callback) {
1342 return transport_->socket()->Write(buf, buf_len, callback);
1345 int MockSSLClientSocket::Connect(const CompletionCallback& callback) {
1346 int rv = transport_->socket()->Connect(
1347 base::Bind(&ConnectCallback, base::Unretained(this), callback));
1348 if (rv == OK) {
1349 if (data_->connect.result == OK)
1350 connected_ = true;
1351 if (data_->connect.mode == ASYNC) {
1352 RunCallbackAsync(callback, data_->connect.result);
1353 return ERR_IO_PENDING;
1355 return data_->connect.result;
1357 return rv;
1360 void MockSSLClientSocket::Disconnect() {
1361 MockClientSocket::Disconnect();
1362 if (transport_->socket() != NULL)
1363 transport_->socket()->Disconnect();
1366 bool MockSSLClientSocket::IsConnected() const {
1367 return transport_->socket()->IsConnected();
1370 bool MockSSLClientSocket::WasEverUsed() const {
1371 return transport_->socket()->WasEverUsed();
1374 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1375 return transport_->socket()->UsingTCPFastOpen();
1378 int MockSSLClientSocket::GetPeerAddress(IPEndPoint* address) const {
1379 return transport_->socket()->GetPeerAddress(address);
1382 bool MockSSLClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1383 ssl_info->Reset();
1384 ssl_info->cert = data_->cert;
1385 ssl_info->client_cert_sent = data_->client_cert_sent;
1386 ssl_info->channel_id_sent = data_->channel_id_sent;
1387 ssl_info->connection_status = data_->connection_status;
1388 return true;
1391 void MockSSLClientSocket::GetSSLCertRequestInfo(
1392 SSLCertRequestInfo* cert_request_info) {
1393 DCHECK(cert_request_info);
1394 if (data_->cert_request_info) {
1395 cert_request_info->host_and_port =
1396 data_->cert_request_info->host_and_port;
1397 cert_request_info->client_certs = data_->cert_request_info->client_certs;
1398 } else {
1399 cert_request_info->Reset();
1403 SSLClientSocket::NextProtoStatus MockSSLClientSocket::GetNextProto(
1404 std::string* proto) {
1405 *proto = data_->next_proto;
1406 return data_->next_proto_status;
1409 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated) {
1410 is_npn_state_set_ = true;
1411 return new_npn_value_ = negotiated;
1414 bool MockSSLClientSocket::WasNpnNegotiated() const {
1415 if (is_npn_state_set_)
1416 return new_npn_value_;
1417 return data_->was_npn_negotiated;
1420 NextProto MockSSLClientSocket::GetNegotiatedProtocol() const {
1421 if (is_protocol_negotiated_set_)
1422 return protocol_negotiated_;
1423 return data_->protocol_negotiated;
1426 void MockSSLClientSocket::set_protocol_negotiated(
1427 NextProto protocol_negotiated) {
1428 is_protocol_negotiated_set_ = true;
1429 protocol_negotiated_ = protocol_negotiated;
1432 bool MockSSLClientSocket::WasChannelIDSent() const {
1433 return data_->channel_id_sent;
1436 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent) {
1437 data_->channel_id_sent = channel_id_sent;
1440 ChannelIDService* MockSSLClientSocket::GetChannelIDService() const {
1441 return data_->channel_id_service;
1444 void MockSSLClientSocket::OnReadComplete(const MockRead& data) {
1445 NOTIMPLEMENTED();
1448 void MockSSLClientSocket::OnConnectComplete(const MockConnect& data) {
1449 NOTIMPLEMENTED();
1452 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data,
1453 net::NetLog* net_log)
1454 : connected_(false),
1455 data_(data),
1456 read_offset_(0),
1457 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
1458 need_read_data_(true),
1459 source_port_(123),
1460 pending_buf_(NULL),
1461 pending_buf_len_(0),
1462 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1463 weak_factory_(this) {
1464 DCHECK(data_);
1465 data_->Reset();
1466 peer_addr_ = data->connect_data().peer_addr;
1469 MockUDPClientSocket::~MockUDPClientSocket() {}
1471 int MockUDPClientSocket::Read(IOBuffer* buf,
1472 int buf_len,
1473 const CompletionCallback& callback) {
1474 if (!connected_)
1475 return ERR_UNEXPECTED;
1477 // If the buffer is already in use, a read is already in progress!
1478 DCHECK(pending_buf_.get() == NULL);
1480 // Store our async IO data.
1481 pending_buf_ = buf;
1482 pending_buf_len_ = buf_len;
1483 pending_callback_ = callback;
1485 if (need_read_data_) {
1486 read_data_ = data_->OnRead();
1487 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1488 // to complete the async IO manually later (via OnReadComplete).
1489 if (read_data_.result == ERR_IO_PENDING) {
1490 // We need to be using async IO in this case.
1491 DCHECK(!callback.is_null());
1492 return ERR_IO_PENDING;
1494 need_read_data_ = false;
1497 return CompleteRead();
1500 int MockUDPClientSocket::Write(IOBuffer* buf, int buf_len,
1501 const CompletionCallback& callback) {
1502 DCHECK(buf);
1503 DCHECK_GT(buf_len, 0);
1505 if (!connected_)
1506 return ERR_UNEXPECTED;
1508 std::string data(buf->data(), buf_len);
1509 MockWriteResult write_result = data_->OnWrite(data);
1511 if (write_result.mode == ASYNC) {
1512 RunCallbackAsync(callback, write_result.result);
1513 return ERR_IO_PENDING;
1515 return write_result.result;
1518 int MockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1519 return OK;
1522 int MockUDPClientSocket::SetSendBufferSize(int32 size) {
1523 return OK;
1526 void MockUDPClientSocket::Close() {
1527 connected_ = false;
1530 int MockUDPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1531 *address = peer_addr_;
1532 return OK;
1535 int MockUDPClientSocket::GetLocalAddress(IPEndPoint* address) const {
1536 IPAddressNumber ip;
1537 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1538 CHECK(rv);
1539 *address = IPEndPoint(ip, source_port_);
1540 return OK;
1543 const BoundNetLog& MockUDPClientSocket::NetLog() const {
1544 return net_log_;
1547 int MockUDPClientSocket::Connect(const IPEndPoint& address) {
1548 connected_ = true;
1549 peer_addr_ = address;
1550 return data_->connect_data().result;
1553 void MockUDPClientSocket::OnReadComplete(const MockRead& data) {
1554 // There must be a read pending.
1555 DCHECK(pending_buf_.get());
1556 // You can't complete a read with another ERR_IO_PENDING status code.
1557 DCHECK_NE(ERR_IO_PENDING, data.result);
1558 // Since we've been waiting for data, need_read_data_ should be true.
1559 DCHECK(need_read_data_);
1561 read_data_ = data;
1562 need_read_data_ = false;
1564 // The caller is simulating that this IO completes right now. Don't
1565 // let CompleteRead() schedule a callback.
1566 read_data_.mode = SYNCHRONOUS;
1568 net::CompletionCallback callback = pending_callback_;
1569 int rv = CompleteRead();
1570 RunCallback(callback, rv);
1573 void MockUDPClientSocket::OnConnectComplete(const MockConnect& data) {
1574 NOTIMPLEMENTED();
1577 int MockUDPClientSocket::CompleteRead() {
1578 DCHECK(pending_buf_.get());
1579 DCHECK(pending_buf_len_ > 0);
1581 // Save the pending async IO data and reset our |pending_| state.
1582 scoped_refptr<IOBuffer> buf = pending_buf_;
1583 int buf_len = pending_buf_len_;
1584 CompletionCallback callback = pending_callback_;
1585 pending_buf_ = NULL;
1586 pending_buf_len_ = 0;
1587 pending_callback_.Reset();
1589 int result = read_data_.result;
1590 DCHECK(result != ERR_IO_PENDING);
1592 if (read_data_.data) {
1593 if (read_data_.data_len - read_offset_ > 0) {
1594 result = std::min(buf_len, read_data_.data_len - read_offset_);
1595 memcpy(buf->data(), read_data_.data + read_offset_, result);
1596 read_offset_ += result;
1597 if (read_offset_ == read_data_.data_len) {
1598 need_read_data_ = true;
1599 read_offset_ = 0;
1601 } else {
1602 result = 0; // EOF
1606 if (read_data_.mode == ASYNC) {
1607 DCHECK(!callback.is_null());
1608 RunCallbackAsync(callback, result);
1609 return ERR_IO_PENDING;
1611 return result;
1614 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback& callback,
1615 int result) {
1616 base::MessageLoop::current()->PostTask(
1617 FROM_HERE,
1618 base::Bind(&MockUDPClientSocket::RunCallback,
1619 weak_factory_.GetWeakPtr(),
1620 callback,
1621 result));
1624 void MockUDPClientSocket::RunCallback(const CompletionCallback& callback,
1625 int result) {
1626 if (!callback.is_null())
1627 callback.Run(result);
1630 TestSocketRequest::TestSocketRequest(
1631 std::vector<TestSocketRequest*>* request_order, size_t* completion_count)
1632 : request_order_(request_order),
1633 completion_count_(completion_count),
1634 callback_(base::Bind(&TestSocketRequest::OnComplete,
1635 base::Unretained(this))) {
1636 DCHECK(request_order);
1637 DCHECK(completion_count);
1640 TestSocketRequest::~TestSocketRequest() {
1643 void TestSocketRequest::OnComplete(int result) {
1644 SetResult(result);
1645 (*completion_count_)++;
1646 request_order_->push_back(this);
1649 // static
1650 const int ClientSocketPoolTest::kIndexOutOfBounds = -1;
1652 // static
1653 const int ClientSocketPoolTest::kRequestNotFound = -2;
1655 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1656 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1658 int ClientSocketPoolTest::GetOrderOfRequest(size_t index) const {
1659 index--;
1660 if (index >= requests_.size())
1661 return kIndexOutOfBounds;
1663 for (size_t i = 0; i < request_order_.size(); i++)
1664 if (requests_[index] == request_order_[i])
1665 return i + 1;
1667 return kRequestNotFound;
1670 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
1671 ScopedVector<TestSocketRequest>::iterator i;
1672 for (i = requests_.begin(); i != requests_.end(); ++i) {
1673 if ((*i)->handle()->is_initialized()) {
1674 if (keep_alive == NO_KEEP_ALIVE)
1675 (*i)->handle()->socket()->Disconnect();
1676 (*i)->handle()->Reset();
1677 base::RunLoop().RunUntilIdle();
1678 return true;
1681 return false;
1684 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
1685 bool released_one;
1686 do {
1687 released_one = ReleaseOneConnection(keep_alive);
1688 } while (released_one);
1691 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1692 scoped_ptr<StreamSocket> socket,
1693 ClientSocketHandle* handle,
1694 const CompletionCallback& callback)
1695 : socket_(socket.Pass()),
1696 handle_(handle),
1697 user_callback_(callback) {
1700 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1702 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1703 int rv = socket_->Connect(base::Bind(&MockConnectJob::OnConnect,
1704 base::Unretained(this)));
1705 if (rv == OK) {
1706 user_callback_.Reset();
1707 OnConnect(OK);
1709 return rv;
1712 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1713 const ClientSocketHandle* handle) {
1714 if (handle != handle_)
1715 return false;
1716 socket_.reset();
1717 handle_ = NULL;
1718 user_callback_.Reset();
1719 return true;
1722 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) {
1723 if (!socket_.get())
1724 return;
1725 if (rv == OK) {
1726 handle_->SetSocket(socket_.Pass());
1728 // Needed for socket pool tests that layer other sockets on top of mock
1729 // sockets.
1730 LoadTimingInfo::ConnectTiming connect_timing;
1731 base::TimeTicks now = base::TimeTicks::Now();
1732 connect_timing.dns_start = now;
1733 connect_timing.dns_end = now;
1734 connect_timing.connect_start = now;
1735 connect_timing.connect_end = now;
1736 handle_->set_connect_timing(connect_timing);
1737 } else {
1738 socket_.reset();
1741 handle_ = NULL;
1743 if (!user_callback_.is_null()) {
1744 CompletionCallback callback = user_callback_;
1745 user_callback_.Reset();
1746 callback.Run(rv);
1750 MockTransportClientSocketPool::MockTransportClientSocketPool(
1751 int max_sockets,
1752 int max_sockets_per_group,
1753 ClientSocketFactory* socket_factory)
1754 : TransportClientSocketPool(max_sockets,
1755 max_sockets_per_group,
1756 NULL,
1757 NULL,
1758 NULL),
1759 client_socket_factory_(socket_factory),
1760 last_request_priority_(DEFAULT_PRIORITY),
1761 release_count_(0),
1762 cancel_count_(0) {
1765 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1767 int MockTransportClientSocketPool::RequestSocket(
1768 const std::string& group_name, const void* socket_params,
1769 RequestPriority priority, ClientSocketHandle* handle,
1770 const CompletionCallback& callback, const BoundNetLog& net_log) {
1771 last_request_priority_ = priority;
1772 scoped_ptr<StreamSocket> socket =
1773 client_socket_factory_->CreateTransportClientSocket(
1774 AddressList(), net_log.net_log(), net::NetLog::Source());
1775 MockConnectJob* job = new MockConnectJob(socket.Pass(), handle, callback);
1776 job_list_.push_back(job);
1777 handle->set_pool_id(1);
1778 return job->Connect();
1781 void MockTransportClientSocketPool::CancelRequest(const std::string& group_name,
1782 ClientSocketHandle* handle) {
1783 std::vector<MockConnectJob*>::iterator i;
1784 for (i = job_list_.begin(); i != job_list_.end(); ++i) {
1785 if ((*i)->CancelHandle(handle)) {
1786 cancel_count_++;
1787 break;
1792 void MockTransportClientSocketPool::ReleaseSocket(
1793 const std::string& group_name,
1794 scoped_ptr<StreamSocket> socket,
1795 int id) {
1796 EXPECT_EQ(1, id);
1797 release_count_++;
1800 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1802 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1804 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1805 DeterministicSocketData* data) {
1806 mock_data_.Add(data);
1809 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1810 SSLSocketDataProvider* data) {
1811 mock_ssl_data_.Add(data);
1814 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1815 mock_data_.ResetNextIndex();
1816 mock_ssl_data_.ResetNextIndex();
1819 MockSSLClientSocket* DeterministicMockClientSocketFactory::
1820 GetMockSSLClientSocket(size_t index) const {
1821 DCHECK_LT(index, ssl_client_sockets_.size());
1822 return ssl_client_sockets_[index];
1825 scoped_ptr<DatagramClientSocket>
1826 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1827 DatagramSocket::BindType bind_type,
1828 const RandIntCallback& rand_int_cb,
1829 net::NetLog* net_log,
1830 const NetLog::Source& source) {
1831 DeterministicSocketData* data_provider = mock_data().GetNext();
1832 scoped_ptr<DeterministicMockUDPClientSocket> socket(
1833 new DeterministicMockUDPClientSocket(net_log, data_provider));
1834 data_provider->set_delegate(socket->AsWeakPtr());
1835 udp_client_sockets().push_back(socket.get());
1836 if (bind_type == DatagramSocket::RANDOM_BIND)
1837 socket->set_source_port(static_cast<uint16>(rand_int_cb.Run(1025, 65535)));
1838 return socket.Pass();
1841 scoped_ptr<StreamSocket>
1842 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1843 const AddressList& addresses,
1844 net::NetLog* net_log,
1845 const net::NetLog::Source& source) {
1846 DeterministicSocketData* data_provider = mock_data().GetNext();
1847 scoped_ptr<DeterministicMockTCPClientSocket> socket(
1848 new DeterministicMockTCPClientSocket(net_log, data_provider));
1849 data_provider->set_delegate(socket->AsWeakPtr());
1850 tcp_client_sockets().push_back(socket.get());
1851 return socket.Pass();
1854 scoped_ptr<SSLClientSocket>
1855 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1856 scoped_ptr<ClientSocketHandle> transport_socket,
1857 const HostPortPair& host_and_port,
1858 const SSLConfig& ssl_config,
1859 const SSLClientSocketContext& context) {
1860 scoped_ptr<MockSSLClientSocket> socket(
1861 new MockSSLClientSocket(transport_socket.Pass(),
1862 host_and_port, ssl_config,
1863 mock_ssl_data_.GetNext()));
1864 ssl_client_sockets_.push_back(socket.get());
1865 return socket.Pass();
1868 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1871 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1872 int max_sockets,
1873 int max_sockets_per_group,
1874 TransportClientSocketPool* transport_pool)
1875 : SOCKSClientSocketPool(max_sockets,
1876 max_sockets_per_group,
1877 NULL,
1878 transport_pool,
1879 NULL),
1880 transport_pool_(transport_pool) {
1883 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1885 int MockSOCKSClientSocketPool::RequestSocket(
1886 const std::string& group_name, const void* socket_params,
1887 RequestPriority priority, ClientSocketHandle* handle,
1888 const CompletionCallback& callback, const BoundNetLog& net_log) {
1889 return transport_pool_->RequestSocket(
1890 group_name, socket_params, priority, handle, callback, net_log);
1893 void MockSOCKSClientSocketPool::CancelRequest(
1894 const std::string& group_name,
1895 ClientSocketHandle* handle) {
1896 return transport_pool_->CancelRequest(group_name, handle);
1899 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string& group_name,
1900 scoped_ptr<StreamSocket> socket,
1901 int id) {
1902 return transport_pool_->ReleaseSocket(group_name, socket.Pass(), id);
1905 ScopedWebSocketEndpointZeroUnlockDelay::
1906 ScopedWebSocketEndpointZeroUnlockDelay() {
1907 old_delay_ =
1908 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
1909 base::TimeDelta());
1912 ScopedWebSocketEndpointZeroUnlockDelay::
1913 ~ScopedWebSocketEndpointZeroUnlockDelay() {
1914 base::TimeDelta active_delay =
1915 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
1916 old_delay_);
1917 EXPECT_EQ(active_delay, base::TimeDelta());
1920 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
1921 const int kSOCKS5GreetRequestLength = arraysize(kSOCKS5GreetRequest);
1923 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
1924 const int kSOCKS5GreetResponseLength = arraysize(kSOCKS5GreetResponse);
1926 const char kSOCKS5OkRequest[] =
1927 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1928 const int kSOCKS5OkRequestLength = arraysize(kSOCKS5OkRequest);
1930 const char kSOCKS5OkResponse[] =
1931 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1932 const int kSOCKS5OkResponseLength = arraysize(kSOCKS5OkResponse);
1934 } // namespace net