Refactors gesture conversion functions to ui/events/blink
[chromium-blink-merge.git] / net / socket / socket_test_util.cc
blob4de30ddde09d505c4e70daabe23a911dbf788be0
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/socket/socket_test_util.h"
7 #include <algorithm>
8 #include <vector>
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/compiler_specific.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/run_loop.h"
16 #include "base/time/time.h"
17 #include "net/base/address_family.h"
18 #include "net/base/address_list.h"
19 #include "net/base/auth.h"
20 #include "net/base/load_timing_info.h"
21 #include "net/http/http_network_session.h"
22 #include "net/http/http_request_headers.h"
23 #include "net/http/http_response_headers.h"
24 #include "net/socket/socket.h"
25 #include "net/socket/websocket_endpoint_lock_manager.h"
26 #include "net/ssl/ssl_cert_request_info.h"
27 #include "net/ssl/ssl_connection_status_flags.h"
28 #include "net/ssl/ssl_info.h"
29 #include "testing/gtest/include/gtest/gtest.h"
31 // 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(static_cast<uint16>(rand_int_cb.Run(1025, 65535)));
683 return socket.Pass();
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.Pass();
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 SSLSocketDataProvider* next_ssl_data = mock_ssl_data_.GetNext();
703 if (!next_ssl_data->next_protos_expected_in_ssl_config.empty()) {
704 EXPECT_EQ(next_ssl_data->next_protos_expected_in_ssl_config.size(),
705 ssl_config.next_protos.size());
706 EXPECT_TRUE(
707 std::equal(next_ssl_data->next_protos_expected_in_ssl_config.begin(),
708 next_ssl_data->next_protos_expected_in_ssl_config.end(),
709 ssl_config.next_protos.begin()));
711 return scoped_ptr<SSLClientSocket>(new MockSSLClientSocket(
712 transport_socket.Pass(), host_and_port, ssl_config, next_ssl_data));
715 void MockClientSocketFactory::ClearSSLSessionCache() {
718 const char MockClientSocket::kTlsUnique[] = "MOCK_TLSUNIQ";
720 MockClientSocket::MockClientSocket(const BoundNetLog& net_log)
721 : connected_(false),
722 net_log_(net_log),
723 weak_factory_(this) {
724 IPAddressNumber ip;
725 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
726 peer_addr_ = IPEndPoint(ip, 0);
729 int MockClientSocket::SetReceiveBufferSize(int32 size) {
730 return OK;
733 int MockClientSocket::SetSendBufferSize(int32 size) {
734 return OK;
737 void MockClientSocket::Disconnect() {
738 connected_ = false;
741 bool MockClientSocket::IsConnected() const {
742 return connected_;
745 bool MockClientSocket::IsConnectedAndIdle() const {
746 return connected_;
749 int MockClientSocket::GetPeerAddress(IPEndPoint* address) const {
750 if (!IsConnected())
751 return ERR_SOCKET_NOT_CONNECTED;
752 *address = peer_addr_;
753 return OK;
756 int MockClientSocket::GetLocalAddress(IPEndPoint* address) const {
757 IPAddressNumber ip;
758 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
759 CHECK(rv);
760 *address = IPEndPoint(ip, 123);
761 return OK;
764 const BoundNetLog& MockClientSocket::NetLog() const {
765 return net_log_;
768 void MockClientSocket::GetSSLCertRequestInfo(
769 SSLCertRequestInfo* cert_request_info) {
772 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece& label,
773 bool has_context,
774 const base::StringPiece& context,
775 unsigned char* out,
776 unsigned int outlen) {
777 memset(out, 'A', outlen);
778 return OK;
781 int MockClientSocket::GetTLSUniqueChannelBinding(std::string* out) {
782 out->assign(MockClientSocket::kTlsUnique);
783 return OK;
786 ChannelIDService* MockClientSocket::GetChannelIDService() const {
787 NOTREACHED();
788 return NULL;
791 SSLClientSocket::NextProtoStatus
792 MockClientSocket::GetNextProto(std::string* proto) {
793 proto->clear();
794 return SSLClientSocket::kNextProtoUnsupported;
797 scoped_refptr<X509Certificate>
798 MockClientSocket::GetUnverifiedServerCertificateChain() const {
799 NOTREACHED();
800 return NULL;
803 MockClientSocket::~MockClientSocket() {}
805 void MockClientSocket::RunCallbackAsync(const CompletionCallback& callback,
806 int result) {
807 base::MessageLoop::current()->PostTask(
808 FROM_HERE,
809 base::Bind(&MockClientSocket::RunCallback,
810 weak_factory_.GetWeakPtr(),
811 callback,
812 result));
815 void MockClientSocket::RunCallback(const net::CompletionCallback& callback,
816 int result) {
817 if (!callback.is_null())
818 callback.Run(result);
821 MockTCPClientSocket::MockTCPClientSocket(const AddressList& addresses,
822 net::NetLog* net_log,
823 SocketDataProvider* data)
824 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
825 addresses_(addresses),
826 data_(data),
827 read_offset_(0),
828 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
829 need_read_data_(true),
830 peer_closed_connection_(false),
831 pending_buf_(NULL),
832 pending_buf_len_(0),
833 was_used_to_convey_data_(false) {
834 DCHECK(data_);
835 peer_addr_ = data->connect_data().peer_addr;
836 data_->Reset();
839 MockTCPClientSocket::~MockTCPClientSocket() {}
841 int MockTCPClientSocket::Read(IOBuffer* buf, int buf_len,
842 const CompletionCallback& callback) {
843 if (!connected_)
844 return ERR_UNEXPECTED;
846 // If the buffer is already in use, a read is already in progress!
847 DCHECK(pending_buf_.get() == NULL);
849 // Store our async IO data.
850 pending_buf_ = buf;
851 pending_buf_len_ = buf_len;
852 pending_callback_ = callback;
854 if (need_read_data_) {
855 read_data_ = data_->GetNextRead();
856 if (read_data_.result == ERR_CONNECTION_CLOSED) {
857 // This MockRead is just a marker to instruct us to set
858 // peer_closed_connection_.
859 peer_closed_connection_ = true;
861 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
862 // This MockRead is just a marker to instruct us to set
863 // peer_closed_connection_. Skip it and get the next one.
864 read_data_ = data_->GetNextRead();
865 peer_closed_connection_ = true;
867 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
868 // to complete the async IO manually later (via OnReadComplete).
869 if (read_data_.result == ERR_IO_PENDING) {
870 // We need to be using async IO in this case.
871 DCHECK(!callback.is_null());
872 return ERR_IO_PENDING;
874 need_read_data_ = false;
877 return CompleteRead();
880 int MockTCPClientSocket::Write(IOBuffer* buf, int buf_len,
881 const CompletionCallback& callback) {
882 DCHECK(buf);
883 DCHECK_GT(buf_len, 0);
885 if (!connected_)
886 return ERR_UNEXPECTED;
888 std::string data(buf->data(), buf_len);
889 MockWriteResult write_result = data_->OnWrite(data);
891 was_used_to_convey_data_ = true;
893 if (write_result.mode == ASYNC) {
894 RunCallbackAsync(callback, write_result.result);
895 return ERR_IO_PENDING;
898 return write_result.result;
901 int MockTCPClientSocket::Connect(const CompletionCallback& callback) {
902 if (connected_)
903 return OK;
904 connected_ = true;
905 peer_closed_connection_ = false;
906 if (data_->connect_data().mode == ASYNC) {
907 if (data_->connect_data().result == ERR_IO_PENDING)
908 pending_callback_ = callback;
909 else
910 RunCallbackAsync(callback, data_->connect_data().result);
911 return ERR_IO_PENDING;
913 return data_->connect_data().result;
916 void MockTCPClientSocket::Disconnect() {
917 MockClientSocket::Disconnect();
918 pending_callback_.Reset();
921 bool MockTCPClientSocket::IsConnected() const {
922 return connected_ && !peer_closed_connection_;
925 bool MockTCPClientSocket::IsConnectedAndIdle() const {
926 return IsConnected();
929 int MockTCPClientSocket::GetPeerAddress(IPEndPoint* address) const {
930 if (addresses_.empty())
931 return MockClientSocket::GetPeerAddress(address);
933 *address = addresses_[0];
934 return OK;
937 bool MockTCPClientSocket::WasEverUsed() const {
938 return was_used_to_convey_data_;
941 bool MockTCPClientSocket::UsingTCPFastOpen() const {
942 return false;
945 bool MockTCPClientSocket::WasNpnNegotiated() const {
946 return false;
949 bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
950 return false;
953 void MockTCPClientSocket::OnReadComplete(const MockRead& data) {
954 // There must be a read pending.
955 DCHECK(pending_buf_.get());
956 // You can't complete a read with another ERR_IO_PENDING status code.
957 DCHECK_NE(ERR_IO_PENDING, data.result);
958 // Since we've been waiting for data, need_read_data_ should be true.
959 DCHECK(need_read_data_);
961 read_data_ = data;
962 need_read_data_ = false;
964 // The caller is simulating that this IO completes right now. Don't
965 // let CompleteRead() schedule a callback.
966 read_data_.mode = SYNCHRONOUS;
968 CompletionCallback callback = pending_callback_;
969 int rv = CompleteRead();
970 RunCallback(callback, rv);
973 void MockTCPClientSocket::OnConnectComplete(const MockConnect& data) {
974 CompletionCallback callback = pending_callback_;
975 RunCallback(callback, data.result);
978 int MockTCPClientSocket::CompleteRead() {
979 DCHECK(pending_buf_.get());
980 DCHECK(pending_buf_len_ > 0);
982 was_used_to_convey_data_ = true;
984 // Save the pending async IO data and reset our |pending_| state.
985 scoped_refptr<IOBuffer> buf = pending_buf_;
986 int buf_len = pending_buf_len_;
987 CompletionCallback callback = pending_callback_;
988 pending_buf_ = NULL;
989 pending_buf_len_ = 0;
990 pending_callback_.Reset();
992 int result = read_data_.result;
993 DCHECK(result != ERR_IO_PENDING);
995 if (read_data_.data) {
996 if (read_data_.data_len - read_offset_ > 0) {
997 result = std::min(buf_len, read_data_.data_len - read_offset_);
998 memcpy(buf->data(), read_data_.data + read_offset_, result);
999 read_offset_ += result;
1000 if (read_offset_ == read_data_.data_len) {
1001 need_read_data_ = true;
1002 read_offset_ = 0;
1004 } else {
1005 result = 0; // EOF
1009 if (read_data_.mode == ASYNC) {
1010 DCHECK(!callback.is_null());
1011 RunCallbackAsync(callback, result);
1012 return ERR_IO_PENDING;
1014 return result;
1017 DeterministicSocketHelper::DeterministicSocketHelper(
1018 net::NetLog* net_log,
1019 DeterministicSocketData* data)
1020 : write_pending_(false),
1021 write_result_(0),
1022 read_data_(),
1023 read_buf_(NULL),
1024 read_buf_len_(0),
1025 read_pending_(false),
1026 data_(data),
1027 was_used_to_convey_data_(false),
1028 peer_closed_connection_(false),
1029 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)) {
1032 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1034 void DeterministicSocketHelper::CompleteWrite() {
1035 was_used_to_convey_data_ = true;
1036 write_pending_ = false;
1037 write_callback_.Run(write_result_);
1040 int DeterministicSocketHelper::CompleteRead() {
1041 DCHECK_GT(read_buf_len_, 0);
1042 DCHECK_LE(read_data_.data_len, read_buf_len_);
1043 DCHECK(read_buf_);
1045 was_used_to_convey_data_ = true;
1047 if (read_data_.result == ERR_IO_PENDING)
1048 read_data_ = data_->GetNextRead();
1049 DCHECK_NE(ERR_IO_PENDING, read_data_.result);
1050 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1051 // the callback. Therefore we don't even bother to check it.
1052 int result = read_data_.result;
1054 if (read_data_.data_len > 0) {
1055 DCHECK(read_data_.data);
1056 result = std::min(read_buf_len_, read_data_.data_len);
1057 memcpy(read_buf_->data(), read_data_.data, result);
1060 if (read_pending_) {
1061 read_pending_ = false;
1062 read_callback_.Run(result);
1065 return result;
1068 int DeterministicSocketHelper::Write(
1069 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1070 DCHECK(buf);
1071 DCHECK_GT(buf_len, 0);
1073 std::string data(buf->data(), buf_len);
1074 MockWriteResult write_result = data_->OnWrite(data);
1076 if (write_result.mode == ASYNC) {
1077 write_callback_ = callback;
1078 write_result_ = write_result.result;
1079 DCHECK(!write_callback_.is_null());
1080 write_pending_ = true;
1081 return ERR_IO_PENDING;
1084 was_used_to_convey_data_ = true;
1085 write_pending_ = false;
1086 return write_result.result;
1089 int DeterministicSocketHelper::Read(
1090 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1092 read_data_ = data_->GetNextRead();
1093 // The buffer should always be big enough to contain all the MockRead data. To
1094 // use small buffers, split the data into multiple MockReads.
1095 DCHECK_LE(read_data_.data_len, buf_len);
1097 if (read_data_.result == ERR_CONNECTION_CLOSED) {
1098 // This MockRead is just a marker to instruct us to set
1099 // peer_closed_connection_.
1100 peer_closed_connection_ = true;
1102 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
1103 // This MockRead is just a marker to instruct us to set
1104 // peer_closed_connection_. Skip it and get the next one.
1105 read_data_ = data_->GetNextRead();
1106 peer_closed_connection_ = true;
1109 read_buf_ = buf;
1110 read_buf_len_ = buf_len;
1111 read_callback_ = callback;
1113 if (read_data_.mode == ASYNC || (read_data_.result == ERR_IO_PENDING)) {
1114 read_pending_ = true;
1115 DCHECK(!read_callback_.is_null());
1116 return ERR_IO_PENDING;
1119 was_used_to_convey_data_ = true;
1120 return CompleteRead();
1123 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1124 net::NetLog* net_log,
1125 DeterministicSocketData* data)
1126 : connected_(false),
1127 helper_(net_log, data),
1128 source_port_(123) {
1131 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1133 bool DeterministicMockUDPClientSocket::WritePending() const {
1134 return helper_.write_pending();
1137 bool DeterministicMockUDPClientSocket::ReadPending() const {
1138 return helper_.read_pending();
1141 void DeterministicMockUDPClientSocket::CompleteWrite() {
1142 helper_.CompleteWrite();
1145 int DeterministicMockUDPClientSocket::CompleteRead() {
1146 return helper_.CompleteRead();
1149 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint& address) {
1150 if (connected_)
1151 return OK;
1152 connected_ = true;
1153 peer_address_ = address;
1154 return helper_.data()->connect_data().result;
1157 int DeterministicMockUDPClientSocket::Write(
1158 IOBuffer* buf,
1159 int buf_len,
1160 const CompletionCallback& callback) {
1161 if (!connected_)
1162 return ERR_UNEXPECTED;
1164 return helper_.Write(buf, buf_len, callback);
1167 int DeterministicMockUDPClientSocket::Read(
1168 IOBuffer* buf,
1169 int buf_len,
1170 const CompletionCallback& callback) {
1171 if (!connected_)
1172 return ERR_UNEXPECTED;
1174 return helper_.Read(buf, buf_len, callback);
1177 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1178 return OK;
1181 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size) {
1182 return OK;
1185 void DeterministicMockUDPClientSocket::Close() {
1186 connected_ = false;
1189 int DeterministicMockUDPClientSocket::GetPeerAddress(
1190 IPEndPoint* address) const {
1191 *address = peer_address_;
1192 return OK;
1195 int DeterministicMockUDPClientSocket::GetLocalAddress(
1196 IPEndPoint* address) const {
1197 IPAddressNumber ip;
1198 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1199 CHECK(rv);
1200 *address = IPEndPoint(ip, source_port_);
1201 return OK;
1204 const BoundNetLog& DeterministicMockUDPClientSocket::NetLog() const {
1205 return helper_.net_log();
1208 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead& data) {}
1210 void DeterministicMockUDPClientSocket::OnConnectComplete(
1211 const MockConnect& data) {
1212 NOTIMPLEMENTED();
1215 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1216 net::NetLog* net_log,
1217 DeterministicSocketData* data)
1218 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1219 helper_(net_log, data) {
1220 peer_addr_ = data->connect_data().peer_addr;
1223 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1225 bool DeterministicMockTCPClientSocket::WritePending() const {
1226 return helper_.write_pending();
1229 bool DeterministicMockTCPClientSocket::ReadPending() const {
1230 return helper_.read_pending();
1233 void DeterministicMockTCPClientSocket::CompleteWrite() {
1234 helper_.CompleteWrite();
1237 int DeterministicMockTCPClientSocket::CompleteRead() {
1238 return helper_.CompleteRead();
1241 int DeterministicMockTCPClientSocket::Write(
1242 IOBuffer* buf,
1243 int buf_len,
1244 const CompletionCallback& callback) {
1245 if (!connected_)
1246 return ERR_UNEXPECTED;
1248 return helper_.Write(buf, buf_len, callback);
1251 int DeterministicMockTCPClientSocket::Read(
1252 IOBuffer* buf,
1253 int buf_len,
1254 const CompletionCallback& callback) {
1255 if (!connected_)
1256 return ERR_UNEXPECTED;
1258 return helper_.Read(buf, buf_len, callback);
1261 // TODO(erikchen): Support connect sequencing.
1262 int DeterministicMockTCPClientSocket::Connect(
1263 const CompletionCallback& callback) {
1264 if (connected_)
1265 return OK;
1266 connected_ = true;
1267 if (helper_.data()->connect_data().mode == ASYNC) {
1268 RunCallbackAsync(callback, helper_.data()->connect_data().result);
1269 return ERR_IO_PENDING;
1271 return helper_.data()->connect_data().result;
1274 void DeterministicMockTCPClientSocket::Disconnect() {
1275 MockClientSocket::Disconnect();
1278 bool DeterministicMockTCPClientSocket::IsConnected() const {
1279 return connected_ && !helper_.peer_closed_connection();
1282 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1283 return IsConnected();
1286 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1287 return helper_.was_used_to_convey_data();
1290 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1291 return false;
1294 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1295 return false;
1298 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1299 return false;
1302 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead& data) {}
1304 void DeterministicMockTCPClientSocket::OnConnectComplete(
1305 const MockConnect& data) {}
1307 // static
1308 void MockSSLClientSocket::ConnectCallback(
1309 MockSSLClientSocket* ssl_client_socket,
1310 const CompletionCallback& callback,
1311 int rv) {
1312 if (rv == OK)
1313 ssl_client_socket->connected_ = true;
1314 callback.Run(rv);
1317 MockSSLClientSocket::MockSSLClientSocket(
1318 scoped_ptr<ClientSocketHandle> transport_socket,
1319 const HostPortPair& host_port_pair,
1320 const SSLConfig& ssl_config,
1321 SSLSocketDataProvider* data)
1322 : MockClientSocket(
1323 // Have to use the right BoundNetLog for LoadTimingInfo regression
1324 // tests.
1325 transport_socket->socket()->NetLog()),
1326 transport_(transport_socket.Pass()),
1327 data_(data),
1328 is_npn_state_set_(false),
1329 new_npn_value_(false),
1330 is_protocol_negotiated_set_(false),
1331 protocol_negotiated_(kProtoUnknown) {
1332 DCHECK(data_);
1333 peer_addr_ = data->connect.peer_addr;
1336 MockSSLClientSocket::~MockSSLClientSocket() {
1337 Disconnect();
1340 int MockSSLClientSocket::Read(IOBuffer* buf, int buf_len,
1341 const CompletionCallback& callback) {
1342 return transport_->socket()->Read(buf, buf_len, callback);
1345 int MockSSLClientSocket::Write(IOBuffer* buf, int buf_len,
1346 const CompletionCallback& callback) {
1347 return transport_->socket()->Write(buf, buf_len, callback);
1350 int MockSSLClientSocket::Connect(const CompletionCallback& callback) {
1351 int rv = transport_->socket()->Connect(
1352 base::Bind(&ConnectCallback, base::Unretained(this), callback));
1353 if (rv == OK) {
1354 if (data_->connect.result == OK)
1355 connected_ = true;
1356 if (data_->connect.mode == ASYNC) {
1357 RunCallbackAsync(callback, data_->connect.result);
1358 return ERR_IO_PENDING;
1360 return data_->connect.result;
1362 return rv;
1365 void MockSSLClientSocket::Disconnect() {
1366 MockClientSocket::Disconnect();
1367 if (transport_->socket() != NULL)
1368 transport_->socket()->Disconnect();
1371 bool MockSSLClientSocket::IsConnected() const {
1372 return transport_->socket()->IsConnected();
1375 bool MockSSLClientSocket::WasEverUsed() const {
1376 return transport_->socket()->WasEverUsed();
1379 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1380 return transport_->socket()->UsingTCPFastOpen();
1383 int MockSSLClientSocket::GetPeerAddress(IPEndPoint* address) const {
1384 return transport_->socket()->GetPeerAddress(address);
1387 bool MockSSLClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1388 ssl_info->Reset();
1389 ssl_info->cert = data_->cert;
1390 ssl_info->client_cert_sent = data_->client_cert_sent;
1391 ssl_info->channel_id_sent = data_->channel_id_sent;
1392 ssl_info->connection_status = data_->connection_status;
1393 return true;
1396 void MockSSLClientSocket::GetSSLCertRequestInfo(
1397 SSLCertRequestInfo* cert_request_info) {
1398 DCHECK(cert_request_info);
1399 if (data_->cert_request_info) {
1400 cert_request_info->host_and_port =
1401 data_->cert_request_info->host_and_port;
1402 cert_request_info->client_certs = data_->cert_request_info->client_certs;
1403 } else {
1404 cert_request_info->Reset();
1408 SSLClientSocket::NextProtoStatus MockSSLClientSocket::GetNextProto(
1409 std::string* proto) {
1410 *proto = data_->next_proto;
1411 return data_->next_proto_status;
1414 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated) {
1415 is_npn_state_set_ = true;
1416 return new_npn_value_ = negotiated;
1419 bool MockSSLClientSocket::WasNpnNegotiated() const {
1420 if (is_npn_state_set_)
1421 return new_npn_value_;
1422 return data_->was_npn_negotiated;
1425 NextProto MockSSLClientSocket::GetNegotiatedProtocol() const {
1426 if (is_protocol_negotiated_set_)
1427 return protocol_negotiated_;
1428 return data_->protocol_negotiated;
1431 void MockSSLClientSocket::set_protocol_negotiated(
1432 NextProto protocol_negotiated) {
1433 is_protocol_negotiated_set_ = true;
1434 protocol_negotiated_ = protocol_negotiated;
1437 bool MockSSLClientSocket::WasChannelIDSent() const {
1438 return data_->channel_id_sent;
1441 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent) {
1442 data_->channel_id_sent = channel_id_sent;
1445 ChannelIDService* MockSSLClientSocket::GetChannelIDService() const {
1446 return data_->channel_id_service;
1449 void MockSSLClientSocket::OnReadComplete(const MockRead& data) {
1450 NOTIMPLEMENTED();
1453 void MockSSLClientSocket::OnConnectComplete(const MockConnect& data) {
1454 NOTIMPLEMENTED();
1457 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data,
1458 net::NetLog* net_log)
1459 : connected_(false),
1460 data_(data),
1461 read_offset_(0),
1462 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
1463 need_read_data_(true),
1464 source_port_(123),
1465 pending_buf_(NULL),
1466 pending_buf_len_(0),
1467 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1468 weak_factory_(this) {
1469 DCHECK(data_);
1470 data_->Reset();
1471 peer_addr_ = data->connect_data().peer_addr;
1474 MockUDPClientSocket::~MockUDPClientSocket() {}
1476 int MockUDPClientSocket::Read(IOBuffer* buf,
1477 int buf_len,
1478 const CompletionCallback& callback) {
1479 if (!connected_)
1480 return ERR_UNEXPECTED;
1482 // If the buffer is already in use, a read is already in progress!
1483 DCHECK(pending_buf_.get() == NULL);
1485 // Store our async IO data.
1486 pending_buf_ = buf;
1487 pending_buf_len_ = buf_len;
1488 pending_callback_ = callback;
1490 if (need_read_data_) {
1491 read_data_ = data_->GetNextRead();
1492 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1493 // to complete the async IO manually later (via OnReadComplete).
1494 if (read_data_.result == ERR_IO_PENDING) {
1495 // We need to be using async IO in this case.
1496 DCHECK(!callback.is_null());
1497 return ERR_IO_PENDING;
1499 need_read_data_ = false;
1502 return CompleteRead();
1505 int MockUDPClientSocket::Write(IOBuffer* buf, int buf_len,
1506 const CompletionCallback& callback) {
1507 DCHECK(buf);
1508 DCHECK_GT(buf_len, 0);
1510 if (!connected_)
1511 return ERR_UNEXPECTED;
1513 std::string data(buf->data(), buf_len);
1514 MockWriteResult write_result = data_->OnWrite(data);
1516 if (write_result.mode == ASYNC) {
1517 RunCallbackAsync(callback, write_result.result);
1518 return ERR_IO_PENDING;
1520 return write_result.result;
1523 int MockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1524 return OK;
1527 int MockUDPClientSocket::SetSendBufferSize(int32 size) {
1528 return OK;
1531 void MockUDPClientSocket::Close() {
1532 connected_ = false;
1535 int MockUDPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1536 *address = peer_addr_;
1537 return OK;
1540 int MockUDPClientSocket::GetLocalAddress(IPEndPoint* address) const {
1541 IPAddressNumber ip;
1542 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1543 CHECK(rv);
1544 *address = IPEndPoint(ip, source_port_);
1545 return OK;
1548 const BoundNetLog& MockUDPClientSocket::NetLog() const {
1549 return net_log_;
1552 int MockUDPClientSocket::Connect(const IPEndPoint& address) {
1553 connected_ = true;
1554 peer_addr_ = address;
1555 return data_->connect_data().result;
1558 void MockUDPClientSocket::OnReadComplete(const MockRead& data) {
1559 // There must be a read pending.
1560 DCHECK(pending_buf_.get());
1561 // You can't complete a read with another ERR_IO_PENDING status code.
1562 DCHECK_NE(ERR_IO_PENDING, data.result);
1563 // Since we've been waiting for data, need_read_data_ should be true.
1564 DCHECK(need_read_data_);
1566 read_data_ = data;
1567 need_read_data_ = false;
1569 // The caller is simulating that this IO completes right now. Don't
1570 // let CompleteRead() schedule a callback.
1571 read_data_.mode = SYNCHRONOUS;
1573 net::CompletionCallback callback = pending_callback_;
1574 int rv = CompleteRead();
1575 RunCallback(callback, rv);
1578 void MockUDPClientSocket::OnConnectComplete(const MockConnect& data) {
1579 NOTIMPLEMENTED();
1582 int MockUDPClientSocket::CompleteRead() {
1583 DCHECK(pending_buf_.get());
1584 DCHECK(pending_buf_len_ > 0);
1586 // Save the pending async IO data and reset our |pending_| state.
1587 scoped_refptr<IOBuffer> buf = pending_buf_;
1588 int buf_len = pending_buf_len_;
1589 CompletionCallback callback = pending_callback_;
1590 pending_buf_ = NULL;
1591 pending_buf_len_ = 0;
1592 pending_callback_.Reset();
1594 int result = read_data_.result;
1595 DCHECK(result != ERR_IO_PENDING);
1597 if (read_data_.data) {
1598 if (read_data_.data_len - read_offset_ > 0) {
1599 result = std::min(buf_len, read_data_.data_len - read_offset_);
1600 memcpy(buf->data(), read_data_.data + read_offset_, result);
1601 read_offset_ += result;
1602 if (read_offset_ == read_data_.data_len) {
1603 need_read_data_ = true;
1604 read_offset_ = 0;
1606 } else {
1607 result = 0; // EOF
1611 if (read_data_.mode == ASYNC) {
1612 DCHECK(!callback.is_null());
1613 RunCallbackAsync(callback, result);
1614 return ERR_IO_PENDING;
1616 return result;
1619 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback& callback,
1620 int result) {
1621 base::MessageLoop::current()->PostTask(
1622 FROM_HERE,
1623 base::Bind(&MockUDPClientSocket::RunCallback,
1624 weak_factory_.GetWeakPtr(),
1625 callback,
1626 result));
1629 void MockUDPClientSocket::RunCallback(const CompletionCallback& callback,
1630 int result) {
1631 if (!callback.is_null())
1632 callback.Run(result);
1635 TestSocketRequest::TestSocketRequest(
1636 std::vector<TestSocketRequest*>* request_order, size_t* completion_count)
1637 : request_order_(request_order),
1638 completion_count_(completion_count),
1639 callback_(base::Bind(&TestSocketRequest::OnComplete,
1640 base::Unretained(this))) {
1641 DCHECK(request_order);
1642 DCHECK(completion_count);
1645 TestSocketRequest::~TestSocketRequest() {
1648 void TestSocketRequest::OnComplete(int result) {
1649 SetResult(result);
1650 (*completion_count_)++;
1651 request_order_->push_back(this);
1654 // static
1655 const int ClientSocketPoolTest::kIndexOutOfBounds = -1;
1657 // static
1658 const int ClientSocketPoolTest::kRequestNotFound = -2;
1660 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1661 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1663 int ClientSocketPoolTest::GetOrderOfRequest(size_t index) const {
1664 index--;
1665 if (index >= requests_.size())
1666 return kIndexOutOfBounds;
1668 for (size_t i = 0; i < request_order_.size(); i++)
1669 if (requests_[index] == request_order_[i])
1670 return i + 1;
1672 return kRequestNotFound;
1675 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
1676 ScopedVector<TestSocketRequest>::iterator i;
1677 for (i = requests_.begin(); i != requests_.end(); ++i) {
1678 if ((*i)->handle()->is_initialized()) {
1679 if (keep_alive == NO_KEEP_ALIVE)
1680 (*i)->handle()->socket()->Disconnect();
1681 (*i)->handle()->Reset();
1682 base::RunLoop().RunUntilIdle();
1683 return true;
1686 return false;
1689 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
1690 bool released_one;
1691 do {
1692 released_one = ReleaseOneConnection(keep_alive);
1693 } while (released_one);
1696 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1697 scoped_ptr<StreamSocket> socket,
1698 ClientSocketHandle* handle,
1699 const CompletionCallback& callback)
1700 : socket_(socket.Pass()),
1701 handle_(handle),
1702 user_callback_(callback) {
1705 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1707 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1708 int rv = socket_->Connect(base::Bind(&MockConnectJob::OnConnect,
1709 base::Unretained(this)));
1710 if (rv == OK) {
1711 user_callback_.Reset();
1712 OnConnect(OK);
1714 return rv;
1717 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1718 const ClientSocketHandle* handle) {
1719 if (handle != handle_)
1720 return false;
1721 socket_.reset();
1722 handle_ = NULL;
1723 user_callback_.Reset();
1724 return true;
1727 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) {
1728 if (!socket_.get())
1729 return;
1730 if (rv == OK) {
1731 handle_->SetSocket(socket_.Pass());
1733 // Needed for socket pool tests that layer other sockets on top of mock
1734 // sockets.
1735 LoadTimingInfo::ConnectTiming connect_timing;
1736 base::TimeTicks now = base::TimeTicks::Now();
1737 connect_timing.dns_start = now;
1738 connect_timing.dns_end = now;
1739 connect_timing.connect_start = now;
1740 connect_timing.connect_end = now;
1741 handle_->set_connect_timing(connect_timing);
1742 } else {
1743 socket_.reset();
1746 handle_ = NULL;
1748 if (!user_callback_.is_null()) {
1749 CompletionCallback callback = user_callback_;
1750 user_callback_.Reset();
1751 callback.Run(rv);
1755 MockTransportClientSocketPool::MockTransportClientSocketPool(
1756 int max_sockets,
1757 int max_sockets_per_group,
1758 ClientSocketFactory* socket_factory)
1759 : TransportClientSocketPool(max_sockets,
1760 max_sockets_per_group,
1761 NULL,
1762 NULL,
1763 NULL),
1764 client_socket_factory_(socket_factory),
1765 last_request_priority_(DEFAULT_PRIORITY),
1766 release_count_(0),
1767 cancel_count_(0) {
1770 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1772 int MockTransportClientSocketPool::RequestSocket(
1773 const std::string& group_name, const void* socket_params,
1774 RequestPriority priority, ClientSocketHandle* handle,
1775 const CompletionCallback& callback, const BoundNetLog& net_log) {
1776 last_request_priority_ = priority;
1777 scoped_ptr<StreamSocket> socket =
1778 client_socket_factory_->CreateTransportClientSocket(
1779 AddressList(), net_log.net_log(), net::NetLog::Source());
1780 MockConnectJob* job = new MockConnectJob(socket.Pass(), handle, callback);
1781 job_list_.push_back(job);
1782 handle->set_pool_id(1);
1783 return job->Connect();
1786 void MockTransportClientSocketPool::CancelRequest(const std::string& group_name,
1787 ClientSocketHandle* handle) {
1788 std::vector<MockConnectJob*>::iterator i;
1789 for (i = job_list_.begin(); i != job_list_.end(); ++i) {
1790 if ((*i)->CancelHandle(handle)) {
1791 cancel_count_++;
1792 break;
1797 void MockTransportClientSocketPool::ReleaseSocket(
1798 const std::string& group_name,
1799 scoped_ptr<StreamSocket> socket,
1800 int id) {
1801 EXPECT_EQ(1, id);
1802 release_count_++;
1805 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1807 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1809 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1810 DeterministicSocketData* data) {
1811 mock_data_.Add(data);
1814 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1815 SSLSocketDataProvider* data) {
1816 mock_ssl_data_.Add(data);
1819 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1820 mock_data_.ResetNextIndex();
1821 mock_ssl_data_.ResetNextIndex();
1824 MockSSLClientSocket* DeterministicMockClientSocketFactory::
1825 GetMockSSLClientSocket(size_t index) const {
1826 DCHECK_LT(index, ssl_client_sockets_.size());
1827 return ssl_client_sockets_[index];
1830 scoped_ptr<DatagramClientSocket>
1831 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1832 DatagramSocket::BindType bind_type,
1833 const RandIntCallback& rand_int_cb,
1834 net::NetLog* net_log,
1835 const NetLog::Source& source) {
1836 DeterministicSocketData* data_provider = mock_data().GetNext();
1837 scoped_ptr<DeterministicMockUDPClientSocket> socket(
1838 new DeterministicMockUDPClientSocket(net_log, data_provider));
1839 data_provider->set_delegate(socket->AsWeakPtr());
1840 udp_client_sockets().push_back(socket.get());
1841 if (bind_type == DatagramSocket::RANDOM_BIND)
1842 socket->set_source_port(static_cast<uint16>(rand_int_cb.Run(1025, 65535)));
1843 return socket.Pass();
1846 scoped_ptr<StreamSocket>
1847 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1848 const AddressList& addresses,
1849 net::NetLog* net_log,
1850 const net::NetLog::Source& source) {
1851 DeterministicSocketData* data_provider = mock_data().GetNext();
1852 scoped_ptr<DeterministicMockTCPClientSocket> socket(
1853 new DeterministicMockTCPClientSocket(net_log, data_provider));
1854 data_provider->set_delegate(socket->AsWeakPtr());
1855 tcp_client_sockets().push_back(socket.get());
1856 return socket.Pass();
1859 scoped_ptr<SSLClientSocket>
1860 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1861 scoped_ptr<ClientSocketHandle> transport_socket,
1862 const HostPortPair& host_and_port,
1863 const SSLConfig& ssl_config,
1864 const SSLClientSocketContext& context) {
1865 scoped_ptr<MockSSLClientSocket> socket(
1866 new MockSSLClientSocket(transport_socket.Pass(),
1867 host_and_port, ssl_config,
1868 mock_ssl_data_.GetNext()));
1869 ssl_client_sockets_.push_back(socket.get());
1870 return socket.Pass();
1873 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1876 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1877 int max_sockets,
1878 int max_sockets_per_group,
1879 TransportClientSocketPool* transport_pool)
1880 : SOCKSClientSocketPool(max_sockets,
1881 max_sockets_per_group,
1882 NULL,
1883 transport_pool,
1884 NULL),
1885 transport_pool_(transport_pool) {
1888 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1890 int MockSOCKSClientSocketPool::RequestSocket(
1891 const std::string& group_name, const void* socket_params,
1892 RequestPriority priority, ClientSocketHandle* handle,
1893 const CompletionCallback& callback, const BoundNetLog& net_log) {
1894 return transport_pool_->RequestSocket(
1895 group_name, socket_params, priority, handle, callback, net_log);
1898 void MockSOCKSClientSocketPool::CancelRequest(
1899 const std::string& group_name,
1900 ClientSocketHandle* handle) {
1901 return transport_pool_->CancelRequest(group_name, handle);
1904 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string& group_name,
1905 scoped_ptr<StreamSocket> socket,
1906 int id) {
1907 return transport_pool_->ReleaseSocket(group_name, socket.Pass(), id);
1910 ScopedWebSocketEndpointZeroUnlockDelay::
1911 ScopedWebSocketEndpointZeroUnlockDelay() {
1912 old_delay_ =
1913 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
1914 base::TimeDelta());
1917 ScopedWebSocketEndpointZeroUnlockDelay::
1918 ~ScopedWebSocketEndpointZeroUnlockDelay() {
1919 base::TimeDelta active_delay =
1920 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
1921 old_delay_);
1922 EXPECT_EQ(active_delay, base::TimeDelta());
1925 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
1926 const int kSOCKS5GreetRequestLength = arraysize(kSOCKS5GreetRequest);
1928 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
1929 const int kSOCKS5GreetResponseLength = arraysize(kSOCKS5GreetResponse);
1931 const char kSOCKS5OkRequest[] =
1932 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1933 const int kSOCKS5OkRequestLength = arraysize(kSOCKS5OkRequest);
1935 const char kSOCKS5OkResponse[] =
1936 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1937 const int kSOCKS5OkResponseLength = arraysize(kSOCKS5OkResponse);
1939 } // namespace net