QUIC - enable persisting of QUICServerInfo (server config) to disk
[chromium-blink-merge.git] / net / socket / socket_test_util.cc
blob287bb53a37087867e30b9c98eb669d5d67935b89
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/client_socket_pool_histograms.h"
25 #include "net/socket/socket.h"
26 #include "net/ssl/ssl_cert_request_info.h"
27 #include "net/ssl/ssl_connection_status_flags.h"
28 #include "net/ssl/ssl_info.h"
29 #include "testing/gtest/include/gtest/gtest.h"
31 // Socket events are easier to debug if you log individual reads and writes.
32 // Enable these if locally debugging, but they are too noisy for the waterfall.
33 #if 0
34 #define NET_TRACE(level, s) DLOG(level) << s << __FUNCTION__ << "() "
35 #else
36 #define NET_TRACE(level, s) EAT_STREAM_PARAMETERS
37 #endif
39 namespace net {
41 namespace {
43 inline char AsciifyHigh(char x) {
44 char nybble = static_cast<char>((x >> 4) & 0x0F);
45 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
48 inline char AsciifyLow(char x) {
49 char nybble = static_cast<char>((x >> 0) & 0x0F);
50 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
53 inline char Asciify(char x) {
54 if ((x < 0) || !isprint(x))
55 return '.';
56 return x;
59 void DumpData(const char* data, int data_len) {
60 if (logging::LOG_INFO < logging::GetMinLogLevel())
61 return;
62 DVLOG(1) << "Length: " << data_len;
63 const char* pfx = "Data: ";
64 if (!data || (data_len <= 0)) {
65 DVLOG(1) << pfx << "<None>";
66 } else {
67 int i;
68 for (i = 0; i <= (data_len - 4); i += 4) {
69 DVLOG(1) << pfx
70 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
71 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
72 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
73 << AsciifyHigh(data[i + 3]) << AsciifyLow(data[i + 3])
74 << " '"
75 << Asciify(data[i + 0])
76 << Asciify(data[i + 1])
77 << Asciify(data[i + 2])
78 << Asciify(data[i + 3])
79 << "'";
80 pfx = " ";
82 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
83 switch (data_len - i) {
84 case 3:
85 DVLOG(1) << pfx
86 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
87 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
88 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
89 << " '"
90 << Asciify(data[i + 0])
91 << Asciify(data[i + 1])
92 << Asciify(data[i + 2])
93 << " '";
94 break;
95 case 2:
96 DVLOG(1) << pfx
97 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
98 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
99 << " '"
100 << Asciify(data[i + 0])
101 << Asciify(data[i + 1])
102 << " '";
103 break;
104 case 1:
105 DVLOG(1) << pfx
106 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
107 << " '"
108 << Asciify(data[i + 0])
109 << " '";
110 break;
115 template <MockReadWriteType type>
116 void DumpMockReadWrite(const MockReadWrite<type>& r) {
117 if (logging::LOG_INFO < logging::GetMinLogLevel())
118 return;
119 DVLOG(1) << "Async: " << (r.mode == ASYNC)
120 << "\nResult: " << r.result;
121 DumpData(r.data, r.data_len);
122 const char* stop = (r.sequence_number & MockRead::STOPLOOP) ? " (STOP)" : "";
123 DVLOG(1) << "Stage: " << (r.sequence_number & ~MockRead::STOPLOOP) << stop
124 << "\nTime: " << r.time_stamp.ToInternalValue();
127 } // namespace
129 MockConnect::MockConnect() : mode(ASYNC), result(OK) {
130 IPAddressNumber ip;
131 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
132 peer_addr = IPEndPoint(ip, 0);
135 MockConnect::MockConnect(IoMode io_mode, int r) : mode(io_mode), result(r) {
136 IPAddressNumber ip;
137 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
138 peer_addr = IPEndPoint(ip, 0);
141 MockConnect::MockConnect(IoMode io_mode, int r, IPEndPoint addr) :
142 mode(io_mode),
143 result(r),
144 peer_addr(addr) {
147 MockConnect::~MockConnect() {}
149 StaticSocketDataProvider::StaticSocketDataProvider()
150 : reads_(NULL),
151 read_index_(0),
152 read_count_(0),
153 writes_(NULL),
154 write_index_(0),
155 write_count_(0) {
158 StaticSocketDataProvider::StaticSocketDataProvider(MockRead* reads,
159 size_t reads_count,
160 MockWrite* writes,
161 size_t writes_count)
162 : reads_(reads),
163 read_index_(0),
164 read_count_(reads_count),
165 writes_(writes),
166 write_index_(0),
167 write_count_(writes_count) {
170 StaticSocketDataProvider::~StaticSocketDataProvider() {}
172 const MockRead& StaticSocketDataProvider::PeekRead() const {
173 CHECK(!at_read_eof());
174 return reads_[read_index_];
177 const MockWrite& StaticSocketDataProvider::PeekWrite() const {
178 CHECK(!at_write_eof());
179 return writes_[write_index_];
182 const MockRead& StaticSocketDataProvider::PeekRead(size_t index) const {
183 CHECK_LT(index, read_count_);
184 return reads_[index];
187 const MockWrite& StaticSocketDataProvider::PeekWrite(size_t index) const {
188 CHECK_LT(index, write_count_);
189 return writes_[index];
192 MockRead StaticSocketDataProvider::GetNextRead() {
193 CHECK(!at_read_eof());
194 reads_[read_index_].time_stamp = base::Time::Now();
195 return reads_[read_index_++];
198 MockWriteResult StaticSocketDataProvider::OnWrite(const std::string& data) {
199 if (!writes_) {
200 // Not using mock writes; succeed synchronously.
201 return MockWriteResult(SYNCHRONOUS, data.length());
203 EXPECT_FALSE(at_write_eof());
204 if (at_write_eof()) {
205 // Show what the extra write actually consists of.
206 EXPECT_EQ("<unexpected write>", data);
207 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
210 // Check that what we are writing matches the expectation.
211 // Then give the mocked return value.
212 MockWrite* w = &writes_[write_index_++];
213 w->time_stamp = base::Time::Now();
214 int result = w->result;
215 if (w->data) {
216 // Note - we can simulate a partial write here. If the expected data
217 // is a match, but shorter than the write actually written, that is legal.
218 // Example:
219 // Application writes "foobarbaz" (9 bytes)
220 // Expected write was "foo" (3 bytes)
221 // This is a success, and we return 3 to the application.
222 std::string expected_data(w->data, w->data_len);
223 EXPECT_GE(data.length(), expected_data.length());
224 std::string actual_data(data.substr(0, w->data_len));
225 EXPECT_EQ(expected_data, actual_data);
226 if (expected_data != actual_data)
227 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
228 if (result == OK)
229 result = w->data_len;
231 return MockWriteResult(w->mode, result);
234 void StaticSocketDataProvider::Reset() {
235 read_index_ = 0;
236 write_index_ = 0;
239 DynamicSocketDataProvider::DynamicSocketDataProvider()
240 : short_read_limit_(0),
241 allow_unconsumed_reads_(false) {
244 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
246 MockRead DynamicSocketDataProvider::GetNextRead() {
247 if (reads_.empty())
248 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
249 MockRead result = reads_.front();
250 if (short_read_limit_ == 0 || result.data_len <= short_read_limit_) {
251 reads_.pop_front();
252 } else {
253 result.data_len = short_read_limit_;
254 reads_.front().data += result.data_len;
255 reads_.front().data_len -= result.data_len;
257 return result;
260 void DynamicSocketDataProvider::Reset() {
261 reads_.clear();
264 void DynamicSocketDataProvider::SimulateRead(const char* data,
265 const size_t length) {
266 if (!allow_unconsumed_reads_) {
267 EXPECT_TRUE(reads_.empty()) << "Unconsumed read: " << reads_.front().data;
269 reads_.push_back(MockRead(ASYNC, data, length));
272 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode, int result)
273 : connect(mode, result),
274 next_proto_status(SSLClientSocket::kNextProtoUnsupported),
275 was_npn_negotiated(false),
276 protocol_negotiated(kProtoUnknown),
277 client_cert_sent(false),
278 cert_request_info(NULL),
279 channel_id_sent(false),
280 connection_status(0) {
281 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2,
282 &connection_status);
283 // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
284 SSLConnectionStatusSetCipherSuite(0xcc14, &connection_status);
287 SSLSocketDataProvider::~SSLSocketDataProvider() {
290 void SSLSocketDataProvider::SetNextProto(NextProto proto) {
291 was_npn_negotiated = true;
292 next_proto_status = SSLClientSocket::kNextProtoNegotiated;
293 protocol_negotiated = proto;
294 next_proto = SSLClientSocket::NextProtoToString(proto);
297 DelayedSocketData::DelayedSocketData(
298 int write_delay, MockRead* reads, size_t reads_count,
299 MockWrite* writes, size_t writes_count)
300 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
301 write_delay_(write_delay),
302 read_in_progress_(false),
303 weak_factory_(this) {
304 DCHECK_GE(write_delay_, 0);
307 DelayedSocketData::DelayedSocketData(
308 const MockConnect& connect, int write_delay, MockRead* reads,
309 size_t reads_count, MockWrite* writes, size_t writes_count)
310 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
311 write_delay_(write_delay),
312 read_in_progress_(false),
313 weak_factory_(this) {
314 DCHECK_GE(write_delay_, 0);
315 set_connect_data(connect);
318 DelayedSocketData::~DelayedSocketData() {
321 void DelayedSocketData::ForceNextRead() {
322 DCHECK(read_in_progress_);
323 write_delay_ = 0;
324 CompleteRead();
327 MockRead DelayedSocketData::GetNextRead() {
328 MockRead out = MockRead(ASYNC, ERR_IO_PENDING);
329 if (write_delay_ <= 0)
330 out = StaticSocketDataProvider::GetNextRead();
331 read_in_progress_ = (out.result == ERR_IO_PENDING);
332 return out;
335 MockWriteResult DelayedSocketData::OnWrite(const std::string& data) {
336 MockWriteResult rv = StaticSocketDataProvider::OnWrite(data);
337 // Now that our write has completed, we can allow reads to continue.
338 if (!--write_delay_ && read_in_progress_)
339 base::MessageLoop::current()->PostDelayedTask(
340 FROM_HERE,
341 base::Bind(&DelayedSocketData::CompleteRead,
342 weak_factory_.GetWeakPtr()),
343 base::TimeDelta::FromMilliseconds(100));
344 return rv;
347 void DelayedSocketData::Reset() {
348 set_socket(NULL);
349 read_in_progress_ = false;
350 weak_factory_.InvalidateWeakPtrs();
351 StaticSocketDataProvider::Reset();
354 void DelayedSocketData::CompleteRead() {
355 if (socket() && read_in_progress_)
356 socket()->OnReadComplete(GetNextRead());
359 OrderedSocketData::OrderedSocketData(
360 MockRead* reads, size_t reads_count, MockWrite* writes, size_t writes_count)
361 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
362 sequence_number_(0), loop_stop_stage_(0),
363 blocked_(false), weak_factory_(this) {
366 OrderedSocketData::OrderedSocketData(
367 const MockConnect& connect,
368 MockRead* reads, size_t reads_count,
369 MockWrite* writes, size_t writes_count)
370 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
371 sequence_number_(0), loop_stop_stage_(0),
372 blocked_(false), weak_factory_(this) {
373 set_connect_data(connect);
376 void OrderedSocketData::EndLoop() {
377 // If we've already stopped the loop, don't do it again until we've advanced
378 // to the next sequence_number.
379 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_ << ": EndLoop()";
380 if (loop_stop_stage_ > 0) {
381 const MockRead& next_read = StaticSocketDataProvider::PeekRead();
382 if ((next_read.sequence_number & ~MockRead::STOPLOOP) >
383 loop_stop_stage_) {
384 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
385 << ": Clearing stop index";
386 loop_stop_stage_ = 0;
387 } else {
388 return;
391 // Record the sequence_number at which we stopped the loop.
392 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
393 << ": Posting Quit at read " << read_index();
394 loop_stop_stage_ = sequence_number_;
397 MockRead OrderedSocketData::GetNextRead() {
398 weak_factory_.InvalidateWeakPtrs();
399 blocked_ = false;
400 const MockRead& next_read = StaticSocketDataProvider::PeekRead();
401 if (next_read.sequence_number & MockRead::STOPLOOP)
402 EndLoop();
403 if ((next_read.sequence_number & ~MockRead::STOPLOOP) <=
404 sequence_number_++) {
405 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_ - 1
406 << ": Read " << read_index();
407 DumpMockReadWrite(next_read);
408 blocked_ = (next_read.result == ERR_IO_PENDING);
409 return StaticSocketDataProvider::GetNextRead();
411 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_ - 1
412 << ": 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(INFO, " *** ") << "Stage " << sequence_number_
421 << ": Write " << write_index();
422 DumpMockReadWrite(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(INFO, " *** ") << "Stage "
441 << sequence_number_ << ": Reset()";
442 sequence_number_ = 0;
443 loop_stop_stage_ = 0;
444 set_socket(NULL);
445 weak_factory_.InvalidateWeakPtrs();
446 StaticSocketDataProvider::Reset();
449 void OrderedSocketData::CompleteRead() {
450 if (socket() && blocked_) {
451 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_;
452 socket()->OnReadComplete(GetNextRead());
456 OrderedSocketData::~OrderedSocketData() {}
458 DeterministicSocketData::DeterministicSocketData(MockRead* reads,
459 size_t reads_count, MockWrite* writes, size_t writes_count)
460 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
461 sequence_number_(0),
462 current_read_(),
463 current_write_(),
464 stopping_sequence_number_(0),
465 stopped_(false),
466 print_debug_(false),
467 is_running_(false) {
468 VerifyCorrectSequenceNumbers(reads, reads_count, writes, writes_count);
471 DeterministicSocketData::~DeterministicSocketData() {}
473 void DeterministicSocketData::Run() {
474 DCHECK(!is_running_);
475 is_running_ = true;
477 SetStopped(false);
478 int counter = 0;
479 // Continue to consume data until all data has run out, or the stopped_ flag
480 // has been set. Consuming data requires two separate operations -- running
481 // the tasks in the message loop, and explicitly invoking the read/write
482 // callbacks (simulating network I/O). We check our conditions between each,
483 // since they can change in either.
484 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
485 if (counter % 2 == 0)
486 base::RunLoop().RunUntilIdle();
487 if (counter % 2 == 1) {
488 InvokeCallbacks();
490 counter++;
492 // We're done consuming new data, but it is possible there are still some
493 // pending callbacks which we expect to complete before returning.
494 while (delegate_.get() &&
495 (delegate_->WritePending() || delegate_->ReadPending()) &&
496 !stopped()) {
497 InvokeCallbacks();
498 base::RunLoop().RunUntilIdle();
500 SetStopped(false);
501 is_running_ = false;
504 void DeterministicSocketData::RunFor(int steps) {
505 StopAfter(steps);
506 Run();
509 void DeterministicSocketData::SetStop(int seq) {
510 DCHECK_LT(sequence_number_, seq);
511 stopping_sequence_number_ = seq;
512 stopped_ = false;
515 void DeterministicSocketData::StopAfter(int seq) {
516 SetStop(sequence_number_ + seq);
519 MockRead DeterministicSocketData::GetNextRead() {
520 current_read_ = StaticSocketDataProvider::PeekRead();
522 // Synchronous read while stopped is an error
523 if (stopped() && current_read_.mode == SYNCHRONOUS) {
524 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
525 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
528 // Async read which will be called back in a future step.
529 if (sequence_number_ < current_read_.sequence_number) {
530 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
531 << ": I/O Pending";
532 MockRead result = MockRead(SYNCHRONOUS, ERR_IO_PENDING);
533 if (current_read_.mode == SYNCHRONOUS) {
534 LOG(ERROR) << "Unable to perform synchronous read: "
535 << current_read_.sequence_number
536 << " at stage: " << sequence_number_;
537 result = MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
539 if (print_debug_)
540 DumpMockReadWrite(result);
541 return result;
544 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
545 << ": Read " << read_index();
546 if (print_debug_)
547 DumpMockReadWrite(current_read_);
549 // Increment the sequence number if IO is complete
550 if (current_read_.mode == SYNCHRONOUS)
551 NextStep();
553 DCHECK_NE(ERR_IO_PENDING, current_read_.result);
554 StaticSocketDataProvider::GetNextRead();
556 return current_read_;
559 MockWriteResult DeterministicSocketData::OnWrite(const std::string& data) {
560 const MockWrite& next_write = StaticSocketDataProvider::PeekWrite();
561 current_write_ = next_write;
563 // Synchronous write while stopped is an error
564 if (stopped() && next_write.mode == SYNCHRONOUS) {
565 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
566 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
569 // Async write which will be called back in a future step.
570 if (sequence_number_ < next_write.sequence_number) {
571 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
572 << ": I/O Pending";
573 if (next_write.mode == SYNCHRONOUS) {
574 LOG(ERROR) << "Unable to perform synchronous write: "
575 << next_write.sequence_number << " at stage: " << sequence_number_;
576 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
578 } else {
579 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
580 << ": Write " << write_index();
583 if (print_debug_)
584 DumpMockReadWrite(next_write);
586 // Move to the next step if I/O is synchronous, since the operation will
587 // complete when this method returns.
588 if (next_write.mode == SYNCHRONOUS)
589 NextStep();
591 // This is either a sync write for this step, or an async write.
592 return StaticSocketDataProvider::OnWrite(data);
595 void DeterministicSocketData::Reset() {
596 NET_TRACE(INFO, " *** ") << "Stage "
597 << sequence_number_ << ": Reset()";
598 sequence_number_ = 0;
599 StaticSocketDataProvider::Reset();
600 NOTREACHED();
603 void DeterministicSocketData::InvokeCallbacks() {
604 if (delegate_.get() && delegate_->WritePending() &&
605 (current_write().sequence_number == sequence_number())) {
606 NextStep();
607 delegate_->CompleteWrite();
608 return;
610 if (delegate_.get() && delegate_->ReadPending() &&
611 (current_read().sequence_number == sequence_number())) {
612 NextStep();
613 delegate_->CompleteRead();
614 return;
618 void DeterministicSocketData::NextStep() {
619 // Invariant: Can never move *past* the stopping step.
620 DCHECK_LT(sequence_number_, stopping_sequence_number_);
621 sequence_number_++;
622 if (sequence_number_ == stopping_sequence_number_)
623 SetStopped(true);
626 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
627 MockRead* reads, size_t reads_count,
628 MockWrite* writes, size_t writes_count) {
629 size_t read = 0;
630 size_t write = 0;
631 int expected = 0;
632 while (read < reads_count || write < writes_count) {
633 // Check to see that we have a read or write at the expected
634 // state.
635 if (read < reads_count && reads[read].sequence_number == expected) {
636 ++read;
637 ++expected;
638 continue;
640 if (write < writes_count && writes[write].sequence_number == expected) {
641 ++write;
642 ++expected;
643 continue;
645 NOTREACHED() << "Missing sequence number: " << expected;
646 return;
648 DCHECK_EQ(read, reads_count);
649 DCHECK_EQ(write, writes_count);
652 MockClientSocketFactory::MockClientSocketFactory() {}
654 MockClientSocketFactory::~MockClientSocketFactory() {}
656 void MockClientSocketFactory::AddSocketDataProvider(
657 SocketDataProvider* data) {
658 mock_data_.Add(data);
661 void MockClientSocketFactory::AddSSLSocketDataProvider(
662 SSLSocketDataProvider* data) {
663 mock_ssl_data_.Add(data);
666 void MockClientSocketFactory::ResetNextMockIndexes() {
667 mock_data_.ResetNextIndex();
668 mock_ssl_data_.ResetNextIndex();
671 scoped_ptr<DatagramClientSocket>
672 MockClientSocketFactory::CreateDatagramClientSocket(
673 DatagramSocket::BindType bind_type,
674 const RandIntCallback& rand_int_cb,
675 net::NetLog* net_log,
676 const net::NetLog::Source& source) {
677 SocketDataProvider* data_provider = mock_data_.GetNext();
678 scoped_ptr<MockUDPClientSocket> socket(
679 new MockUDPClientSocket(data_provider, net_log));
680 data_provider->set_socket(socket.get());
681 if (bind_type == DatagramSocket::RANDOM_BIND)
682 socket->set_source_port(rand_int_cb.Run(1025, 65535));
683 return socket.PassAs<DatagramClientSocket>();
686 scoped_ptr<StreamSocket> MockClientSocketFactory::CreateTransportClientSocket(
687 const AddressList& addresses,
688 net::NetLog* net_log,
689 const net::NetLog::Source& source) {
690 SocketDataProvider* data_provider = mock_data_.GetNext();
691 scoped_ptr<MockTCPClientSocket> socket(
692 new MockTCPClientSocket(addresses, net_log, data_provider));
693 data_provider->set_socket(socket.get());
694 return socket.PassAs<StreamSocket>();
697 scoped_ptr<SSLClientSocket> MockClientSocketFactory::CreateSSLClientSocket(
698 scoped_ptr<ClientSocketHandle> transport_socket,
699 const HostPortPair& host_and_port,
700 const SSLConfig& ssl_config,
701 const SSLClientSocketContext& context) {
702 return scoped_ptr<SSLClientSocket>(
703 new MockSSLClientSocket(transport_socket.Pass(),
704 host_and_port, ssl_config,
705 mock_ssl_data_.GetNext()));
708 void MockClientSocketFactory::ClearSSLSessionCache() {
711 const char MockClientSocket::kTlsUnique[] = "MOCK_TLSUNIQ";
713 MockClientSocket::MockClientSocket(const BoundNetLog& net_log)
714 : connected_(false),
715 net_log_(net_log),
716 weak_factory_(this) {
717 IPAddressNumber ip;
718 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
719 peer_addr_ = IPEndPoint(ip, 0);
722 int MockClientSocket::SetReceiveBufferSize(int32 size) {
723 return OK;
726 int MockClientSocket::SetSendBufferSize(int32 size) {
727 return OK;
730 void MockClientSocket::Disconnect() {
731 connected_ = false;
734 bool MockClientSocket::IsConnected() const {
735 return connected_;
738 bool MockClientSocket::IsConnectedAndIdle() const {
739 return connected_;
742 int MockClientSocket::GetPeerAddress(IPEndPoint* address) const {
743 if (!IsConnected())
744 return ERR_SOCKET_NOT_CONNECTED;
745 *address = peer_addr_;
746 return OK;
749 int MockClientSocket::GetLocalAddress(IPEndPoint* address) const {
750 IPAddressNumber ip;
751 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
752 CHECK(rv);
753 *address = IPEndPoint(ip, 123);
754 return OK;
757 const BoundNetLog& MockClientSocket::NetLog() const {
758 return net_log_;
761 void MockClientSocket::GetSSLCertRequestInfo(
762 SSLCertRequestInfo* cert_request_info) {
765 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece& label,
766 bool has_context,
767 const base::StringPiece& context,
768 unsigned char* out,
769 unsigned int outlen) {
770 memset(out, 'A', outlen);
771 return OK;
774 int MockClientSocket::GetTLSUniqueChannelBinding(std::string* out) {
775 out->assign(MockClientSocket::kTlsUnique);
776 return OK;
779 ChannelIDService* MockClientSocket::GetChannelIDService() const {
780 NOTREACHED();
781 return NULL;
784 SSLClientSocket::NextProtoStatus
785 MockClientSocket::GetNextProto(std::string* proto) {
786 proto->clear();
787 return SSLClientSocket::kNextProtoUnsupported;
790 scoped_refptr<X509Certificate>
791 MockClientSocket::GetUnverifiedServerCertificateChain() const {
792 NOTREACHED();
793 return NULL;
796 MockClientSocket::~MockClientSocket() {}
798 void MockClientSocket::RunCallbackAsync(const CompletionCallback& callback,
799 int result) {
800 base::MessageLoop::current()->PostTask(
801 FROM_HERE,
802 base::Bind(&MockClientSocket::RunCallback,
803 weak_factory_.GetWeakPtr(),
804 callback,
805 result));
808 void MockClientSocket::RunCallback(const net::CompletionCallback& callback,
809 int result) {
810 if (!callback.is_null())
811 callback.Run(result);
814 MockTCPClientSocket::MockTCPClientSocket(const AddressList& addresses,
815 net::NetLog* net_log,
816 SocketDataProvider* data)
817 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
818 addresses_(addresses),
819 data_(data),
820 read_offset_(0),
821 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
822 need_read_data_(true),
823 peer_closed_connection_(false),
824 pending_buf_(NULL),
825 pending_buf_len_(0),
826 was_used_to_convey_data_(false) {
827 DCHECK(data_);
828 peer_addr_ = data->connect_data().peer_addr;
829 data_->Reset();
832 MockTCPClientSocket::~MockTCPClientSocket() {}
834 int MockTCPClientSocket::Read(IOBuffer* buf, int buf_len,
835 const CompletionCallback& callback) {
836 if (!connected_)
837 return ERR_UNEXPECTED;
839 // If the buffer is already in use, a read is already in progress!
840 DCHECK(pending_buf_ == NULL);
842 // Store our async IO data.
843 pending_buf_ = buf;
844 pending_buf_len_ = buf_len;
845 pending_callback_ = callback;
847 if (need_read_data_) {
848 read_data_ = data_->GetNextRead();
849 if (read_data_.result == ERR_CONNECTION_CLOSED) {
850 // This MockRead is just a marker to instruct us to set
851 // peer_closed_connection_.
852 peer_closed_connection_ = true;
854 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
855 // This MockRead is just a marker to instruct us to set
856 // peer_closed_connection_. Skip it and get the next one.
857 read_data_ = data_->GetNextRead();
858 peer_closed_connection_ = true;
860 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
861 // to complete the async IO manually later (via OnReadComplete).
862 if (read_data_.result == ERR_IO_PENDING) {
863 // We need to be using async IO in this case.
864 DCHECK(!callback.is_null());
865 return ERR_IO_PENDING;
867 need_read_data_ = false;
870 return CompleteRead();
873 int MockTCPClientSocket::Write(IOBuffer* buf, int buf_len,
874 const CompletionCallback& callback) {
875 DCHECK(buf);
876 DCHECK_GT(buf_len, 0);
878 if (!connected_)
879 return ERR_UNEXPECTED;
881 std::string data(buf->data(), buf_len);
882 MockWriteResult write_result = data_->OnWrite(data);
884 was_used_to_convey_data_ = true;
886 if (write_result.mode == ASYNC) {
887 RunCallbackAsync(callback, write_result.result);
888 return ERR_IO_PENDING;
891 return write_result.result;
894 int MockTCPClientSocket::Connect(const CompletionCallback& callback) {
895 if (connected_)
896 return OK;
897 connected_ = true;
898 peer_closed_connection_ = false;
899 if (data_->connect_data().mode == ASYNC) {
900 if (data_->connect_data().result == ERR_IO_PENDING)
901 pending_callback_ = callback;
902 else
903 RunCallbackAsync(callback, data_->connect_data().result);
904 return ERR_IO_PENDING;
906 return data_->connect_data().result;
909 void MockTCPClientSocket::Disconnect() {
910 MockClientSocket::Disconnect();
911 pending_callback_.Reset();
914 bool MockTCPClientSocket::IsConnected() const {
915 return connected_ && !peer_closed_connection_;
918 bool MockTCPClientSocket::IsConnectedAndIdle() const {
919 return IsConnected();
922 int MockTCPClientSocket::GetPeerAddress(IPEndPoint* address) const {
923 if (addresses_.empty())
924 return MockClientSocket::GetPeerAddress(address);
926 *address = addresses_[0];
927 return OK;
930 bool MockTCPClientSocket::WasEverUsed() const {
931 return was_used_to_convey_data_;
934 bool MockTCPClientSocket::UsingTCPFastOpen() const {
935 return false;
938 bool MockTCPClientSocket::WasNpnNegotiated() const {
939 return false;
942 bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
943 return false;
946 void MockTCPClientSocket::OnReadComplete(const MockRead& data) {
947 // There must be a read pending.
948 DCHECK(pending_buf_);
949 // You can't complete a read with another ERR_IO_PENDING status code.
950 DCHECK_NE(ERR_IO_PENDING, data.result);
951 // Since we've been waiting for data, need_read_data_ should be true.
952 DCHECK(need_read_data_);
954 read_data_ = data;
955 need_read_data_ = false;
957 // The caller is simulating that this IO completes right now. Don't
958 // let CompleteRead() schedule a callback.
959 read_data_.mode = SYNCHRONOUS;
961 CompletionCallback callback = pending_callback_;
962 int rv = CompleteRead();
963 RunCallback(callback, rv);
966 void MockTCPClientSocket::OnConnectComplete(const MockConnect& data) {
967 CompletionCallback callback = pending_callback_;
968 RunCallback(callback, data.result);
971 int MockTCPClientSocket::CompleteRead() {
972 DCHECK(pending_buf_);
973 DCHECK(pending_buf_len_ > 0);
975 was_used_to_convey_data_ = true;
977 // Save the pending async IO data and reset our |pending_| state.
978 scoped_refptr<IOBuffer> buf = pending_buf_;
979 int buf_len = pending_buf_len_;
980 CompletionCallback callback = pending_callback_;
981 pending_buf_ = NULL;
982 pending_buf_len_ = 0;
983 pending_callback_.Reset();
985 int result = read_data_.result;
986 DCHECK(result != ERR_IO_PENDING);
988 if (read_data_.data) {
989 if (read_data_.data_len - read_offset_ > 0) {
990 result = std::min(buf_len, read_data_.data_len - read_offset_);
991 memcpy(buf->data(), read_data_.data + read_offset_, result);
992 read_offset_ += result;
993 if (read_offset_ == read_data_.data_len) {
994 need_read_data_ = true;
995 read_offset_ = 0;
997 } else {
998 result = 0; // EOF
1002 if (read_data_.mode == ASYNC) {
1003 DCHECK(!callback.is_null());
1004 RunCallbackAsync(callback, result);
1005 return ERR_IO_PENDING;
1007 return result;
1010 DeterministicSocketHelper::DeterministicSocketHelper(
1011 net::NetLog* net_log,
1012 DeterministicSocketData* data)
1013 : write_pending_(false),
1014 write_result_(0),
1015 read_data_(),
1016 read_buf_(NULL),
1017 read_buf_len_(0),
1018 read_pending_(false),
1019 data_(data),
1020 was_used_to_convey_data_(false),
1021 peer_closed_connection_(false),
1022 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)) {
1025 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1027 void DeterministicSocketHelper::CompleteWrite() {
1028 was_used_to_convey_data_ = true;
1029 write_pending_ = false;
1030 write_callback_.Run(write_result_);
1033 int DeterministicSocketHelper::CompleteRead() {
1034 DCHECK_GT(read_buf_len_, 0);
1035 DCHECK_LE(read_data_.data_len, read_buf_len_);
1036 DCHECK(read_buf_);
1038 was_used_to_convey_data_ = true;
1040 if (read_data_.result == ERR_IO_PENDING)
1041 read_data_ = data_->GetNextRead();
1042 DCHECK_NE(ERR_IO_PENDING, read_data_.result);
1043 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1044 // the callback. Therefore we don't even bother to check it.
1045 int result = read_data_.result;
1047 if (read_data_.data_len > 0) {
1048 DCHECK(read_data_.data);
1049 result = std::min(read_buf_len_, read_data_.data_len);
1050 memcpy(read_buf_->data(), read_data_.data, result);
1053 if (read_pending_) {
1054 read_pending_ = false;
1055 read_callback_.Run(result);
1058 return result;
1061 int DeterministicSocketHelper::Write(
1062 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1063 DCHECK(buf);
1064 DCHECK_GT(buf_len, 0);
1066 std::string data(buf->data(), buf_len);
1067 MockWriteResult write_result = data_->OnWrite(data);
1069 if (write_result.mode == ASYNC) {
1070 write_callback_ = callback;
1071 write_result_ = write_result.result;
1072 DCHECK(!write_callback_.is_null());
1073 write_pending_ = true;
1074 return ERR_IO_PENDING;
1077 was_used_to_convey_data_ = true;
1078 write_pending_ = false;
1079 return write_result.result;
1082 int DeterministicSocketHelper::Read(
1083 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1085 read_data_ = data_->GetNextRead();
1086 // The buffer should always be big enough to contain all the MockRead data. To
1087 // use small buffers, split the data into multiple MockReads.
1088 DCHECK_LE(read_data_.data_len, buf_len);
1090 if (read_data_.result == ERR_CONNECTION_CLOSED) {
1091 // This MockRead is just a marker to instruct us to set
1092 // peer_closed_connection_.
1093 peer_closed_connection_ = true;
1095 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
1096 // This MockRead is just a marker to instruct us to set
1097 // peer_closed_connection_. Skip it and get the next one.
1098 read_data_ = data_->GetNextRead();
1099 peer_closed_connection_ = true;
1102 read_buf_ = buf;
1103 read_buf_len_ = buf_len;
1104 read_callback_ = callback;
1106 if (read_data_.mode == ASYNC || (read_data_.result == ERR_IO_PENDING)) {
1107 read_pending_ = true;
1108 DCHECK(!read_callback_.is_null());
1109 return ERR_IO_PENDING;
1112 was_used_to_convey_data_ = true;
1113 return CompleteRead();
1116 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1117 net::NetLog* net_log,
1118 DeterministicSocketData* data)
1119 : connected_(false),
1120 helper_(net_log, data),
1121 source_port_(123) {
1124 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1126 bool DeterministicMockUDPClientSocket::WritePending() const {
1127 return helper_.write_pending();
1130 bool DeterministicMockUDPClientSocket::ReadPending() const {
1131 return helper_.read_pending();
1134 void DeterministicMockUDPClientSocket::CompleteWrite() {
1135 helper_.CompleteWrite();
1138 int DeterministicMockUDPClientSocket::CompleteRead() {
1139 return helper_.CompleteRead();
1142 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint& address) {
1143 if (connected_)
1144 return OK;
1145 connected_ = true;
1146 peer_address_ = address;
1147 return helper_.data()->connect_data().result;
1150 int DeterministicMockUDPClientSocket::Write(
1151 IOBuffer* buf,
1152 int buf_len,
1153 const CompletionCallback& callback) {
1154 if (!connected_)
1155 return ERR_UNEXPECTED;
1157 return helper_.Write(buf, buf_len, callback);
1160 int DeterministicMockUDPClientSocket::Read(
1161 IOBuffer* buf,
1162 int buf_len,
1163 const CompletionCallback& callback) {
1164 if (!connected_)
1165 return ERR_UNEXPECTED;
1167 return helper_.Read(buf, buf_len, callback);
1170 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1171 return OK;
1174 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size) {
1175 return OK;
1178 void DeterministicMockUDPClientSocket::Close() {
1179 connected_ = false;
1182 int DeterministicMockUDPClientSocket::GetPeerAddress(
1183 IPEndPoint* address) const {
1184 *address = peer_address_;
1185 return OK;
1188 int DeterministicMockUDPClientSocket::GetLocalAddress(
1189 IPEndPoint* address) const {
1190 IPAddressNumber ip;
1191 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1192 CHECK(rv);
1193 *address = IPEndPoint(ip, source_port_);
1194 return OK;
1197 const BoundNetLog& DeterministicMockUDPClientSocket::NetLog() const {
1198 return helper_.net_log();
1201 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead& data) {}
1203 void DeterministicMockUDPClientSocket::OnConnectComplete(
1204 const MockConnect& data) {
1205 NOTIMPLEMENTED();
1208 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1209 net::NetLog* net_log,
1210 DeterministicSocketData* data)
1211 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1212 helper_(net_log, data) {
1213 peer_addr_ = data->connect_data().peer_addr;
1216 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1218 bool DeterministicMockTCPClientSocket::WritePending() const {
1219 return helper_.write_pending();
1222 bool DeterministicMockTCPClientSocket::ReadPending() const {
1223 return helper_.read_pending();
1226 void DeterministicMockTCPClientSocket::CompleteWrite() {
1227 helper_.CompleteWrite();
1230 int DeterministicMockTCPClientSocket::CompleteRead() {
1231 return helper_.CompleteRead();
1234 int DeterministicMockTCPClientSocket::Write(
1235 IOBuffer* buf,
1236 int buf_len,
1237 const CompletionCallback& callback) {
1238 if (!connected_)
1239 return ERR_UNEXPECTED;
1241 return helper_.Write(buf, buf_len, callback);
1244 int DeterministicMockTCPClientSocket::Read(
1245 IOBuffer* buf,
1246 int buf_len,
1247 const CompletionCallback& callback) {
1248 if (!connected_)
1249 return ERR_UNEXPECTED;
1251 return helper_.Read(buf, buf_len, callback);
1254 // TODO(erikchen): Support connect sequencing.
1255 int DeterministicMockTCPClientSocket::Connect(
1256 const CompletionCallback& callback) {
1257 if (connected_)
1258 return OK;
1259 connected_ = true;
1260 if (helper_.data()->connect_data().mode == ASYNC) {
1261 RunCallbackAsync(callback, helper_.data()->connect_data().result);
1262 return ERR_IO_PENDING;
1264 return helper_.data()->connect_data().result;
1267 void DeterministicMockTCPClientSocket::Disconnect() {
1268 MockClientSocket::Disconnect();
1271 bool DeterministicMockTCPClientSocket::IsConnected() const {
1272 return connected_ && !helper_.peer_closed_connection();
1275 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1276 return IsConnected();
1279 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1280 return helper_.was_used_to_convey_data();
1283 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1284 return false;
1287 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1288 return false;
1291 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1292 return false;
1295 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead& data) {}
1297 void DeterministicMockTCPClientSocket::OnConnectComplete(
1298 const MockConnect& data) {}
1300 // static
1301 void MockSSLClientSocket::ConnectCallback(
1302 MockSSLClientSocket* ssl_client_socket,
1303 const CompletionCallback& callback,
1304 int rv) {
1305 if (rv == OK)
1306 ssl_client_socket->connected_ = true;
1307 callback.Run(rv);
1310 MockSSLClientSocket::MockSSLClientSocket(
1311 scoped_ptr<ClientSocketHandle> transport_socket,
1312 const HostPortPair& host_port_pair,
1313 const SSLConfig& ssl_config,
1314 SSLSocketDataProvider* data)
1315 : MockClientSocket(
1316 // Have to use the right BoundNetLog for LoadTimingInfo regression
1317 // tests.
1318 transport_socket->socket()->NetLog()),
1319 transport_(transport_socket.Pass()),
1320 data_(data),
1321 is_npn_state_set_(false),
1322 new_npn_value_(false),
1323 is_protocol_negotiated_set_(false),
1324 protocol_negotiated_(kProtoUnknown) {
1325 DCHECK(data_);
1326 peer_addr_ = data->connect.peer_addr;
1329 MockSSLClientSocket::~MockSSLClientSocket() {
1330 Disconnect();
1333 int MockSSLClientSocket::Read(IOBuffer* buf, int buf_len,
1334 const CompletionCallback& callback) {
1335 return transport_->socket()->Read(buf, buf_len, callback);
1338 int MockSSLClientSocket::Write(IOBuffer* buf, int buf_len,
1339 const CompletionCallback& callback) {
1340 return transport_->socket()->Write(buf, buf_len, callback);
1343 int MockSSLClientSocket::Connect(const CompletionCallback& callback) {
1344 int rv = transport_->socket()->Connect(
1345 base::Bind(&ConnectCallback, base::Unretained(this), callback));
1346 if (rv == OK) {
1347 if (data_->connect.result == OK)
1348 connected_ = true;
1349 if (data_->connect.mode == ASYNC) {
1350 RunCallbackAsync(callback, data_->connect.result);
1351 return ERR_IO_PENDING;
1353 return data_->connect.result;
1355 return rv;
1358 void MockSSLClientSocket::Disconnect() {
1359 MockClientSocket::Disconnect();
1360 if (transport_->socket() != NULL)
1361 transport_->socket()->Disconnect();
1364 bool MockSSLClientSocket::IsConnected() const {
1365 return transport_->socket()->IsConnected();
1368 bool MockSSLClientSocket::WasEverUsed() const {
1369 return transport_->socket()->WasEverUsed();
1372 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1373 return transport_->socket()->UsingTCPFastOpen();
1376 int MockSSLClientSocket::GetPeerAddress(IPEndPoint* address) const {
1377 return transport_->socket()->GetPeerAddress(address);
1380 bool MockSSLClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1381 ssl_info->Reset();
1382 ssl_info->cert = data_->cert;
1383 ssl_info->client_cert_sent = data_->client_cert_sent;
1384 ssl_info->channel_id_sent = data_->channel_id_sent;
1385 ssl_info->connection_status = data_->connection_status;
1386 return true;
1389 void MockSSLClientSocket::GetSSLCertRequestInfo(
1390 SSLCertRequestInfo* cert_request_info) {
1391 DCHECK(cert_request_info);
1392 if (data_->cert_request_info) {
1393 cert_request_info->host_and_port =
1394 data_->cert_request_info->host_and_port;
1395 cert_request_info->client_certs = data_->cert_request_info->client_certs;
1396 } else {
1397 cert_request_info->Reset();
1401 SSLClientSocket::NextProtoStatus MockSSLClientSocket::GetNextProto(
1402 std::string* proto) {
1403 *proto = data_->next_proto;
1404 return data_->next_proto_status;
1407 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated) {
1408 is_npn_state_set_ = true;
1409 return new_npn_value_ = negotiated;
1412 bool MockSSLClientSocket::WasNpnNegotiated() const {
1413 if (is_npn_state_set_)
1414 return new_npn_value_;
1415 return data_->was_npn_negotiated;
1418 NextProto MockSSLClientSocket::GetNegotiatedProtocol() const {
1419 if (is_protocol_negotiated_set_)
1420 return protocol_negotiated_;
1421 return data_->protocol_negotiated;
1424 void MockSSLClientSocket::set_protocol_negotiated(
1425 NextProto protocol_negotiated) {
1426 is_protocol_negotiated_set_ = true;
1427 protocol_negotiated_ = protocol_negotiated;
1430 bool MockSSLClientSocket::WasChannelIDSent() const {
1431 return data_->channel_id_sent;
1434 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent) {
1435 data_->channel_id_sent = channel_id_sent;
1438 ChannelIDService* MockSSLClientSocket::GetChannelIDService() const {
1439 return data_->channel_id_service;
1442 void MockSSLClientSocket::OnReadComplete(const MockRead& data) {
1443 NOTIMPLEMENTED();
1446 void MockSSLClientSocket::OnConnectComplete(const MockConnect& data) {
1447 NOTIMPLEMENTED();
1450 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data,
1451 net::NetLog* net_log)
1452 : connected_(false),
1453 data_(data),
1454 read_offset_(0),
1455 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
1456 need_read_data_(true),
1457 source_port_(123),
1458 pending_buf_(NULL),
1459 pending_buf_len_(0),
1460 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1461 weak_factory_(this) {
1462 DCHECK(data_);
1463 data_->Reset();
1464 peer_addr_ = data->connect_data().peer_addr;
1467 MockUDPClientSocket::~MockUDPClientSocket() {}
1469 int MockUDPClientSocket::Read(IOBuffer* buf,
1470 int buf_len,
1471 const CompletionCallback& callback) {
1472 if (!connected_)
1473 return ERR_UNEXPECTED;
1475 // If the buffer is already in use, a read is already in progress!
1476 DCHECK(pending_buf_ == NULL);
1478 // Store our async IO data.
1479 pending_buf_ = buf;
1480 pending_buf_len_ = buf_len;
1481 pending_callback_ = callback;
1483 if (need_read_data_) {
1484 read_data_ = data_->GetNextRead();
1485 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1486 // to complete the async IO manually later (via OnReadComplete).
1487 if (read_data_.result == ERR_IO_PENDING) {
1488 // We need to be using async IO in this case.
1489 DCHECK(!callback.is_null());
1490 return ERR_IO_PENDING;
1492 need_read_data_ = false;
1495 return CompleteRead();
1498 int MockUDPClientSocket::Write(IOBuffer* buf, int buf_len,
1499 const CompletionCallback& callback) {
1500 DCHECK(buf);
1501 DCHECK_GT(buf_len, 0);
1503 if (!connected_)
1504 return ERR_UNEXPECTED;
1506 std::string data(buf->data(), buf_len);
1507 MockWriteResult write_result = data_->OnWrite(data);
1509 if (write_result.mode == ASYNC) {
1510 RunCallbackAsync(callback, write_result.result);
1511 return ERR_IO_PENDING;
1513 return write_result.result;
1516 int MockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1517 return OK;
1520 int MockUDPClientSocket::SetSendBufferSize(int32 size) {
1521 return OK;
1524 void MockUDPClientSocket::Close() {
1525 connected_ = false;
1528 int MockUDPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1529 *address = peer_addr_;
1530 return OK;
1533 int MockUDPClientSocket::GetLocalAddress(IPEndPoint* address) const {
1534 IPAddressNumber ip;
1535 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1536 CHECK(rv);
1537 *address = IPEndPoint(ip, source_port_);
1538 return OK;
1541 const BoundNetLog& MockUDPClientSocket::NetLog() const {
1542 return net_log_;
1545 int MockUDPClientSocket::Connect(const IPEndPoint& address) {
1546 connected_ = true;
1547 peer_addr_ = address;
1548 return data_->connect_data().result;
1551 void MockUDPClientSocket::OnReadComplete(const MockRead& data) {
1552 // There must be a read pending.
1553 DCHECK(pending_buf_);
1554 // You can't complete a read with another ERR_IO_PENDING status code.
1555 DCHECK_NE(ERR_IO_PENDING, data.result);
1556 // Since we've been waiting for data, need_read_data_ should be true.
1557 DCHECK(need_read_data_);
1559 read_data_ = data;
1560 need_read_data_ = false;
1562 // The caller is simulating that this IO completes right now. Don't
1563 // let CompleteRead() schedule a callback.
1564 read_data_.mode = SYNCHRONOUS;
1566 net::CompletionCallback callback = pending_callback_;
1567 int rv = CompleteRead();
1568 RunCallback(callback, rv);
1571 void MockUDPClientSocket::OnConnectComplete(const MockConnect& data) {
1572 NOTIMPLEMENTED();
1575 int MockUDPClientSocket::CompleteRead() {
1576 DCHECK(pending_buf_);
1577 DCHECK(pending_buf_len_ > 0);
1579 // Save the pending async IO data and reset our |pending_| state.
1580 scoped_refptr<IOBuffer> buf = pending_buf_;
1581 int buf_len = pending_buf_len_;
1582 CompletionCallback callback = pending_callback_;
1583 pending_buf_ = NULL;
1584 pending_buf_len_ = 0;
1585 pending_callback_.Reset();
1587 int result = read_data_.result;
1588 DCHECK(result != ERR_IO_PENDING);
1590 if (read_data_.data) {
1591 if (read_data_.data_len - read_offset_ > 0) {
1592 result = std::min(buf_len, read_data_.data_len - read_offset_);
1593 memcpy(buf->data(), read_data_.data + read_offset_, result);
1594 read_offset_ += result;
1595 if (read_offset_ == read_data_.data_len) {
1596 need_read_data_ = true;
1597 read_offset_ = 0;
1599 } else {
1600 result = 0; // EOF
1604 if (read_data_.mode == ASYNC) {
1605 DCHECK(!callback.is_null());
1606 RunCallbackAsync(callback, result);
1607 return ERR_IO_PENDING;
1609 return result;
1612 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback& callback,
1613 int result) {
1614 base::MessageLoop::current()->PostTask(
1615 FROM_HERE,
1616 base::Bind(&MockUDPClientSocket::RunCallback,
1617 weak_factory_.GetWeakPtr(),
1618 callback,
1619 result));
1622 void MockUDPClientSocket::RunCallback(const CompletionCallback& callback,
1623 int result) {
1624 if (!callback.is_null())
1625 callback.Run(result);
1628 TestSocketRequest::TestSocketRequest(
1629 std::vector<TestSocketRequest*>* request_order, size_t* completion_count)
1630 : request_order_(request_order),
1631 completion_count_(completion_count),
1632 callback_(base::Bind(&TestSocketRequest::OnComplete,
1633 base::Unretained(this))) {
1634 DCHECK(request_order);
1635 DCHECK(completion_count);
1638 TestSocketRequest::~TestSocketRequest() {
1641 void TestSocketRequest::OnComplete(int result) {
1642 SetResult(result);
1643 (*completion_count_)++;
1644 request_order_->push_back(this);
1647 // static
1648 const int ClientSocketPoolTest::kIndexOutOfBounds = -1;
1650 // static
1651 const int ClientSocketPoolTest::kRequestNotFound = -2;
1653 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1654 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1656 int ClientSocketPoolTest::GetOrderOfRequest(size_t index) const {
1657 index--;
1658 if (index >= requests_.size())
1659 return kIndexOutOfBounds;
1661 for (size_t i = 0; i < request_order_.size(); i++)
1662 if (requests_[index] == request_order_[i])
1663 return i + 1;
1665 return kRequestNotFound;
1668 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
1669 ScopedVector<TestSocketRequest>::iterator i;
1670 for (i = requests_.begin(); i != requests_.end(); ++i) {
1671 if ((*i)->handle()->is_initialized()) {
1672 if (keep_alive == NO_KEEP_ALIVE)
1673 (*i)->handle()->socket()->Disconnect();
1674 (*i)->handle()->Reset();
1675 base::RunLoop().RunUntilIdle();
1676 return true;
1679 return false;
1682 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
1683 bool released_one;
1684 do {
1685 released_one = ReleaseOneConnection(keep_alive);
1686 } while (released_one);
1689 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1690 scoped_ptr<StreamSocket> socket,
1691 ClientSocketHandle* handle,
1692 const CompletionCallback& callback)
1693 : socket_(socket.Pass()),
1694 handle_(handle),
1695 user_callback_(callback) {
1698 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1700 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1701 int rv = socket_->Connect(base::Bind(&MockConnectJob::OnConnect,
1702 base::Unretained(this)));
1703 if (rv == OK) {
1704 user_callback_.Reset();
1705 OnConnect(OK);
1707 return rv;
1710 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1711 const ClientSocketHandle* handle) {
1712 if (handle != handle_)
1713 return false;
1714 socket_.reset();
1715 handle_ = NULL;
1716 user_callback_.Reset();
1717 return true;
1720 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) {
1721 if (!socket_.get())
1722 return;
1723 if (rv == OK) {
1724 handle_->SetSocket(socket_.Pass());
1726 // Needed for socket pool tests that layer other sockets on top of mock
1727 // sockets.
1728 LoadTimingInfo::ConnectTiming connect_timing;
1729 base::TimeTicks now = base::TimeTicks::Now();
1730 connect_timing.dns_start = now;
1731 connect_timing.dns_end = now;
1732 connect_timing.connect_start = now;
1733 connect_timing.connect_end = now;
1734 handle_->set_connect_timing(connect_timing);
1735 } else {
1736 socket_.reset();
1739 handle_ = NULL;
1741 if (!user_callback_.is_null()) {
1742 CompletionCallback callback = user_callback_;
1743 user_callback_.Reset();
1744 callback.Run(rv);
1748 MockTransportClientSocketPool::MockTransportClientSocketPool(
1749 int max_sockets,
1750 int max_sockets_per_group,
1751 ClientSocketPoolHistograms* histograms,
1752 ClientSocketFactory* socket_factory)
1753 : TransportClientSocketPool(max_sockets, max_sockets_per_group, histograms,
1754 NULL, NULL, NULL),
1755 client_socket_factory_(socket_factory),
1756 last_request_priority_(DEFAULT_PRIORITY),
1757 release_count_(0),
1758 cancel_count_(0) {
1761 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1763 int MockTransportClientSocketPool::RequestSocket(
1764 const std::string& group_name, const void* socket_params,
1765 RequestPriority priority, ClientSocketHandle* handle,
1766 const CompletionCallback& callback, const BoundNetLog& net_log) {
1767 last_request_priority_ = priority;
1768 scoped_ptr<StreamSocket> socket =
1769 client_socket_factory_->CreateTransportClientSocket(
1770 AddressList(), net_log.net_log(), net::NetLog::Source());
1771 MockConnectJob* job = new MockConnectJob(socket.Pass(), handle, callback);
1772 job_list_.push_back(job);
1773 handle->set_pool_id(1);
1774 return job->Connect();
1777 void MockTransportClientSocketPool::CancelRequest(const std::string& group_name,
1778 ClientSocketHandle* handle) {
1779 std::vector<MockConnectJob*>::iterator i;
1780 for (i = job_list_.begin(); i != job_list_.end(); ++i) {
1781 if ((*i)->CancelHandle(handle)) {
1782 cancel_count_++;
1783 break;
1788 void MockTransportClientSocketPool::ReleaseSocket(
1789 const std::string& group_name,
1790 scoped_ptr<StreamSocket> socket,
1791 int id) {
1792 EXPECT_EQ(1, id);
1793 release_count_++;
1796 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1798 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1800 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1801 DeterministicSocketData* data) {
1802 mock_data_.Add(data);
1805 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1806 SSLSocketDataProvider* data) {
1807 mock_ssl_data_.Add(data);
1810 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1811 mock_data_.ResetNextIndex();
1812 mock_ssl_data_.ResetNextIndex();
1815 MockSSLClientSocket* DeterministicMockClientSocketFactory::
1816 GetMockSSLClientSocket(size_t index) const {
1817 DCHECK_LT(index, ssl_client_sockets_.size());
1818 return ssl_client_sockets_[index];
1821 scoped_ptr<DatagramClientSocket>
1822 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1823 DatagramSocket::BindType bind_type,
1824 const RandIntCallback& rand_int_cb,
1825 net::NetLog* net_log,
1826 const NetLog::Source& source) {
1827 DeterministicSocketData* data_provider = mock_data().GetNext();
1828 scoped_ptr<DeterministicMockUDPClientSocket> socket(
1829 new DeterministicMockUDPClientSocket(net_log, data_provider));
1830 data_provider->set_delegate(socket->AsWeakPtr());
1831 udp_client_sockets().push_back(socket.get());
1832 if (bind_type == DatagramSocket::RANDOM_BIND)
1833 socket->set_source_port(rand_int_cb.Run(1025, 65535));
1834 return socket.PassAs<DatagramClientSocket>();
1837 scoped_ptr<StreamSocket>
1838 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1839 const AddressList& addresses,
1840 net::NetLog* net_log,
1841 const net::NetLog::Source& source) {
1842 DeterministicSocketData* data_provider = mock_data().GetNext();
1843 scoped_ptr<DeterministicMockTCPClientSocket> socket(
1844 new DeterministicMockTCPClientSocket(net_log, data_provider));
1845 data_provider->set_delegate(socket->AsWeakPtr());
1846 tcp_client_sockets().push_back(socket.get());
1847 return socket.PassAs<StreamSocket>();
1850 scoped_ptr<SSLClientSocket>
1851 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1852 scoped_ptr<ClientSocketHandle> transport_socket,
1853 const HostPortPair& host_and_port,
1854 const SSLConfig& ssl_config,
1855 const SSLClientSocketContext& context) {
1856 scoped_ptr<MockSSLClientSocket> socket(
1857 new MockSSLClientSocket(transport_socket.Pass(),
1858 host_and_port, ssl_config,
1859 mock_ssl_data_.GetNext()));
1860 ssl_client_sockets_.push_back(socket.get());
1861 return socket.PassAs<SSLClientSocket>();
1864 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1867 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1868 int max_sockets,
1869 int max_sockets_per_group,
1870 ClientSocketPoolHistograms* histograms,
1871 TransportClientSocketPool* transport_pool)
1872 : SOCKSClientSocketPool(max_sockets, max_sockets_per_group, histograms,
1873 NULL, transport_pool, NULL),
1874 transport_pool_(transport_pool) {
1877 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1879 int MockSOCKSClientSocketPool::RequestSocket(
1880 const std::string& group_name, const void* socket_params,
1881 RequestPriority priority, ClientSocketHandle* handle,
1882 const CompletionCallback& callback, const BoundNetLog& net_log) {
1883 return transport_pool_->RequestSocket(
1884 group_name, socket_params, priority, handle, callback, net_log);
1887 void MockSOCKSClientSocketPool::CancelRequest(
1888 const std::string& group_name,
1889 ClientSocketHandle* handle) {
1890 return transport_pool_->CancelRequest(group_name, handle);
1893 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string& group_name,
1894 scoped_ptr<StreamSocket> socket,
1895 int id) {
1896 return transport_pool_->ReleaseSocket(group_name, socket.Pass(), id);
1899 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
1900 const int kSOCKS5GreetRequestLength = arraysize(kSOCKS5GreetRequest);
1902 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
1903 const int kSOCKS5GreetResponseLength = arraysize(kSOCKS5GreetResponse);
1905 const char kSOCKS5OkRequest[] =
1906 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1907 const int kSOCKS5OkRequestLength = arraysize(kSOCKS5OkRequest);
1909 const char kSOCKS5OkResponse[] =
1910 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1911 const int kSOCKS5OkResponseLength = arraysize(kSOCKS5OkResponse);
1913 } // namespace net