Add UMA reporting to CdmPromise.
[chromium-blink-merge.git] / net / socket / socket_test_util.cc
blob3498c13428d26ee04ff61c04387ecf3b5a946eec
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/callback_helpers.h"
14 #include "base/compiler_specific.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/run_loop.h"
17 #include "base/time/time.h"
18 #include "net/base/address_family.h"
19 #include "net/base/address_list.h"
20 #include "net/base/auth.h"
21 #include "net/base/load_timing_info.h"
22 #include "net/http/http_network_session.h"
23 #include "net/http/http_request_headers.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/socket/client_socket_pool_histograms.h"
26 #include "net/socket/socket.h"
27 #include "net/ssl/ssl_cert_request_info.h"
28 #include "net/ssl/ssl_connection_status_flags.h"
29 #include "net/ssl/ssl_info.h"
30 #include "testing/gtest/include/gtest/gtest.h"
32 // Socket events are easier to debug if you log individual reads and writes.
33 // Enable these if locally debugging, but they are too noisy for the waterfall.
34 #if 0
35 #define NET_TRACE(level, s) DLOG(level) << s << __FUNCTION__ << "() "
36 #else
37 #define NET_TRACE(level, s) EAT_STREAM_PARAMETERS
38 #endif
40 namespace net {
42 namespace {
44 inline char AsciifyHigh(char x) {
45 char nybble = static_cast<char>((x >> 4) & 0x0F);
46 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
49 inline char AsciifyLow(char x) {
50 char nybble = static_cast<char>((x >> 0) & 0x0F);
51 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
54 inline char Asciify(char x) {
55 if ((x < 0) || !isprint(x))
56 return '.';
57 return x;
60 void DumpData(const char* data, int data_len) {
61 if (logging::LOG_INFO < logging::GetMinLogLevel())
62 return;
63 DVLOG(1) << "Length: " << data_len;
64 const char* pfx = "Data: ";
65 if (!data || (data_len <= 0)) {
66 DVLOG(1) << pfx << "<None>";
67 } else {
68 int i;
69 for (i = 0; i <= (data_len - 4); i += 4) {
70 DVLOG(1) << pfx
71 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
72 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
73 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
74 << AsciifyHigh(data[i + 3]) << AsciifyLow(data[i + 3])
75 << " '"
76 << Asciify(data[i + 0])
77 << Asciify(data[i + 1])
78 << Asciify(data[i + 2])
79 << Asciify(data[i + 3])
80 << "'";
81 pfx = " ";
83 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
84 switch (data_len - i) {
85 case 3:
86 DVLOG(1) << pfx
87 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
88 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
89 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
90 << " '"
91 << Asciify(data[i + 0])
92 << Asciify(data[i + 1])
93 << Asciify(data[i + 2])
94 << " '";
95 break;
96 case 2:
97 DVLOG(1) << pfx
98 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
99 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
100 << " '"
101 << Asciify(data[i + 0])
102 << Asciify(data[i + 1])
103 << " '";
104 break;
105 case 1:
106 DVLOG(1) << pfx
107 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
108 << " '"
109 << Asciify(data[i + 0])
110 << " '";
111 break;
116 template <MockReadWriteType type>
117 void DumpMockReadWrite(const MockReadWrite<type>& r) {
118 if (logging::LOG_INFO < logging::GetMinLogLevel())
119 return;
120 DVLOG(1) << "Async: " << (r.mode == ASYNC)
121 << "\nResult: " << r.result;
122 DumpData(r.data, r.data_len);
123 const char* stop = (r.sequence_number & MockRead::STOPLOOP) ? " (STOP)" : "";
124 DVLOG(1) << "Stage: " << (r.sequence_number & ~MockRead::STOPLOOP) << stop
125 << "\nTime: " << r.time_stamp.ToInternalValue();
128 } // namespace
130 MockConnect::MockConnect() : mode(ASYNC), result(OK) {
131 IPAddressNumber ip;
132 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
133 peer_addr = IPEndPoint(ip, 0);
136 MockConnect::MockConnect(IoMode io_mode, int r) : mode(io_mode), result(r) {
137 IPAddressNumber ip;
138 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
139 peer_addr = IPEndPoint(ip, 0);
142 MockConnect::MockConnect(IoMode io_mode, int r, IPEndPoint addr) :
143 mode(io_mode),
144 result(r),
145 peer_addr(addr) {
148 MockConnect::~MockConnect() {}
150 StaticSocketDataProvider::StaticSocketDataProvider()
151 : reads_(NULL),
152 read_index_(0),
153 read_count_(0),
154 writes_(NULL),
155 write_index_(0),
156 write_count_(0) {
159 StaticSocketDataProvider::StaticSocketDataProvider(MockRead* reads,
160 size_t reads_count,
161 MockWrite* writes,
162 size_t writes_count)
163 : reads_(reads),
164 read_index_(0),
165 read_count_(reads_count),
166 writes_(writes),
167 write_index_(0),
168 write_count_(writes_count) {
171 StaticSocketDataProvider::~StaticSocketDataProvider() {}
173 const MockRead& StaticSocketDataProvider::PeekRead() const {
174 CHECK(!at_read_eof());
175 return reads_[read_index_];
178 const MockWrite& StaticSocketDataProvider::PeekWrite() const {
179 CHECK(!at_write_eof());
180 return writes_[write_index_];
183 const MockRead& StaticSocketDataProvider::PeekRead(size_t index) const {
184 CHECK_LT(index, read_count_);
185 return reads_[index];
188 const MockWrite& StaticSocketDataProvider::PeekWrite(size_t index) const {
189 CHECK_LT(index, write_count_);
190 return writes_[index];
193 MockRead StaticSocketDataProvider::GetNextRead() {
194 CHECK(!at_read_eof());
195 reads_[read_index_].time_stamp = base::Time::Now();
196 return reads_[read_index_++];
199 MockWriteResult StaticSocketDataProvider::OnWrite(const std::string& data) {
200 if (!writes_) {
201 // Not using mock writes; succeed synchronously.
202 return MockWriteResult(SYNCHRONOUS, data.length());
204 EXPECT_FALSE(at_write_eof());
205 if (at_write_eof()) {
206 // Show what the extra write actually consists of.
207 EXPECT_EQ("<unexpected write>", data);
208 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
211 // Check that what we are writing matches the expectation.
212 // Then give the mocked return value.
213 MockWrite* w = &writes_[write_index_++];
214 w->time_stamp = base::Time::Now();
215 int result = w->result;
216 if (w->data) {
217 // Note - we can simulate a partial write here. If the expected data
218 // is a match, but shorter than the write actually written, that is legal.
219 // Example:
220 // Application writes "foobarbaz" (9 bytes)
221 // Expected write was "foo" (3 bytes)
222 // This is a success, and we return 3 to the application.
223 std::string expected_data(w->data, w->data_len);
224 EXPECT_GE(data.length(), expected_data.length());
225 std::string actual_data(data.substr(0, w->data_len));
226 EXPECT_EQ(expected_data, actual_data);
227 if (expected_data != actual_data)
228 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
229 if (result == OK)
230 result = w->data_len;
232 return MockWriteResult(w->mode, result);
235 void StaticSocketDataProvider::Reset() {
236 read_index_ = 0;
237 write_index_ = 0;
240 DynamicSocketDataProvider::DynamicSocketDataProvider()
241 : short_read_limit_(0),
242 allow_unconsumed_reads_(false) {
245 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
247 MockRead DynamicSocketDataProvider::GetNextRead() {
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 should_pause_on_connect(false),
283 is_in_session_cache(false) {
284 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2,
285 &connection_status);
286 // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
287 SSLConnectionStatusSetCipherSuite(0xcc14, &connection_status);
290 SSLSocketDataProvider::~SSLSocketDataProvider() {
293 void SSLSocketDataProvider::SetNextProto(NextProto proto) {
294 was_npn_negotiated = true;
295 next_proto_status = SSLClientSocket::kNextProtoNegotiated;
296 protocol_negotiated = proto;
297 next_proto = SSLClientSocket::NextProtoToString(proto);
300 DelayedSocketData::DelayedSocketData(
301 int write_delay, MockRead* reads, size_t reads_count,
302 MockWrite* writes, size_t writes_count)
303 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
304 write_delay_(write_delay),
305 read_in_progress_(false),
306 weak_factory_(this) {
307 DCHECK_GE(write_delay_, 0);
310 DelayedSocketData::DelayedSocketData(
311 const MockConnect& connect, int write_delay, MockRead* reads,
312 size_t reads_count, MockWrite* writes, size_t writes_count)
313 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
314 write_delay_(write_delay),
315 read_in_progress_(false),
316 weak_factory_(this) {
317 DCHECK_GE(write_delay_, 0);
318 set_connect_data(connect);
321 DelayedSocketData::~DelayedSocketData() {
324 void DelayedSocketData::ForceNextRead() {
325 DCHECK(read_in_progress_);
326 write_delay_ = 0;
327 CompleteRead();
330 MockRead DelayedSocketData::GetNextRead() {
331 MockRead out = MockRead(ASYNC, ERR_IO_PENDING);
332 if (write_delay_ <= 0)
333 out = StaticSocketDataProvider::GetNextRead();
334 read_in_progress_ = (out.result == ERR_IO_PENDING);
335 return out;
338 MockWriteResult DelayedSocketData::OnWrite(const std::string& data) {
339 MockWriteResult rv = StaticSocketDataProvider::OnWrite(data);
340 // Now that our write has completed, we can allow reads to continue.
341 if (!--write_delay_ && read_in_progress_)
342 base::MessageLoop::current()->PostDelayedTask(
343 FROM_HERE,
344 base::Bind(&DelayedSocketData::CompleteRead,
345 weak_factory_.GetWeakPtr()),
346 base::TimeDelta::FromMilliseconds(100));
347 return rv;
350 void DelayedSocketData::Reset() {
351 set_socket(NULL);
352 read_in_progress_ = false;
353 weak_factory_.InvalidateWeakPtrs();
354 StaticSocketDataProvider::Reset();
357 void DelayedSocketData::CompleteRead() {
358 if (socket() && read_in_progress_)
359 socket()->OnReadComplete(GetNextRead());
362 OrderedSocketData::OrderedSocketData(
363 MockRead* reads, size_t reads_count, MockWrite* writes, size_t writes_count)
364 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
365 sequence_number_(0), loop_stop_stage_(0),
366 blocked_(false), weak_factory_(this) {
369 OrderedSocketData::OrderedSocketData(
370 const MockConnect& connect,
371 MockRead* reads, size_t reads_count,
372 MockWrite* writes, size_t writes_count)
373 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
374 sequence_number_(0), loop_stop_stage_(0),
375 blocked_(false), weak_factory_(this) {
376 set_connect_data(connect);
379 void OrderedSocketData::EndLoop() {
380 // If we've already stopped the loop, don't do it again until we've advanced
381 // to the next sequence_number.
382 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_ << ": EndLoop()";
383 if (loop_stop_stage_ > 0) {
384 const MockRead& next_read = StaticSocketDataProvider::PeekRead();
385 if ((next_read.sequence_number & ~MockRead::STOPLOOP) >
386 loop_stop_stage_) {
387 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
388 << ": Clearing stop index";
389 loop_stop_stage_ = 0;
390 } else {
391 return;
394 // Record the sequence_number at which we stopped the loop.
395 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
396 << ": Posting Quit at read " << read_index();
397 loop_stop_stage_ = sequence_number_;
400 MockRead OrderedSocketData::GetNextRead() {
401 weak_factory_.InvalidateWeakPtrs();
402 blocked_ = false;
403 const MockRead& next_read = StaticSocketDataProvider::PeekRead();
404 if (next_read.sequence_number & MockRead::STOPLOOP)
405 EndLoop();
406 if ((next_read.sequence_number & ~MockRead::STOPLOOP) <=
407 sequence_number_++) {
408 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_ - 1
409 << ": Read " << read_index();
410 DumpMockReadWrite(next_read);
411 blocked_ = (next_read.result == ERR_IO_PENDING);
412 return StaticSocketDataProvider::GetNextRead();
414 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_ - 1
415 << ": I/O Pending";
416 MockRead result = MockRead(ASYNC, ERR_IO_PENDING);
417 DumpMockReadWrite(result);
418 blocked_ = true;
419 return result;
422 MockWriteResult OrderedSocketData::OnWrite(const std::string& data) {
423 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
424 << ": Write " << write_index();
425 DumpMockReadWrite(PeekWrite());
426 ++sequence_number_;
427 if (blocked_) {
428 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
429 // should probably fix the weirdness. One example is in SpdyStream,
430 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
431 // SYN_REPLY causes OnResponseReceived() to get called before
432 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
433 base::MessageLoop::current()->PostDelayedTask(
434 FROM_HERE,
435 base::Bind(&OrderedSocketData::CompleteRead,
436 weak_factory_.GetWeakPtr()),
437 base::TimeDelta::FromMilliseconds(100));
439 return StaticSocketDataProvider::OnWrite(data);
442 void OrderedSocketData::Reset() {
443 NET_TRACE(INFO, " *** ") << "Stage "
444 << sequence_number_ << ": Reset()";
445 sequence_number_ = 0;
446 loop_stop_stage_ = 0;
447 set_socket(NULL);
448 weak_factory_.InvalidateWeakPtrs();
449 StaticSocketDataProvider::Reset();
452 void OrderedSocketData::CompleteRead() {
453 if (socket() && blocked_) {
454 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_;
455 socket()->OnReadComplete(GetNextRead());
459 OrderedSocketData::~OrderedSocketData() {}
461 DeterministicSocketData::DeterministicSocketData(MockRead* reads,
462 size_t reads_count, MockWrite* writes, size_t writes_count)
463 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
464 sequence_number_(0),
465 current_read_(),
466 current_write_(),
467 stopping_sequence_number_(0),
468 stopped_(false),
469 print_debug_(false),
470 is_running_(false) {
471 VerifyCorrectSequenceNumbers(reads, reads_count, writes, writes_count);
474 DeterministicSocketData::~DeterministicSocketData() {}
476 void DeterministicSocketData::Run() {
477 DCHECK(!is_running_);
478 is_running_ = true;
480 SetStopped(false);
481 int counter = 0;
482 // Continue to consume data until all data has run out, or the stopped_ flag
483 // has been set. Consuming data requires two separate operations -- running
484 // the tasks in the message loop, and explicitly invoking the read/write
485 // callbacks (simulating network I/O). We check our conditions between each,
486 // since they can change in either.
487 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
488 if (counter % 2 == 0)
489 base::RunLoop().RunUntilIdle();
490 if (counter % 2 == 1) {
491 InvokeCallbacks();
493 counter++;
495 // We're done consuming new data, but it is possible there are still some
496 // pending callbacks which we expect to complete before returning.
497 while (delegate_.get() &&
498 (delegate_->WritePending() || delegate_->ReadPending()) &&
499 !stopped()) {
500 InvokeCallbacks();
501 base::RunLoop().RunUntilIdle();
503 SetStopped(false);
504 is_running_ = false;
507 void DeterministicSocketData::RunFor(int steps) {
508 StopAfter(steps);
509 Run();
512 void DeterministicSocketData::SetStop(int seq) {
513 DCHECK_LT(sequence_number_, seq);
514 stopping_sequence_number_ = seq;
515 stopped_ = false;
518 void DeterministicSocketData::StopAfter(int seq) {
519 SetStop(sequence_number_ + seq);
522 MockRead DeterministicSocketData::GetNextRead() {
523 current_read_ = StaticSocketDataProvider::PeekRead();
525 // Synchronous read while stopped is an error
526 if (stopped() && current_read_.mode == SYNCHRONOUS) {
527 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
528 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
531 // Async read which will be called back in a future step.
532 if (sequence_number_ < current_read_.sequence_number) {
533 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
534 << ": I/O Pending";
535 MockRead result = MockRead(SYNCHRONOUS, ERR_IO_PENDING);
536 if (current_read_.mode == SYNCHRONOUS) {
537 LOG(ERROR) << "Unable to perform synchronous read: "
538 << current_read_.sequence_number
539 << " at stage: " << sequence_number_;
540 result = MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
542 if (print_debug_)
543 DumpMockReadWrite(result);
544 return result;
547 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
548 << ": Read " << read_index();
549 if (print_debug_)
550 DumpMockReadWrite(current_read_);
552 // Increment the sequence number if IO is complete
553 if (current_read_.mode == SYNCHRONOUS)
554 NextStep();
556 DCHECK_NE(ERR_IO_PENDING, current_read_.result);
557 StaticSocketDataProvider::GetNextRead();
559 return current_read_;
562 MockWriteResult DeterministicSocketData::OnWrite(const std::string& data) {
563 const MockWrite& next_write = StaticSocketDataProvider::PeekWrite();
564 current_write_ = next_write;
566 // Synchronous write while stopped is an error
567 if (stopped() && next_write.mode == SYNCHRONOUS) {
568 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
569 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
572 // Async write which will be called back in a future step.
573 if (sequence_number_ < next_write.sequence_number) {
574 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
575 << ": I/O Pending";
576 if (next_write.mode == SYNCHRONOUS) {
577 LOG(ERROR) << "Unable to perform synchronous write: "
578 << next_write.sequence_number << " at stage: " << sequence_number_;
579 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
581 } else {
582 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
583 << ": Write " << write_index();
586 if (print_debug_)
587 DumpMockReadWrite(next_write);
589 // Move to the next step if I/O is synchronous, since the operation will
590 // complete when this method returns.
591 if (next_write.mode == SYNCHRONOUS)
592 NextStep();
594 // This is either a sync write for this step, or an async write.
595 return StaticSocketDataProvider::OnWrite(data);
598 void DeterministicSocketData::Reset() {
599 NET_TRACE(INFO, " *** ") << "Stage "
600 << sequence_number_ << ": Reset()";
601 sequence_number_ = 0;
602 StaticSocketDataProvider::Reset();
603 NOTREACHED();
606 void DeterministicSocketData::InvokeCallbacks() {
607 if (delegate_.get() && delegate_->WritePending() &&
608 (current_write().sequence_number == sequence_number())) {
609 NextStep();
610 delegate_->CompleteWrite();
611 return;
613 if (delegate_.get() && delegate_->ReadPending() &&
614 (current_read().sequence_number == sequence_number())) {
615 NextStep();
616 delegate_->CompleteRead();
617 return;
621 void DeterministicSocketData::NextStep() {
622 // Invariant: Can never move *past* the stopping step.
623 DCHECK_LT(sequence_number_, stopping_sequence_number_);
624 sequence_number_++;
625 if (sequence_number_ == stopping_sequence_number_)
626 SetStopped(true);
629 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
630 MockRead* reads, size_t reads_count,
631 MockWrite* writes, size_t writes_count) {
632 size_t read = 0;
633 size_t write = 0;
634 int expected = 0;
635 while (read < reads_count || write < writes_count) {
636 // Check to see that we have a read or write at the expected
637 // state.
638 if (read < reads_count && reads[read].sequence_number == expected) {
639 ++read;
640 ++expected;
641 continue;
643 if (write < writes_count && writes[write].sequence_number == expected) {
644 ++write;
645 ++expected;
646 continue;
648 NOTREACHED() << "Missing sequence number: " << expected;
649 return;
651 DCHECK_EQ(read, reads_count);
652 DCHECK_EQ(write, writes_count);
655 MockClientSocketFactory::MockClientSocketFactory() {}
657 MockClientSocketFactory::~MockClientSocketFactory() {}
659 void MockClientSocketFactory::AddSocketDataProvider(
660 SocketDataProvider* data) {
661 mock_data_.Add(data);
664 void MockClientSocketFactory::AddSSLSocketDataProvider(
665 SSLSocketDataProvider* data) {
666 mock_ssl_data_.Add(data);
669 void MockClientSocketFactory::ResetNextMockIndexes() {
670 mock_data_.ResetNextIndex();
671 mock_ssl_data_.ResetNextIndex();
674 scoped_ptr<DatagramClientSocket>
675 MockClientSocketFactory::CreateDatagramClientSocket(
676 DatagramSocket::BindType bind_type,
677 const RandIntCallback& rand_int_cb,
678 net::NetLog* net_log,
679 const net::NetLog::Source& source) {
680 SocketDataProvider* data_provider = mock_data_.GetNext();
681 scoped_ptr<MockUDPClientSocket> socket(
682 new MockUDPClientSocket(data_provider, net_log));
683 data_provider->set_socket(socket.get());
684 if (bind_type == DatagramSocket::RANDOM_BIND)
685 socket->set_source_port(rand_int_cb.Run(1025, 65535));
686 return socket.PassAs<DatagramClientSocket>();
689 scoped_ptr<StreamSocket> MockClientSocketFactory::CreateTransportClientSocket(
690 const AddressList& addresses,
691 net::NetLog* net_log,
692 const net::NetLog::Source& source) {
693 SocketDataProvider* data_provider = mock_data_.GetNext();
694 scoped_ptr<MockTCPClientSocket> socket(
695 new MockTCPClientSocket(addresses, net_log, data_provider));
696 data_provider->set_socket(socket.get());
697 return socket.PassAs<StreamSocket>();
700 scoped_ptr<SSLClientSocket> MockClientSocketFactory::CreateSSLClientSocket(
701 scoped_ptr<ClientSocketHandle> transport_socket,
702 const HostPortPair& host_and_port,
703 const SSLConfig& ssl_config,
704 const SSLClientSocketContext& context) {
705 scoped_ptr<MockSSLClientSocket> socket(
706 new MockSSLClientSocket(transport_socket.Pass(),
707 host_and_port,
708 ssl_config,
709 mock_ssl_data_.GetNext()));
710 ssl_client_sockets_.push_back(socket.get());
711 return socket.PassAs<SSLClientSocket>();
714 void MockClientSocketFactory::ClearSSLSessionCache() {
717 const char MockClientSocket::kTlsUnique[] = "MOCK_TLSUNIQ";
719 MockClientSocket::MockClientSocket(const BoundNetLog& net_log)
720 : connected_(false),
721 net_log_(net_log),
722 weak_factory_(this) {
723 IPAddressNumber ip;
724 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
725 peer_addr_ = IPEndPoint(ip, 0);
728 int MockClientSocket::SetReceiveBufferSize(int32 size) {
729 return OK;
732 int MockClientSocket::SetSendBufferSize(int32 size) {
733 return OK;
736 void MockClientSocket::Disconnect() {
737 connected_ = false;
740 bool MockClientSocket::IsConnected() const {
741 return connected_;
744 bool MockClientSocket::IsConnectedAndIdle() const {
745 return connected_;
748 int MockClientSocket::GetPeerAddress(IPEndPoint* address) const {
749 if (!IsConnected())
750 return ERR_SOCKET_NOT_CONNECTED;
751 *address = peer_addr_;
752 return OK;
755 int MockClientSocket::GetLocalAddress(IPEndPoint* address) const {
756 IPAddressNumber ip;
757 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
758 CHECK(rv);
759 *address = IPEndPoint(ip, 123);
760 return OK;
763 const BoundNetLog& MockClientSocket::NetLog() const {
764 return net_log_;
767 bool MockClientSocket::InSessionCache() const {
768 NOTIMPLEMENTED();
769 return false;
772 void MockClientSocket::SetHandshakeCompletionCallback(const base::Closure& cb) {
773 NOTIMPLEMENTED();
776 void MockClientSocket::GetSSLCertRequestInfo(
777 SSLCertRequestInfo* cert_request_info) {
780 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece& label,
781 bool has_context,
782 const base::StringPiece& context,
783 unsigned char* out,
784 unsigned int outlen) {
785 memset(out, 'A', outlen);
786 return OK;
789 int MockClientSocket::GetTLSUniqueChannelBinding(std::string* out) {
790 out->assign(MockClientSocket::kTlsUnique);
791 return OK;
794 ChannelIDService* MockClientSocket::GetChannelIDService() const {
795 NOTREACHED();
796 return NULL;
799 SSLClientSocket::NextProtoStatus
800 MockClientSocket::GetNextProto(std::string* proto) {
801 proto->clear();
802 return SSLClientSocket::kNextProtoUnsupported;
805 scoped_refptr<X509Certificate>
806 MockClientSocket::GetUnverifiedServerCertificateChain() const {
807 NOTREACHED();
808 return NULL;
811 MockClientSocket::~MockClientSocket() {}
813 void MockClientSocket::RunCallbackAsync(const CompletionCallback& callback,
814 int result) {
815 base::MessageLoop::current()->PostTask(
816 FROM_HERE,
817 base::Bind(&MockClientSocket::RunCallback,
818 weak_factory_.GetWeakPtr(),
819 callback,
820 result));
823 void MockClientSocket::RunCallback(const net::CompletionCallback& callback,
824 int result) {
825 if (!callback.is_null())
826 callback.Run(result);
829 MockTCPClientSocket::MockTCPClientSocket(const AddressList& addresses,
830 net::NetLog* net_log,
831 SocketDataProvider* data)
832 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
833 addresses_(addresses),
834 data_(data),
835 read_offset_(0),
836 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
837 need_read_data_(true),
838 peer_closed_connection_(false),
839 pending_buf_(NULL),
840 pending_buf_len_(0),
841 was_used_to_convey_data_(false) {
842 DCHECK(data_);
843 peer_addr_ = data->connect_data().peer_addr;
844 data_->Reset();
847 MockTCPClientSocket::~MockTCPClientSocket() {}
849 int MockTCPClientSocket::Read(IOBuffer* buf, int buf_len,
850 const CompletionCallback& callback) {
851 if (!connected_)
852 return ERR_UNEXPECTED;
854 // If the buffer is already in use, a read is already in progress!
855 DCHECK(pending_buf_ == NULL);
857 // Store our async IO data.
858 pending_buf_ = buf;
859 pending_buf_len_ = buf_len;
860 pending_callback_ = callback;
862 if (need_read_data_) {
863 read_data_ = data_->GetNextRead();
864 if (read_data_.result == ERR_CONNECTION_CLOSED) {
865 // This MockRead is just a marker to instruct us to set
866 // peer_closed_connection_.
867 peer_closed_connection_ = true;
869 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
870 // This MockRead is just a marker to instruct us to set
871 // peer_closed_connection_. Skip it and get the next one.
872 read_data_ = data_->GetNextRead();
873 peer_closed_connection_ = true;
875 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
876 // to complete the async IO manually later (via OnReadComplete).
877 if (read_data_.result == ERR_IO_PENDING) {
878 // We need to be using async IO in this case.
879 DCHECK(!callback.is_null());
880 return ERR_IO_PENDING;
882 need_read_data_ = false;
885 return CompleteRead();
888 int MockTCPClientSocket::Write(IOBuffer* buf, int buf_len,
889 const CompletionCallback& callback) {
890 DCHECK(buf);
891 DCHECK_GT(buf_len, 0);
893 if (!connected_)
894 return ERR_UNEXPECTED;
896 std::string data(buf->data(), buf_len);
897 MockWriteResult write_result = data_->OnWrite(data);
899 was_used_to_convey_data_ = true;
901 if (write_result.mode == ASYNC) {
902 RunCallbackAsync(callback, write_result.result);
903 return ERR_IO_PENDING;
906 return write_result.result;
909 int MockTCPClientSocket::Connect(const CompletionCallback& callback) {
910 if (connected_)
911 return OK;
912 connected_ = true;
913 peer_closed_connection_ = false;
914 if (data_->connect_data().mode == ASYNC) {
915 if (data_->connect_data().result == ERR_IO_PENDING)
916 pending_callback_ = callback;
917 else
918 RunCallbackAsync(callback, data_->connect_data().result);
919 return ERR_IO_PENDING;
921 return data_->connect_data().result;
924 void MockTCPClientSocket::Disconnect() {
925 MockClientSocket::Disconnect();
926 pending_callback_.Reset();
929 bool MockTCPClientSocket::IsConnected() const {
930 return connected_ && !peer_closed_connection_;
933 bool MockTCPClientSocket::IsConnectedAndIdle() const {
934 return IsConnected();
937 int MockTCPClientSocket::GetPeerAddress(IPEndPoint* address) const {
938 if (addresses_.empty())
939 return MockClientSocket::GetPeerAddress(address);
941 *address = addresses_[0];
942 return OK;
945 bool MockTCPClientSocket::WasEverUsed() const {
946 return was_used_to_convey_data_;
949 bool MockTCPClientSocket::UsingTCPFastOpen() const {
950 return false;
953 bool MockTCPClientSocket::WasNpnNegotiated() const {
954 return false;
957 bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
958 return false;
961 void MockTCPClientSocket::OnReadComplete(const MockRead& data) {
962 // There must be a read pending.
963 DCHECK(pending_buf_);
964 // You can't complete a read with another ERR_IO_PENDING status code.
965 DCHECK_NE(ERR_IO_PENDING, data.result);
966 // Since we've been waiting for data, need_read_data_ should be true.
967 DCHECK(need_read_data_);
969 read_data_ = data;
970 need_read_data_ = false;
972 // The caller is simulating that this IO completes right now. Don't
973 // let CompleteRead() schedule a callback.
974 read_data_.mode = SYNCHRONOUS;
976 CompletionCallback callback = pending_callback_;
977 int rv = CompleteRead();
978 RunCallback(callback, rv);
981 void MockTCPClientSocket::OnConnectComplete(const MockConnect& data) {
982 CompletionCallback callback = pending_callback_;
983 RunCallback(callback, data.result);
986 int MockTCPClientSocket::CompleteRead() {
987 DCHECK(pending_buf_);
988 DCHECK(pending_buf_len_ > 0);
990 was_used_to_convey_data_ = true;
992 // Save the pending async IO data and reset our |pending_| state.
993 scoped_refptr<IOBuffer> buf = pending_buf_;
994 int buf_len = pending_buf_len_;
995 CompletionCallback callback = pending_callback_;
996 pending_buf_ = NULL;
997 pending_buf_len_ = 0;
998 pending_callback_.Reset();
1000 int result = read_data_.result;
1001 DCHECK(result != ERR_IO_PENDING);
1003 if (read_data_.data) {
1004 if (read_data_.data_len - read_offset_ > 0) {
1005 result = std::min(buf_len, read_data_.data_len - read_offset_);
1006 memcpy(buf->data(), read_data_.data + read_offset_, result);
1007 read_offset_ += result;
1008 if (read_offset_ == read_data_.data_len) {
1009 need_read_data_ = true;
1010 read_offset_ = 0;
1012 } else {
1013 result = 0; // EOF
1017 if (read_data_.mode == ASYNC) {
1018 DCHECK(!callback.is_null());
1019 RunCallbackAsync(callback, result);
1020 return ERR_IO_PENDING;
1022 return result;
1025 DeterministicSocketHelper::DeterministicSocketHelper(
1026 net::NetLog* net_log,
1027 DeterministicSocketData* data)
1028 : write_pending_(false),
1029 write_result_(0),
1030 read_data_(),
1031 read_buf_(NULL),
1032 read_buf_len_(0),
1033 read_pending_(false),
1034 data_(data),
1035 was_used_to_convey_data_(false),
1036 peer_closed_connection_(false),
1037 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)) {
1040 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1042 void DeterministicSocketHelper::CompleteWrite() {
1043 was_used_to_convey_data_ = true;
1044 write_pending_ = false;
1045 write_callback_.Run(write_result_);
1048 int DeterministicSocketHelper::CompleteRead() {
1049 DCHECK_GT(read_buf_len_, 0);
1050 DCHECK_LE(read_data_.data_len, read_buf_len_);
1051 DCHECK(read_buf_);
1053 was_used_to_convey_data_ = true;
1055 if (read_data_.result == ERR_IO_PENDING)
1056 read_data_ = data_->GetNextRead();
1057 DCHECK_NE(ERR_IO_PENDING, read_data_.result);
1058 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1059 // the callback. Therefore we don't even bother to check it.
1060 int result = read_data_.result;
1062 if (read_data_.data_len > 0) {
1063 DCHECK(read_data_.data);
1064 result = std::min(read_buf_len_, read_data_.data_len);
1065 memcpy(read_buf_->data(), read_data_.data, result);
1068 if (read_pending_) {
1069 read_pending_ = false;
1070 read_callback_.Run(result);
1073 return result;
1076 int DeterministicSocketHelper::Write(
1077 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1078 DCHECK(buf);
1079 DCHECK_GT(buf_len, 0);
1081 std::string data(buf->data(), buf_len);
1082 MockWriteResult write_result = data_->OnWrite(data);
1084 if (write_result.mode == ASYNC) {
1085 write_callback_ = callback;
1086 write_result_ = write_result.result;
1087 DCHECK(!write_callback_.is_null());
1088 write_pending_ = true;
1089 return ERR_IO_PENDING;
1092 was_used_to_convey_data_ = true;
1093 write_pending_ = false;
1094 return write_result.result;
1097 int DeterministicSocketHelper::Read(
1098 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1100 read_data_ = data_->GetNextRead();
1101 // The buffer should always be big enough to contain all the MockRead data. To
1102 // use small buffers, split the data into multiple MockReads.
1103 DCHECK_LE(read_data_.data_len, buf_len);
1105 if (read_data_.result == ERR_CONNECTION_CLOSED) {
1106 // This MockRead is just a marker to instruct us to set
1107 // peer_closed_connection_.
1108 peer_closed_connection_ = true;
1110 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
1111 // This MockRead is just a marker to instruct us to set
1112 // peer_closed_connection_. Skip it and get the next one.
1113 read_data_ = data_->GetNextRead();
1114 peer_closed_connection_ = true;
1117 read_buf_ = buf;
1118 read_buf_len_ = buf_len;
1119 read_callback_ = callback;
1121 if (read_data_.mode == ASYNC || (read_data_.result == ERR_IO_PENDING)) {
1122 read_pending_ = true;
1123 DCHECK(!read_callback_.is_null());
1124 return ERR_IO_PENDING;
1127 was_used_to_convey_data_ = true;
1128 return CompleteRead();
1131 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1132 net::NetLog* net_log,
1133 DeterministicSocketData* data)
1134 : connected_(false),
1135 helper_(net_log, data),
1136 source_port_(123) {
1139 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1141 bool DeterministicMockUDPClientSocket::WritePending() const {
1142 return helper_.write_pending();
1145 bool DeterministicMockUDPClientSocket::ReadPending() const {
1146 return helper_.read_pending();
1149 void DeterministicMockUDPClientSocket::CompleteWrite() {
1150 helper_.CompleteWrite();
1153 int DeterministicMockUDPClientSocket::CompleteRead() {
1154 return helper_.CompleteRead();
1157 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint& address) {
1158 if (connected_)
1159 return OK;
1160 connected_ = true;
1161 peer_address_ = address;
1162 return helper_.data()->connect_data().result;
1165 int DeterministicMockUDPClientSocket::Write(
1166 IOBuffer* buf,
1167 int buf_len,
1168 const CompletionCallback& callback) {
1169 if (!connected_)
1170 return ERR_UNEXPECTED;
1172 return helper_.Write(buf, buf_len, callback);
1175 int DeterministicMockUDPClientSocket::Read(
1176 IOBuffer* buf,
1177 int buf_len,
1178 const CompletionCallback& callback) {
1179 if (!connected_)
1180 return ERR_UNEXPECTED;
1182 return helper_.Read(buf, buf_len, callback);
1185 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1186 return OK;
1189 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size) {
1190 return OK;
1193 void DeterministicMockUDPClientSocket::Close() {
1194 connected_ = false;
1197 int DeterministicMockUDPClientSocket::GetPeerAddress(
1198 IPEndPoint* address) const {
1199 *address = peer_address_;
1200 return OK;
1203 int DeterministicMockUDPClientSocket::GetLocalAddress(
1204 IPEndPoint* address) const {
1205 IPAddressNumber ip;
1206 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1207 CHECK(rv);
1208 *address = IPEndPoint(ip, source_port_);
1209 return OK;
1212 const BoundNetLog& DeterministicMockUDPClientSocket::NetLog() const {
1213 return helper_.net_log();
1216 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead& data) {}
1218 void DeterministicMockUDPClientSocket::OnConnectComplete(
1219 const MockConnect& data) {
1220 NOTIMPLEMENTED();
1223 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1224 net::NetLog* net_log,
1225 DeterministicSocketData* data)
1226 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1227 helper_(net_log, data) {
1228 peer_addr_ = data->connect_data().peer_addr;
1231 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1233 bool DeterministicMockTCPClientSocket::WritePending() const {
1234 return helper_.write_pending();
1237 bool DeterministicMockTCPClientSocket::ReadPending() const {
1238 return helper_.read_pending();
1241 void DeterministicMockTCPClientSocket::CompleteWrite() {
1242 helper_.CompleteWrite();
1245 int DeterministicMockTCPClientSocket::CompleteRead() {
1246 return helper_.CompleteRead();
1249 int DeterministicMockTCPClientSocket::Write(
1250 IOBuffer* buf,
1251 int buf_len,
1252 const CompletionCallback& callback) {
1253 if (!connected_)
1254 return ERR_UNEXPECTED;
1256 return helper_.Write(buf, buf_len, callback);
1259 int DeterministicMockTCPClientSocket::Read(
1260 IOBuffer* buf,
1261 int buf_len,
1262 const CompletionCallback& callback) {
1263 if (!connected_)
1264 return ERR_UNEXPECTED;
1266 return helper_.Read(buf, buf_len, callback);
1269 // TODO(erikchen): Support connect sequencing.
1270 int DeterministicMockTCPClientSocket::Connect(
1271 const CompletionCallback& callback) {
1272 if (connected_)
1273 return OK;
1274 connected_ = true;
1275 if (helper_.data()->connect_data().mode == ASYNC) {
1276 RunCallbackAsync(callback, helper_.data()->connect_data().result);
1277 return ERR_IO_PENDING;
1279 return helper_.data()->connect_data().result;
1282 void DeterministicMockTCPClientSocket::Disconnect() {
1283 MockClientSocket::Disconnect();
1286 bool DeterministicMockTCPClientSocket::IsConnected() const {
1287 return connected_ && !helper_.peer_closed_connection();
1290 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1291 return IsConnected();
1294 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1295 return helper_.was_used_to_convey_data();
1298 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1299 return false;
1302 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1303 return false;
1306 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1307 return false;
1310 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead& data) {}
1312 void DeterministicMockTCPClientSocket::OnConnectComplete(
1313 const MockConnect& data) {}
1315 MockSSLClientSocket::MockSSLClientSocket(
1316 scoped_ptr<ClientSocketHandle> transport_socket,
1317 const HostPortPair& host_port_pair,
1318 const SSLConfig& ssl_config,
1319 SSLSocketDataProvider* data)
1320 : MockClientSocket(
1321 // Have to use the right BoundNetLog for LoadTimingInfo regression
1322 // tests.
1323 transport_socket->socket()->NetLog()),
1324 transport_(transport_socket.Pass()),
1325 data_(data),
1326 is_npn_state_set_(false),
1327 new_npn_value_(false),
1328 is_protocol_negotiated_set_(false),
1329 protocol_negotiated_(kProtoUnknown),
1330 next_connect_state_(STATE_NONE),
1331 reached_connect_(false),
1332 weak_factory_(this) {
1333 DCHECK(data_);
1334 peer_addr_ = data->connect.peer_addr;
1337 MockSSLClientSocket::~MockSSLClientSocket() {
1338 Disconnect();
1341 int MockSSLClientSocket::Read(IOBuffer* buf, int buf_len,
1342 const CompletionCallback& callback) {
1343 return transport_->socket()->Read(buf, buf_len, callback);
1346 int MockSSLClientSocket::Write(IOBuffer* buf, int buf_len,
1347 const CompletionCallback& callback) {
1348 return transport_->socket()->Write(buf, buf_len, callback);
1351 int MockSSLClientSocket::Connect(const CompletionCallback& callback) {
1352 next_connect_state_ = STATE_SSL_CONNECT;
1353 reached_connect_ = true;
1354 int rv = DoConnectLoop(OK);
1355 if (rv == ERR_IO_PENDING)
1356 connect_callback_ = callback;
1357 return rv;
1360 void MockSSLClientSocket::Disconnect() {
1361 weak_factory_.InvalidateWeakPtrs();
1362 MockClientSocket::Disconnect();
1363 if (transport_->socket() != NULL)
1364 transport_->socket()->Disconnect();
1367 bool MockSSLClientSocket::IsConnected() const {
1368 return transport_->socket()->IsConnected() && connected_;
1371 bool MockSSLClientSocket::WasEverUsed() const {
1372 return transport_->socket()->WasEverUsed();
1375 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1376 return transport_->socket()->UsingTCPFastOpen();
1379 int MockSSLClientSocket::GetPeerAddress(IPEndPoint* address) const {
1380 return transport_->socket()->GetPeerAddress(address);
1383 bool MockSSLClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1384 ssl_info->Reset();
1385 ssl_info->cert = data_->cert;
1386 ssl_info->client_cert_sent = data_->client_cert_sent;
1387 ssl_info->channel_id_sent = data_->channel_id_sent;
1388 ssl_info->connection_status = data_->connection_status;
1389 return true;
1392 bool MockSSLClientSocket::InSessionCache() const {
1393 return data_->is_in_session_cache;
1396 void MockSSLClientSocket::SetHandshakeCompletionCallback(
1397 const base::Closure& cb) {
1398 handshake_completion_callback_ = cb;
1401 void MockSSLClientSocket::GetSSLCertRequestInfo(
1402 SSLCertRequestInfo* cert_request_info) {
1403 DCHECK(cert_request_info);
1404 if (data_->cert_request_info) {
1405 cert_request_info->host_and_port =
1406 data_->cert_request_info->host_and_port;
1407 cert_request_info->client_certs = data_->cert_request_info->client_certs;
1408 } else {
1409 cert_request_info->Reset();
1413 SSLClientSocket::NextProtoStatus MockSSLClientSocket::GetNextProto(
1414 std::string* proto) {
1415 *proto = data_->next_proto;
1416 return data_->next_proto_status;
1419 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated) {
1420 is_npn_state_set_ = true;
1421 return new_npn_value_ = negotiated;
1424 bool MockSSLClientSocket::WasNpnNegotiated() const {
1425 if (is_npn_state_set_)
1426 return new_npn_value_;
1427 return data_->was_npn_negotiated;
1430 NextProto MockSSLClientSocket::GetNegotiatedProtocol() const {
1431 if (is_protocol_negotiated_set_)
1432 return protocol_negotiated_;
1433 return data_->protocol_negotiated;
1436 void MockSSLClientSocket::set_protocol_negotiated(
1437 NextProto protocol_negotiated) {
1438 is_protocol_negotiated_set_ = true;
1439 protocol_negotiated_ = protocol_negotiated;
1442 bool MockSSLClientSocket::WasChannelIDSent() const {
1443 return data_->channel_id_sent;
1446 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent) {
1447 data_->channel_id_sent = channel_id_sent;
1450 ChannelIDService* MockSSLClientSocket::GetChannelIDService() const {
1451 return data_->channel_id_service;
1454 void MockSSLClientSocket::OnReadComplete(const MockRead& data) {
1455 NOTIMPLEMENTED();
1458 void MockSSLClientSocket::OnConnectComplete(const MockConnect& data) {
1459 NOTIMPLEMENTED();
1462 void MockSSLClientSocket::RestartPausedConnect() {
1463 DCHECK(data_->should_pause_on_connect);
1464 DCHECK_EQ(next_connect_state_, STATE_SSL_CONNECT_COMPLETE);
1465 OnIOComplete(data_->connect.result);
1468 void MockSSLClientSocket::OnIOComplete(int result) {
1469 int rv = DoConnectLoop(result);
1470 if (rv != ERR_IO_PENDING)
1471 base::ResetAndReturn(&connect_callback_).Run(rv);
1474 int MockSSLClientSocket::DoConnectLoop(int result) {
1475 DCHECK_NE(next_connect_state_, STATE_NONE);
1477 int rv = result;
1478 do {
1479 ConnectState state = next_connect_state_;
1480 next_connect_state_ = STATE_NONE;
1481 switch (state) {
1482 case STATE_SSL_CONNECT:
1483 rv = DoSSLConnect();
1484 break;
1485 case STATE_SSL_CONNECT_COMPLETE:
1486 rv = DoSSLConnectComplete(rv);
1487 break;
1488 default:
1489 NOTREACHED() << "bad state";
1490 rv = ERR_UNEXPECTED;
1491 break;
1493 } while (rv != ERR_IO_PENDING && next_connect_state_ != STATE_NONE);
1495 return rv;
1498 int MockSSLClientSocket::DoSSLConnect() {
1499 next_connect_state_ = STATE_SSL_CONNECT_COMPLETE;
1501 if (data_->should_pause_on_connect)
1502 return ERR_IO_PENDING;
1504 if (data_->connect.mode == ASYNC) {
1505 base::MessageLoop::current()->PostTask(
1506 FROM_HERE,
1507 base::Bind(&MockSSLClientSocket::OnIOComplete,
1508 weak_factory_.GetWeakPtr(),
1509 data_->connect.result));
1510 return ERR_IO_PENDING;
1513 return data_->connect.result;
1516 int MockSSLClientSocket::DoSSLConnectComplete(int result) {
1517 if (result == OK)
1518 connected_ = true;
1520 if (!handshake_completion_callback_.is_null())
1521 base::ResetAndReturn(&handshake_completion_callback_).Run();
1522 return result;
1525 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data,
1526 net::NetLog* net_log)
1527 : connected_(false),
1528 data_(data),
1529 read_offset_(0),
1530 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
1531 need_read_data_(true),
1532 source_port_(123),
1533 pending_buf_(NULL),
1534 pending_buf_len_(0),
1535 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1536 weak_factory_(this) {
1537 DCHECK(data_);
1538 data_->Reset();
1539 peer_addr_ = data->connect_data().peer_addr;
1542 MockUDPClientSocket::~MockUDPClientSocket() {}
1544 int MockUDPClientSocket::Read(IOBuffer* buf,
1545 int buf_len,
1546 const CompletionCallback& callback) {
1547 if (!connected_)
1548 return ERR_UNEXPECTED;
1550 // If the buffer is already in use, a read is already in progress!
1551 DCHECK(pending_buf_ == NULL);
1553 // Store our async IO data.
1554 pending_buf_ = buf;
1555 pending_buf_len_ = buf_len;
1556 pending_callback_ = callback;
1558 if (need_read_data_) {
1559 read_data_ = data_->GetNextRead();
1560 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1561 // to complete the async IO manually later (via OnReadComplete).
1562 if (read_data_.result == ERR_IO_PENDING) {
1563 // We need to be using async IO in this case.
1564 DCHECK(!callback.is_null());
1565 return ERR_IO_PENDING;
1567 need_read_data_ = false;
1570 return CompleteRead();
1573 int MockUDPClientSocket::Write(IOBuffer* buf, int buf_len,
1574 const CompletionCallback& callback) {
1575 DCHECK(buf);
1576 DCHECK_GT(buf_len, 0);
1578 if (!connected_)
1579 return ERR_UNEXPECTED;
1581 std::string data(buf->data(), buf_len);
1582 MockWriteResult write_result = data_->OnWrite(data);
1584 if (write_result.mode == ASYNC) {
1585 RunCallbackAsync(callback, write_result.result);
1586 return ERR_IO_PENDING;
1588 return write_result.result;
1591 int MockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1592 return OK;
1595 int MockUDPClientSocket::SetSendBufferSize(int32 size) {
1596 return OK;
1599 void MockUDPClientSocket::Close() {
1600 connected_ = false;
1603 int MockUDPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1604 *address = peer_addr_;
1605 return OK;
1608 int MockUDPClientSocket::GetLocalAddress(IPEndPoint* address) const {
1609 IPAddressNumber ip;
1610 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1611 CHECK(rv);
1612 *address = IPEndPoint(ip, source_port_);
1613 return OK;
1616 const BoundNetLog& MockUDPClientSocket::NetLog() const {
1617 return net_log_;
1620 int MockUDPClientSocket::Connect(const IPEndPoint& address) {
1621 connected_ = true;
1622 peer_addr_ = address;
1623 return data_->connect_data().result;
1626 void MockUDPClientSocket::OnReadComplete(const MockRead& data) {
1627 // There must be a read pending.
1628 DCHECK(pending_buf_);
1629 // You can't complete a read with another ERR_IO_PENDING status code.
1630 DCHECK_NE(ERR_IO_PENDING, data.result);
1631 // Since we've been waiting for data, need_read_data_ should be true.
1632 DCHECK(need_read_data_);
1634 read_data_ = data;
1635 need_read_data_ = false;
1637 // The caller is simulating that this IO completes right now. Don't
1638 // let CompleteRead() schedule a callback.
1639 read_data_.mode = SYNCHRONOUS;
1641 net::CompletionCallback callback = pending_callback_;
1642 int rv = CompleteRead();
1643 RunCallback(callback, rv);
1646 void MockUDPClientSocket::OnConnectComplete(const MockConnect& data) {
1647 NOTIMPLEMENTED();
1650 int MockUDPClientSocket::CompleteRead() {
1651 DCHECK(pending_buf_);
1652 DCHECK(pending_buf_len_ > 0);
1654 // Save the pending async IO data and reset our |pending_| state.
1655 scoped_refptr<IOBuffer> buf = pending_buf_;
1656 int buf_len = pending_buf_len_;
1657 CompletionCallback callback = pending_callback_;
1658 pending_buf_ = NULL;
1659 pending_buf_len_ = 0;
1660 pending_callback_.Reset();
1662 int result = read_data_.result;
1663 DCHECK(result != ERR_IO_PENDING);
1665 if (read_data_.data) {
1666 if (read_data_.data_len - read_offset_ > 0) {
1667 result = std::min(buf_len, read_data_.data_len - read_offset_);
1668 memcpy(buf->data(), read_data_.data + read_offset_, result);
1669 read_offset_ += result;
1670 if (read_offset_ == read_data_.data_len) {
1671 need_read_data_ = true;
1672 read_offset_ = 0;
1674 } else {
1675 result = 0; // EOF
1679 if (read_data_.mode == ASYNC) {
1680 DCHECK(!callback.is_null());
1681 RunCallbackAsync(callback, result);
1682 return ERR_IO_PENDING;
1684 return result;
1687 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback& callback,
1688 int result) {
1689 base::MessageLoop::current()->PostTask(
1690 FROM_HERE,
1691 base::Bind(&MockUDPClientSocket::RunCallback,
1692 weak_factory_.GetWeakPtr(),
1693 callback,
1694 result));
1697 void MockUDPClientSocket::RunCallback(const CompletionCallback& callback,
1698 int result) {
1699 if (!callback.is_null())
1700 callback.Run(result);
1703 TestSocketRequest::TestSocketRequest(
1704 std::vector<TestSocketRequest*>* request_order, size_t* completion_count)
1705 : request_order_(request_order),
1706 completion_count_(completion_count),
1707 callback_(base::Bind(&TestSocketRequest::OnComplete,
1708 base::Unretained(this))) {
1709 DCHECK(request_order);
1710 DCHECK(completion_count);
1713 TestSocketRequest::~TestSocketRequest() {
1716 void TestSocketRequest::OnComplete(int result) {
1717 SetResult(result);
1718 (*completion_count_)++;
1719 request_order_->push_back(this);
1722 // static
1723 const int ClientSocketPoolTest::kIndexOutOfBounds = -1;
1725 // static
1726 const int ClientSocketPoolTest::kRequestNotFound = -2;
1728 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1729 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1731 int ClientSocketPoolTest::GetOrderOfRequest(size_t index) const {
1732 index--;
1733 if (index >= requests_.size())
1734 return kIndexOutOfBounds;
1736 for (size_t i = 0; i < request_order_.size(); i++)
1737 if (requests_[index] == request_order_[i])
1738 return i + 1;
1740 return kRequestNotFound;
1743 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
1744 ScopedVector<TestSocketRequest>::iterator i;
1745 for (i = requests_.begin(); i != requests_.end(); ++i) {
1746 if ((*i)->handle()->is_initialized()) {
1747 if (keep_alive == NO_KEEP_ALIVE)
1748 (*i)->handle()->socket()->Disconnect();
1749 (*i)->handle()->Reset();
1750 base::RunLoop().RunUntilIdle();
1751 return true;
1754 return false;
1757 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
1758 bool released_one;
1759 do {
1760 released_one = ReleaseOneConnection(keep_alive);
1761 } while (released_one);
1764 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1765 scoped_ptr<StreamSocket> socket,
1766 ClientSocketHandle* handle,
1767 const CompletionCallback& callback)
1768 : socket_(socket.Pass()),
1769 handle_(handle),
1770 user_callback_(callback) {
1773 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1775 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1776 int rv = socket_->Connect(base::Bind(&MockConnectJob::OnConnect,
1777 base::Unretained(this)));
1778 if (rv == OK) {
1779 user_callback_.Reset();
1780 OnConnect(OK);
1782 return rv;
1785 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1786 const ClientSocketHandle* handle) {
1787 if (handle != handle_)
1788 return false;
1789 socket_.reset();
1790 handle_ = NULL;
1791 user_callback_.Reset();
1792 return true;
1795 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) {
1796 if (!socket_.get())
1797 return;
1798 if (rv == OK) {
1799 handle_->SetSocket(socket_.Pass());
1801 // Needed for socket pool tests that layer other sockets on top of mock
1802 // sockets.
1803 LoadTimingInfo::ConnectTiming connect_timing;
1804 base::TimeTicks now = base::TimeTicks::Now();
1805 connect_timing.dns_start = now;
1806 connect_timing.dns_end = now;
1807 connect_timing.connect_start = now;
1808 connect_timing.connect_end = now;
1809 handle_->set_connect_timing(connect_timing);
1810 } else {
1811 socket_.reset();
1814 handle_ = NULL;
1816 if (!user_callback_.is_null()) {
1817 CompletionCallback callback = user_callback_;
1818 user_callback_.Reset();
1819 callback.Run(rv);
1823 MockTransportClientSocketPool::MockTransportClientSocketPool(
1824 int max_sockets,
1825 int max_sockets_per_group,
1826 ClientSocketPoolHistograms* histograms,
1827 ClientSocketFactory* socket_factory)
1828 : TransportClientSocketPool(max_sockets, max_sockets_per_group, histograms,
1829 NULL, NULL, NULL),
1830 client_socket_factory_(socket_factory),
1831 last_request_priority_(DEFAULT_PRIORITY),
1832 release_count_(0),
1833 cancel_count_(0) {
1836 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1838 int MockTransportClientSocketPool::RequestSocket(
1839 const std::string& group_name, const void* socket_params,
1840 RequestPriority priority, ClientSocketHandle* handle,
1841 const CompletionCallback& callback, const BoundNetLog& net_log) {
1842 last_request_priority_ = priority;
1843 scoped_ptr<StreamSocket> socket =
1844 client_socket_factory_->CreateTransportClientSocket(
1845 AddressList(), net_log.net_log(), net::NetLog::Source());
1846 MockConnectJob* job = new MockConnectJob(socket.Pass(), handle, callback);
1847 job_list_.push_back(job);
1848 handle->set_pool_id(1);
1849 return job->Connect();
1852 void MockTransportClientSocketPool::CancelRequest(const std::string& group_name,
1853 ClientSocketHandle* handle) {
1854 std::vector<MockConnectJob*>::iterator i;
1855 for (i = job_list_.begin(); i != job_list_.end(); ++i) {
1856 if ((*i)->CancelHandle(handle)) {
1857 cancel_count_++;
1858 break;
1863 void MockTransportClientSocketPool::ReleaseSocket(
1864 const std::string& group_name,
1865 scoped_ptr<StreamSocket> socket,
1866 int id) {
1867 EXPECT_EQ(1, id);
1868 release_count_++;
1871 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1873 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1875 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1876 DeterministicSocketData* data) {
1877 mock_data_.Add(data);
1880 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1881 SSLSocketDataProvider* data) {
1882 mock_ssl_data_.Add(data);
1885 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1886 mock_data_.ResetNextIndex();
1887 mock_ssl_data_.ResetNextIndex();
1890 MockSSLClientSocket* DeterministicMockClientSocketFactory::
1891 GetMockSSLClientSocket(size_t index) const {
1892 DCHECK_LT(index, ssl_client_sockets_.size());
1893 return ssl_client_sockets_[index];
1896 scoped_ptr<DatagramClientSocket>
1897 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1898 DatagramSocket::BindType bind_type,
1899 const RandIntCallback& rand_int_cb,
1900 net::NetLog* net_log,
1901 const NetLog::Source& source) {
1902 DeterministicSocketData* data_provider = mock_data().GetNext();
1903 scoped_ptr<DeterministicMockUDPClientSocket> socket(
1904 new DeterministicMockUDPClientSocket(net_log, data_provider));
1905 data_provider->set_delegate(socket->AsWeakPtr());
1906 udp_client_sockets().push_back(socket.get());
1907 if (bind_type == DatagramSocket::RANDOM_BIND)
1908 socket->set_source_port(rand_int_cb.Run(1025, 65535));
1909 return socket.PassAs<DatagramClientSocket>();
1912 scoped_ptr<StreamSocket>
1913 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1914 const AddressList& addresses,
1915 net::NetLog* net_log,
1916 const net::NetLog::Source& source) {
1917 DeterministicSocketData* data_provider = mock_data().GetNext();
1918 scoped_ptr<DeterministicMockTCPClientSocket> socket(
1919 new DeterministicMockTCPClientSocket(net_log, data_provider));
1920 data_provider->set_delegate(socket->AsWeakPtr());
1921 tcp_client_sockets().push_back(socket.get());
1922 return socket.PassAs<StreamSocket>();
1925 scoped_ptr<SSLClientSocket>
1926 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1927 scoped_ptr<ClientSocketHandle> transport_socket,
1928 const HostPortPair& host_and_port,
1929 const SSLConfig& ssl_config,
1930 const SSLClientSocketContext& context) {
1931 scoped_ptr<MockSSLClientSocket> socket(
1932 new MockSSLClientSocket(transport_socket.Pass(),
1933 host_and_port, ssl_config,
1934 mock_ssl_data_.GetNext()));
1935 ssl_client_sockets_.push_back(socket.get());
1936 return socket.PassAs<SSLClientSocket>();
1939 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1942 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1943 int max_sockets,
1944 int max_sockets_per_group,
1945 ClientSocketPoolHistograms* histograms,
1946 TransportClientSocketPool* transport_pool)
1947 : SOCKSClientSocketPool(max_sockets, max_sockets_per_group, histograms,
1948 NULL, transport_pool, NULL),
1949 transport_pool_(transport_pool) {
1952 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1954 int MockSOCKSClientSocketPool::RequestSocket(
1955 const std::string& group_name, const void* socket_params,
1956 RequestPriority priority, ClientSocketHandle* handle,
1957 const CompletionCallback& callback, const BoundNetLog& net_log) {
1958 return transport_pool_->RequestSocket(
1959 group_name, socket_params, priority, handle, callback, net_log);
1962 void MockSOCKSClientSocketPool::CancelRequest(
1963 const std::string& group_name,
1964 ClientSocketHandle* handle) {
1965 return transport_pool_->CancelRequest(group_name, handle);
1968 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string& group_name,
1969 scoped_ptr<StreamSocket> socket,
1970 int id) {
1971 return transport_pool_->ReleaseSocket(group_name, socket.Pass(), id);
1974 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
1975 const int kSOCKS5GreetRequestLength = arraysize(kSOCKS5GreetRequest);
1977 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
1978 const int kSOCKS5GreetResponseLength = arraysize(kSOCKS5GreetResponse);
1980 const char kSOCKS5OkRequest[] =
1981 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1982 const int kSOCKS5OkRequestLength = arraysize(kSOCKS5OkRequest);
1984 const char kSOCKS5OkResponse[] =
1985 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1986 const int kSOCKS5OkResponseLength = arraysize(kSOCKS5OkResponse);
1988 } // namespace net