DevTools: kill codeschool extension from whitelist
[chromium-blink-merge.git] / net / socket / socket_test_util.cc
blobb3f5040e35436fe8d0ed9d21d588758ede343617
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/logging.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/run_loop.h"
17 #include "base/time/time.h"
18 #include "net/base/address_family.h"
19 #include "net/base/address_list.h"
20 #include "net/base/auth.h"
21 #include "net/base/load_timing_info.h"
22 #include "net/http/http_network_session.h"
23 #include "net/http/http_request_headers.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/socket/socket.h"
26 #include "net/socket/websocket_endpoint_lock_manager.h"
27 #include "net/ssl/ssl_cert_request_info.h"
28 #include "net/ssl/ssl_connection_status_flags.h"
29 #include "net/ssl/ssl_info.h"
30 #include "testing/gtest/include/gtest/gtest.h"
32 #define NET_TRACE(level, s) VLOG(level) << s << __FUNCTION__ << "() "
34 namespace net {
36 namespace {
38 inline char AsciifyHigh(char x) {
39 char nybble = static_cast<char>((x >> 4) & 0x0F);
40 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
43 inline char AsciifyLow(char x) {
44 char nybble = static_cast<char>((x >> 0) & 0x0F);
45 return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
48 inline char Asciify(char x) {
49 if ((x < 0) || !isprint(x))
50 return '.';
51 return x;
54 void DumpData(const char* data, int data_len) {
55 if (logging::LOG_INFO < logging::GetMinLogLevel())
56 return;
57 DVLOG(1) << "Length: " << data_len;
58 const char* pfx = "Data: ";
59 if (!data || (data_len <= 0)) {
60 DVLOG(1) << pfx << "<None>";
61 } else {
62 int i;
63 for (i = 0; i <= (data_len - 4); i += 4) {
64 DVLOG(1) << pfx
65 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
66 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
67 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
68 << AsciifyHigh(data[i + 3]) << AsciifyLow(data[i + 3])
69 << " '"
70 << Asciify(data[i + 0])
71 << Asciify(data[i + 1])
72 << Asciify(data[i + 2])
73 << Asciify(data[i + 3])
74 << "'";
75 pfx = " ";
77 // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
78 switch (data_len - i) {
79 case 3:
80 DVLOG(1) << pfx
81 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
82 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
83 << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
84 << " '"
85 << Asciify(data[i + 0])
86 << Asciify(data[i + 1])
87 << Asciify(data[i + 2])
88 << " '";
89 break;
90 case 2:
91 DVLOG(1) << pfx
92 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
93 << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
94 << " '"
95 << Asciify(data[i + 0])
96 << Asciify(data[i + 1])
97 << " '";
98 break;
99 case 1:
100 DVLOG(1) << pfx
101 << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
102 << " '"
103 << Asciify(data[i + 0])
104 << " '";
105 break;
110 template <MockReadWriteType type>
111 void DumpMockReadWrite(const MockReadWrite<type>& r) {
112 if (logging::LOG_INFO < logging::GetMinLogLevel())
113 return;
114 DVLOG(1) << "Async: " << (r.mode == ASYNC)
115 << "\nResult: " << r.result;
116 DumpData(r.data, r.data_len);
117 const char* stop = (r.sequence_number & MockRead::STOPLOOP) ? " (STOP)" : "";
118 DVLOG(1) << "Stage: " << (r.sequence_number & ~MockRead::STOPLOOP) << stop;
121 } // namespace
123 MockConnect::MockConnect() : mode(ASYNC), result(OK) {
124 IPAddressNumber ip;
125 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
126 peer_addr = IPEndPoint(ip, 0);
129 MockConnect::MockConnect(IoMode io_mode, int r) : mode(io_mode), result(r) {
130 IPAddressNumber ip;
131 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
132 peer_addr = IPEndPoint(ip, 0);
135 MockConnect::MockConnect(IoMode io_mode, int r, IPEndPoint addr) :
136 mode(io_mode),
137 result(r),
138 peer_addr(addr) {
141 MockConnect::~MockConnect() {}
143 StaticSocketDataHelper::StaticSocketDataHelper(MockRead* reads,
144 size_t reads_count,
145 MockWrite* writes,
146 size_t writes_count)
147 : reads_(reads),
148 read_index_(0),
149 read_count_(reads_count),
150 writes_(writes),
151 write_index_(0),
152 write_count_(writes_count) {
155 StaticSocketDataHelper::~StaticSocketDataHelper() {
158 const MockRead& StaticSocketDataHelper::PeekRead() const {
159 CHECK(!at_read_eof());
160 return reads_[read_index_];
163 const MockWrite& StaticSocketDataHelper::PeekWrite() const {
164 CHECK(!at_write_eof());
165 return writes_[write_index_];
168 const MockRead& StaticSocketDataHelper::AdvanceRead() {
169 CHECK(!at_read_eof());
170 return reads_[read_index_++];
173 const MockWrite& StaticSocketDataHelper::AdvanceWrite() {
174 CHECK(!at_write_eof());
175 return writes_[write_index_++];
178 bool StaticSocketDataHelper::VerifyWriteData(const std::string& data) {
179 CHECK(!at_write_eof());
180 // Check that what the actual data matches the expectations.
181 const MockWrite& next_write = PeekWrite();
182 if (!next_write.data)
183 return true;
185 // Note: Partial writes are supported here. If the expected data
186 // is a match, but shorter than the write actually written, that is legal.
187 // Example:
188 // Application writes "foobarbaz" (9 bytes)
189 // Expected write was "foo" (3 bytes)
190 // This is a success, and the function returns true.
191 std::string expected_data(next_write.data, next_write.data_len);
192 std::string actual_data(data.substr(0, next_write.data_len));
193 EXPECT_GE(data.length(), expected_data.length());
194 EXPECT_EQ(expected_data, actual_data);
195 return expected_data == actual_data;
198 void StaticSocketDataHelper::Reset() {
199 read_index_ = 0;
200 write_index_ = 0;
203 StaticSocketDataProvider::StaticSocketDataProvider()
204 : StaticSocketDataProvider(nullptr, 0, nullptr, 0) {
207 StaticSocketDataProvider::StaticSocketDataProvider(MockRead* reads,
208 size_t reads_count,
209 MockWrite* writes,
210 size_t writes_count)
211 : helper_(reads, reads_count, writes, writes_count) {
214 StaticSocketDataProvider::~StaticSocketDataProvider() {
217 MockRead StaticSocketDataProvider::OnRead() {
218 CHECK(!helper_.at_read_eof());
219 return helper_.AdvanceRead();
222 MockWriteResult StaticSocketDataProvider::OnWrite(const std::string& data) {
223 if (helper_.write_count() == 0) {
224 // Not using mock writes; succeed synchronously.
225 return MockWriteResult(SYNCHRONOUS, data.length());
227 EXPECT_FALSE(helper_.at_write_eof());
228 if (helper_.at_write_eof()) {
229 // Show what the extra write actually consists of.
230 EXPECT_EQ("<unexpected write>", data);
231 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
234 // Check that what we are writing matches the expectation.
235 // Then give the mocked return value.
236 if (!helper_.VerifyWriteData(data))
237 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
239 const MockWrite& next_write = helper_.AdvanceWrite();
240 // In the case that the write was successful, return the number of bytes
241 // written. Otherwise return the error code.
242 int result =
243 next_write.result == OK ? next_write.data_len : next_write.result;
244 return MockWriteResult(next_write.mode, result);
247 void StaticSocketDataProvider::Reset() {
248 helper_.Reset();
251 DynamicSocketDataProvider::DynamicSocketDataProvider()
252 : short_read_limit_(0),
253 allow_unconsumed_reads_(false) {
256 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
258 MockRead DynamicSocketDataProvider::OnRead() {
259 if (reads_.empty())
260 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
261 MockRead result = reads_.front();
262 if (short_read_limit_ == 0 || result.data_len <= short_read_limit_) {
263 reads_.pop_front();
264 } else {
265 result.data_len = short_read_limit_;
266 reads_.front().data += result.data_len;
267 reads_.front().data_len -= result.data_len;
269 return result;
272 void DynamicSocketDataProvider::Reset() {
273 reads_.clear();
276 void DynamicSocketDataProvider::SimulateRead(const char* data,
277 const size_t length) {
278 if (!allow_unconsumed_reads_) {
279 EXPECT_TRUE(reads_.empty()) << "Unconsumed read: " << reads_.front().data;
281 reads_.push_back(MockRead(ASYNC, data, length));
284 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode, int result)
285 : connect(mode, result),
286 next_proto_status(SSLClientSocket::kNextProtoUnsupported),
287 was_npn_negotiated(false),
288 protocol_negotiated(kProtoUnknown),
289 client_cert_sent(false),
290 cert_request_info(NULL),
291 channel_id_sent(false),
292 connection_status(0) {
293 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2,
294 &connection_status);
295 // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
296 SSLConnectionStatusSetCipherSuite(0xcc14, &connection_status);
299 SSLSocketDataProvider::~SSLSocketDataProvider() {
302 void SSLSocketDataProvider::SetNextProto(NextProto proto) {
303 was_npn_negotiated = true;
304 next_proto_status = SSLClientSocket::kNextProtoNegotiated;
305 protocol_negotiated = proto;
306 next_proto = SSLClientSocket::NextProtoToString(proto);
309 DelayedSocketData::DelayedSocketData(
310 int write_delay, MockRead* reads, size_t reads_count,
311 MockWrite* writes, size_t writes_count)
312 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
313 write_delay_(write_delay),
314 read_in_progress_(false),
315 weak_factory_(this) {
316 DCHECK_GE(write_delay_, 0);
319 DelayedSocketData::DelayedSocketData(
320 const MockConnect& connect, int write_delay, MockRead* reads,
321 size_t reads_count, MockWrite* writes, size_t writes_count)
322 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
323 write_delay_(write_delay),
324 read_in_progress_(false),
325 weak_factory_(this) {
326 DCHECK_GE(write_delay_, 0);
327 set_connect_data(connect);
330 DelayedSocketData::~DelayedSocketData() {
333 void DelayedSocketData::ForceNextRead() {
334 DCHECK(read_in_progress_);
335 write_delay_ = 0;
336 CompleteRead();
339 MockRead DelayedSocketData::OnRead() {
340 MockRead out = MockRead(ASYNC, ERR_IO_PENDING);
341 if (write_delay_ <= 0)
342 out = StaticSocketDataProvider::OnRead();
343 read_in_progress_ = (out.result == ERR_IO_PENDING);
344 return out;
347 MockWriteResult DelayedSocketData::OnWrite(const std::string& data) {
348 MockWriteResult rv = StaticSocketDataProvider::OnWrite(data);
349 // Now that our write has completed, we can allow reads to continue.
350 if (!--write_delay_ && read_in_progress_)
351 base::MessageLoop::current()->PostDelayedTask(
352 FROM_HERE,
353 base::Bind(&DelayedSocketData::CompleteRead,
354 weak_factory_.GetWeakPtr()),
355 base::TimeDelta::FromMilliseconds(100));
356 return rv;
359 void DelayedSocketData::Reset() {
360 set_socket(NULL);
361 read_in_progress_ = false;
362 weak_factory_.InvalidateWeakPtrs();
363 StaticSocketDataProvider::Reset();
366 void DelayedSocketData::CompleteRead() {
367 if (socket() && read_in_progress_)
368 socket()->OnReadComplete(OnRead());
371 OrderedSocketData::OrderedSocketData(
372 MockRead* reads, size_t reads_count, MockWrite* writes, size_t writes_count)
373 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
374 sequence_number_(0), loop_stop_stage_(0),
375 blocked_(false), weak_factory_(this) {
378 OrderedSocketData::OrderedSocketData(
379 const MockConnect& connect,
380 MockRead* reads, size_t reads_count,
381 MockWrite* writes, size_t writes_count)
382 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
383 sequence_number_(0), loop_stop_stage_(0),
384 blocked_(false), weak_factory_(this) {
385 set_connect_data(connect);
388 void OrderedSocketData::EndLoop() {
389 // If we've already stopped the loop, don't do it again until we've advanced
390 // to the next sequence_number.
391 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": EndLoop()";
392 if (loop_stop_stage_ > 0) {
393 const MockRead& next_read = helper()->PeekRead();
394 if ((next_read.sequence_number & ~MockRead::STOPLOOP) >
395 loop_stop_stage_) {
396 NET_TRACE(1, " *** ") << "Stage " << sequence_number_
397 << ": Clearing stop index";
398 loop_stop_stage_ = 0;
399 } else {
400 return;
403 // Record the sequence_number at which we stopped the loop.
404 NET_TRACE(1, " *** ") << "Stage " << sequence_number_
405 << ": Posting Quit at read " << read_index();
406 loop_stop_stage_ = sequence_number_;
409 MockRead OrderedSocketData::OnRead() {
410 weak_factory_.InvalidateWeakPtrs();
411 blocked_ = false;
412 const MockRead& next_read = helper()->PeekRead();
413 if (next_read.sequence_number & MockRead::STOPLOOP)
414 EndLoop();
415 if ((next_read.sequence_number & ~MockRead::STOPLOOP) <=
416 sequence_number_++) {
417 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ - 1 << ": Read "
418 << read_index();
419 DumpMockReadWrite(next_read);
420 blocked_ = (next_read.result == ERR_IO_PENDING);
421 return StaticSocketDataProvider::OnRead();
423 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ - 1 << ": I/O Pending";
424 MockRead result = MockRead(ASYNC, ERR_IO_PENDING);
425 DumpMockReadWrite(result);
426 blocked_ = true;
427 return result;
430 MockWriteResult OrderedSocketData::OnWrite(const std::string& data) {
431 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Write "
432 << write_index();
433 DumpMockReadWrite(helper()->PeekWrite());
434 ++sequence_number_;
435 if (blocked_) {
436 // TODO(willchan): This 100ms delay seems to work around some weirdness. We
437 // should probably fix the weirdness. One example is in SpdyStream,
438 // DoSendRequest() will return ERR_IO_PENDING, and there's a race. If the
439 // SYN_REPLY causes OnResponseReceived() to get called before
440 // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
441 base::MessageLoop::current()->PostDelayedTask(
442 FROM_HERE,
443 base::Bind(&OrderedSocketData::CompleteRead,
444 weak_factory_.GetWeakPtr()),
445 base::TimeDelta::FromMilliseconds(100));
447 return StaticSocketDataProvider::OnWrite(data);
450 void OrderedSocketData::Reset() {
451 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Reset()";
452 sequence_number_ = 0;
453 loop_stop_stage_ = 0;
454 set_socket(NULL);
455 weak_factory_.InvalidateWeakPtrs();
456 StaticSocketDataProvider::Reset();
459 void OrderedSocketData::CompleteRead() {
460 if (socket() && blocked_) {
461 NET_TRACE(1, " *** ") << "Stage " << sequence_number_;
462 socket()->OnReadComplete(OnRead());
466 OrderedSocketData::~OrderedSocketData() {}
468 SequencedSocketData::SequencedSocketData(MockRead* reads,
469 size_t reads_count,
470 MockWrite* writes,
471 size_t writes_count)
472 : helper_(reads, reads_count, writes, writes_count),
473 sequence_number_(0),
474 read_state_(IDLE),
475 write_state_(IDLE),
476 weak_factory_(this) {
477 // Check that reads and writes have a contiguous set of sequence numbers
478 // starting from 0 and working their way up, with no repeats and skipping
479 // no values.
480 size_t next_read = 0;
481 size_t next_write = 0;
482 int next_sequence_number = 0;
483 while (next_read < reads_count || next_write < writes_count) {
484 if (next_read < reads_count &&
485 reads[next_read].sequence_number == next_sequence_number) {
486 ++next_read;
487 ++next_sequence_number;
488 continue;
490 if (next_write < writes_count &&
491 writes[next_write].sequence_number == next_sequence_number) {
492 ++next_write;
493 ++next_sequence_number;
494 continue;
496 CHECK(false) << "Sequence number not found where expected: "
497 << next_sequence_number;
498 return;
500 CHECK_EQ(next_read, reads_count);
501 CHECK_EQ(next_write, writes_count);
504 SequencedSocketData::SequencedSocketData(const MockConnect& connect,
505 MockRead* reads,
506 size_t reads_count,
507 MockWrite* writes,
508 size_t writes_count)
509 : SequencedSocketData(reads, reads_count, writes, writes_count) {
510 set_connect_data(connect);
513 MockRead SequencedSocketData::OnRead() {
514 CHECK_EQ(IDLE, read_state_);
515 CHECK(!helper_.at_read_eof());
517 NET_TRACE(1, " *** ") << "sequence_number: " << sequence_number_;
518 const MockRead& next_read = helper_.PeekRead();
519 NET_TRACE(1, " *** ") << "next_read: " << next_read.sequence_number;
520 CHECK_GE(next_read.sequence_number, sequence_number_);
522 if (next_read.sequence_number <= sequence_number_) {
523 if (next_read.mode == SYNCHRONOUS) {
524 NET_TRACE(1, " *** ") << "Returning synchronously";
525 DumpMockReadWrite(next_read);
526 helper_.AdvanceRead();
527 ++sequence_number_;
528 MaybePostWriteCompleteTask();
529 return next_read;
532 base::MessageLoop::current()->PostTask(
533 FROM_HERE, base::Bind(&SequencedSocketData::OnReadComplete,
534 weak_factory_.GetWeakPtr()));
535 CHECK_NE(COMPLETING, write_state_);
536 read_state_ = COMPLETING;
537 } else if (next_read.mode == SYNCHRONOUS) {
538 ADD_FAILURE() << "Unable to perform synchronous IO while stopped";
539 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
540 } else {
541 NET_TRACE(1, " *** ") << "Waiting for write to trigger read";
542 read_state_ = PENDING;
545 return MockRead(SYNCHRONOUS, ERR_IO_PENDING);
548 MockWriteResult SequencedSocketData::OnWrite(const std::string& data) {
549 CHECK_EQ(IDLE, write_state_);
550 CHECK(!helper_.at_write_eof());
552 NET_TRACE(1, " *** ") << "sequence_number: " << sequence_number_;
553 const MockWrite& next_write = helper_.PeekWrite();
554 NET_TRACE(1, " *** ") << "next_write: " << next_write.sequence_number;
555 CHECK_GE(next_write.sequence_number, sequence_number_);
557 if (!helper_.VerifyWriteData(data))
558 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
560 if (next_write.sequence_number <= sequence_number_) {
561 if (next_write.mode == SYNCHRONOUS) {
562 helper_.AdvanceWrite();
563 ++sequence_number_;
564 MaybePostReadCompleteTask();
565 // In the case that the write was successful, return the number of bytes
566 // written. Otherwise return the error code.
567 int rv =
568 next_write.result != OK ? next_write.result : next_write.data_len;
569 NET_TRACE(1, " *** ") << "Returning synchronously";
570 return MockWriteResult(SYNCHRONOUS, rv);
573 NET_TRACE(1, " *** ") << "Posting task to complete write";
574 base::MessageLoop::current()->PostTask(
575 FROM_HERE, base::Bind(&SequencedSocketData::OnWriteComplete,
576 weak_factory_.GetWeakPtr()));
577 CHECK_NE(COMPLETING, read_state_);
578 write_state_ = COMPLETING;
579 } else if (next_write.mode == SYNCHRONOUS) {
580 ADD_FAILURE() << "Unable to perform synchronous IO while stopped";
581 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
582 } else {
583 NET_TRACE(1, " *** ") << "Waiting for read to trigger write";
584 write_state_ = PENDING;
587 return MockWriteResult(SYNCHRONOUS, ERR_IO_PENDING);
590 void SequencedSocketData::Reset() {
591 helper_.Reset();
592 sequence_number_ = 0;
593 read_state_ = IDLE;
594 write_state_ = IDLE;
595 weak_factory_.InvalidateWeakPtrs();
598 bool SequencedSocketData::at_read_eof() {
599 return helper_.at_read_eof();
602 bool SequencedSocketData::at_write_eof() {
603 return helper_.at_read_eof();
606 void SequencedSocketData::MaybePostReadCompleteTask() {
607 NET_TRACE(1, " ****** ") << " current: " << sequence_number_;
608 // Only trigger the next read to complete if there is already a read pending
609 // which should complete at the current sequence number.
610 if (read_state_ != PENDING ||
611 helper_.PeekRead().sequence_number != sequence_number_) {
612 return;
615 NET_TRACE(1, " ****** ") << "Posting task to complete read: "
616 << sequence_number_;
617 base::MessageLoop::current()->PostTask(
618 FROM_HERE, base::Bind(&SequencedSocketData::OnReadComplete,
619 weak_factory_.GetWeakPtr()));
620 CHECK_NE(COMPLETING, write_state_);
621 read_state_ = COMPLETING;
624 void SequencedSocketData::MaybePostWriteCompleteTask() {
625 NET_TRACE(1, " ****** ") << " current: " << sequence_number_;
626 // Only trigger the next write to complete if there is already a write pending
627 // which should complete at the current sequence number.
628 if (write_state_ != PENDING ||
629 helper_.PeekWrite().sequence_number != sequence_number_) {
630 return;
633 NET_TRACE(1, " ****** ") << "Posting task to complete write: "
634 << sequence_number_;
635 base::MessageLoop::current()->PostTask(
636 FROM_HERE, base::Bind(&SequencedSocketData::OnWriteComplete,
637 weak_factory_.GetWeakPtr()));
638 CHECK_NE(COMPLETING, read_state_);
639 write_state_ = COMPLETING;
642 void SequencedSocketData::OnReadComplete() {
643 CHECK_EQ(COMPLETING, read_state_);
644 NET_TRACE(1, " *** ") << "Completing read for: " << sequence_number_;
645 if (!socket()) {
646 NET_TRACE(1, " *** ") << "No socket available to complete read";
647 return;
650 MockRead data = helper_.AdvanceRead();
651 DCHECK_EQ(sequence_number_, data.sequence_number);
652 sequence_number_++;
653 read_state_ = IDLE;
655 // The result of this read completing might trigger the completion
656 // of a pending write. If so, post a task to complete the write later.
657 // Since the socket may call back into the SequencedSocketData
658 // from socket()->OnReadComplete(), trigger the write task to be posted
659 // before calling that.
660 MaybePostWriteCompleteTask();
662 NET_TRACE(1, " *** ") << "Completing socket read for: " << sequence_number_;
663 DumpMockReadWrite(data);
664 socket()->OnReadComplete(data);
665 NET_TRACE(1, " *** ") << "Done";
668 void SequencedSocketData::OnWriteComplete() {
669 CHECK_EQ(COMPLETING, write_state_);
670 NET_TRACE(1, " *** ") << " Completing write for: " << sequence_number_;
671 if (!socket()) {
672 NET_TRACE(1, " *** ") << "No socket available to complete write.";
673 return;
676 const MockWrite& data = helper_.AdvanceWrite();
677 DCHECK_EQ(sequence_number_, data.sequence_number);
678 sequence_number_++;
679 write_state_ = IDLE;
680 int rv = data.result == OK ? data.data_len : data.result;
682 // The result of this write completing might trigger the completion
683 // of a pending read. If so, post a task to complete the read later.
684 // Since the socket may call back into the SequencedSocketData
685 // from socket()->OnWriteComplete(), trigger the write task to be posted
686 // before calling that.
687 MaybePostReadCompleteTask();
689 NET_TRACE(1, " *** ") << " Completing socket write for: " << sequence_number_;
690 socket()->OnWriteComplete(rv);
691 NET_TRACE(1, " *** ") << "Done";
694 SequencedSocketData::~SequencedSocketData() {
697 DeterministicSocketData::DeterministicSocketData(MockRead* reads,
698 size_t reads_count, MockWrite* writes, size_t writes_count)
699 : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
700 sequence_number_(0),
701 current_read_(),
702 current_write_(),
703 stopping_sequence_number_(0),
704 stopped_(false),
705 print_debug_(false),
706 is_running_(false) {
707 VerifyCorrectSequenceNumbers(reads, reads_count, writes, writes_count);
710 DeterministicSocketData::~DeterministicSocketData() {}
712 void DeterministicSocketData::Run() {
713 DCHECK(!is_running_);
714 is_running_ = true;
716 SetStopped(false);
717 int counter = 0;
718 // Continue to consume data until all data has run out, or the stopped_ flag
719 // has been set. Consuming data requires two separate operations -- running
720 // the tasks in the message loop, and explicitly invoking the read/write
721 // callbacks (simulating network I/O). We check our conditions between each,
722 // since they can change in either.
723 while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
724 if (counter % 2 == 0)
725 base::RunLoop().RunUntilIdle();
726 if (counter % 2 == 1) {
727 InvokeCallbacks();
729 counter++;
731 // We're done consuming new data, but it is possible there are still some
732 // pending callbacks which we expect to complete before returning.
733 while (delegate_.get() &&
734 (delegate_->WritePending() || delegate_->ReadPending()) &&
735 !stopped()) {
736 InvokeCallbacks();
737 base::RunLoop().RunUntilIdle();
739 SetStopped(false);
740 is_running_ = false;
743 void DeterministicSocketData::RunFor(int steps) {
744 StopAfter(steps);
745 Run();
748 void DeterministicSocketData::SetStop(int seq) {
749 DCHECK_LT(sequence_number_, seq);
750 stopping_sequence_number_ = seq;
751 stopped_ = false;
754 void DeterministicSocketData::StopAfter(int seq) {
755 SetStop(sequence_number_ + seq);
758 MockRead DeterministicSocketData::OnRead() {
759 current_read_ = helper()->PeekRead();
761 // Synchronous read while stopped is an error
762 if (stopped() && current_read_.mode == SYNCHRONOUS) {
763 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
764 return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
767 // Async read which will be called back in a future step.
768 if (sequence_number_ < current_read_.sequence_number) {
769 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": I/O Pending";
770 MockRead result = MockRead(SYNCHRONOUS, ERR_IO_PENDING);
771 if (current_read_.mode == SYNCHRONOUS) {
772 LOG(ERROR) << "Unable to perform synchronous read: "
773 << current_read_.sequence_number
774 << " at stage: " << sequence_number_;
775 result = MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
777 if (print_debug_)
778 DumpMockReadWrite(result);
779 return result;
782 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Read "
783 << read_index();
784 if (print_debug_)
785 DumpMockReadWrite(current_read_);
787 // Increment the sequence number if IO is complete
788 if (current_read_.mode == SYNCHRONOUS)
789 NextStep();
791 DCHECK_NE(ERR_IO_PENDING, current_read_.result);
792 StaticSocketDataProvider::OnRead();
794 return current_read_;
797 MockWriteResult DeterministicSocketData::OnWrite(const std::string& data) {
798 const MockWrite& next_write = helper()->PeekWrite();
799 current_write_ = next_write;
801 // Synchronous write while stopped is an error
802 if (stopped() && next_write.mode == SYNCHRONOUS) {
803 LOG(ERROR) << "Unable to perform synchronous IO while stopped";
804 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
807 // Async write which will be called back in a future step.
808 if (sequence_number_ < next_write.sequence_number) {
809 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": I/O Pending";
810 if (next_write.mode == SYNCHRONOUS) {
811 LOG(ERROR) << "Unable to perform synchronous write: "
812 << next_write.sequence_number << " at stage: " << sequence_number_;
813 return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
815 } else {
816 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Write "
817 << write_index();
820 if (print_debug_)
821 DumpMockReadWrite(next_write);
823 // Move to the next step if I/O is synchronous, since the operation will
824 // complete when this method returns.
825 if (next_write.mode == SYNCHRONOUS)
826 NextStep();
828 // This is either a sync write for this step, or an async write.
829 return StaticSocketDataProvider::OnWrite(data);
832 void DeterministicSocketData::Reset() {
833 NET_TRACE(1, " *** ") << "Stage " << sequence_number_ << ": Reset()";
834 sequence_number_ = 0;
835 StaticSocketDataProvider::Reset();
836 NOTREACHED();
839 void DeterministicSocketData::InvokeCallbacks() {
840 if (delegate_.get() && delegate_->WritePending() &&
841 (current_write().sequence_number == sequence_number())) {
842 NextStep();
843 delegate_->CompleteWrite();
844 return;
846 if (delegate_.get() && delegate_->ReadPending() &&
847 (current_read().sequence_number == sequence_number())) {
848 NextStep();
849 delegate_->CompleteRead();
850 return;
854 void DeterministicSocketData::NextStep() {
855 // Invariant: Can never move *past* the stopping step.
856 DCHECK_LT(sequence_number_, stopping_sequence_number_);
857 sequence_number_++;
858 if (sequence_number_ == stopping_sequence_number_)
859 SetStopped(true);
862 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
863 MockRead* reads, size_t reads_count,
864 MockWrite* writes, size_t writes_count) {
865 size_t read = 0;
866 size_t write = 0;
867 int expected = 0;
868 while (read < reads_count || write < writes_count) {
869 // Check to see that we have a read or write at the expected
870 // state.
871 if (read < reads_count && reads[read].sequence_number == expected) {
872 ++read;
873 ++expected;
874 continue;
876 if (write < writes_count && writes[write].sequence_number == expected) {
877 ++write;
878 ++expected;
879 continue;
881 NOTREACHED() << "Missing sequence number: " << expected;
882 return;
884 DCHECK_EQ(read, reads_count);
885 DCHECK_EQ(write, writes_count);
888 MockClientSocketFactory::MockClientSocketFactory() {}
890 MockClientSocketFactory::~MockClientSocketFactory() {}
892 void MockClientSocketFactory::AddSocketDataProvider(
893 SocketDataProvider* data) {
894 mock_data_.Add(data);
897 void MockClientSocketFactory::AddSSLSocketDataProvider(
898 SSLSocketDataProvider* data) {
899 mock_ssl_data_.Add(data);
902 void MockClientSocketFactory::ResetNextMockIndexes() {
903 mock_data_.ResetNextIndex();
904 mock_ssl_data_.ResetNextIndex();
907 scoped_ptr<DatagramClientSocket>
908 MockClientSocketFactory::CreateDatagramClientSocket(
909 DatagramSocket::BindType bind_type,
910 const RandIntCallback& rand_int_cb,
911 net::NetLog* net_log,
912 const net::NetLog::Source& source) {
913 SocketDataProvider* data_provider = mock_data_.GetNext();
914 scoped_ptr<MockUDPClientSocket> socket(
915 new MockUDPClientSocket(data_provider, net_log));
916 data_provider->set_socket(socket.get());
917 if (bind_type == DatagramSocket::RANDOM_BIND)
918 socket->set_source_port(static_cast<uint16>(rand_int_cb.Run(1025, 65535)));
919 return socket.Pass();
922 scoped_ptr<StreamSocket> MockClientSocketFactory::CreateTransportClientSocket(
923 const AddressList& addresses,
924 net::NetLog* net_log,
925 const net::NetLog::Source& source) {
926 SocketDataProvider* data_provider = mock_data_.GetNext();
927 scoped_ptr<MockTCPClientSocket> socket(
928 new MockTCPClientSocket(addresses, net_log, data_provider));
929 data_provider->set_socket(socket.get());
930 return socket.Pass();
933 scoped_ptr<SSLClientSocket> MockClientSocketFactory::CreateSSLClientSocket(
934 scoped_ptr<ClientSocketHandle> transport_socket,
935 const HostPortPair& host_and_port,
936 const SSLConfig& ssl_config,
937 const SSLClientSocketContext& context) {
938 SSLSocketDataProvider* next_ssl_data = mock_ssl_data_.GetNext();
939 if (!next_ssl_data->next_protos_expected_in_ssl_config.empty()) {
940 EXPECT_EQ(next_ssl_data->next_protos_expected_in_ssl_config.size(),
941 ssl_config.next_protos.size());
942 EXPECT_TRUE(
943 std::equal(next_ssl_data->next_protos_expected_in_ssl_config.begin(),
944 next_ssl_data->next_protos_expected_in_ssl_config.end(),
945 ssl_config.next_protos.begin()));
947 return scoped_ptr<SSLClientSocket>(new MockSSLClientSocket(
948 transport_socket.Pass(), host_and_port, ssl_config, next_ssl_data));
951 void MockClientSocketFactory::ClearSSLSessionCache() {
954 const char MockClientSocket::kTlsUnique[] = "MOCK_TLSUNIQ";
956 MockClientSocket::MockClientSocket(const BoundNetLog& net_log)
957 : connected_(false),
958 net_log_(net_log),
959 weak_factory_(this) {
960 IPAddressNumber ip;
961 CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
962 peer_addr_ = IPEndPoint(ip, 0);
965 int MockClientSocket::SetReceiveBufferSize(int32 size) {
966 return OK;
969 int MockClientSocket::SetSendBufferSize(int32 size) {
970 return OK;
973 void MockClientSocket::Disconnect() {
974 connected_ = false;
977 bool MockClientSocket::IsConnected() const {
978 return connected_;
981 bool MockClientSocket::IsConnectedAndIdle() const {
982 return connected_;
985 int MockClientSocket::GetPeerAddress(IPEndPoint* address) const {
986 if (!IsConnected())
987 return ERR_SOCKET_NOT_CONNECTED;
988 *address = peer_addr_;
989 return OK;
992 int MockClientSocket::GetLocalAddress(IPEndPoint* address) const {
993 IPAddressNumber ip;
994 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
995 CHECK(rv);
996 *address = IPEndPoint(ip, 123);
997 return OK;
1000 const BoundNetLog& MockClientSocket::NetLog() const {
1001 return net_log_;
1004 void MockClientSocket::GetSSLCertRequestInfo(
1005 SSLCertRequestInfo* cert_request_info) {
1008 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece& label,
1009 bool has_context,
1010 const base::StringPiece& context,
1011 unsigned char* out,
1012 unsigned int outlen) {
1013 memset(out, 'A', outlen);
1014 return OK;
1017 int MockClientSocket::GetTLSUniqueChannelBinding(std::string* out) {
1018 out->assign(MockClientSocket::kTlsUnique);
1019 return OK;
1022 ChannelIDService* MockClientSocket::GetChannelIDService() const {
1023 NOTREACHED();
1024 return NULL;
1027 SSLClientSocket::NextProtoStatus
1028 MockClientSocket::GetNextProto(std::string* proto) {
1029 proto->clear();
1030 return SSLClientSocket::kNextProtoUnsupported;
1033 scoped_refptr<X509Certificate>
1034 MockClientSocket::GetUnverifiedServerCertificateChain() const {
1035 NOTREACHED();
1036 return NULL;
1039 MockClientSocket::~MockClientSocket() {}
1041 void MockClientSocket::RunCallbackAsync(const CompletionCallback& callback,
1042 int result) {
1043 base::MessageLoop::current()->PostTask(
1044 FROM_HERE,
1045 base::Bind(&MockClientSocket::RunCallback,
1046 weak_factory_.GetWeakPtr(),
1047 callback,
1048 result));
1051 void MockClientSocket::RunCallback(const net::CompletionCallback& callback,
1052 int result) {
1053 if (!callback.is_null())
1054 callback.Run(result);
1057 MockTCPClientSocket::MockTCPClientSocket(const AddressList& addresses,
1058 net::NetLog* net_log,
1059 SocketDataProvider* data)
1060 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1061 addresses_(addresses),
1062 data_(data),
1063 read_offset_(0),
1064 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
1065 need_read_data_(true),
1066 peer_closed_connection_(false),
1067 pending_read_buf_(NULL),
1068 pending_read_buf_len_(0),
1069 was_used_to_convey_data_(false) {
1070 DCHECK(data_);
1071 peer_addr_ = data->connect_data().peer_addr;
1072 data_->Reset();
1075 MockTCPClientSocket::~MockTCPClientSocket() {}
1077 int MockTCPClientSocket::Read(IOBuffer* buf, int buf_len,
1078 const CompletionCallback& callback) {
1079 if (!connected_)
1080 return ERR_UNEXPECTED;
1082 // If the buffer is already in use, a read is already in progress!
1083 DCHECK(pending_read_buf_.get() == NULL);
1085 // Store our async IO data.
1086 pending_read_buf_ = buf;
1087 pending_read_buf_len_ = buf_len;
1088 pending_read_callback_ = callback;
1090 if (need_read_data_) {
1091 read_data_ = data_->OnRead();
1092 if (read_data_.result == ERR_CONNECTION_CLOSED) {
1093 // This MockRead is just a marker to instruct us to set
1094 // peer_closed_connection_.
1095 peer_closed_connection_ = true;
1097 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
1098 // This MockRead is just a marker to instruct us to set
1099 // peer_closed_connection_. Skip it and get the next one.
1100 read_data_ = data_->OnRead();
1101 peer_closed_connection_ = true;
1103 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1104 // to complete the async IO manually later (via OnReadComplete).
1105 if (read_data_.result == ERR_IO_PENDING) {
1106 // We need to be using async IO in this case.
1107 DCHECK(!callback.is_null());
1108 return ERR_IO_PENDING;
1110 need_read_data_ = false;
1113 return CompleteRead();
1116 int MockTCPClientSocket::Write(IOBuffer* buf, int buf_len,
1117 const CompletionCallback& callback) {
1118 DCHECK(buf);
1119 DCHECK_GT(buf_len, 0);
1121 if (!connected_)
1122 return ERR_UNEXPECTED;
1124 std::string data(buf->data(), buf_len);
1125 MockWriteResult write_result = data_->OnWrite(data);
1127 was_used_to_convey_data_ = true;
1129 // ERR_IO_PENDING is a signal that the socket data will call back
1130 // asynchronously later.
1131 if (write_result.result == ERR_IO_PENDING) {
1132 pending_write_callback_ = callback;
1133 return ERR_IO_PENDING;
1136 // TODO(rch): remove this once OrderedSocketData and DelayedSocketData
1137 // have been removed.
1138 if (write_result.mode == ASYNC) {
1139 RunCallbackAsync(callback, write_result.result);
1140 return ERR_IO_PENDING;
1143 return write_result.result;
1146 int MockTCPClientSocket::Connect(const CompletionCallback& callback) {
1147 if (connected_)
1148 return OK;
1149 connected_ = true;
1150 peer_closed_connection_ = false;
1151 if (data_->connect_data().mode == ASYNC) {
1152 if (data_->connect_data().result == ERR_IO_PENDING)
1153 pending_read_callback_ = callback;
1154 else
1155 RunCallbackAsync(callback, data_->connect_data().result);
1156 return ERR_IO_PENDING;
1158 return data_->connect_data().result;
1161 void MockTCPClientSocket::Disconnect() {
1162 MockClientSocket::Disconnect();
1163 pending_read_callback_.Reset();
1166 bool MockTCPClientSocket::IsConnected() const {
1167 return connected_ && !peer_closed_connection_;
1170 bool MockTCPClientSocket::IsConnectedAndIdle() const {
1171 return IsConnected();
1174 int MockTCPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1175 if (addresses_.empty())
1176 return MockClientSocket::GetPeerAddress(address);
1178 *address = addresses_[0];
1179 return OK;
1182 bool MockTCPClientSocket::WasEverUsed() const {
1183 return was_used_to_convey_data_;
1186 bool MockTCPClientSocket::UsingTCPFastOpen() const {
1187 return false;
1190 bool MockTCPClientSocket::WasNpnNegotiated() const {
1191 return false;
1194 bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1195 return false;
1198 void MockTCPClientSocket::OnReadComplete(const MockRead& data) {
1199 // There must be a read pending.
1200 DCHECK(pending_read_buf_.get());
1201 // You can't complete a read with another ERR_IO_PENDING status code.
1202 DCHECK_NE(ERR_IO_PENDING, data.result);
1203 // Since we've been waiting for data, need_read_data_ should be true.
1204 DCHECK(need_read_data_);
1206 read_data_ = data;
1207 need_read_data_ = false;
1209 // The caller is simulating that this IO completes right now. Don't
1210 // let CompleteRead() schedule a callback.
1211 read_data_.mode = SYNCHRONOUS;
1213 CompletionCallback callback = pending_read_callback_;
1214 int rv = CompleteRead();
1215 RunCallback(callback, rv);
1218 void MockTCPClientSocket::OnWriteComplete(int rv) {
1219 // There must be a read pending.
1220 DCHECK(!pending_write_callback_.is_null());
1221 CompletionCallback callback = pending_write_callback_;
1222 RunCallback(callback, rv);
1225 void MockTCPClientSocket::OnConnectComplete(const MockConnect& data) {
1226 CompletionCallback callback = pending_read_callback_;
1227 RunCallback(callback, data.result);
1230 int MockTCPClientSocket::CompleteRead() {
1231 DCHECK(pending_read_buf_.get());
1232 DCHECK(pending_read_buf_len_ > 0);
1234 was_used_to_convey_data_ = true;
1236 // Save the pending async IO data and reset our |pending_| state.
1237 scoped_refptr<IOBuffer> buf = pending_read_buf_;
1238 int buf_len = pending_read_buf_len_;
1239 CompletionCallback callback = pending_read_callback_;
1240 pending_read_buf_ = NULL;
1241 pending_read_buf_len_ = 0;
1242 pending_read_callback_.Reset();
1244 int result = read_data_.result;
1245 DCHECK(result != ERR_IO_PENDING);
1247 if (read_data_.data) {
1248 if (read_data_.data_len - read_offset_ > 0) {
1249 result = std::min(buf_len, read_data_.data_len - read_offset_);
1250 memcpy(buf->data(), read_data_.data + read_offset_, result);
1251 read_offset_ += result;
1252 if (read_offset_ == read_data_.data_len) {
1253 need_read_data_ = true;
1254 read_offset_ = 0;
1256 } else {
1257 result = 0; // EOF
1261 if (read_data_.mode == ASYNC) {
1262 DCHECK(!callback.is_null());
1263 RunCallbackAsync(callback, result);
1264 return ERR_IO_PENDING;
1266 return result;
1269 DeterministicSocketHelper::DeterministicSocketHelper(
1270 net::NetLog* net_log,
1271 DeterministicSocketData* data)
1272 : write_pending_(false),
1273 write_result_(0),
1274 read_data_(),
1275 read_buf_(NULL),
1276 read_buf_len_(0),
1277 read_pending_(false),
1278 data_(data),
1279 was_used_to_convey_data_(false),
1280 peer_closed_connection_(false),
1281 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)) {
1284 DeterministicSocketHelper::~DeterministicSocketHelper() {}
1286 void DeterministicSocketHelper::CompleteWrite() {
1287 was_used_to_convey_data_ = true;
1288 write_pending_ = false;
1289 write_callback_.Run(write_result_);
1292 int DeterministicSocketHelper::CompleteRead() {
1293 DCHECK_GT(read_buf_len_, 0);
1294 DCHECK_LE(read_data_.data_len, read_buf_len_);
1295 DCHECK(read_buf_);
1297 was_used_to_convey_data_ = true;
1299 if (read_data_.result == ERR_IO_PENDING)
1300 read_data_ = data_->OnRead();
1301 DCHECK_NE(ERR_IO_PENDING, read_data_.result);
1302 // If read_data_.mode is ASYNC, we do not need to wait, since this is already
1303 // the callback. Therefore we don't even bother to check it.
1304 int result = read_data_.result;
1306 if (read_data_.data_len > 0) {
1307 DCHECK(read_data_.data);
1308 result = std::min(read_buf_len_, read_data_.data_len);
1309 memcpy(read_buf_->data(), read_data_.data, result);
1312 if (read_pending_) {
1313 read_pending_ = false;
1314 read_callback_.Run(result);
1317 return result;
1320 int DeterministicSocketHelper::Write(
1321 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1322 DCHECK(buf);
1323 DCHECK_GT(buf_len, 0);
1325 std::string data(buf->data(), buf_len);
1326 MockWriteResult write_result = data_->OnWrite(data);
1328 if (write_result.mode == ASYNC) {
1329 write_callback_ = callback;
1330 write_result_ = write_result.result;
1331 DCHECK(!write_callback_.is_null());
1332 write_pending_ = true;
1333 return ERR_IO_PENDING;
1336 was_used_to_convey_data_ = true;
1337 write_pending_ = false;
1338 return write_result.result;
1341 int DeterministicSocketHelper::Read(
1342 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
1343 read_data_ = data_->OnRead();
1344 // The buffer should always be big enough to contain all the MockRead data. To
1345 // use small buffers, split the data into multiple MockReads.
1346 DCHECK_LE(read_data_.data_len, buf_len);
1348 if (read_data_.result == ERR_CONNECTION_CLOSED) {
1349 // This MockRead is just a marker to instruct us to set
1350 // peer_closed_connection_.
1351 peer_closed_connection_ = true;
1353 if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
1354 // This MockRead is just a marker to instruct us to set
1355 // peer_closed_connection_. Skip it and get the next one.
1356 read_data_ = data_->OnRead();
1357 peer_closed_connection_ = true;
1360 read_buf_ = buf;
1361 read_buf_len_ = buf_len;
1362 read_callback_ = callback;
1364 if (read_data_.mode == ASYNC || (read_data_.result == ERR_IO_PENDING)) {
1365 read_pending_ = true;
1366 DCHECK(!read_callback_.is_null());
1367 return ERR_IO_PENDING;
1370 was_used_to_convey_data_ = true;
1371 return CompleteRead();
1374 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
1375 net::NetLog* net_log,
1376 DeterministicSocketData* data)
1377 : connected_(false),
1378 helper_(net_log, data),
1379 source_port_(123) {
1382 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
1384 bool DeterministicMockUDPClientSocket::WritePending() const {
1385 return helper_.write_pending();
1388 bool DeterministicMockUDPClientSocket::ReadPending() const {
1389 return helper_.read_pending();
1392 void DeterministicMockUDPClientSocket::CompleteWrite() {
1393 helper_.CompleteWrite();
1396 int DeterministicMockUDPClientSocket::CompleteRead() {
1397 return helper_.CompleteRead();
1400 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint& address) {
1401 if (connected_)
1402 return OK;
1403 connected_ = true;
1404 peer_address_ = address;
1405 return helper_.data()->connect_data().result;
1408 int DeterministicMockUDPClientSocket::Write(
1409 IOBuffer* buf,
1410 int buf_len,
1411 const CompletionCallback& callback) {
1412 if (!connected_)
1413 return ERR_UNEXPECTED;
1415 return helper_.Write(buf, buf_len, callback);
1418 int DeterministicMockUDPClientSocket::Read(
1419 IOBuffer* buf,
1420 int buf_len,
1421 const CompletionCallback& callback) {
1422 if (!connected_)
1423 return ERR_UNEXPECTED;
1425 return helper_.Read(buf, buf_len, callback);
1428 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1429 return OK;
1432 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size) {
1433 return OK;
1436 void DeterministicMockUDPClientSocket::Close() {
1437 connected_ = false;
1440 int DeterministicMockUDPClientSocket::GetPeerAddress(
1441 IPEndPoint* address) const {
1442 *address = peer_address_;
1443 return OK;
1446 int DeterministicMockUDPClientSocket::GetLocalAddress(
1447 IPEndPoint* address) const {
1448 IPAddressNumber ip;
1449 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1450 CHECK(rv);
1451 *address = IPEndPoint(ip, source_port_);
1452 return OK;
1455 const BoundNetLog& DeterministicMockUDPClientSocket::NetLog() const {
1456 return helper_.net_log();
1459 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead& data) {}
1461 void DeterministicMockUDPClientSocket::OnWriteComplete(int rv) {
1464 void DeterministicMockUDPClientSocket::OnConnectComplete(
1465 const MockConnect& data) {
1466 NOTIMPLEMENTED();
1469 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
1470 net::NetLog* net_log,
1471 DeterministicSocketData* data)
1472 : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1473 helper_(net_log, data) {
1474 peer_addr_ = data->connect_data().peer_addr;
1477 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
1479 bool DeterministicMockTCPClientSocket::WritePending() const {
1480 return helper_.write_pending();
1483 bool DeterministicMockTCPClientSocket::ReadPending() const {
1484 return helper_.read_pending();
1487 void DeterministicMockTCPClientSocket::CompleteWrite() {
1488 helper_.CompleteWrite();
1491 int DeterministicMockTCPClientSocket::CompleteRead() {
1492 return helper_.CompleteRead();
1495 int DeterministicMockTCPClientSocket::Write(
1496 IOBuffer* buf,
1497 int buf_len,
1498 const CompletionCallback& callback) {
1499 if (!connected_)
1500 return ERR_UNEXPECTED;
1502 return helper_.Write(buf, buf_len, callback);
1505 int DeterministicMockTCPClientSocket::Read(
1506 IOBuffer* buf,
1507 int buf_len,
1508 const CompletionCallback& callback) {
1509 if (!connected_)
1510 return ERR_UNEXPECTED;
1512 return helper_.Read(buf, buf_len, callback);
1515 // TODO(erikchen): Support connect sequencing.
1516 int DeterministicMockTCPClientSocket::Connect(
1517 const CompletionCallback& callback) {
1518 if (connected_)
1519 return OK;
1520 connected_ = true;
1521 if (helper_.data()->connect_data().mode == ASYNC) {
1522 RunCallbackAsync(callback, helper_.data()->connect_data().result);
1523 return ERR_IO_PENDING;
1525 return helper_.data()->connect_data().result;
1528 void DeterministicMockTCPClientSocket::Disconnect() {
1529 MockClientSocket::Disconnect();
1532 bool DeterministicMockTCPClientSocket::IsConnected() const {
1533 return connected_ && !helper_.peer_closed_connection();
1536 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
1537 return IsConnected();
1540 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
1541 return helper_.was_used_to_convey_data();
1544 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
1545 return false;
1548 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
1549 return false;
1552 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1553 return false;
1556 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead& data) {}
1558 void DeterministicMockTCPClientSocket::OnWriteComplete(int rv) {
1561 void DeterministicMockTCPClientSocket::OnConnectComplete(
1562 const MockConnect& data) {}
1564 // static
1565 void MockSSLClientSocket::ConnectCallback(
1566 MockSSLClientSocket* ssl_client_socket,
1567 const CompletionCallback& callback,
1568 int rv) {
1569 if (rv == OK)
1570 ssl_client_socket->connected_ = true;
1571 callback.Run(rv);
1574 MockSSLClientSocket::MockSSLClientSocket(
1575 scoped_ptr<ClientSocketHandle> transport_socket,
1576 const HostPortPair& host_port_pair,
1577 const SSLConfig& ssl_config,
1578 SSLSocketDataProvider* data)
1579 : MockClientSocket(
1580 // Have to use the right BoundNetLog for LoadTimingInfo regression
1581 // tests.
1582 transport_socket->socket()->NetLog()),
1583 transport_(transport_socket.Pass()),
1584 data_(data),
1585 is_npn_state_set_(false),
1586 new_npn_value_(false),
1587 is_protocol_negotiated_set_(false),
1588 protocol_negotiated_(kProtoUnknown) {
1589 DCHECK(data_);
1590 peer_addr_ = data->connect.peer_addr;
1593 MockSSLClientSocket::~MockSSLClientSocket() {
1594 Disconnect();
1597 int MockSSLClientSocket::Read(IOBuffer* buf, int buf_len,
1598 const CompletionCallback& callback) {
1599 return transport_->socket()->Read(buf, buf_len, callback);
1602 int MockSSLClientSocket::Write(IOBuffer* buf, int buf_len,
1603 const CompletionCallback& callback) {
1604 return transport_->socket()->Write(buf, buf_len, callback);
1607 int MockSSLClientSocket::Connect(const CompletionCallback& callback) {
1608 int rv = transport_->socket()->Connect(
1609 base::Bind(&ConnectCallback, base::Unretained(this), callback));
1610 if (rv == OK) {
1611 if (data_->connect.result == OK)
1612 connected_ = true;
1613 if (data_->connect.mode == ASYNC) {
1614 RunCallbackAsync(callback, data_->connect.result);
1615 return ERR_IO_PENDING;
1617 return data_->connect.result;
1619 return rv;
1622 void MockSSLClientSocket::Disconnect() {
1623 MockClientSocket::Disconnect();
1624 if (transport_->socket() != NULL)
1625 transport_->socket()->Disconnect();
1628 bool MockSSLClientSocket::IsConnected() const {
1629 return transport_->socket()->IsConnected();
1632 bool MockSSLClientSocket::WasEverUsed() const {
1633 return transport_->socket()->WasEverUsed();
1636 bool MockSSLClientSocket::UsingTCPFastOpen() const {
1637 return transport_->socket()->UsingTCPFastOpen();
1640 int MockSSLClientSocket::GetPeerAddress(IPEndPoint* address) const {
1641 return transport_->socket()->GetPeerAddress(address);
1644 bool MockSSLClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
1645 ssl_info->Reset();
1646 ssl_info->cert = data_->cert;
1647 ssl_info->client_cert_sent = data_->client_cert_sent;
1648 ssl_info->channel_id_sent = data_->channel_id_sent;
1649 ssl_info->connection_status = data_->connection_status;
1650 return true;
1653 void MockSSLClientSocket::GetSSLCertRequestInfo(
1654 SSLCertRequestInfo* cert_request_info) {
1655 DCHECK(cert_request_info);
1656 if (data_->cert_request_info) {
1657 cert_request_info->host_and_port =
1658 data_->cert_request_info->host_and_port;
1659 cert_request_info->client_certs = data_->cert_request_info->client_certs;
1660 } else {
1661 cert_request_info->Reset();
1665 SSLClientSocket::NextProtoStatus MockSSLClientSocket::GetNextProto(
1666 std::string* proto) {
1667 *proto = data_->next_proto;
1668 return data_->next_proto_status;
1671 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated) {
1672 is_npn_state_set_ = true;
1673 return new_npn_value_ = negotiated;
1676 bool MockSSLClientSocket::WasNpnNegotiated() const {
1677 if (is_npn_state_set_)
1678 return new_npn_value_;
1679 return data_->was_npn_negotiated;
1682 NextProto MockSSLClientSocket::GetNegotiatedProtocol() const {
1683 if (is_protocol_negotiated_set_)
1684 return protocol_negotiated_;
1685 return data_->protocol_negotiated;
1688 void MockSSLClientSocket::set_protocol_negotiated(
1689 NextProto protocol_negotiated) {
1690 is_protocol_negotiated_set_ = true;
1691 protocol_negotiated_ = protocol_negotiated;
1694 bool MockSSLClientSocket::WasChannelIDSent() const {
1695 return data_->channel_id_sent;
1698 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent) {
1699 data_->channel_id_sent = channel_id_sent;
1702 ChannelIDService* MockSSLClientSocket::GetChannelIDService() const {
1703 return data_->channel_id_service;
1706 void MockSSLClientSocket::OnReadComplete(const MockRead& data) {
1707 NOTIMPLEMENTED();
1710 void MockSSLClientSocket::OnWriteComplete(int rv) {
1711 NOTIMPLEMENTED();
1714 void MockSSLClientSocket::OnConnectComplete(const MockConnect& data) {
1715 NOTIMPLEMENTED();
1718 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data,
1719 net::NetLog* net_log)
1720 : connected_(false),
1721 data_(data),
1722 read_offset_(0),
1723 read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
1724 need_read_data_(true),
1725 source_port_(123),
1726 pending_read_buf_(NULL),
1727 pending_read_buf_len_(0),
1728 net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
1729 weak_factory_(this) {
1730 DCHECK(data_);
1731 data_->Reset();
1732 peer_addr_ = data->connect_data().peer_addr;
1735 MockUDPClientSocket::~MockUDPClientSocket() {}
1737 int MockUDPClientSocket::Read(IOBuffer* buf,
1738 int buf_len,
1739 const CompletionCallback& callback) {
1740 if (!connected_)
1741 return ERR_UNEXPECTED;
1743 // If the buffer is already in use, a read is already in progress!
1744 DCHECK(pending_read_buf_.get() == NULL);
1746 // Store our async IO data.
1747 pending_read_buf_ = buf;
1748 pending_read_buf_len_ = buf_len;
1749 pending_read_callback_ = callback;
1751 if (need_read_data_) {
1752 read_data_ = data_->OnRead();
1753 // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
1754 // to complete the async IO manually later (via OnReadComplete).
1755 if (read_data_.result == ERR_IO_PENDING) {
1756 // We need to be using async IO in this case.
1757 DCHECK(!callback.is_null());
1758 return ERR_IO_PENDING;
1760 need_read_data_ = false;
1763 return CompleteRead();
1766 int MockUDPClientSocket::Write(IOBuffer* buf, int buf_len,
1767 const CompletionCallback& callback) {
1768 DCHECK(buf);
1769 DCHECK_GT(buf_len, 0);
1771 if (!connected_)
1772 return ERR_UNEXPECTED;
1774 std::string data(buf->data(), buf_len);
1775 MockWriteResult write_result = data_->OnWrite(data);
1777 // ERR_IO_PENDING is a signal that the socket data will call back
1778 // asynchronously.
1779 if (write_result.result == ERR_IO_PENDING) {
1780 pending_write_callback_ = callback;
1781 return ERR_IO_PENDING;
1783 if (write_result.mode == ASYNC) {
1784 RunCallbackAsync(callback, write_result.result);
1785 return ERR_IO_PENDING;
1787 return write_result.result;
1790 int MockUDPClientSocket::SetReceiveBufferSize(int32 size) {
1791 return OK;
1794 int MockUDPClientSocket::SetSendBufferSize(int32 size) {
1795 return OK;
1798 void MockUDPClientSocket::Close() {
1799 connected_ = false;
1802 int MockUDPClientSocket::GetPeerAddress(IPEndPoint* address) const {
1803 *address = peer_addr_;
1804 return OK;
1807 int MockUDPClientSocket::GetLocalAddress(IPEndPoint* address) const {
1808 IPAddressNumber ip;
1809 bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
1810 CHECK(rv);
1811 *address = IPEndPoint(ip, source_port_);
1812 return OK;
1815 const BoundNetLog& MockUDPClientSocket::NetLog() const {
1816 return net_log_;
1819 int MockUDPClientSocket::Connect(const IPEndPoint& address) {
1820 connected_ = true;
1821 peer_addr_ = address;
1822 return data_->connect_data().result;
1825 void MockUDPClientSocket::OnReadComplete(const MockRead& data) {
1826 // There must be a read pending.
1827 DCHECK(pending_read_buf_.get());
1828 // You can't complete a read with another ERR_IO_PENDING status code.
1829 DCHECK_NE(ERR_IO_PENDING, data.result);
1830 // Since we've been waiting for data, need_read_data_ should be true.
1831 DCHECK(need_read_data_);
1833 read_data_ = data;
1834 need_read_data_ = false;
1836 // The caller is simulating that this IO completes right now. Don't
1837 // let CompleteRead() schedule a callback.
1838 read_data_.mode = SYNCHRONOUS;
1840 net::CompletionCallback callback = pending_read_callback_;
1841 int rv = CompleteRead();
1842 RunCallback(callback, rv);
1845 void MockUDPClientSocket::OnWriteComplete(int rv) {
1846 // There must be a read pending.
1847 DCHECK(!pending_write_callback_.is_null());
1848 CompletionCallback callback = pending_write_callback_;
1849 RunCallback(callback, rv);
1852 void MockUDPClientSocket::OnConnectComplete(const MockConnect& data) {
1853 NOTIMPLEMENTED();
1856 int MockUDPClientSocket::CompleteRead() {
1857 DCHECK(pending_read_buf_.get());
1858 DCHECK(pending_read_buf_len_ > 0);
1860 // Save the pending async IO data and reset our |pending_| state.
1861 scoped_refptr<IOBuffer> buf = pending_read_buf_;
1862 int buf_len = pending_read_buf_len_;
1863 CompletionCallback callback = pending_read_callback_;
1864 pending_read_buf_ = NULL;
1865 pending_read_buf_len_ = 0;
1866 pending_read_callback_.Reset();
1868 int result = read_data_.result;
1869 DCHECK(result != ERR_IO_PENDING);
1871 if (read_data_.data) {
1872 if (read_data_.data_len - read_offset_ > 0) {
1873 result = std::min(buf_len, read_data_.data_len - read_offset_);
1874 memcpy(buf->data(), read_data_.data + read_offset_, result);
1875 read_offset_ += result;
1876 if (read_offset_ == read_data_.data_len) {
1877 need_read_data_ = true;
1878 read_offset_ = 0;
1880 } else {
1881 result = 0; // EOF
1885 if (read_data_.mode == ASYNC) {
1886 DCHECK(!callback.is_null());
1887 RunCallbackAsync(callback, result);
1888 return ERR_IO_PENDING;
1890 return result;
1893 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback& callback,
1894 int result) {
1895 base::MessageLoop::current()->PostTask(
1896 FROM_HERE,
1897 base::Bind(&MockUDPClientSocket::RunCallback,
1898 weak_factory_.GetWeakPtr(),
1899 callback,
1900 result));
1903 void MockUDPClientSocket::RunCallback(const CompletionCallback& callback,
1904 int result) {
1905 if (!callback.is_null())
1906 callback.Run(result);
1909 TestSocketRequest::TestSocketRequest(
1910 std::vector<TestSocketRequest*>* request_order, size_t* completion_count)
1911 : request_order_(request_order),
1912 completion_count_(completion_count),
1913 callback_(base::Bind(&TestSocketRequest::OnComplete,
1914 base::Unretained(this))) {
1915 DCHECK(request_order);
1916 DCHECK(completion_count);
1919 TestSocketRequest::~TestSocketRequest() {
1922 void TestSocketRequest::OnComplete(int result) {
1923 SetResult(result);
1924 (*completion_count_)++;
1925 request_order_->push_back(this);
1928 // static
1929 const int ClientSocketPoolTest::kIndexOutOfBounds = -1;
1931 // static
1932 const int ClientSocketPoolTest::kRequestNotFound = -2;
1934 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
1935 ClientSocketPoolTest::~ClientSocketPoolTest() {}
1937 int ClientSocketPoolTest::GetOrderOfRequest(size_t index) const {
1938 index--;
1939 if (index >= requests_.size())
1940 return kIndexOutOfBounds;
1942 for (size_t i = 0; i < request_order_.size(); i++)
1943 if (requests_[index] == request_order_[i])
1944 return i + 1;
1946 return kRequestNotFound;
1949 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
1950 ScopedVector<TestSocketRequest>::iterator i;
1951 for (i = requests_.begin(); i != requests_.end(); ++i) {
1952 if ((*i)->handle()->is_initialized()) {
1953 if (keep_alive == NO_KEEP_ALIVE)
1954 (*i)->handle()->socket()->Disconnect();
1955 (*i)->handle()->Reset();
1956 base::RunLoop().RunUntilIdle();
1957 return true;
1960 return false;
1963 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
1964 bool released_one;
1965 do {
1966 released_one = ReleaseOneConnection(keep_alive);
1967 } while (released_one);
1970 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
1971 scoped_ptr<StreamSocket> socket,
1972 ClientSocketHandle* handle,
1973 const CompletionCallback& callback)
1974 : socket_(socket.Pass()),
1975 handle_(handle),
1976 user_callback_(callback) {
1979 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
1981 int MockTransportClientSocketPool::MockConnectJob::Connect() {
1982 int rv = socket_->Connect(base::Bind(&MockConnectJob::OnConnect,
1983 base::Unretained(this)));
1984 if (rv == OK) {
1985 user_callback_.Reset();
1986 OnConnect(OK);
1988 return rv;
1991 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
1992 const ClientSocketHandle* handle) {
1993 if (handle != handle_)
1994 return false;
1995 socket_.reset();
1996 handle_ = NULL;
1997 user_callback_.Reset();
1998 return true;
2001 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) {
2002 if (!socket_.get())
2003 return;
2004 if (rv == OK) {
2005 handle_->SetSocket(socket_.Pass());
2007 // Needed for socket pool tests that layer other sockets on top of mock
2008 // sockets.
2009 LoadTimingInfo::ConnectTiming connect_timing;
2010 base::TimeTicks now = base::TimeTicks::Now();
2011 connect_timing.dns_start = now;
2012 connect_timing.dns_end = now;
2013 connect_timing.connect_start = now;
2014 connect_timing.connect_end = now;
2015 handle_->set_connect_timing(connect_timing);
2016 } else {
2017 socket_.reset();
2020 handle_ = NULL;
2022 if (!user_callback_.is_null()) {
2023 CompletionCallback callback = user_callback_;
2024 user_callback_.Reset();
2025 callback.Run(rv);
2029 MockTransportClientSocketPool::MockTransportClientSocketPool(
2030 int max_sockets,
2031 int max_sockets_per_group,
2032 ClientSocketFactory* socket_factory)
2033 : TransportClientSocketPool(max_sockets,
2034 max_sockets_per_group,
2035 NULL,
2036 NULL,
2037 NULL),
2038 client_socket_factory_(socket_factory),
2039 last_request_priority_(DEFAULT_PRIORITY),
2040 release_count_(0),
2041 cancel_count_(0) {
2044 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
2046 int MockTransportClientSocketPool::RequestSocket(
2047 const std::string& group_name, const void* socket_params,
2048 RequestPriority priority, ClientSocketHandle* handle,
2049 const CompletionCallback& callback, const BoundNetLog& net_log) {
2050 last_request_priority_ = priority;
2051 scoped_ptr<StreamSocket> socket =
2052 client_socket_factory_->CreateTransportClientSocket(
2053 AddressList(), net_log.net_log(), net::NetLog::Source());
2054 MockConnectJob* job = new MockConnectJob(socket.Pass(), handle, callback);
2055 job_list_.push_back(job);
2056 handle->set_pool_id(1);
2057 return job->Connect();
2060 void MockTransportClientSocketPool::CancelRequest(const std::string& group_name,
2061 ClientSocketHandle* handle) {
2062 std::vector<MockConnectJob*>::iterator i;
2063 for (i = job_list_.begin(); i != job_list_.end(); ++i) {
2064 if ((*i)->CancelHandle(handle)) {
2065 cancel_count_++;
2066 break;
2071 void MockTransportClientSocketPool::ReleaseSocket(
2072 const std::string& group_name,
2073 scoped_ptr<StreamSocket> socket,
2074 int id) {
2075 EXPECT_EQ(1, id);
2076 release_count_++;
2079 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
2081 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
2083 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
2084 DeterministicSocketData* data) {
2085 mock_data_.Add(data);
2088 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
2089 SSLSocketDataProvider* data) {
2090 mock_ssl_data_.Add(data);
2093 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
2094 mock_data_.ResetNextIndex();
2095 mock_ssl_data_.ResetNextIndex();
2098 MockSSLClientSocket* DeterministicMockClientSocketFactory::
2099 GetMockSSLClientSocket(size_t index) const {
2100 DCHECK_LT(index, ssl_client_sockets_.size());
2101 return ssl_client_sockets_[index];
2104 scoped_ptr<DatagramClientSocket>
2105 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
2106 DatagramSocket::BindType bind_type,
2107 const RandIntCallback& rand_int_cb,
2108 net::NetLog* net_log,
2109 const NetLog::Source& source) {
2110 DeterministicSocketData* data_provider = mock_data().GetNext();
2111 scoped_ptr<DeterministicMockUDPClientSocket> socket(
2112 new DeterministicMockUDPClientSocket(net_log, data_provider));
2113 data_provider->set_delegate(socket->AsWeakPtr());
2114 udp_client_sockets().push_back(socket.get());
2115 if (bind_type == DatagramSocket::RANDOM_BIND)
2116 socket->set_source_port(static_cast<uint16>(rand_int_cb.Run(1025, 65535)));
2117 return socket.Pass();
2120 scoped_ptr<StreamSocket>
2121 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
2122 const AddressList& addresses,
2123 net::NetLog* net_log,
2124 const net::NetLog::Source& source) {
2125 DeterministicSocketData* data_provider = mock_data().GetNext();
2126 scoped_ptr<DeterministicMockTCPClientSocket> socket(
2127 new DeterministicMockTCPClientSocket(net_log, data_provider));
2128 data_provider->set_delegate(socket->AsWeakPtr());
2129 tcp_client_sockets().push_back(socket.get());
2130 return socket.Pass();
2133 scoped_ptr<SSLClientSocket>
2134 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
2135 scoped_ptr<ClientSocketHandle> transport_socket,
2136 const HostPortPair& host_and_port,
2137 const SSLConfig& ssl_config,
2138 const SSLClientSocketContext& context) {
2139 scoped_ptr<MockSSLClientSocket> socket(
2140 new MockSSLClientSocket(transport_socket.Pass(),
2141 host_and_port, ssl_config,
2142 mock_ssl_data_.GetNext()));
2143 ssl_client_sockets_.push_back(socket.get());
2144 return socket.Pass();
2147 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
2150 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
2151 int max_sockets,
2152 int max_sockets_per_group,
2153 TransportClientSocketPool* transport_pool)
2154 : SOCKSClientSocketPool(max_sockets,
2155 max_sockets_per_group,
2156 NULL,
2157 transport_pool,
2158 NULL),
2159 transport_pool_(transport_pool) {
2162 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
2164 int MockSOCKSClientSocketPool::RequestSocket(
2165 const std::string& group_name, const void* socket_params,
2166 RequestPriority priority, ClientSocketHandle* handle,
2167 const CompletionCallback& callback, const BoundNetLog& net_log) {
2168 return transport_pool_->RequestSocket(
2169 group_name, socket_params, priority, handle, callback, net_log);
2172 void MockSOCKSClientSocketPool::CancelRequest(
2173 const std::string& group_name,
2174 ClientSocketHandle* handle) {
2175 return transport_pool_->CancelRequest(group_name, handle);
2178 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string& group_name,
2179 scoped_ptr<StreamSocket> socket,
2180 int id) {
2181 return transport_pool_->ReleaseSocket(group_name, socket.Pass(), id);
2184 ScopedWebSocketEndpointZeroUnlockDelay::
2185 ScopedWebSocketEndpointZeroUnlockDelay() {
2186 old_delay_ =
2187 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
2188 base::TimeDelta());
2191 ScopedWebSocketEndpointZeroUnlockDelay::
2192 ~ScopedWebSocketEndpointZeroUnlockDelay() {
2193 base::TimeDelta active_delay =
2194 WebSocketEndpointLockManager::GetInstance()->SetUnlockDelayForTesting(
2195 old_delay_);
2196 EXPECT_EQ(active_delay, base::TimeDelta());
2199 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
2200 const int kSOCKS5GreetRequestLength = arraysize(kSOCKS5GreetRequest);
2202 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
2203 const int kSOCKS5GreetResponseLength = arraysize(kSOCKS5GreetResponse);
2205 const char kSOCKS5OkRequest[] =
2206 { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
2207 const int kSOCKS5OkRequestLength = arraysize(kSOCKS5OkRequest);
2209 const char kSOCKS5OkResponse[] =
2210 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
2211 const int kSOCKS5OkResponseLength = arraysize(kSOCKS5OkResponse);
2213 } // namespace net