Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / net / socket / socket_test_util.cc
blob98bf32235ec3e6a38eb2b3c2e1457bb9e88080c1
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/location.h"
15 #include "base/logging.h"
16 #include "base/run_loop.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/thread_task_runner_handle.h"
19 #include "base/time/time.h"
20 #include "net/base/address_family.h"
21 #include "net/base/address_list.h"
22 #include "net/base/auth.h"
23 #include "net/base/load_timing_info.h"
24 #include "net/http/http_network_session.h"
25 #include "net/http/http_request_headers.h"
26 #include "net/http/http_response_headers.h"
27 #include "net/socket/socket.h"
28 #include "net/socket/websocket_endpoint_lock_manager.h"
29 #include "net/ssl/ssl_cert_request_info.h"
30 #include "net/ssl/ssl_connection_status_flags.h"
31 #include "net/ssl/ssl_failure_state.h"
32 #include "net/ssl/ssl_info.h"
33 #include "testing/gtest/include/gtest/gtest.h"
35 #define NET_TRACE(level, s) VLOG(level) << s << __FUNCTION__ << "() "
37 namespace net {
39 namespace {
41 inline char AsciifyHigh(char x) {
42 char nybble = static_cast<char>((x >> 4) & 0x0F);
43 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
46 inline char AsciifyLow(char x) {
47 char nybble = static_cast<char>((x >> 0) & 0x0F);
48 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
51 inline char Asciify(char x) {
52 if ((x < 0) || !isprint(x))
53 return '.';
54 return x;
57 void DumpData(const char* data, int data_len) {
58 if (logging::LOG_INFO < logging::GetMinLogLevel())
59 return;
60 DVLOG(1) << "Length: " << data_len;
61 const char* pfx = "Data: ";
62 if (!data || (data_len <= 0)) {
63 DVLOG(1) << pfx << "<None>";
64 } else {
65 int i;
66 for (i = 0; i <= (data_len - 4); i += 4) {
67 DVLOG(1) << pfx
68 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
69 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
70 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
71 << AsciifyHigh(data[i + 3]) << AsciifyLow(data[i + 3])
72 << " '"
73 << Asciify(data[i + 0])
74 << Asciify(data[i + 1])
75 << Asciify(data[i + 2])
76 << Asciify(data[i + 3])
77 << "'";
78 pfx = " ";
80 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
81 switch (data_len - i) {
82 case 3:
83 DVLOG(1) << pfx
84 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
85 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
86 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
87 << " '"
88 << Asciify(data[i + 0])
89 << Asciify(data[i + 1])
90 << Asciify(data[i + 2])
91 << " '";
92 break;
93 case 2:
94 DVLOG(1) << pfx
95 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
96 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
97 << " '"
98 << Asciify(data[i + 0])
99 << Asciify(data[i + 1])
100 << " '";
101 break;
102 case 1:
103 DVLOG(1) << pfx
104 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
105 << " '"
106 << Asciify(data[i + 0])
107 << " '";
108 break;
113 template <MockReadWriteType type>
114 void DumpMockReadWrite(const MockReadWrite<type>& r) {
115 if (logging::LOG_INFO < logging::GetMinLogLevel())
116 return;
117 DVLOG(1) << "Async: " << (r.mode == ASYNC)
118 << "\nResult: " << r.result;
119 DumpData(r.data, r.data_len);
120 const char* stop = (r.sequence_number & MockRead::STOPLOOP) ? " (STOP)" : "";
121 DVLOG(1) << "Stage: " << (r.sequence_number & ~MockRead::STOPLOOP) << stop;
124 } // namespace
126 MockConnect::MockConnect() : mode(ASYNC), result(OK) {
127 IPAddressNumber ip;
128 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
129 peer_addr = IPEndPoint(ip, 0);
132 MockConnect::MockConnect(IoMode io_mode, int r) : mode(io_mode), result(r) {
133 IPAddressNumber ip;
134 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
135 peer_addr = IPEndPoint(ip, 0);
138 MockConnect::MockConnect(IoMode io_mode, int r, IPEndPoint addr) :
139 mode(io_mode),
140 result(r),
141 peer_addr(addr) {
144 MockConnect::~MockConnect() {}
146 StaticSocketDataHelper::StaticSocketDataHelper(MockRead* reads,
147 size_t reads_count,
148 MockWrite* writes,
149 size_t writes_count)
150 : reads_(reads),
151 read_index_(0),
152 read_count_(reads_count),
153 writes_(writes),
154 write_index_(0),
155 write_count_(writes_count) {
158 StaticSocketDataHelper::~StaticSocketDataHelper() {
161 const MockRead& StaticSocketDataHelper::PeekRead() const {
162 CHECK(!AllReadDataConsumed());
163 return reads_[read_index_];
166 const MockWrite& StaticSocketDataHelper::PeekWrite() const {
167 CHECK(!AllWriteDataConsumed());
168 return writes_[write_index_];
171 const MockRead& StaticSocketDataHelper::AdvanceRead() {
172 CHECK(!AllReadDataConsumed());
173 return reads_[read_index_++];
176 const MockWrite& StaticSocketDataHelper::AdvanceWrite() {
177 CHECK(!AllWriteDataConsumed());
178 return writes_[write_index_++];
181 bool StaticSocketDataHelper::VerifyWriteData(const std::string& data) {
182 CHECK(!AllWriteDataConsumed());
183 // Check that what the actual data matches the expectations.
184 const MockWrite& next_write = PeekWrite();
185 if (!next_write.data)
186 return true;
188 // Note: Partial writes are supported here. If the expected data
189 // is a match, but shorter than the write actually written, that is legal.
190 // Example:
191 // Application writes "foobarbaz" (9 bytes)
192 // Expected write was "foo" (3 bytes)
193 // This is a success, and the function returns true.
194 std::string expected_data(next_write.data, next_write.data_len);
195 std::string actual_data(data.substr(0, next_write.data_len));
196 EXPECT_GE(data.length(), expected_data.length());
197 EXPECT_EQ(expected_data, actual_data);
198 return expected_data == actual_data;
201 void StaticSocketDataHelper::Reset() {
202 read_index_ = 0;
203 write_index_ = 0;
206 StaticSocketDataProvider::StaticSocketDataProvider()
207 : StaticSocketDataProvider(nullptr, 0, nullptr, 0) {
210 StaticSocketDataProvider::StaticSocketDataProvider(MockRead* reads,
211 size_t reads_count,
212 MockWrite* writes,
213 size_t writes_count)
214 : helper_(reads, reads_count, writes, writes_count) {
217 StaticSocketDataProvider::~StaticSocketDataProvider() {
220 MockRead StaticSocketDataProvider::OnRead() {
221 CHECK(!helper_.AllReadDataConsumed());
222 return helper_.AdvanceRead();
225 MockWriteResult StaticSocketDataProvider::OnWrite(const std::string& data) {
226 if (helper_.write_count() == 0) {
227 // Not using mock writes; succeed synchronously.
228 return MockWriteResult(SYNCHRONOUS, data.length());
230 EXPECT_FALSE(helper_.AllWriteDataConsumed());
231 if (helper_.AllWriteDataConsumed()) {
232 // Show what the extra write actually consists of.
233 EXPECT_EQ("<unexpected write>", data);
234 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
237 // Check that what we are writing matches the expectation.
238 // Then give the mocked return value.
239 if (!helper_.VerifyWriteData(data))
240 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
242 const MockWrite& next_write = helper_.AdvanceWrite();
243 // In the case that the write was successful, return the number of bytes
244 // written. Otherwise return the error code.
245 int result =
246 next_write.result == OK ? next_write.data_len : next_write.result;
247 return MockWriteResult(next_write.mode, result);
250 void StaticSocketDataProvider::Reset() {
251 helper_.Reset();
254 bool StaticSocketDataProvider::AllReadDataConsumed() const {
255 return helper_.AllReadDataConsumed();
258 bool StaticSocketDataProvider::AllWriteDataConsumed() const {
259 return helper_.AllWriteDataConsumed();
262 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode, int result)
263 : connect(mode, result),
264 next_proto_status(SSLClientSocket::kNextProtoUnsupported),
265 client_cert_sent(false),
266 cert_request_info(NULL),
267 channel_id_sent(false),
268 connection_status(0) {
269 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2,
270 &connection_status);
271 // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
272 SSLConnectionStatusSetCipherSuite(0xcc14, &connection_status);
275 SSLSocketDataProvider::~SSLSocketDataProvider() {
278 void SSLSocketDataProvider::SetNextProto(NextProto proto) {
279 next_proto_status = SSLClientSocket::kNextProtoNegotiated;
280 next_proto = SSLClientSocket::NextProtoToString(proto);
283 SequencedSocketData::SequencedSocketData(MockRead* reads,
284 size_t reads_count,
285 MockWrite* writes,
286 size_t writes_count)
287 : helper_(reads, reads_count, writes, writes_count),
288 sequence_number_(0),
289 read_state_(IDLE),
290 write_state_(IDLE),
291 weak_factory_(this) {
292 // Check that reads and writes have a contiguous set of sequence numbers
293 // starting from 0 and working their way up, with no repeats and skipping
294 // no values.
295 size_t next_read = 0;
296 size_t next_write = 0;
297 int next_sequence_number = 0;
298 while (next_read < reads_count || next_write < writes_count) {
299 if (next_read < reads_count &&
300 reads[next_read].sequence_number == next_sequence_number) {
301 ++next_read;
302 ++next_sequence_number;
303 continue;
305 if (next_write < writes_count &&
306 writes[next_write].sequence_number == next_sequence_number) {
307 ++next_write;
308 ++next_sequence_number;
309 continue;
311 CHECK(false) << "Sequence number not found where expected: "
312 << next_sequence_number;
313 return;
315 CHECK_EQ(next_read, reads_count);
316 CHECK_EQ(next_write, writes_count);
319 SequencedSocketData::SequencedSocketData(const MockConnect& connect,
320 MockRead* reads,
321 size_t reads_count,
322 MockWrite* writes,
323 size_t writes_count)
324 : SequencedSocketData(reads, reads_count, writes, writes_count) {
325 set_connect_data(connect);
328 MockRead SequencedSocketData::OnRead() {
329 CHECK_EQ(IDLE, read_state_);
330 CHECK(!helper_.AllReadDataConsumed());
332 NET_TRACE(1, " *** ") << "sequence_number: " << sequence_number_;
333 const MockRead& next_read = helper_.PeekRead();
334 NET_TRACE(1, " *** ") << "next_read: " << next_read.sequence_number;
335 CHECK_GE(next_read.sequence_number, sequence_number_);
337 if (next_read.sequence_number <= sequence_number_) {
338 if (next_read.mode == SYNCHRONOUS) {
339 NET_TRACE(1, " *** ") << "Returning synchronously";
340 DumpMockReadWrite(next_read);
341 helper_.AdvanceRead();
342 ++sequence_number_;
343 MaybePostWriteCompleteTask();
344 return next_read;
347 // If the result is ERR_IO_PENDING, then advance to the next state
348 // and pause reads.
349 if (next_read.result == ERR_IO_PENDING) {
350 NET_TRACE(1, " *** ") << "Pausing at: " << sequence_number_;
351 ++sequence_number_;
352 helper_.AdvanceRead();
353 read_state_ = PAUSED;
354 return MockRead(SYNCHRONOUS, ERR_IO_PENDING);
356 base::ThreadTaskRunnerHandle::Get()->PostTask(
357 FROM_HERE, base::Bind(&SequencedSocketData::OnReadComplete,
358 weak_factory_.GetWeakPtr()));
359 CHECK_NE(COMPLETING, write_state_);
360 read_state_ = COMPLETING;
361 } else if (next_read.mode == SYNCHRONOUS) {
362 ADD_FAILURE() << "Unable to perform synchronous IO while stopped";
363 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
364 } else {
365 NET_TRACE(1, " *** ") << "Waiting for write to trigger read";
366 read_state_ = PENDING;
369 return MockRead(SYNCHRONOUS, ERR_IO_PENDING);
372 MockWriteResult SequencedSocketData::OnWrite(const std::string& data) {
373 CHECK_EQ(IDLE, write_state_);
374 CHECK(!helper_.AllWriteDataConsumed());
376 NET_TRACE(1, " *** ") << "sequence_number: " << sequence_number_;
377 const MockWrite& next_write = helper_.PeekWrite();
378 NET_TRACE(1, " *** ") << "next_write: " << next_write.sequence_number;
379 CHECK_GE(next_write.sequence_number, sequence_number_);
381 if (!helper_.VerifyWriteData(data))
382 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
384 if (next_write.sequence_number <= sequence_number_) {
385 if (next_write.mode == SYNCHRONOUS) {
386 helper_.AdvanceWrite();
387 ++sequence_number_;
388 MaybePostReadCompleteTask();
389 // In the case that the write was successful, return the number of bytes
390 // written. Otherwise return the error code.
391 int rv =
392 next_write.result != OK ? next_write.result : next_write.data_len;
393 NET_TRACE(1, " *** ") << "Returning synchronously";
394 return MockWriteResult(SYNCHRONOUS, rv);
397 NET_TRACE(1, " *** ") << "Posting task to complete write";
398 base::ThreadTaskRunnerHandle::Get()->PostTask(
399 FROM_HERE, base::Bind(&SequencedSocketData::OnWriteComplete,
400 weak_factory_.GetWeakPtr()));
401 CHECK_NE(COMPLETING, read_state_);
402 write_state_ = COMPLETING;
403 } else if (next_write.mode == SYNCHRONOUS) {
404 ADD_FAILURE() << "Unable to perform synchronous IO while stopped";
405 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
406 } else {
407 NET_TRACE(1, " *** ") << "Waiting for read to trigger write";
408 write_state_ = PENDING;
411 return MockWriteResult(SYNCHRONOUS, ERR_IO_PENDING);
414 void SequencedSocketData::Reset() {
415 helper_.Reset();
416 sequence_number_ = 0;
417 read_state_ = IDLE;
418 write_state_ = IDLE;
419 weak_factory_.InvalidateWeakPtrs();
422 bool SequencedSocketData::AllReadDataConsumed() const {
423 return helper_.AllReadDataConsumed();
426 bool SequencedSocketData::AllWriteDataConsumed() const {
427 return helper_.AllWriteDataConsumed();
430 bool SequencedSocketData::IsReadPaused() {
431 return read_state_ == PAUSED;
434 void SequencedSocketData::CompleteRead() {
435 if (read_state_ != PAUSED) {
436 ADD_FAILURE() << "Unable to CompleteRead when not paused.";
437 return;
439 read_state_ = COMPLETING;
440 OnReadComplete();
443 void SequencedSocketData::MaybePostReadCompleteTask() {
444 NET_TRACE(1, " ****** ") << " current: " << sequence_number_;
445 // Only trigger the next read to complete if there is already a read pending
446 // which should complete at the current sequence number.
447 if (read_state_ != PENDING ||
448 helper_.PeekRead().sequence_number != sequence_number_) {
449 return;
452 // If the result is ERR_IO_PENDING, then advance to the next state
453 // and pause reads.
454 if (helper_.PeekRead().result == ERR_IO_PENDING) {
455 NET_TRACE(1, " *** ") << "Pausing read at: " << sequence_number_;
456 ++sequence_number_;
457 helper_.AdvanceRead();
458 read_state_ = PAUSED;
459 return;
462 NET_TRACE(1, " ****** ") << "Posting task to complete read: "
463 << sequence_number_;
464 base::ThreadTaskRunnerHandle::Get()->PostTask(
465 FROM_HERE, base::Bind(&SequencedSocketData::OnReadComplete,
466 weak_factory_.GetWeakPtr()));
467 CHECK_NE(COMPLETING, write_state_);
468 read_state_ = COMPLETING;
471 void SequencedSocketData::MaybePostWriteCompleteTask() {
472 NET_TRACE(1, " ****** ") << " current: " << sequence_number_;
473 // Only trigger the next write to complete if there is already a write pending
474 // which should complete at the current sequence number.
475 if (write_state_ != PENDING ||
476 helper_.PeekWrite().sequence_number != sequence_number_) {
477 return;
480 NET_TRACE(1, " ****** ") << "Posting task to complete write: "
481 << sequence_number_;
482 base::ThreadTaskRunnerHandle::Get()->PostTask(
483 FROM_HERE, base::Bind(&SequencedSocketData::OnWriteComplete,
484 weak_factory_.GetWeakPtr()));
485 CHECK_NE(COMPLETING, read_state_);
486 write_state_ = COMPLETING;
489 void SequencedSocketData::OnReadComplete() {
490 CHECK_EQ(COMPLETING, read_state_);
491 NET_TRACE(1, " *** ") << "Completing read for: " << sequence_number_;
493 MockRead data = helper_.AdvanceRead();
494 DCHECK_EQ(sequence_number_, data.sequence_number);
495 sequence_number_++;
496 read_state_ = IDLE;
498 // The result of this read completing might trigger the completion
499 // of a pending write. If so, post a task to complete the write later.
500 // Since the socket may call back into the SequencedSocketData
501 // from socket()->OnReadComplete(), trigger the write task to be posted
502 // before calling that.
503 MaybePostWriteCompleteTask();
505 if (!socket()) {
506 NET_TRACE(1, " *** ") << "No socket available to complete read";
507 return;
510 NET_TRACE(1, " *** ") << "Completing socket read for: "
511 << data.sequence_number;
512 DumpMockReadWrite(data);
513 socket()->OnReadComplete(data);
514 NET_TRACE(1, " *** ") << "Done";
517 void SequencedSocketData::OnWriteComplete() {
518 CHECK_EQ(COMPLETING, write_state_);
519 NET_TRACE(1, " *** ") << " Completing write for: " << sequence_number_;
521 const MockWrite& data = helper_.AdvanceWrite();
522 DCHECK_EQ(sequence_number_, data.sequence_number);
523 sequence_number_++;
524 write_state_ = IDLE;
525 int rv = data.result == OK ? data.data_len : data.result;
527 // The result of this write completing might trigger the completion
528 // of a pending read. If so, post a task to complete the read later.
529 // Since the socket may call back into the SequencedSocketData
530 // from socket()->OnWriteComplete(), trigger the write task to be posted
531 // before calling that.
532 MaybePostReadCompleteTask();
534 if (!socket()) {
535 NET_TRACE(1, " *** ") << "No socket available to complete write";
536 return;
539 NET_TRACE(1, " *** ") << " Completing socket write for: "
540 << data.sequence_number;
541 socket()->OnWriteComplete(rv);
542 NET_TRACE(1, " *** ") << "Done";
545 SequencedSocketData::~SequencedSocketData() {
548 DeterministicSocketData::DeterministicSocketData(MockRead* reads,
549 size_t reads_count,
550 MockWrite* writes,
551 size_t writes_count)
552 : helper_(reads, reads_count, writes, writes_count),
553 sequence_number_(0),
554 current_read_(),
555 current_write_(),
556 stopping_sequence_number_(0),
557 stopped_(false),
558 print_debug_(false),
559 is_running_(false) {
560 VerifyCorrectSequenceNumbers(reads, reads_count, writes, writes_count);
563 DeterministicSocketData::~DeterministicSocketData() {}
565 void DeterministicSocketData::Run() {
566 DCHECK(!is_running_);
567 is_running_ = true;
569 SetStopped(false);
570 int counter = 0;
571 // Continue to consume data until all data has run out, or the stopped_ flag
572 // has been set. Consuming data requires two separate operations -- running
573 // the tasks in the message loop, and explicitly invoking the read/write
574 // callbacks (simulating network I/O). We check our conditions between each,
575 // since they can change in either.
576 while ((!AllWriteDataConsumed() || !AllReadDataConsumed()) && !stopped()) {
577 if (counter % 2 == 0)
578 base::RunLoop().RunUntilIdle();
579 if (counter % 2 == 1) {
580 InvokeCallbacks();
582 counter++;
584 // We're done consuming new data, but it is possible there are still some
585 // pending callbacks which we expect to complete before returning.
586 while (delegate_.get() &&
587 (delegate_->WritePending() || delegate_->ReadPending()) &&
588 !stopped()) {
589 InvokeCallbacks();
590 base::RunLoop().RunUntilIdle();
592 SetStopped(false);
593 is_running_ = false;
596 void DeterministicSocketData::RunFor(int steps) {
597 StopAfter(steps);
598 Run();
601 void DeterministicSocketData::SetStop(int seq) {
602 DCHECK_LT(sequence_number_, seq);
603 stopping_sequence_number_ = seq;
604 stopped_ = false;
607 void DeterministicSocketData::StopAfter(int seq) {
608 SetStop(sequence_number_ + seq);
611 MockRead DeterministicSocketData::OnRead() {
612 current_read_ = helper_.PeekRead();
614 // Synchronous read while stopped is an error
615 if (stopped() && current_read_.mode == SYNCHRONOUS) {
616 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
617 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
620 // Async read which will be called back in a future step.
621 if (sequence_number_ < current_read_.sequence_number) {
622 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": I/O Pending";
623 MockRead result = MockRead(SYNCHRONOUS, ERR_IO_PENDING);
624 if (current_read_.mode == SYNCHRONOUS) {
625 LOG(ERROR) << "Unable to perform synchronous read: "
626 << current_read_.sequence_number
627 << " at stage: " << sequence_number_;
628 result = MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
630 if (print_debug_)
631 DumpMockReadWrite(result);
632 return result;
635 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Read "
636 << helper_.read_index();
637 if (print_debug_)
638 DumpMockReadWrite(current_read_);
640 // Increment the sequence number if IO is complete
641 if (current_read_.mode == SYNCHRONOUS)
642 NextStep();
644 DCHECK_NE(ERR_IO_PENDING, current_read_.result);
646 helper_.AdvanceRead();
647 return current_read_;
650 MockWriteResult DeterministicSocketData::OnWrite(const std::string& data) {
651 const MockWrite& next_write = helper_.PeekWrite();
652 current_write_ = next_write;
654 // Synchronous write while stopped is an error
655 if (stopped() && next_write.mode == SYNCHRONOUS) {
656 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
657 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
660 // Async write which will be called back in a future step.
661 if (sequence_number_ < next_write.sequence_number) {
662 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": I/O Pending";
663 if (next_write.mode == SYNCHRONOUS) {
664 LOG(ERROR) << "Unable to perform synchronous write: "
665 << next_write.sequence_number << " at stage: " << sequence_number_;
666 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
668 } else {
669 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Write "
670 << helper_.write_index();
673 if (print_debug_)
674 DumpMockReadWrite(next_write);
676 // Move to the next step if I/O is synchronous, since the operation will
677 // complete when this method returns.
678 if (next_write.mode == SYNCHRONOUS)
679 NextStep();
681 // Check that what we are writing matches the expectation.
682 // Then give the mocked return value.
683 if (!helper_.VerifyWriteData(data))
684 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
686 helper_.AdvanceWrite();
688 // In the case that the write was successful, return the number of bytes
689 // written. Otherwise return the error code.
690 int result =
691 next_write.result == OK ? next_write.data_len : next_write.result;
692 return MockWriteResult(next_write.mode, result);
695 bool DeterministicSocketData::AllReadDataConsumed() const {
696 return helper_.AllReadDataConsumed();
699 bool DeterministicSocketData::AllWriteDataConsumed() const {
700 return helper_.AllWriteDataConsumed();
703 void DeterministicSocketData::InvokeCallbacks() {
704 if (delegate_.get() && delegate_->WritePending() &&
705 (current_write().sequence_number == sequence_number())) {
706 NextStep();
707 delegate_->CompleteWrite();
708 return;
710 if (delegate_.get() && delegate_->ReadPending() &&
711 (current_read().sequence_number == sequence_number())) {
712 NextStep();
713 delegate_->CompleteRead();
714 return;
718 void DeterministicSocketData::NextStep() {
719 // Invariant: Can never move *past* the stopping step.
720 DCHECK_LT(sequence_number_, stopping_sequence_number_);
721 sequence_number_++;
722 if (sequence_number_ == stopping_sequence_number_)
723 SetStopped(true);
726 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
727 MockRead* reads, size_t reads_count,
728 MockWrite* writes, size_t writes_count) {
729 size_t read = 0;
730 size_t write = 0;
731 int expected = 0;
732 while (read < reads_count || write < writes_count) {
733 // Check to see that we have a read or write at the expected
734 // state.
735 if (read < reads_count && reads[read].sequence_number == expected) {
736 ++read;
737 ++expected;
738 continue;
740 if (write < writes_count && writes[write].sequence_number == expected) {
741 ++write;
742 ++expected;
743 continue;
745 NOTREACHED() << "Missing sequence number: " << expected;
746 return;
748 DCHECK_EQ(read, reads_count);
749 DCHECK_EQ(write, writes_count);
752 MockClientSocketFactory::MockClientSocketFactory() {}
754 MockClientSocketFactory::~MockClientSocketFactory() {}
756 void MockClientSocketFactory::AddSocketDataProvider(
757 SocketDataProvider* data) {
758 mock_data_.Add(data);
761 void MockClientSocketFactory::AddSSLSocketDataProvider(
762 SSLSocketDataProvider* data) {
763 mock_ssl_data_.Add(data);
766 void MockClientSocketFactory::ResetNextMockIndexes() {
767 mock_data_.ResetNextIndex();
768 mock_ssl_data_.ResetNextIndex();
771 scoped_ptr<DatagramClientSocket>
772 MockClientSocketFactory::CreateDatagramClientSocket(
773 DatagramSocket::BindType bind_type,
774 const RandIntCallback& rand_int_cb,
775 NetLog* net_log,
776 const NetLog::Source& source) {
777 SocketDataProvider* data_provider = mock_data_.GetNext();
778 scoped_ptr<MockUDPClientSocket> socket(
779 new MockUDPClientSocket(data_provider, net_log));
780 data_provider->set_socket(socket.get());
781 if (bind_type == DatagramSocket::RANDOM_BIND)
782 socket->set_source_port(static_cast<uint16>(rand_int_cb.Run(1025, 65535)));
783 return socket.Pass();
786 scoped_ptr<StreamSocket> MockClientSocketFactory::CreateTransportClientSocket(
787 const AddressList& addresses,
788 NetLog* net_log,
789 const NetLog::Source& source) {
790 SocketDataProvider* data_provider = mock_data_.GetNext();
791 scoped_ptr<MockTCPClientSocket> socket(
792 new MockTCPClientSocket(addresses, net_log, data_provider));
793 data_provider->set_socket(socket.get());
794 return socket.Pass();
797 scoped_ptr<SSLClientSocket> MockClientSocketFactory::CreateSSLClientSocket(
798 scoped_ptr<ClientSocketHandle> transport_socket,
799 const HostPortPair& host_and_port,
800 const SSLConfig& ssl_config,
801 const SSLClientSocketContext& context) {
802 SSLSocketDataProvider* next_ssl_data = mock_ssl_data_.GetNext();
803 if (!next_ssl_data->next_protos_expected_in_ssl_config.empty()) {
804 EXPECT_EQ(next_ssl_data->next_protos_expected_in_ssl_config.size(),
805 ssl_config.next_protos.size());
806 EXPECT_TRUE(
807 std::equal(next_ssl_data->next_protos_expected_in_ssl_config.begin(),
808 next_ssl_data->next_protos_expected_in_ssl_config.end(),
809 ssl_config.next_protos.begin()));
811 return scoped_ptr<SSLClientSocket>(new MockSSLClientSocket(
812 transport_socket.Pass(), host_and_port, ssl_config, next_ssl_data));
815 void MockClientSocketFactory::ClearSSLSessionCache() {
818 const char MockClientSocket::kTlsUnique[] = "MOCK_TLSUNIQ";
820 MockClientSocket::MockClientSocket(const BoundNetLog& net_log)
821 : connected_(false),
822 net_log_(net_log),
823 weak_factory_(this) {
824 IPAddressNumber ip;
825 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
826 peer_addr_ = IPEndPoint(ip, 0);
829 int MockClientSocket::SetReceiveBufferSize(int32 size) {
830 return OK;
833 int MockClientSocket::SetSendBufferSize(int32 size) {
834 return OK;
837 void MockClientSocket::Disconnect() {
838 connected_ = false;
841 bool MockClientSocket::IsConnected() const {
842 return connected_;
845 bool MockClientSocket::IsConnectedAndIdle() const {
846 return connected_;
849 int MockClientSocket::GetPeerAddress(IPEndPoint* address) const {
850 if (!IsConnected())
851 return ERR_SOCKET_NOT_CONNECTED;
852 *address = peer_addr_;
853 return OK;
856 int MockClientSocket::GetLocalAddress(IPEndPoint* address) const {
857 IPAddressNumber ip;
858 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
859 CHECK(rv);
860 *address = IPEndPoint(ip, 123);
861 return OK;
864 const BoundNetLog& MockClientSocket::NetLog() const {
865 return net_log_;
868 void MockClientSocket::GetConnectionAttempts(ConnectionAttempts* out) const {
869 out->clear();
872 void MockClientSocket::GetSSLCertRequestInfo(
873 SSLCertRequestInfo* cert_request_info) {
876 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece& label,
877 bool has_context,
878 const base::StringPiece& context,
879 unsigned char* out,
880 unsigned int outlen) {
881 memset(out, 'A', outlen);
882 return OK;
885 int MockClientSocket::GetTLSUniqueChannelBinding(std::string* out) {
886 out->assign(MockClientSocket::kTlsUnique);
887 return OK;
890 ChannelIDService* MockClientSocket::GetChannelIDService() const {
891 NOTREACHED();
892 return NULL;
895 SSLFailureState MockClientSocket::GetSSLFailureState() const {
896 return IsConnected() ? SSL_FAILURE_NONE : SSL_FAILURE_UNKNOWN;
899 SSLClientSocket::NextProtoStatus MockClientSocket::GetNextProto(
900 std::string* proto) const {
901 proto->clear();
902 return SSLClientSocket::kNextProtoUnsupported;
905 MockClientSocket::~MockClientSocket() {}
907 void MockClientSocket::RunCallbackAsync(const CompletionCallback& callback,
908 int result) {
909 base::ThreadTaskRunnerHandle::Get()->PostTask(
910 FROM_HERE, base::Bind(&MockClientSocket::RunCallback,
911 weak_factory_.GetWeakPtr(), callback, result));
914 void MockClientSocket::RunCallback(const CompletionCallback& callback,
915 int result) {
916 if (!callback.is_null())
917 callback.Run(result);
920 MockTCPClientSocket::MockTCPClientSocket(const AddressList& addresses,
921 net::NetLog* net_log,
922 SocketDataProvider* data)
923 : MockClientSocket(BoundNetLog::Make(net_log, NetLog::SOURCE_NONE)),
924 addresses_(addresses),
925 data_(data),
926 read_offset_(0),
927 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
928 need_read_data_(true),
929 peer_closed_connection_(false),
930 pending_read_buf_(NULL),
931 pending_read_buf_len_(0),
932 was_used_to_convey_data_(false) {
933 DCHECK(data_);
934 peer_addr_ = data->connect_data().peer_addr;
935 data_->Reset();
938 MockTCPClientSocket::~MockTCPClientSocket() {}
940 int MockTCPClientSocket::Read(IOBuffer* buf, int buf_len,
941 const CompletionCallback& callback) {
942 if (!connected_)
943 return ERR_UNEXPECTED;
945 // If the buffer is already in use, a read is already in progress!
946 DCHECK(pending_read_buf_.get() == NULL);
948 // Store our async IO data.
949 pending_read_buf_ = buf;
950 pending_read_buf_len_ = buf_len;
951 pending_read_callback_ = callback;
953 if (need_read_data_) {
954 read_data_ = data_->OnRead();
955 if (read_data_.result == ERR_CONNECTION_CLOSED) {
956 // This MockRead is just a marker to instruct us to set
957 // peer_closed_connection_.
958 peer_closed_connection_ = true;
960 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
961 // This MockRead is just a marker to instruct us to set
962 // peer_closed_connection_. Skip it and get the next one.
963 read_data_ = data_->OnRead();
964 peer_closed_connection_ = true;
966 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
967 // to complete the async IO manually later (via OnReadComplete).
968 if (read_data_.result == ERR_IO_PENDING) {
969 // We need to be using async IO in this case.
970 DCHECK(!callback.is_null());
971 return ERR_IO_PENDING;
973 need_read_data_ = false;
976 return CompleteRead();
979 int MockTCPClientSocket::Write(IOBuffer* buf, int buf_len,
980 const CompletionCallback& callback) {
981 DCHECK(buf);
982 DCHECK_GT(buf_len, 0);
984 if (!connected_)
985 return ERR_UNEXPECTED;
987 std::string data(buf->data(), buf_len);
988 MockWriteResult write_result = data_->OnWrite(data);
990 was_used_to_convey_data_ = true;
992 // ERR_IO_PENDING is a signal that the socket data will call back
993 // asynchronously later.
994 if (write_result.result == ERR_IO_PENDING) {
995 pending_write_callback_ = callback;
996 return ERR_IO_PENDING;
999 // TODO(rch): remove this once OrderedSocketData and DelayedSocketData
1000 // have been removed.
1001 if (write_result.mode == ASYNC) {
1002 RunCallbackAsync(callback, write_result.result);
1003 return ERR_IO_PENDING;
1006 return write_result.result;
1009 void MockTCPClientSocket::GetConnectionAttempts(ConnectionAttempts* out) const {
1010 int connect_result = data_->connect_data().result;
1012 out->clear();
1013 if (connected_ && connect_result != OK)
1014 out->push_back(ConnectionAttempt(addresses_[0], connect_result));
1017 void MockTCPClientSocket::ClearConnectionAttempts() {
1018 NOTIMPLEMENTED();
1021 void MockTCPClientSocket::AddConnectionAttempts(const ConnectionAttempts& in) {
1022 NOTIMPLEMENTED();
1025 int MockTCPClientSocket::Connect(const CompletionCallback& callback) {
1026 if (connected_)
1027 return OK;
1028 connected_ = true;
1029 peer_closed_connection_ = false;
1030 if (data_->connect_data().mode == ASYNC) {
1031 if (data_->connect_data().result == ERR_IO_PENDING)
1032 pending_read_callback_ = callback;
1033 else
1034 RunCallbackAsync(callback, data_->connect_data().result);
1035 return ERR_IO_PENDING;
1037 return data_->connect_data().result;
1040 void MockTCPClientSocket::Disconnect() {
1041 MockClientSocket::Disconnect();
1042 pending_read_callback_.Reset();
1045 bool MockTCPClientSocket::IsConnected() const {
1046 return connected_ && !peer_closed_connection_;
1049 bool MockTCPClientSocket::IsConnectedAndIdle() const {
1050 return IsConnected();
1053 int MockTCPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1054 if (addresses_.empty())
1055 return MockClientSocket::GetPeerAddress(address);
1057 *address = addresses_[0];
1058 return OK;
1061 bool MockTCPClientSocket::WasEverUsed() const {
1062 return was_used_to_convey_data_;
1065 bool MockTCPClientSocket::UsingTCPFastOpen() const {
1066 return false;
1069 bool MockTCPClientSocket::WasNpnNegotiated() const {
1070 return false;
1073 bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1074 return false;
1077 void MockTCPClientSocket::OnReadComplete(const MockRead& data) {
1078 // There must be a read pending.
1079 DCHECK(pending_read_buf_.get());
1080 // You can't complete a read with another ERR_IO_PENDING status code.
1081 DCHECK_NE(ERR_IO_PENDING, data.result);
1082 // Since we've been waiting for data, need_read_data_ should be true.
1083 DCHECK(need_read_data_);
1085 read_data_ = data;
1086 need_read_data_ = false;
1088 // The caller is simulating that this IO completes right now. Don't
1089 // let CompleteRead() schedule a callback.
1090 read_data_.mode = SYNCHRONOUS;
1092 CompletionCallback callback = pending_read_callback_;
1093 int rv = CompleteRead();
1094 RunCallback(callback, rv);
1097 void MockTCPClientSocket::OnWriteComplete(int rv) {
1098 // There must be a read pending.
1099 DCHECK(!pending_write_callback_.is_null());
1100 CompletionCallback callback = pending_write_callback_;
1101 RunCallback(callback, rv);
1104 void MockTCPClientSocket::OnConnectComplete(const MockConnect& data) {
1105 CompletionCallback callback = pending_read_callback_;
1106 RunCallback(callback, data.result);
1109 int MockTCPClientSocket::CompleteRead() {
1110 DCHECK(pending_read_buf_.get());
1111 DCHECK(pending_read_buf_len_ > 0);
1113 was_used_to_convey_data_ = true;
1115 // Save the pending async IO data and reset our |pending_| state.
1116 scoped_refptr<IOBuffer> buf = pending_read_buf_;
1117 int buf_len = pending_read_buf_len_;
1118 CompletionCallback callback = pending_read_callback_;
1119 pending_read_buf_ = NULL;
1120 pending_read_buf_len_ = 0;
1121 pending_read_callback_.Reset();
1123 int result = read_data_.result;
1124 DCHECK(result != ERR_IO_PENDING);
1126 if (read_data_.data) {
1127 if (read_data_.data_len - read_offset_ > 0) {
1128 result = std::min(buf_len, read_data_.data_len - read_offset_);
1129 memcpy(buf->data(), read_data_.data + read_offset_, result);
1130 read_offset_ += result;
1131 if (read_offset_ == read_data_.data_len) {
1132 need_read_data_ = true;
1133 read_offset_ = 0;
1135 } else {
1136 result = 0; // EOF
1140 if (read_data_.mode == ASYNC) {
1141 DCHECK(!callback.is_null());
1142 RunCallbackAsync(callback, result);
1143 return ERR_IO_PENDING;
1145 return result;
1148 DeterministicSocketHelper::DeterministicSocketHelper(
1149 NetLog* net_log,
1150 DeterministicSocketData* data)
1151 : write_pending_(false),
1152 write_result_(0),
1153 read_data_(),
1154 read_buf_(NULL),
1155 read_buf_len_(0),
1156 read_pending_(false),
1157 data_(data),
1158 was_used_to_convey_data_(false),
1159 peer_closed_connection_(false),
1160 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_NONE)) {
1163 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1165 void DeterministicSocketHelper::CompleteWrite() {
1166 was_used_to_convey_data_ = true;
1167 write_pending_ = false;
1168 write_callback_.Run(write_result_);
1171 int DeterministicSocketHelper::CompleteRead() {
1172 DCHECK_GT(read_buf_len_, 0);
1173 DCHECK_LE(read_data_.data_len, read_buf_len_);
1174 DCHECK(read_buf_);
1176 was_used_to_convey_data_ = true;
1178 if (read_data_.result == ERR_IO_PENDING)
1179 read_data_ = data_->OnRead();
1180 DCHECK_NE(ERR_IO_PENDING, read_data_.result);
1181 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1182 // the callback. Therefore we don't even bother to check it.
1183 int result = read_data_.result;
1185 if (read_data_.data_len > 0) {
1186 DCHECK(read_data_.data);
1187 result = std::min(read_buf_len_, read_data_.data_len);
1188 memcpy(read_buf_->data(), read_data_.data, result);
1191 if (read_pending_) {
1192 read_pending_ = false;
1193 read_callback_.Run(result);
1196 return result;
1199 int DeterministicSocketHelper::Write(
1200 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1201 DCHECK(buf);
1202 DCHECK_GT(buf_len, 0);
1204 std::string data(buf->data(), buf_len);
1205 MockWriteResult write_result = data_->OnWrite(data);
1207 if (write_result.mode == ASYNC) {
1208 write_callback_ = callback;
1209 write_result_ = write_result.result;
1210 DCHECK(!write_callback_.is_null());
1211 write_pending_ = true;
1212 return ERR_IO_PENDING;
1215 was_used_to_convey_data_ = true;
1216 write_pending_ = false;
1217 return write_result.result;
1220 int DeterministicSocketHelper::Read(
1221 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1222 read_data_ = data_->OnRead();
1223 // The buffer should always be big enough to contain all the MockRead data. To
1224 // use small buffers, split the data into multiple MockReads.
1225 DCHECK_LE(read_data_.data_len, buf_len);
1227 if (read_data_.result == ERR_CONNECTION_CLOSED) {
1228 // This MockRead is just a marker to instruct us to set
1229 // peer_closed_connection_.
1230 peer_closed_connection_ = true;
1232 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
1233 // This MockRead is just a marker to instruct us to set
1234 // peer_closed_connection_. Skip it and get the next one.
1235 read_data_ = data_->OnRead();
1236 peer_closed_connection_ = true;
1239 read_buf_ = buf;
1240 read_buf_len_ = buf_len;
1241 read_callback_ = callback;
1243 if (read_data_.mode == ASYNC || (read_data_.result == ERR_IO_PENDING)) {
1244 read_pending_ = true;
1245 DCHECK(!read_callback_.is_null());
1246 return ERR_IO_PENDING;
1249 was_used_to_convey_data_ = true;
1250 return CompleteRead();
1253 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1254 net::NetLog* net_log,
1255 DeterministicSocketData* data)
1256 : connected_(false),
1257 helper_(net_log, data),
1258 source_port_(123) {
1261 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1263 bool DeterministicMockUDPClientSocket::WritePending() const {
1264 return helper_.write_pending();
1267 bool DeterministicMockUDPClientSocket::ReadPending() const {
1268 return helper_.read_pending();
1271 void DeterministicMockUDPClientSocket::CompleteWrite() {
1272 helper_.CompleteWrite();
1275 int DeterministicMockUDPClientSocket::CompleteRead() {
1276 return helper_.CompleteRead();
1279 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint& address) {
1280 if (connected_)
1281 return OK;
1282 connected_ = true;
1283 peer_address_ = address;
1284 return helper_.data()->connect_data().result;
1287 int DeterministicMockUDPClientSocket::Write(
1288 IOBuffer* buf,
1289 int buf_len,
1290 const CompletionCallback& callback) {
1291 if (!connected_)
1292 return ERR_UNEXPECTED;
1294 return helper_.Write(buf, buf_len, callback);
1297 int DeterministicMockUDPClientSocket::Read(
1298 IOBuffer* buf,
1299 int buf_len,
1300 const CompletionCallback& callback) {
1301 if (!connected_)
1302 return ERR_UNEXPECTED;
1304 return helper_.Read(buf, buf_len, callback);
1307 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1308 return OK;
1311 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size) {
1312 return OK;
1315 void DeterministicMockUDPClientSocket::Close() {
1316 connected_ = false;
1319 int DeterministicMockUDPClientSocket::GetPeerAddress(
1320 IPEndPoint* address) const {
1321 *address = peer_address_;
1322 return OK;
1325 int DeterministicMockUDPClientSocket::GetLocalAddress(
1326 IPEndPoint* address) const {
1327 IPAddressNumber ip;
1328 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1329 CHECK(rv);
1330 *address = IPEndPoint(ip, source_port_);
1331 return OK;
1334 const BoundNetLog& DeterministicMockUDPClientSocket::NetLog() const {
1335 return helper_.net_log();
1338 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1339 net::NetLog* net_log,
1340 DeterministicSocketData* data)
1341 : MockClientSocket(BoundNetLog::Make(net_log, NetLog::SOURCE_NONE)),
1342 helper_(net_log, data) {
1343 peer_addr_ = data->connect_data().peer_addr;
1346 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1348 bool DeterministicMockTCPClientSocket::WritePending() const {
1349 return helper_.write_pending();
1352 bool DeterministicMockTCPClientSocket::ReadPending() const {
1353 return helper_.read_pending();
1356 void DeterministicMockTCPClientSocket::CompleteWrite() {
1357 helper_.CompleteWrite();
1360 int DeterministicMockTCPClientSocket::CompleteRead() {
1361 return helper_.CompleteRead();
1364 int DeterministicMockTCPClientSocket::Write(
1365 IOBuffer* buf,
1366 int buf_len,
1367 const CompletionCallback& callback) {
1368 if (!connected_)
1369 return ERR_UNEXPECTED;
1371 return helper_.Write(buf, buf_len, callback);
1374 int DeterministicMockTCPClientSocket::Read(
1375 IOBuffer* buf,
1376 int buf_len,
1377 const CompletionCallback& callback) {
1378 if (!connected_)
1379 return ERR_UNEXPECTED;
1381 return helper_.Read(buf, buf_len, callback);
1384 // TODO(erikchen): Support connect sequencing.
1385 int DeterministicMockTCPClientSocket::Connect(
1386 const CompletionCallback& callback) {
1387 if (connected_)
1388 return OK;
1389 connected_ = true;
1390 if (helper_.data()->connect_data().mode == ASYNC) {
1391 RunCallbackAsync(callback, helper_.data()->connect_data().result);
1392 return ERR_IO_PENDING;
1394 return helper_.data()->connect_data().result;
1397 void DeterministicMockTCPClientSocket::Disconnect() {
1398 MockClientSocket::Disconnect();
1401 bool DeterministicMockTCPClientSocket::IsConnected() const {
1402 return connected_ && !helper_.peer_closed_connection();
1405 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1406 return IsConnected();
1409 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1410 return helper_.was_used_to_convey_data();
1413 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1414 return false;
1417 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1418 return false;
1421 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1422 return false;
1425 // static
1426 void MockSSLClientSocket::ConnectCallback(
1427 MockSSLClientSocket* ssl_client_socket,
1428 const CompletionCallback& callback,
1429 int rv) {
1430 if (rv == OK)
1431 ssl_client_socket->connected_ = true;
1432 callback.Run(rv);
1435 MockSSLClientSocket::MockSSLClientSocket(
1436 scoped_ptr<ClientSocketHandle> transport_socket,
1437 const HostPortPair& host_port_pair,
1438 const SSLConfig& ssl_config,
1439 SSLSocketDataProvider* data)
1440 : MockClientSocket(
1441 // Have to use the right BoundNetLog for LoadTimingInfo regression
1442 // tests.
1443 transport_socket->socket()->NetLog()),
1444 transport_(transport_socket.Pass()),
1445 data_(data) {
1446 DCHECK(data_);
1447 peer_addr_ = data->connect.peer_addr;
1450 MockSSLClientSocket::~MockSSLClientSocket() {
1451 Disconnect();
1454 int MockSSLClientSocket::Read(IOBuffer* buf, int buf_len,
1455 const CompletionCallback& callback) {
1456 return transport_->socket()->Read(buf, buf_len, callback);
1459 int MockSSLClientSocket::Write(IOBuffer* buf, int buf_len,
1460 const CompletionCallback& callback) {
1461 return transport_->socket()->Write(buf, buf_len, callback);
1464 int MockSSLClientSocket::Connect(const CompletionCallback& callback) {
1465 int rv = transport_->socket()->Connect(
1466 base::Bind(&ConnectCallback, base::Unretained(this), callback));
1467 if (rv == OK) {
1468 if (data_->connect.result == OK)
1469 connected_ = true;
1470 if (data_->connect.mode == ASYNC) {
1471 RunCallbackAsync(callback, data_->connect.result);
1472 return ERR_IO_PENDING;
1474 return data_->connect.result;
1476 return rv;
1479 void MockSSLClientSocket::Disconnect() {
1480 MockClientSocket::Disconnect();
1481 if (transport_->socket() != NULL)
1482 transport_->socket()->Disconnect();
1485 bool MockSSLClientSocket::IsConnected() const {
1486 return transport_->socket()->IsConnected();
1489 bool MockSSLClientSocket::WasEverUsed() const {
1490 return transport_->socket()->WasEverUsed();
1493 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1494 return transport_->socket()->UsingTCPFastOpen();
1497 int MockSSLClientSocket::GetPeerAddress(IPEndPoint* address) const {
1498 return transport_->socket()->GetPeerAddress(address);
1501 bool MockSSLClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1502 ssl_info->Reset();
1503 ssl_info->cert = data_->cert;
1504 ssl_info->client_cert_sent = data_->client_cert_sent;
1505 ssl_info->channel_id_sent = data_->channel_id_sent;
1506 ssl_info->connection_status = data_->connection_status;
1507 return true;
1510 void MockSSLClientSocket::GetSSLCertRequestInfo(
1511 SSLCertRequestInfo* cert_request_info) {
1512 DCHECK(cert_request_info);
1513 if (data_->cert_request_info) {
1514 cert_request_info->host_and_port =
1515 data_->cert_request_info->host_and_port;
1516 cert_request_info->client_certs = data_->cert_request_info->client_certs;
1517 } else {
1518 cert_request_info->Reset();
1522 SSLClientSocket::NextProtoStatus MockSSLClientSocket::GetNextProto(
1523 std::string* proto) const {
1524 *proto = data_->next_proto;
1525 return data_->next_proto_status;
1528 ChannelIDService* MockSSLClientSocket::GetChannelIDService() const {
1529 return data_->channel_id_service;
1532 void MockSSLClientSocket::OnReadComplete(const MockRead& data) {
1533 NOTIMPLEMENTED();
1536 void MockSSLClientSocket::OnWriteComplete(int rv) {
1537 NOTIMPLEMENTED();
1540 void MockSSLClientSocket::OnConnectComplete(const MockConnect& data) {
1541 NOTIMPLEMENTED();
1544 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data,
1545 net::NetLog* net_log)
1546 : connected_(false),
1547 data_(data),
1548 read_offset_(0),
1549 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
1550 need_read_data_(true),
1551 source_port_(123),
1552 pending_read_buf_(NULL),
1553 pending_read_buf_len_(0),
1554 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_NONE)),
1555 weak_factory_(this) {
1556 DCHECK(data_);
1557 data_->Reset();
1558 peer_addr_ = data->connect_data().peer_addr;
1561 MockUDPClientSocket::~MockUDPClientSocket() {}
1563 int MockUDPClientSocket::Read(IOBuffer* buf,
1564 int buf_len,
1565 const CompletionCallback& callback) {
1566 if (!connected_)
1567 return ERR_UNEXPECTED;
1569 // If the buffer is already in use, a read is already in progress!
1570 DCHECK(pending_read_buf_.get() == NULL);
1572 // Store our async IO data.
1573 pending_read_buf_ = buf;
1574 pending_read_buf_len_ = buf_len;
1575 pending_read_callback_ = callback;
1577 if (need_read_data_) {
1578 read_data_ = data_->OnRead();
1579 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1580 // to complete the async IO manually later (via OnReadComplete).
1581 if (read_data_.result == ERR_IO_PENDING) {
1582 // We need to be using async IO in this case.
1583 DCHECK(!callback.is_null());
1584 return ERR_IO_PENDING;
1586 need_read_data_ = false;
1589 return CompleteRead();
1592 int MockUDPClientSocket::Write(IOBuffer* buf, int buf_len,
1593 const CompletionCallback& callback) {
1594 DCHECK(buf);
1595 DCHECK_GT(buf_len, 0);
1597 if (!connected_)
1598 return ERR_UNEXPECTED;
1600 std::string data(buf->data(), buf_len);
1601 MockWriteResult write_result = data_->OnWrite(data);
1603 // ERR_IO_PENDING is a signal that the socket data will call back
1604 // asynchronously.
1605 if (write_result.result == ERR_IO_PENDING) {
1606 pending_write_callback_ = callback;
1607 return ERR_IO_PENDING;
1609 if (write_result.mode == ASYNC) {
1610 RunCallbackAsync(callback, write_result.result);
1611 return ERR_IO_PENDING;
1613 return write_result.result;
1616 int MockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1617 return OK;
1620 int MockUDPClientSocket::SetSendBufferSize(int32 size) {
1621 return OK;
1624 void MockUDPClientSocket::Close() {
1625 connected_ = false;
1628 int MockUDPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1629 *address = peer_addr_;
1630 return OK;
1633 int MockUDPClientSocket::GetLocalAddress(IPEndPoint* address) const {
1634 IPAddressNumber ip;
1635 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1636 CHECK(rv);
1637 *address = IPEndPoint(ip, source_port_);
1638 return OK;
1641 const BoundNetLog& MockUDPClientSocket::NetLog() const {
1642 return net_log_;
1645 int MockUDPClientSocket::Connect(const IPEndPoint& address) {
1646 connected_ = true;
1647 peer_addr_ = address;
1648 return data_->connect_data().result;
1651 void MockUDPClientSocket::OnReadComplete(const MockRead& data) {
1652 // There must be a read pending.
1653 DCHECK(pending_read_buf_.get());
1654 // You can't complete a read with another ERR_IO_PENDING status code.
1655 DCHECK_NE(ERR_IO_PENDING, data.result);
1656 // Since we've been waiting for data, need_read_data_ should be true.
1657 DCHECK(need_read_data_);
1659 read_data_ = data;
1660 need_read_data_ = false;
1662 // The caller is simulating that this IO completes right now. Don't
1663 // let CompleteRead() schedule a callback.
1664 read_data_.mode = SYNCHRONOUS;
1666 CompletionCallback callback = pending_read_callback_;
1667 int rv = CompleteRead();
1668 RunCallback(callback, rv);
1671 void MockUDPClientSocket::OnWriteComplete(int rv) {
1672 // There must be a read pending.
1673 DCHECK(!pending_write_callback_.is_null());
1674 CompletionCallback callback = pending_write_callback_;
1675 RunCallback(callback, rv);
1678 void MockUDPClientSocket::OnConnectComplete(const MockConnect& data) {
1679 NOTIMPLEMENTED();
1682 int MockUDPClientSocket::CompleteRead() {
1683 DCHECK(pending_read_buf_.get());
1684 DCHECK(pending_read_buf_len_ > 0);
1686 // Save the pending async IO data and reset our |pending_| state.
1687 scoped_refptr<IOBuffer> buf = pending_read_buf_;
1688 int buf_len = pending_read_buf_len_;
1689 CompletionCallback callback = pending_read_callback_;
1690 pending_read_buf_ = NULL;
1691 pending_read_buf_len_ = 0;
1692 pending_read_callback_.Reset();
1694 int result = read_data_.result;
1695 DCHECK(result != ERR_IO_PENDING);
1697 if (read_data_.data) {
1698 if (read_data_.data_len - read_offset_ > 0) {
1699 result = std::min(buf_len, read_data_.data_len - read_offset_);
1700 memcpy(buf->data(), read_data_.data + read_offset_, result);
1701 read_offset_ += result;
1702 if (read_offset_ == read_data_.data_len) {
1703 need_read_data_ = true;
1704 read_offset_ = 0;
1706 } else {
1707 result = 0; // EOF
1711 if (read_data_.mode == ASYNC) {
1712 DCHECK(!callback.is_null());
1713 RunCallbackAsync(callback, result);
1714 return ERR_IO_PENDING;
1716 return result;
1719 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback& callback,
1720 int result) {
1721 base::ThreadTaskRunnerHandle::Get()->PostTask(
1722 FROM_HERE, base::Bind(&MockUDPClientSocket::RunCallback,
1723 weak_factory_.GetWeakPtr(), callback, result));
1726 void MockUDPClientSocket::RunCallback(const CompletionCallback& callback,
1727 int result) {
1728 if (!callback.is_null())
1729 callback.Run(result);
1732 TestSocketRequest::TestSocketRequest(
1733 std::vector<TestSocketRequest*>* request_order, size_t* completion_count)
1734 : request_order_(request_order),
1735 completion_count_(completion_count),
1736 callback_(base::Bind(&TestSocketRequest::OnComplete,
1737 base::Unretained(this))) {
1738 DCHECK(request_order);
1739 DCHECK(completion_count);
1742 TestSocketRequest::~TestSocketRequest() {
1745 void TestSocketRequest::OnComplete(int result) {
1746 SetResult(result);
1747 (*completion_count_)++;
1748 request_order_->push_back(this);
1751 // static
1752 const int ClientSocketPoolTest::kIndexOutOfBounds = -1;
1754 // static
1755 const int ClientSocketPoolTest::kRequestNotFound = -2;
1757 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1758 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1760 int ClientSocketPoolTest::GetOrderOfRequest(size_t index) const {
1761 index--;
1762 if (index >= requests_.size())
1763 return kIndexOutOfBounds;
1765 for (size_t i = 0; i < request_order_.size(); i++)
1766 if (requests_[index] == request_order_[i])
1767 return i + 1;
1769 return kRequestNotFound;
1772 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
1773 ScopedVector<TestSocketRequest>::iterator i;
1774 for (i = requests_.begin(); i != requests_.end(); ++i) {
1775 if ((*i)->handle()->is_initialized()) {
1776 if (keep_alive == NO_KEEP_ALIVE)
1777 (*i)->handle()->socket()->Disconnect();
1778 (*i)->handle()->Reset();
1779 base::RunLoop().RunUntilIdle();
1780 return true;
1783 return false;
1786 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
1787 bool released_one;
1788 do {
1789 released_one = ReleaseOneConnection(keep_alive);
1790 } while (released_one);
1793 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1794 scoped_ptr<StreamSocket> socket,
1795 ClientSocketHandle* handle,
1796 const CompletionCallback& callback)
1797 : socket_(socket.Pass()),
1798 handle_(handle),
1799 user_callback_(callback) {
1802 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1804 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1805 int rv = socket_->Connect(base::Bind(&MockConnectJob::OnConnect,
1806 base::Unretained(this)));
1807 if (rv != ERR_IO_PENDING) {
1808 user_callback_.Reset();
1809 OnConnect(rv);
1811 return rv;
1814 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1815 const ClientSocketHandle* handle) {
1816 if (handle != handle_)
1817 return false;
1818 socket_.reset();
1819 handle_ = NULL;
1820 user_callback_.Reset();
1821 return true;
1824 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) {
1825 if (!socket_.get())
1826 return;
1827 if (rv == OK) {
1828 handle_->SetSocket(socket_.Pass());
1830 // Needed for socket pool tests that layer other sockets on top of mock
1831 // sockets.
1832 LoadTimingInfo::ConnectTiming connect_timing;
1833 base::TimeTicks now = base::TimeTicks::Now();
1834 connect_timing.dns_start = now;
1835 connect_timing.dns_end = now;
1836 connect_timing.connect_start = now;
1837 connect_timing.connect_end = now;
1838 handle_->set_connect_timing(connect_timing);
1839 } else {
1840 socket_.reset();
1842 // Needed to test copying of ConnectionAttempts in SSL ConnectJob.
1843 ConnectionAttempts attempts;
1844 attempts.push_back(ConnectionAttempt(IPEndPoint(), rv));
1845 handle_->set_connection_attempts(attempts);
1848 handle_ = NULL;
1850 if (!user_callback_.is_null()) {
1851 CompletionCallback callback = user_callback_;
1852 user_callback_.Reset();
1853 callback.Run(rv);
1857 MockTransportClientSocketPool::MockTransportClientSocketPool(
1858 int max_sockets,
1859 int max_sockets_per_group,
1860 ClientSocketFactory* socket_factory)
1861 : TransportClientSocketPool(max_sockets,
1862 max_sockets_per_group,
1863 NULL,
1864 NULL,
1865 NULL),
1866 client_socket_factory_(socket_factory),
1867 last_request_priority_(DEFAULT_PRIORITY),
1868 release_count_(0),
1869 cancel_count_(0) {
1872 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
1874 int MockTransportClientSocketPool::RequestSocket(
1875 const std::string& group_name, const void* socket_params,
1876 RequestPriority priority, ClientSocketHandle* handle,
1877 const CompletionCallback& callback, const BoundNetLog& net_log) {
1878 last_request_priority_ = priority;
1879 scoped_ptr<StreamSocket> socket =
1880 client_socket_factory_->CreateTransportClientSocket(
1881 AddressList(), net_log.net_log(), NetLog::Source());
1882 MockConnectJob* job = new MockConnectJob(socket.Pass(), handle, callback);
1883 job_list_.push_back(job);
1884 handle->set_pool_id(1);
1885 return job->Connect();
1888 void MockTransportClientSocketPool::CancelRequest(const std::string& group_name,
1889 ClientSocketHandle* handle) {
1890 std::vector<MockConnectJob*>::iterator i;
1891 for (i = job_list_.begin(); i != job_list_.end(); ++i) {
1892 if ((*i)->CancelHandle(handle)) {
1893 cancel_count_++;
1894 break;
1899 void MockTransportClientSocketPool::ReleaseSocket(
1900 const std::string& group_name,
1901 scoped_ptr<StreamSocket> socket,
1902 int id) {
1903 EXPECT_EQ(1, id);
1904 release_count_++;
1907 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
1909 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
1911 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
1912 DeterministicSocketData* data) {
1913 mock_data_.Add(data);
1916 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
1917 SSLSocketDataProvider* data) {
1918 mock_ssl_data_.Add(data);
1921 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
1922 mock_data_.ResetNextIndex();
1923 mock_ssl_data_.ResetNextIndex();
1926 MockSSLClientSocket* DeterministicMockClientSocketFactory::
1927 GetMockSSLClientSocket(size_t index) const {
1928 DCHECK_LT(index, ssl_client_sockets_.size());
1929 return ssl_client_sockets_[index];
1932 scoped_ptr<DatagramClientSocket>
1933 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
1934 DatagramSocket::BindType bind_type,
1935 const RandIntCallback& rand_int_cb,
1936 NetLog* net_log,
1937 const NetLog::Source& source) {
1938 DeterministicSocketData* data_provider = mock_data().GetNext();
1939 scoped_ptr<DeterministicMockUDPClientSocket> socket(
1940 new DeterministicMockUDPClientSocket(net_log, data_provider));
1941 data_provider->set_delegate(socket->AsWeakPtr());
1942 udp_client_sockets().push_back(socket.get());
1943 if (bind_type == DatagramSocket::RANDOM_BIND)
1944 socket->set_source_port(static_cast<uint16>(rand_int_cb.Run(1025, 65535)));
1945 return socket.Pass();
1948 scoped_ptr<StreamSocket>
1949 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
1950 const AddressList& addresses,
1951 NetLog* net_log,
1952 const NetLog::Source& source) {
1953 DeterministicSocketData* data_provider = mock_data().GetNext();
1954 scoped_ptr<DeterministicMockTCPClientSocket> socket(
1955 new DeterministicMockTCPClientSocket(net_log, data_provider));
1956 data_provider->set_delegate(socket->AsWeakPtr());
1957 tcp_client_sockets().push_back(socket.get());
1958 return socket.Pass();
1961 scoped_ptr<SSLClientSocket>
1962 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
1963 scoped_ptr<ClientSocketHandle> transport_socket,
1964 const HostPortPair& host_and_port,
1965 const SSLConfig& ssl_config,
1966 const SSLClientSocketContext& context) {
1967 scoped_ptr<MockSSLClientSocket> socket(
1968 new MockSSLClientSocket(transport_socket.Pass(),
1969 host_and_port, ssl_config,
1970 mock_ssl_data_.GetNext()));
1971 ssl_client_sockets_.push_back(socket.get());
1972 return socket.Pass();
1975 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
1978 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
1979 int max_sockets,
1980 int max_sockets_per_group,
1981 TransportClientSocketPool* transport_pool)
1982 : SOCKSClientSocketPool(max_sockets,
1983 max_sockets_per_group,
1984 NULL,
1985 transport_pool,
1986 NULL),
1987 transport_pool_(transport_pool) {
1990 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
1992 int MockSOCKSClientSocketPool::RequestSocket(
1993 const std::string& group_name, const void* socket_params,
1994 RequestPriority priority, ClientSocketHandle* handle,
1995 const CompletionCallback& callback, const BoundNetLog& net_log) {
1996 return transport_pool_->RequestSocket(
1997 group_name, socket_params, priority, handle, callback, net_log);
2000 void MockSOCKSClientSocketPool::CancelRequest(
2001 const std::string& group_name,
2002 ClientSocketHandle* handle) {
2003 return transport_pool_->CancelRequest(group_name, handle);
2006 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string& group_name,
2007 scoped_ptr<StreamSocket> socket,
2008 int id) {
2009 return transport_pool_->ReleaseSocket(group_name, socket.Pass(), id);
2012 ScopedWebSocketEndpointZeroUnlockDelay::
2013 ScopedWebSocketEndpointZeroUnlockDelay() {
2014 old_delay_ =
2015 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
2016 base::TimeDelta());
2019 ScopedWebSocketEndpointZeroUnlockDelay::
2020 ~ScopedWebSocketEndpointZeroUnlockDelay() {
2021 base::TimeDelta active_delay =
2022 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
2023 old_delay_);
2024 EXPECT_EQ(active_delay, base::TimeDelta());
2027 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
2028 const int kSOCKS5GreetRequestLength = arraysize(kSOCKS5GreetRequest);
2030 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
2031 const int kSOCKS5GreetResponseLength = arraysize(kSOCKS5GreetResponse);
2033 const char kSOCKS5OkRequest[] =
2034 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
2035 const int kSOCKS5OkRequestLength = arraysize(kSOCKS5OkRequest);
2037 const char kSOCKS5OkResponse[] =
2038 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
2039 const int kSOCKS5OkResponseLength = arraysize(kSOCKS5OkResponse);
2041 } // namespace net