Add signalSyncPoint to the WebGraphicsContext3D command buffer impls.
[chromium-blink-merge.git] / net / socket / socket_test_util.cc
blob9c4e02ddd63ef37b45c8c0f2b9d16209625f1678
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/socket/socket_test_util.h"
7 #include <algorithm>
8 #include <vector>
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/compiler_specific.h"
14 #include "base/message_loop.h"
15 #include "base/run_loop.h"
16 #include "base/time.h"
17 #include "net/base/address_family.h"
18 #include "net/base/address_list.h"
19 #include "net/base/auth.h"
20 #include "net/base/load_timing_info.h"
21 #include "net/http/http_network_session.h"
22 #include "net/http/http_request_headers.h"
23 #include "net/http/http_response_headers.h"
24 #include "net/socket/client_socket_pool_histograms.h"
25 #include "net/socket/socket.h"
26 #include "net/ssl/ssl_cert_request_info.h"
27 #include "net/ssl/ssl_info.h"
28 #include "testing/gtest/include/gtest/gtest.h"
30 // Socket events are easier to debug if you log individual reads and writes.
31 // Enable these if locally debugging, but they are too noisy for the waterfall.
32 #if 0
33 #define NET_TRACE(level, s) DLOG(level) << s << __FUNCTION__ << "() "
34 #else
35 #define NET_TRACE(level, s) EAT_STREAM_PARAMETERS
36 #endif
38 namespace net {
40 namespace {
42 inline char AsciifyHigh(char x) {
43 char nybble = static_cast<char>((x >> 4) & 0x0F);
44 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
47 inline char AsciifyLow(char x) {
48 char nybble = static_cast<char>((x >> 0) & 0x0F);
49 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
52 inline char Asciify(char x) {
53 if ((x < 0) || !isprint(x))
54 return '.';
55 return x;
58 void DumpData(const char* data, int data_len) {
59 if (logging::LOG_INFO < logging::GetMinLogLevel())
60 return;
61 DVLOG(1) << "Length: " << data_len;
62 const char* pfx = "Data: ";
63 if (!data || (data_len <= 0)) {
64 DVLOG(1) << pfx << "<None>";
65 } else {
66 int i;
67 for (i = 0; i <= (data_len - 4); i += 4) {
68 DVLOG(1) << pfx
69 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
70 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
71 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
72 << AsciifyHigh(data[i + 3]) << AsciifyLow(data[i + 3])
73 << " '"
74 << Asciify(data[i + 0])
75 << Asciify(data[i + 1])
76 << Asciify(data[i + 2])
77 << Asciify(data[i + 3])
78 << "'";
79 pfx = " ";
81 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
82 switch (data_len - i) {
83 case 3:
84 DVLOG(1) << pfx
85 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
86 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
87 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
88 << " '"
89 << Asciify(data[i + 0])
90 << Asciify(data[i + 1])
91 << Asciify(data[i + 2])
92 << " '";
93 break;
94 case 2:
95 DVLOG(1) << pfx
96 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
97 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
98 << " '"
99 << Asciify(data[i + 0])
100 << Asciify(data[i + 1])
101 << " '";
102 break;
103 case 1:
104 DVLOG(1) << pfx
105 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
106 << " '"
107 << Asciify(data[i + 0])
108 << " '";
109 break;
114 template <MockReadWriteType type>
115 void DumpMockReadWrite(const MockReadWrite<type>& r) {
116 if (logging::LOG_INFO < logging::GetMinLogLevel())
117 return;
118 DVLOG(1) << "Async: " << (r.mode == ASYNC)
119 << "\nResult: " << r.result;
120 DumpData(r.data, r.data_len);
121 const char* stop = (r.sequence_number & MockRead::STOPLOOP) ? " (STOP)" : "";
122 DVLOG(1) << "Stage: " << (r.sequence_number & ~MockRead::STOPLOOP) << stop
123 << "\nTime: " << r.time_stamp.ToInternalValue();
126 } // namespace
128 MockConnect::MockConnect() : mode(ASYNC), result(OK) {
129 IPAddressNumber ip;
130 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
131 peer_addr = IPEndPoint(ip, 0);
134 MockConnect::MockConnect(IoMode io_mode, int r) : mode(io_mode), result(r) {
135 IPAddressNumber ip;
136 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
137 peer_addr = IPEndPoint(ip, 0);
140 MockConnect::MockConnect(IoMode io_mode, int r, IPEndPoint addr) :
141 mode(io_mode),
142 result(r),
143 peer_addr(addr) {
146 MockConnect::~MockConnect() {}
148 StaticSocketDataProvider::StaticSocketDataProvider()
149 : reads_(NULL),
150 read_index_(0),
151 read_count_(0),
152 writes_(NULL),
153 write_index_(0),
154 write_count_(0) {
157 StaticSocketDataProvider::StaticSocketDataProvider(MockRead* reads,
158 size_t reads_count,
159 MockWrite* writes,
160 size_t writes_count)
161 : reads_(reads),
162 read_index_(0),
163 read_count_(reads_count),
164 writes_(writes),
165 write_index_(0),
166 write_count_(writes_count) {
169 StaticSocketDataProvider::~StaticSocketDataProvider() {}
171 const MockRead& StaticSocketDataProvider::PeekRead() const {
172 DCHECK(!at_read_eof());
173 return reads_[read_index_];
176 const MockWrite& StaticSocketDataProvider::PeekWrite() const {
177 DCHECK(!at_write_eof());
178 return writes_[write_index_];
181 const MockRead& StaticSocketDataProvider::PeekRead(size_t index) const {
182 DCHECK_LT(index, read_count_);
183 return reads_[index];
186 const MockWrite& StaticSocketDataProvider::PeekWrite(size_t index) const {
187 DCHECK_LT(index, write_count_);
188 return writes_[index];
191 MockRead StaticSocketDataProvider::GetNextRead() {
192 DCHECK(!at_read_eof());
193 reads_[read_index_].time_stamp = base::Time::Now();
194 return reads_[read_index_++];
197 MockWriteResult StaticSocketDataProvider::OnWrite(const std::string& data) {
198 if (!writes_) {
199 // Not using mock writes; succeed synchronously.
200 return MockWriteResult(SYNCHRONOUS, data.length());
202 DCHECK(!at_write_eof());
204 // Check that what we are writing matches the expectation.
205 // Then give the mocked return value.
206 MockWrite* w = &writes_[write_index_++];
207 w->time_stamp = base::Time::Now();
208 int result = w->result;
209 if (w->data) {
210 // Note - we can simulate a partial write here. If the expected data
211 // is a match, but shorter than the write actually written, that is legal.
212 // Example:
213 // Application writes "foobarbaz" (9 bytes)
214 // Expected write was "foo" (3 bytes)
215 // This is a success, and we return 3 to the application.
216 std::string expected_data(w->data, w->data_len);
217 EXPECT_GE(data.length(), expected_data.length());
218 std::string actual_data(data.substr(0, w->data_len));
219 EXPECT_EQ(expected_data, actual_data);
220 if (expected_data != actual_data)
221 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
222 if (result == OK)
223 result = w->data_len;
225 return MockWriteResult(w->mode, result);
228 void StaticSocketDataProvider::Reset() {
229 read_index_ = 0;
230 write_index_ = 0;
233 DynamicSocketDataProvider::DynamicSocketDataProvider()
234 : short_read_limit_(0),
235 allow_unconsumed_reads_(false) {
238 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
240 MockRead DynamicSocketDataProvider::GetNextRead() {
241 if (reads_.empty())
242 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
243 MockRead result = reads_.front();
244 if (short_read_limit_ == 0 || result.data_len <= short_read_limit_) {
245 reads_.pop_front();
246 } else {
247 result.data_len = short_read_limit_;
248 reads_.front().data += result.data_len;
249 reads_.front().data_len -= result.data_len;
251 return result;
254 void DynamicSocketDataProvider::Reset() {
255 reads_.clear();
258 void DynamicSocketDataProvider::SimulateRead(const char* data,
259 const size_t length) {
260 if (!allow_unconsumed_reads_) {
261 EXPECT_TRUE(reads_.empty()) << "Unconsumed read: " << reads_.front().data;
263 reads_.push_back(MockRead(ASYNC, data, length));
266 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode, int result)
267 : connect(mode, result),
268 next_proto_status(SSLClientSocket::kNextProtoUnsupported),
269 was_npn_negotiated(false),
270 protocol_negotiated(kProtoUnknown),
271 client_cert_sent(false),
272 cert_request_info(NULL),
273 channel_id_sent(false) {
276 SSLSocketDataProvider::~SSLSocketDataProvider() {
279 void SSLSocketDataProvider::SetNextProto(NextProto proto) {
280 was_npn_negotiated = true;
281 next_proto_status = SSLClientSocket::kNextProtoNegotiated;
282 protocol_negotiated = proto;
283 next_proto = SSLClientSocket::NextProtoToString(proto);
286 DelayedSocketData::DelayedSocketData(
287 int write_delay, MockRead* reads, size_t reads_count,
288 MockWrite* writes, size_t writes_count)
289 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
290 write_delay_(write_delay),
291 read_in_progress_(false),
292 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
293 DCHECK_GE(write_delay_, 0);
296 DelayedSocketData::DelayedSocketData(
297 const MockConnect& connect, int write_delay, MockRead* reads,
298 size_t reads_count, MockWrite* writes, size_t writes_count)
299 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
300 write_delay_(write_delay),
301 read_in_progress_(false),
302 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
303 DCHECK_GE(write_delay_, 0);
304 set_connect_data(connect);
307 DelayedSocketData::~DelayedSocketData() {
310 void DelayedSocketData::ForceNextRead() {
311 DCHECK(read_in_progress_);
312 write_delay_ = 0;
313 CompleteRead();
316 MockRead DelayedSocketData::GetNextRead() {
317 MockRead out = MockRead(ASYNC, ERR_IO_PENDING);
318 if (write_delay_ <= 0)
319 out = StaticSocketDataProvider::GetNextRead();
320 read_in_progress_ = (out.result == ERR_IO_PENDING);
321 return out;
324 MockWriteResult DelayedSocketData::OnWrite(const std::string& data) {
325 MockWriteResult rv = StaticSocketDataProvider::OnWrite(data);
326 // Now that our write has completed, we can allow reads to continue.
327 if (!--write_delay_ && read_in_progress_)
328 MessageLoop::current()->PostDelayedTask(
329 FROM_HERE,
330 base::Bind(&DelayedSocketData::CompleteRead,
331 weak_factory_.GetWeakPtr()),
332 base::TimeDelta::FromMilliseconds(100));
333 return rv;
336 void DelayedSocketData::Reset() {
337 set_socket(NULL);
338 read_in_progress_ = false;
339 weak_factory_.InvalidateWeakPtrs();
340 StaticSocketDataProvider::Reset();
343 void DelayedSocketData::CompleteRead() {
344 if (socket() && read_in_progress_)
345 socket()->OnReadComplete(GetNextRead());
348 OrderedSocketData::OrderedSocketData(
349 MockRead* reads, size_t reads_count, MockWrite* writes, size_t writes_count)
350 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
351 sequence_number_(0), loop_stop_stage_(0),
352 blocked_(false), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
355 OrderedSocketData::OrderedSocketData(
356 const MockConnect& connect,
357 MockRead* reads, size_t reads_count,
358 MockWrite* writes, size_t writes_count)
359 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
360 sequence_number_(0), loop_stop_stage_(0),
361 blocked_(false), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
362 set_connect_data(connect);
365 void OrderedSocketData::EndLoop() {
366 // If we've already stopped the loop, don't do it again until we've advanced
367 // to the next sequence_number.
368 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_ << ": EndLoop()";
369 if (loop_stop_stage_ > 0) {
370 const MockRead& next_read = StaticSocketDataProvider::PeekRead();
371 if ((next_read.sequence_number & ~MockRead::STOPLOOP) >
372 loop_stop_stage_) {
373 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
374 << ": Clearing stop index";
375 loop_stop_stage_ = 0;
376 } else {
377 return;
380 // Record the sequence_number at which we stopped the loop.
381 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
382 << ": Posting Quit at read " << read_index();
383 loop_stop_stage_ = sequence_number_;
386 MockRead OrderedSocketData::GetNextRead() {
387 weak_factory_.InvalidateWeakPtrs();
388 blocked_ = false;
389 const MockRead& next_read = StaticSocketDataProvider::PeekRead();
390 if (next_read.sequence_number & MockRead::STOPLOOP)
391 EndLoop();
392 if ((next_read.sequence_number & ~MockRead::STOPLOOP) <=
393 sequence_number_++) {
394 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_ - 1
395 << ": Read " << read_index();
396 DumpMockReadWrite(next_read);
397 blocked_ = (next_read.result == ERR_IO_PENDING);
398 return StaticSocketDataProvider::GetNextRead();
400 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_ - 1
401 << ": I/O Pending";
402 MockRead result = MockRead(ASYNC, ERR_IO_PENDING);
403 DumpMockReadWrite(result);
404 blocked_ = true;
405 return result;
408 MockWriteResult OrderedSocketData::OnWrite(const std::string& data) {
409 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
410 << ": Write " << write_index();
411 DumpMockReadWrite(PeekWrite());
412 ++sequence_number_;
413 if (blocked_) {
414 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
415 // should probably fix the weirdness. One example is in SpdyStream,
416 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
417 // SYN_REPLY causes OnResponseReceived() to get called before
418 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
419 MessageLoop::current()->PostDelayedTask(
420 FROM_HERE,
421 base::Bind(&OrderedSocketData::CompleteRead,
422 weak_factory_.GetWeakPtr()),
423 base::TimeDelta::FromMilliseconds(100));
425 return StaticSocketDataProvider::OnWrite(data);
428 void OrderedSocketData::Reset() {
429 NET_TRACE(INFO, " *** ") << "Stage "
430 << sequence_number_ << ": Reset()";
431 sequence_number_ = 0;
432 loop_stop_stage_ = 0;
433 set_socket(NULL);
434 weak_factory_.InvalidateWeakPtrs();
435 StaticSocketDataProvider::Reset();
438 void OrderedSocketData::CompleteRead() {
439 if (socket() && blocked_) {
440 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_;
441 socket()->OnReadComplete(GetNextRead());
445 OrderedSocketData::~OrderedSocketData() {}
447 DeterministicSocketData::DeterministicSocketData(MockRead* reads,
448 size_t reads_count, MockWrite* writes, size_t writes_count)
449 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
450 sequence_number_(0),
451 current_read_(),
452 current_write_(),
453 stopping_sequence_number_(0),
454 stopped_(false),
455 print_debug_(false),
456 is_running_(false) {
457 VerifyCorrectSequenceNumbers(reads, reads_count, writes, writes_count);
460 DeterministicSocketData::~DeterministicSocketData() {}
462 void DeterministicSocketData::Run() {
463 DCHECK(!is_running_);
464 is_running_ = true;
466 SetStopped(false);
467 int counter = 0;
468 // Continue to consume data until all data has run out, or the stopped_ flag
469 // has been set. Consuming data requires two separate operations -- running
470 // the tasks in the message loop, and explicitly invoking the read/write
471 // callbacks (simulating network I/O). We check our conditions between each,
472 // since they can change in either.
473 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
474 if (counter % 2 == 0)
475 base::RunLoop().RunUntilIdle();
476 if (counter % 2 == 1) {
477 InvokeCallbacks();
479 counter++;
481 // We're done consuming new data, but it is possible there are still some
482 // pending callbacks which we expect to complete before returning.
483 while (socket_ && (socket_->write_pending() || socket_->read_pending()) &&
484 !stopped()) {
485 InvokeCallbacks();
486 base::RunLoop().RunUntilIdle();
488 SetStopped(false);
489 is_running_ = false;
492 void DeterministicSocketData::RunFor(int steps) {
493 StopAfter(steps);
494 Run();
497 void DeterministicSocketData::SetStop(int seq) {
498 DCHECK_LT(sequence_number_, seq);
499 stopping_sequence_number_ = seq;
500 stopped_ = false;
503 void DeterministicSocketData::StopAfter(int seq) {
504 SetStop(sequence_number_ + seq);
507 MockRead DeterministicSocketData::GetNextRead() {
508 current_read_ = StaticSocketDataProvider::PeekRead();
510 // Synchronous read while stopped is an error
511 if (stopped() && current_read_.mode == SYNCHRONOUS) {
512 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
513 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
516 // Async read which will be called back in a future step.
517 if (sequence_number_ < current_read_.sequence_number) {
518 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
519 << ": I/O Pending";
520 MockRead result = MockRead(SYNCHRONOUS, ERR_IO_PENDING);
521 if (current_read_.mode == SYNCHRONOUS) {
522 LOG(ERROR) << "Unable to perform synchronous read: "
523 << current_read_.sequence_number
524 << " at stage: " << sequence_number_;
525 result = MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
527 if (print_debug_)
528 DumpMockReadWrite(result);
529 return result;
532 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
533 << ": Read " << read_index();
534 if (print_debug_)
535 DumpMockReadWrite(current_read_);
537 // Increment the sequence number if IO is complete
538 if (current_read_.mode == SYNCHRONOUS)
539 NextStep();
541 DCHECK_NE(ERR_IO_PENDING, current_read_.result);
542 StaticSocketDataProvider::GetNextRead();
544 return current_read_;
547 MockWriteResult DeterministicSocketData::OnWrite(const std::string& data) {
548 const MockWrite& next_write = StaticSocketDataProvider::PeekWrite();
549 current_write_ = next_write;
551 // Synchronous write while stopped is an error
552 if (stopped() && next_write.mode == SYNCHRONOUS) {
553 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
554 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
557 // Async write which will be called back in a future step.
558 if (sequence_number_ < next_write.sequence_number) {
559 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
560 << ": I/O Pending";
561 if (next_write.mode == SYNCHRONOUS) {
562 LOG(ERROR) << "Unable to perform synchronous write: "
563 << next_write.sequence_number << " at stage: " << sequence_number_;
564 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
566 } else {
567 NET_TRACE(INFO, " *** ") << "Stage " << sequence_number_
568 << ": Write " << write_index();
571 if (print_debug_)
572 DumpMockReadWrite(next_write);
574 // Move to the next step if I/O is synchronous, since the operation will
575 // complete when this method returns.
576 if (next_write.mode == SYNCHRONOUS)
577 NextStep();
579 // This is either a sync write for this step, or an async write.
580 return StaticSocketDataProvider::OnWrite(data);
583 void DeterministicSocketData::Reset() {
584 NET_TRACE(INFO, " *** ") << "Stage "
585 << sequence_number_ << ": Reset()";
586 sequence_number_ = 0;
587 StaticSocketDataProvider::Reset();
588 NOTREACHED();
591 void DeterministicSocketData::InvokeCallbacks() {
592 if (socket_ && socket_->write_pending() &&
593 (current_write().sequence_number == sequence_number())) {
594 NextStep();
595 socket_->CompleteWrite();
596 return;
598 if (socket_ && socket_->read_pending() &&
599 (current_read().sequence_number == sequence_number())) {
600 NextStep();
601 socket_->CompleteRead();
602 return;
606 void DeterministicSocketData::NextStep() {
607 // Invariant: Can never move *past* the stopping step.
608 DCHECK_LT(sequence_number_, stopping_sequence_number_);
609 sequence_number_++;
610 if (sequence_number_ == stopping_sequence_number_)
611 SetStopped(true);
614 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
615 MockRead* reads, size_t reads_count,
616 MockWrite* writes, size_t writes_count) {
617 size_t read = 0;
618 size_t write = 0;
619 int expected = 0;
620 while (read < reads_count || write < writes_count) {
621 // Check to see that we have a read or write at the expected
622 // state.
623 if (read < reads_count && reads[read].sequence_number == expected) {
624 ++read;
625 ++expected;
626 continue;
628 if (write < writes_count && writes[write].sequence_number == expected) {
629 ++write;
630 ++expected;
631 continue;
633 NOTREACHED() << "Missing sequence number: " << expected;
634 return;
636 DCHECK_EQ(read, reads_count);
637 DCHECK_EQ(write, writes_count);
640 MockClientSocketFactory::MockClientSocketFactory() {}
642 MockClientSocketFactory::~MockClientSocketFactory() {}
644 void MockClientSocketFactory::AddSocketDataProvider(
645 SocketDataProvider* data) {
646 mock_data_.Add(data);
649 void MockClientSocketFactory::AddSSLSocketDataProvider(
650 SSLSocketDataProvider* data) {
651 mock_ssl_data_.Add(data);
654 void MockClientSocketFactory::ResetNextMockIndexes() {
655 mock_data_.ResetNextIndex();
656 mock_ssl_data_.ResetNextIndex();
659 DatagramClientSocket* MockClientSocketFactory::CreateDatagramClientSocket(
660 DatagramSocket::BindType bind_type,
661 const RandIntCallback& rand_int_cb,
662 net::NetLog* net_log,
663 const net::NetLog::Source& source) {
664 SocketDataProvider* data_provider = mock_data_.GetNext();
665 MockUDPClientSocket* socket = new MockUDPClientSocket(data_provider, net_log);
666 data_provider->set_socket(socket);
667 return socket;
670 StreamSocket* MockClientSocketFactory::CreateTransportClientSocket(
671 const AddressList& addresses,
672 net::NetLog* net_log,
673 const net::NetLog::Source& source) {
674 SocketDataProvider* data_provider = mock_data_.GetNext();
675 MockTCPClientSocket* socket =
676 new MockTCPClientSocket(addresses, net_log, data_provider);
677 data_provider->set_socket(socket);
678 return socket;
681 SSLClientSocket* MockClientSocketFactory::CreateSSLClientSocket(
682 ClientSocketHandle* transport_socket,
683 const HostPortPair& host_and_port,
684 const SSLConfig& ssl_config,
685 const SSLClientSocketContext& context) {
686 MockSSLClientSocket* socket =
687 new MockSSLClientSocket(transport_socket, host_and_port, ssl_config,
688 mock_ssl_data_.GetNext());
689 return socket;
692 void MockClientSocketFactory::ClearSSLSessionCache() {
695 const char MockClientSocket::kTlsUnique[] = "MOCK_TLSUNIQ";
697 MockClientSocket::MockClientSocket(const BoundNetLog& net_log)
698 : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
699 connected_(false),
700 net_log_(net_log) {
701 IPAddressNumber ip;
702 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
703 peer_addr_ = IPEndPoint(ip, 0);
706 bool MockClientSocket::SetReceiveBufferSize(int32 size) {
707 return true;
710 bool MockClientSocket::SetSendBufferSize(int32 size) {
711 return true;
714 void MockClientSocket::Disconnect() {
715 connected_ = false;
718 bool MockClientSocket::IsConnected() const {
719 return connected_;
722 bool MockClientSocket::IsConnectedAndIdle() const {
723 return connected_;
726 int MockClientSocket::GetPeerAddress(IPEndPoint* address) const {
727 if (!IsConnected())
728 return ERR_SOCKET_NOT_CONNECTED;
729 *address = peer_addr_;
730 return OK;
733 int MockClientSocket::GetLocalAddress(IPEndPoint* address) const {
734 IPAddressNumber ip;
735 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
736 CHECK(rv);
737 *address = IPEndPoint(ip, 123);
738 return OK;
741 const BoundNetLog& MockClientSocket::NetLog() const {
742 return net_log_;
745 void MockClientSocket::GetSSLCertRequestInfo(
746 SSLCertRequestInfo* cert_request_info) {
749 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece& label,
750 bool has_context,
751 const base::StringPiece& context,
752 unsigned char* out,
753 unsigned int outlen) {
754 memset(out, 'A', outlen);
755 return OK;
758 int MockClientSocket::GetTLSUniqueChannelBinding(std::string* out) {
759 out->assign(MockClientSocket::kTlsUnique);
760 return OK;
763 ServerBoundCertService* MockClientSocket::GetServerBoundCertService() const {
764 NOTREACHED();
765 return NULL;
768 SSLClientSocket::NextProtoStatus
769 MockClientSocket::GetNextProto(std::string* proto, std::string* server_protos) {
770 proto->clear();
771 server_protos->clear();
772 return SSLClientSocket::kNextProtoUnsupported;
775 MockClientSocket::~MockClientSocket() {}
777 void MockClientSocket::RunCallbackAsync(const CompletionCallback& callback,
778 int result) {
779 MessageLoop::current()->PostTask(FROM_HERE,
780 base::Bind(&MockClientSocket::RunCallback, weak_factory_.GetWeakPtr(),
781 callback, result));
784 void MockClientSocket::RunCallback(const net::CompletionCallback& callback,
785 int result) {
786 if (!callback.is_null())
787 callback.Run(result);
790 MockTCPClientSocket::MockTCPClientSocket(const AddressList& addresses,
791 net::NetLog* net_log,
792 SocketDataProvider* data)
793 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
794 addresses_(addresses),
795 data_(data),
796 read_offset_(0),
797 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
798 need_read_data_(true),
799 peer_closed_connection_(false),
800 pending_buf_(NULL),
801 pending_buf_len_(0),
802 was_used_to_convey_data_(false) {
803 DCHECK(data_);
804 peer_addr_ = data->connect_data().peer_addr;
805 data_->Reset();
808 MockTCPClientSocket::~MockTCPClientSocket() {}
810 int MockTCPClientSocket::Read(IOBuffer* buf, int buf_len,
811 const CompletionCallback& callback) {
812 if (!connected_)
813 return ERR_UNEXPECTED;
815 // If the buffer is already in use, a read is already in progress!
816 DCHECK(pending_buf_ == NULL);
818 // Store our async IO data.
819 pending_buf_ = buf;
820 pending_buf_len_ = buf_len;
821 pending_callback_ = callback;
823 if (need_read_data_) {
824 read_data_ = data_->GetNextRead();
825 if (read_data_.result == ERR_CONNECTION_CLOSED) {
826 // This MockRead is just a marker to instruct us to set
827 // peer_closed_connection_.
828 peer_closed_connection_ = true;
830 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
831 // This MockRead is just a marker to instruct us to set
832 // peer_closed_connection_. Skip it and get the next one.
833 read_data_ = data_->GetNextRead();
834 peer_closed_connection_ = true;
836 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
837 // to complete the async IO manually later (via OnReadComplete).
838 if (read_data_.result == ERR_IO_PENDING) {
839 // We need to be using async IO in this case.
840 DCHECK(!callback.is_null());
841 return ERR_IO_PENDING;
843 need_read_data_ = false;
846 return CompleteRead();
849 int MockTCPClientSocket::Write(IOBuffer* buf, int buf_len,
850 const CompletionCallback& callback) {
851 DCHECK(buf);
852 DCHECK_GT(buf_len, 0);
854 if (!connected_)
855 return ERR_UNEXPECTED;
857 std::string data(buf->data(), buf_len);
858 MockWriteResult write_result = data_->OnWrite(data);
860 was_used_to_convey_data_ = true;
862 if (write_result.mode == ASYNC) {
863 RunCallbackAsync(callback, write_result.result);
864 return ERR_IO_PENDING;
867 return write_result.result;
870 int MockTCPClientSocket::Connect(const CompletionCallback& callback) {
871 if (connected_)
872 return OK;
873 connected_ = true;
874 peer_closed_connection_ = false;
875 if (data_->connect_data().mode == ASYNC) {
876 RunCallbackAsync(callback, data_->connect_data().result);
877 return ERR_IO_PENDING;
879 return data_->connect_data().result;
882 void MockTCPClientSocket::Disconnect() {
883 MockClientSocket::Disconnect();
884 pending_callback_.Reset();
887 bool MockTCPClientSocket::IsConnected() const {
888 return connected_ && !peer_closed_connection_;
891 bool MockTCPClientSocket::IsConnectedAndIdle() const {
892 return IsConnected();
895 int MockTCPClientSocket::GetPeerAddress(IPEndPoint* address) const {
896 if (addresses_.empty())
897 return MockClientSocket::GetPeerAddress(address);
899 *address = addresses_[0];
900 return OK;
903 bool MockTCPClientSocket::WasEverUsed() const {
904 return was_used_to_convey_data_;
907 bool MockTCPClientSocket::UsingTCPFastOpen() const {
908 return false;
911 bool MockTCPClientSocket::WasNpnNegotiated() const {
912 return false;
915 bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
916 return false;
919 void MockTCPClientSocket::OnReadComplete(const MockRead& data) {
920 // There must be a read pending.
921 DCHECK(pending_buf_);
922 // You can't complete a read with another ERR_IO_PENDING status code.
923 DCHECK_NE(ERR_IO_PENDING, data.result);
924 // Since we've been waiting for data, need_read_data_ should be true.
925 DCHECK(need_read_data_);
927 read_data_ = data;
928 need_read_data_ = false;
930 // The caller is simulating that this IO completes right now. Don't
931 // let CompleteRead() schedule a callback.
932 read_data_.mode = SYNCHRONOUS;
934 CompletionCallback callback = pending_callback_;
935 int rv = CompleteRead();
936 RunCallback(callback, rv);
939 int MockTCPClientSocket::CompleteRead() {
940 DCHECK(pending_buf_);
941 DCHECK(pending_buf_len_ > 0);
943 was_used_to_convey_data_ = true;
945 // Save the pending async IO data and reset our |pending_| state.
946 IOBuffer* buf = pending_buf_;
947 int buf_len = pending_buf_len_;
948 CompletionCallback callback = pending_callback_;
949 pending_buf_ = NULL;
950 pending_buf_len_ = 0;
951 pending_callback_.Reset();
953 int result = read_data_.result;
954 DCHECK(result != ERR_IO_PENDING);
956 if (read_data_.data) {
957 if (read_data_.data_len - read_offset_ > 0) {
958 result = std::min(buf_len, read_data_.data_len - read_offset_);
959 memcpy(buf->data(), read_data_.data + read_offset_, result);
960 read_offset_ += result;
961 if (read_offset_ == read_data_.data_len) {
962 need_read_data_ = true;
963 read_offset_ = 0;
965 } else {
966 result = 0; // EOF
970 if (read_data_.mode == ASYNC) {
971 DCHECK(!callback.is_null());
972 RunCallbackAsync(callback, result);
973 return ERR_IO_PENDING;
975 return result;
978 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
979 net::NetLog* net_log, DeterministicSocketData* data)
980 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
981 write_pending_(false),
982 write_result_(0),
983 read_data_(),
984 read_buf_(NULL),
985 read_buf_len_(0),
986 read_pending_(false),
987 data_(data),
988 was_used_to_convey_data_(false),
989 peer_closed_connection_(false) {
990 peer_addr_ = data->connect_data().peer_addr;
993 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
995 void DeterministicMockTCPClientSocket::CompleteWrite() {
996 was_used_to_convey_data_ = true;
997 write_pending_ = false;
998 write_callback_.Run(write_result_);
1001 int DeterministicMockTCPClientSocket::CompleteRead() {
1002 DCHECK_GT(read_buf_len_, 0);
1003 DCHECK_LE(read_data_.data_len, read_buf_len_);
1004 DCHECK(read_buf_);
1006 was_used_to_convey_data_ = true;
1008 if (read_data_.result == ERR_IO_PENDING)
1009 read_data_ = data_->GetNextRead();
1010 DCHECK_NE(ERR_IO_PENDING, read_data_.result);
1011 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1012 // the callback. Therefore we don't even bother to check it.
1013 int result = read_data_.result;
1015 if (read_data_.data_len > 0) {
1016 DCHECK(read_data_.data);
1017 result = std::min(read_buf_len_, read_data_.data_len);
1018 memcpy(read_buf_->data(), read_data_.data, result);
1021 if (read_pending_) {
1022 read_pending_ = false;
1023 read_callback_.Run(result);
1026 return result;
1029 int DeterministicMockTCPClientSocket::Write(
1030 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1031 DCHECK(buf);
1032 DCHECK_GT(buf_len, 0);
1034 if (!connected_)
1035 return ERR_UNEXPECTED;
1037 std::string data(buf->data(), buf_len);
1038 MockWriteResult write_result = data_->OnWrite(data);
1040 if (write_result.mode == ASYNC) {
1041 write_callback_ = callback;
1042 write_result_ = write_result.result;
1043 DCHECK(!write_callback_.is_null());
1044 write_pending_ = true;
1045 return ERR_IO_PENDING;
1048 was_used_to_convey_data_ = true;
1049 write_pending_ = false;
1050 return write_result.result;
1053 int DeterministicMockTCPClientSocket::Read(
1054 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1055 if (!connected_)
1056 return ERR_UNEXPECTED;
1058 read_data_ = data_->GetNextRead();
1059 // The buffer should always be big enough to contain all the MockRead data. To
1060 // use small buffers, split the data into multiple MockReads.
1061 DCHECK_LE(read_data_.data_len, buf_len);
1063 if (read_data_.result == ERR_CONNECTION_CLOSED) {
1064 // This MockRead is just a marker to instruct us to set
1065 // peer_closed_connection_.
1066 peer_closed_connection_ = true;
1068 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
1069 // This MockRead is just a marker to instruct us to set
1070 // peer_closed_connection_. Skip it and get the next one.
1071 read_data_ = data_->GetNextRead();
1072 peer_closed_connection_ = true;
1075 read_buf_ = buf;
1076 read_buf_len_ = buf_len;
1077 read_callback_ = callback;
1079 if (read_data_.mode == ASYNC || (read_data_.result == ERR_IO_PENDING)) {
1080 read_pending_ = true;
1081 DCHECK(!read_callback_.is_null());
1082 return ERR_IO_PENDING;
1085 was_used_to_convey_data_ = true;
1086 return CompleteRead();
1089 // TODO(erikchen): Support connect sequencing.
1090 int DeterministicMockTCPClientSocket::Connect(
1091 const CompletionCallback& callback) {
1092 if (connected_)
1093 return OK;
1094 connected_ = true;
1095 if (data_->connect_data().mode == ASYNC) {
1096 RunCallbackAsync(callback, data_->connect_data().result);
1097 return ERR_IO_PENDING;
1099 return data_->connect_data().result;
1102 void DeterministicMockTCPClientSocket::Disconnect() {
1103 MockClientSocket::Disconnect();
1106 bool DeterministicMockTCPClientSocket::IsConnected() const {
1107 return connected_ && !peer_closed_connection_;
1110 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1111 return IsConnected();
1114 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1115 return was_used_to_convey_data_;
1118 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1119 return false;
1122 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1123 return false;
1126 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1127 return false;
1130 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead& data) {}
1132 // static
1133 void MockSSLClientSocket::ConnectCallback(
1134 MockSSLClientSocket *ssl_client_socket,
1135 const CompletionCallback& callback,
1136 int rv) {
1137 if (rv == OK)
1138 ssl_client_socket->connected_ = true;
1139 callback.Run(rv);
1142 MockSSLClientSocket::MockSSLClientSocket(
1143 ClientSocketHandle* transport_socket,
1144 const HostPortPair& host_port_pair,
1145 const SSLConfig& ssl_config,
1146 SSLSocketDataProvider* data)
1147 : MockClientSocket(
1148 // Have to use the right BoundNetLog for LoadTimingInfo regression
1149 // tests.
1150 transport_socket->socket()->NetLog()),
1151 transport_(transport_socket),
1152 data_(data),
1153 is_npn_state_set_(false),
1154 new_npn_value_(false),
1155 is_protocol_negotiated_set_(false),
1156 protocol_negotiated_(kProtoUnknown) {
1157 DCHECK(data_);
1158 peer_addr_ = data->connect.peer_addr;
1161 MockSSLClientSocket::~MockSSLClientSocket() {
1162 Disconnect();
1165 int MockSSLClientSocket::Read(IOBuffer* buf, int buf_len,
1166 const CompletionCallback& callback) {
1167 return transport_->socket()->Read(buf, buf_len, callback);
1170 int MockSSLClientSocket::Write(IOBuffer* buf, int buf_len,
1171 const CompletionCallback& callback) {
1172 return transport_->socket()->Write(buf, buf_len, callback);
1175 int MockSSLClientSocket::Connect(const CompletionCallback& callback) {
1176 int rv = transport_->socket()->Connect(
1177 base::Bind(&ConnectCallback, base::Unretained(this), callback));
1178 if (rv == OK) {
1179 if (data_->connect.result == OK)
1180 connected_ = true;
1181 if (data_->connect.mode == ASYNC) {
1182 RunCallbackAsync(callback, data_->connect.result);
1183 return ERR_IO_PENDING;
1185 return data_->connect.result;
1187 return rv;
1190 void MockSSLClientSocket::Disconnect() {
1191 MockClientSocket::Disconnect();
1192 if (transport_->socket() != NULL)
1193 transport_->socket()->Disconnect();
1196 bool MockSSLClientSocket::IsConnected() const {
1197 return transport_->socket()->IsConnected();
1200 bool MockSSLClientSocket::WasEverUsed() const {
1201 return transport_->socket()->WasEverUsed();
1204 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1205 return transport_->socket()->UsingTCPFastOpen();
1208 int MockSSLClientSocket::GetPeerAddress(IPEndPoint* address) const {
1209 return transport_->socket()->GetPeerAddress(address);
1212 bool MockSSLClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1213 ssl_info->Reset();
1214 ssl_info->cert = data_->cert;
1215 ssl_info->client_cert_sent = data_->client_cert_sent;
1216 ssl_info->channel_id_sent = data_->channel_id_sent;
1217 return true;
1220 void MockSSLClientSocket::GetSSLCertRequestInfo(
1221 SSLCertRequestInfo* cert_request_info) {
1222 DCHECK(cert_request_info);
1223 if (data_->cert_request_info) {
1224 cert_request_info->host_and_port =
1225 data_->cert_request_info->host_and_port;
1226 cert_request_info->client_certs = data_->cert_request_info->client_certs;
1227 } else {
1228 cert_request_info->Reset();
1232 SSLClientSocket::NextProtoStatus MockSSLClientSocket::GetNextProto(
1233 std::string* proto, std::string* server_protos) {
1234 *proto = data_->next_proto;
1235 *server_protos = data_->server_protos;
1236 return data_->next_proto_status;
1239 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated) {
1240 is_npn_state_set_ = true;
1241 return new_npn_value_ = negotiated;
1244 bool MockSSLClientSocket::WasNpnNegotiated() const {
1245 if (is_npn_state_set_)
1246 return new_npn_value_;
1247 return data_->was_npn_negotiated;
1250 NextProto MockSSLClientSocket::GetNegotiatedProtocol() const {
1251 if (is_protocol_negotiated_set_)
1252 return protocol_negotiated_;
1253 return data_->protocol_negotiated;
1256 void MockSSLClientSocket::set_protocol_negotiated(
1257 NextProto protocol_negotiated) {
1258 is_protocol_negotiated_set_ = true;
1259 protocol_negotiated_ = protocol_negotiated;
1262 bool MockSSLClientSocket::WasChannelIDSent() const {
1263 return data_->channel_id_sent;
1266 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent) {
1267 data_->channel_id_sent = channel_id_sent;
1270 ServerBoundCertService* MockSSLClientSocket::GetServerBoundCertService() const {
1271 return data_->server_bound_cert_service;
1274 void MockSSLClientSocket::OnReadComplete(const MockRead& data) {
1275 NOTIMPLEMENTED();
1278 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data,
1279 net::NetLog* net_log)
1280 : connected_(false),
1281 data_(data),
1282 read_offset_(0),
1283 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
1284 need_read_data_(true),
1285 pending_buf_(NULL),
1286 pending_buf_len_(0),
1287 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1288 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
1289 DCHECK(data_);
1290 data_->Reset();
1291 peer_addr_ = data->connect_data().peer_addr;
1294 MockUDPClientSocket::~MockUDPClientSocket() {}
1296 int MockUDPClientSocket::Read(IOBuffer* buf, int buf_len,
1297 const CompletionCallback& callback) {
1298 if (!connected_)
1299 return ERR_UNEXPECTED;
1301 // If the buffer is already in use, a read is already in progress!
1302 DCHECK(pending_buf_ == NULL);
1304 // Store our async IO data.
1305 pending_buf_ = buf;
1306 pending_buf_len_ = buf_len;
1307 pending_callback_ = callback;
1309 if (need_read_data_) {
1310 read_data_ = data_->GetNextRead();
1311 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1312 // to complete the async IO manually later (via OnReadComplete).
1313 if (read_data_.result == ERR_IO_PENDING) {
1314 // We need to be using async IO in this case.
1315 DCHECK(!callback.is_null());
1316 return ERR_IO_PENDING;
1318 need_read_data_ = false;
1321 return CompleteRead();
1324 int MockUDPClientSocket::Write(IOBuffer* buf, int buf_len,
1325 const CompletionCallback& callback) {
1326 DCHECK(buf);
1327 DCHECK_GT(buf_len, 0);
1329 if (!connected_)
1330 return ERR_UNEXPECTED;
1332 std::string data(buf->data(), buf_len);
1333 MockWriteResult write_result = data_->OnWrite(data);
1335 if (write_result.mode == ASYNC) {
1336 RunCallbackAsync(callback, write_result.result);
1337 return ERR_IO_PENDING;
1339 return write_result.result;
1342 bool MockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1343 return true;
1346 bool MockUDPClientSocket::SetSendBufferSize(int32 size) {
1347 return true;
1350 void MockUDPClientSocket::Close() {
1351 connected_ = false;
1354 int MockUDPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1355 *address = peer_addr_;
1356 return OK;
1359 int MockUDPClientSocket::GetLocalAddress(IPEndPoint* address) const {
1360 NOTIMPLEMENTED();
1361 return OK;
1364 const BoundNetLog& MockUDPClientSocket::NetLog() const {
1365 return net_log_;
1368 int MockUDPClientSocket::Connect(const IPEndPoint& address) {
1369 connected_ = true;
1370 return OK;
1373 void MockUDPClientSocket::OnReadComplete(const MockRead& data) {
1374 // There must be a read pending.
1375 DCHECK(pending_buf_);
1376 // You can't complete a read with another ERR_IO_PENDING status code.
1377 DCHECK_NE(ERR_IO_PENDING, data.result);
1378 // Since we've been waiting for data, need_read_data_ should be true.
1379 DCHECK(need_read_data_);
1381 read_data_ = data;
1382 need_read_data_ = false;
1384 // The caller is simulating that this IO completes right now. Don't
1385 // let CompleteRead() schedule a callback.
1386 read_data_.mode = SYNCHRONOUS;
1388 net::CompletionCallback callback = pending_callback_;
1389 int rv = CompleteRead();
1390 RunCallback(callback, rv);
1393 int MockUDPClientSocket::CompleteRead() {
1394 DCHECK(pending_buf_);
1395 DCHECK(pending_buf_len_ > 0);
1397 // Save the pending async IO data and reset our |pending_| state.
1398 IOBuffer* buf = pending_buf_;
1399 int buf_len = pending_buf_len_;
1400 CompletionCallback callback = pending_callback_;
1401 pending_buf_ = NULL;
1402 pending_buf_len_ = 0;
1403 pending_callback_.Reset();
1405 int result = read_data_.result;
1406 DCHECK(result != ERR_IO_PENDING);
1408 if (read_data_.data) {
1409 if (read_data_.data_len - read_offset_ > 0) {
1410 result = std::min(buf_len, read_data_.data_len - read_offset_);
1411 memcpy(buf->data(), read_data_.data + read_offset_, result);
1412 read_offset_ += result;
1413 if (read_offset_ == read_data_.data_len) {
1414 need_read_data_ = true;
1415 read_offset_ = 0;
1417 } else {
1418 result = 0; // EOF
1422 if (read_data_.mode == ASYNC) {
1423 DCHECK(!callback.is_null());
1424 RunCallbackAsync(callback, result);
1425 return ERR_IO_PENDING;
1427 return result;
1430 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback& callback,
1431 int result) {
1432 MessageLoop::current()->PostTask(
1433 FROM_HERE,
1434 base::Bind(&MockUDPClientSocket::RunCallback, weak_factory_.GetWeakPtr(),
1435 callback, result));
1438 void MockUDPClientSocket::RunCallback(const CompletionCallback& callback,
1439 int result) {
1440 if (!callback.is_null())
1441 callback.Run(result);
1444 TestSocketRequest::TestSocketRequest(
1445 std::vector<TestSocketRequest*>* request_order, size_t* completion_count)
1446 : request_order_(request_order),
1447 completion_count_(completion_count),
1448 ALLOW_THIS_IN_INITIALIZER_LIST(callback_(
1449 base::Bind(&TestSocketRequest::OnComplete, base::Unretained(this)))) {
1450 DCHECK(request_order);
1451 DCHECK(completion_count);
1454 TestSocketRequest::~TestSocketRequest() {
1457 void TestSocketRequest::OnComplete(int result) {
1458 SetResult(result);
1459 (*completion_count_)++;
1460 request_order_->push_back(this);
1463 // static
1464 const int ClientSocketPoolTest::kIndexOutOfBounds = -1;
1466 // static
1467 const int ClientSocketPoolTest::kRequestNotFound = -2;
1469 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1470 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1472 int ClientSocketPoolTest::GetOrderOfRequest(size_t index) const {
1473 index--;
1474 if (index >= requests_.size())
1475 return kIndexOutOfBounds;
1477 for (size_t i = 0; i < request_order_.size(); i++)
1478 if (requests_[index] == request_order_[i])
1479 return i + 1;
1481 return kRequestNotFound;
1484 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
1485 ScopedVector<TestSocketRequest>::iterator i;
1486 for (i = requests_.begin(); i != requests_.end(); ++i) {
1487 if ((*i)->handle()->is_initialized()) {
1488 if (keep_alive == NO_KEEP_ALIVE)
1489 (*i)->handle()->socket()->Disconnect();
1490 (*i)->handle()->Reset();
1491 base::RunLoop().RunUntilIdle();
1492 return true;
1495 return false;
1498 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
1499 bool released_one;
1500 do {
1501 released_one = ReleaseOneConnection(keep_alive);
1502 } while (released_one);
1505 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1506 StreamSocket* socket,
1507 ClientSocketHandle* handle,
1508 const CompletionCallback& callback)
1509 : socket_(socket),
1510 handle_(handle),
1511 user_callback_(callback) {
1514 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1516 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1517 int rv = socket_->Connect(base::Bind(&MockConnectJob::OnConnect,
1518 base::Unretained(this)));
1519 if (rv == OK) {
1520 user_callback_.Reset();
1521 OnConnect(OK);
1523 return rv;
1526 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1527 const ClientSocketHandle* handle) {
1528 if (handle != handle_)
1529 return false;
1530 socket_.reset();
1531 handle_ = NULL;
1532 user_callback_.Reset();
1533 return true;
1536 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) {
1537 if (!socket_.get())
1538 return;
1539 if (rv == OK) {
1540 handle_->set_socket(socket_.release());
1542 // Needed for socket pool tests that layer other sockets on top of mock
1543 // sockets.
1544 LoadTimingInfo::ConnectTiming connect_timing;
1545 base::TimeTicks now = base::TimeTicks::Now();
1546 connect_timing.dns_start = now;
1547 connect_timing.dns_end = now;
1548 connect_timing.connect_start = now;
1549 connect_timing.connect_end = now;
1550 handle_->set_connect_timing(connect_timing);
1551 } else {
1552 socket_.reset();
1555 handle_ = NULL;
1557 if (!user_callback_.is_null()) {
1558 CompletionCallback callback = user_callback_;
1559 user_callback_.Reset();
1560 callback.Run(rv);
1564 MockTransportClientSocketPool::MockTransportClientSocketPool(
1565 int max_sockets,
1566 int max_sockets_per_group,
1567 ClientSocketPoolHistograms* histograms,
1568 ClientSocketFactory* socket_factory)
1569 : TransportClientSocketPool(max_sockets, max_sockets_per_group, histograms,
1570 NULL, NULL, NULL),
1571 client_socket_factory_(socket_factory),
1572 release_count_(0),
1573 cancel_count_(0) {
1576 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1578 int MockTransportClientSocketPool::RequestSocket(
1579 const std::string& group_name, const void* socket_params,
1580 RequestPriority priority, ClientSocketHandle* handle,
1581 const CompletionCallback& callback, const BoundNetLog& net_log) {
1582 StreamSocket* socket = client_socket_factory_->CreateTransportClientSocket(
1583 AddressList(), net_log.net_log(), net::NetLog::Source());
1584 MockConnectJob* job = new MockConnectJob(socket, handle, callback);
1585 job_list_.push_back(job);
1586 handle->set_pool_id(1);
1587 return job->Connect();
1590 void MockTransportClientSocketPool::CancelRequest(const std::string& group_name,
1591 ClientSocketHandle* handle) {
1592 std::vector<MockConnectJob*>::iterator i;
1593 for (i = job_list_.begin(); i != job_list_.end(); ++i) {
1594 if ((*i)->CancelHandle(handle)) {
1595 cancel_count_++;
1596 break;
1601 void MockTransportClientSocketPool::ReleaseSocket(const std::string& group_name,
1602 StreamSocket* socket, int id) {
1603 EXPECT_EQ(1, id);
1604 release_count_++;
1605 delete socket;
1608 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1610 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1612 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1613 DeterministicSocketData* data) {
1614 mock_data_.Add(data);
1617 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1618 SSLSocketDataProvider* data) {
1619 mock_ssl_data_.Add(data);
1622 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1623 mock_data_.ResetNextIndex();
1624 mock_ssl_data_.ResetNextIndex();
1627 MockSSLClientSocket* DeterministicMockClientSocketFactory::
1628 GetMockSSLClientSocket(size_t index) const {
1629 DCHECK_LT(index, ssl_client_sockets_.size());
1630 return ssl_client_sockets_[index];
1633 DatagramClientSocket*
1634 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1635 DatagramSocket::BindType bind_type,
1636 const RandIntCallback& rand_int_cb,
1637 net::NetLog* net_log,
1638 const NetLog::Source& source) {
1639 NOTREACHED();
1640 return NULL;
1643 StreamSocket* DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1644 const AddressList& addresses,
1645 net::NetLog* net_log,
1646 const net::NetLog::Source& source) {
1647 DeterministicSocketData* data_provider = mock_data().GetNext();
1648 DeterministicMockTCPClientSocket* socket =
1649 new DeterministicMockTCPClientSocket(net_log, data_provider);
1650 data_provider->set_socket(socket->AsWeakPtr());
1651 tcp_client_sockets().push_back(socket);
1652 return socket;
1655 SSLClientSocket* DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1656 ClientSocketHandle* transport_socket,
1657 const HostPortPair& host_and_port,
1658 const SSLConfig& ssl_config,
1659 const SSLClientSocketContext& context) {
1660 MockSSLClientSocket* socket =
1661 new MockSSLClientSocket(transport_socket, host_and_port, ssl_config,
1662 mock_ssl_data_.GetNext());
1663 ssl_client_sockets_.push_back(socket);
1664 return socket;
1667 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1670 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1671 int max_sockets,
1672 int max_sockets_per_group,
1673 ClientSocketPoolHistograms* histograms,
1674 TransportClientSocketPool* transport_pool)
1675 : SOCKSClientSocketPool(max_sockets, max_sockets_per_group, histograms,
1676 NULL, transport_pool, NULL),
1677 transport_pool_(transport_pool) {
1680 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1682 int MockSOCKSClientSocketPool::RequestSocket(
1683 const std::string& group_name, const void* socket_params,
1684 RequestPriority priority, ClientSocketHandle* handle,
1685 const CompletionCallback& callback, const BoundNetLog& net_log) {
1686 return transport_pool_->RequestSocket(
1687 group_name, socket_params, priority, handle, callback, net_log);
1690 void MockSOCKSClientSocketPool::CancelRequest(
1691 const std::string& group_name,
1692 ClientSocketHandle* handle) {
1693 return transport_pool_->CancelRequest(group_name, handle);
1696 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string& group_name,
1697 StreamSocket* socket, int id) {
1698 return transport_pool_->ReleaseSocket(group_name, socket, id);
1701 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
1702 const int kSOCKS5GreetRequestLength = arraysize(kSOCKS5GreetRequest);
1704 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
1705 const int kSOCKS5GreetResponseLength = arraysize(kSOCKS5GreetResponse);
1707 const char kSOCKS5OkRequest[] =
1708 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
1709 const int kSOCKS5OkRequestLength = arraysize(kSOCKS5OkRequest);
1711 const char kSOCKS5OkResponse[] =
1712 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
1713 const int kSOCKS5OkResponseLength = arraysize(kSOCKS5OkResponse);
1715 } // namespace net