Home | History | Annotate | Download | only in socket
      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.
      4 
      5 #include "net/socket/socket_test_util.h"
      6 
      7 #include <algorithm>
      8 #include <vector>
      9 
     10 #include "base/basictypes.h"
     11 #include "base/bind.h"
     12 #include "base/bind_helpers.h"
     13 #include "base/compiler_specific.h"
     14 #include "base/message_loop/message_loop.h"
     15 #include "base/run_loop.h"
     16 #include "base/time/time.h"
     17 #include "net/base/address_family.h"
     18 #include "net/base/address_list.h"
     19 #include "net/base/auth.h"
     20 #include "net/base/load_timing_info.h"
     21 #include "net/http/http_network_session.h"
     22 #include "net/http/http_request_headers.h"
     23 #include "net/http/http_response_headers.h"
     24 #include "net/socket/client_socket_pool_histograms.h"
     25 #include "net/socket/socket.h"
     26 #include "net/ssl/ssl_cert_request_info.h"
     27 #include "net/ssl/ssl_connection_status_flags.h"
     28 #include "net/ssl/ssl_info.h"
     29 #include "testing/gtest/include/gtest/gtest.h"
     30 
     31 // Socket events are easier to debug if you log individual reads and writes.
     32 // Enable these if locally debugging, but they are too noisy for the waterfall.
     33 #if 0
     34 #define NET_TRACE(level, s) DLOG(level) << s << __FUNCTION__ << "() "
     35 #else
     36 #define NET_TRACE(level, s) EAT_STREAM_PARAMETERS
     37 #endif
     38 
     39 namespace net {
     40 
     41 namespace {
     42 
     43 inline char AsciifyHigh(char x) {
     44   char nybble = static_cast<char>((x >> 4) & 0x0F);
     45   return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
     46 }
     47 
     48 inline char AsciifyLow(char x) {
     49   char nybble = static_cast<char>((x >> 0) & 0x0F);
     50   return nybble + ((nybble < 0x0A) ? '0' : 'A' - 10);
     51 }
     52 
     53 inline char Asciify(char x) {
     54   if ((x < 0) || !isprint(x))
     55     return '.';
     56   return x;
     57 }
     58 
     59 void DumpData(const char* data, int data_len) {
     60   if (logging::LOG_INFO < logging::GetMinLogLevel())
     61     return;
     62   DVLOG(1) << "Length:  " << data_len;
     63   const char* pfx = "Data:    ";
     64   if (!data || (data_len <= 0)) {
     65     DVLOG(1) << pfx << "<None>";
     66   } else {
     67     int i;
     68     for (i = 0; i <= (data_len - 4); i += 4) {
     69       DVLOG(1) << pfx
     70                << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
     71                << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
     72                << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
     73                << AsciifyHigh(data[i + 3]) << AsciifyLow(data[i + 3])
     74                << "  '"
     75                << Asciify(data[i + 0])
     76                << Asciify(data[i + 1])
     77                << Asciify(data[i + 2])
     78                << Asciify(data[i + 3])
     79                << "'";
     80       pfx = "         ";
     81     }
     82     // Take care of any 'trailing' bytes, if data_len was not a multiple of 4.
     83     switch (data_len - i) {
     84       case 3:
     85         DVLOG(1) << pfx
     86                  << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
     87                  << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
     88                  << AsciifyHigh(data[i + 2]) << AsciifyLow(data[i + 2])
     89                  << "    '"
     90                  << Asciify(data[i + 0])
     91                  << Asciify(data[i + 1])
     92                  << Asciify(data[i + 2])
     93                  << " '";
     94         break;
     95       case 2:
     96         DVLOG(1) << pfx
     97                  << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
     98                  << AsciifyHigh(data[i + 1]) << AsciifyLow(data[i + 1])
     99                  << "      '"
    100                  << Asciify(data[i + 0])
    101                  << Asciify(data[i + 1])
    102                  << "  '";
    103         break;
    104       case 1:
    105         DVLOG(1) << pfx
    106                  << AsciifyHigh(data[i + 0]) << AsciifyLow(data[i + 0])
    107                  << "        '"
    108                  << Asciify(data[i + 0])
    109                  << "   '";
    110         break;
    111     }
    112   }
    113 }
    114 
    115 template <MockReadWriteType type>
    116 void DumpMockReadWrite(const MockReadWrite<type>& r) {
    117   if (logging::LOG_INFO < logging::GetMinLogLevel())
    118     return;
    119   DVLOG(1) << "Async:   " << (r.mode == ASYNC)
    120            << "\nResult:  " << r.result;
    121   DumpData(r.data, r.data_len);
    122   const char* stop = (r.sequence_number & MockRead::STOPLOOP) ? " (STOP)" : "";
    123   DVLOG(1) << "Stage:   " << (r.sequence_number & ~MockRead::STOPLOOP) << stop
    124            << "\nTime:    " << r.time_stamp.ToInternalValue();
    125 }
    126 
    127 }  // namespace
    128 
    129 MockConnect::MockConnect() : mode(ASYNC), result(OK) {
    130   IPAddressNumber ip;
    131   CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
    132   peer_addr = IPEndPoint(ip, 0);
    133 }
    134 
    135 MockConnect::MockConnect(IoMode io_mode, int r) : mode(io_mode), result(r) {
    136   IPAddressNumber ip;
    137   CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
    138   peer_addr = IPEndPoint(ip, 0);
    139 }
    140 
    141 MockConnect::MockConnect(IoMode io_mode, int r, IPEndPoint addr) :
    142     mode(io_mode),
    143     result(r),
    144     peer_addr(addr) {
    145 }
    146 
    147 MockConnect::~MockConnect() {}
    148 
    149 StaticSocketDataProvider::StaticSocketDataProvider()
    150     : reads_(NULL),
    151       read_index_(0),
    152       read_count_(0),
    153       writes_(NULL),
    154       write_index_(0),
    155       write_count_(0) {
    156 }
    157 
    158 StaticSocketDataProvider::StaticSocketDataProvider(MockRead* reads,
    159                                                    size_t reads_count,
    160                                                    MockWrite* writes,
    161                                                    size_t writes_count)
    162     : reads_(reads),
    163       read_index_(0),
    164       read_count_(reads_count),
    165       writes_(writes),
    166       write_index_(0),
    167       write_count_(writes_count) {
    168 }
    169 
    170 StaticSocketDataProvider::~StaticSocketDataProvider() {}
    171 
    172 const MockRead& StaticSocketDataProvider::PeekRead() const {
    173   CHECK(!at_read_eof());
    174   return reads_[read_index_];
    175 }
    176 
    177 const MockWrite& StaticSocketDataProvider::PeekWrite() const {
    178   CHECK(!at_write_eof());
    179   return writes_[write_index_];
    180 }
    181 
    182 const MockRead& StaticSocketDataProvider::PeekRead(size_t index) const {
    183   CHECK_LT(index, read_count_);
    184   return reads_[index];
    185 }
    186 
    187 const MockWrite& StaticSocketDataProvider::PeekWrite(size_t index) const {
    188   CHECK_LT(index, write_count_);
    189   return writes_[index];
    190 }
    191 
    192 MockRead StaticSocketDataProvider::GetNextRead() {
    193   CHECK(!at_read_eof());
    194   reads_[read_index_].time_stamp = base::Time::Now();
    195   return reads_[read_index_++];
    196 }
    197 
    198 MockWriteResult StaticSocketDataProvider::OnWrite(const std::string& data) {
    199   if (!writes_) {
    200     // Not using mock writes; succeed synchronously.
    201     return MockWriteResult(SYNCHRONOUS, data.length());
    202   }
    203   EXPECT_FALSE(at_write_eof());
    204   if (at_write_eof()) {
    205     // Show what the extra write actually consists of.
    206     EXPECT_EQ("<unexpected write>", data);
    207     return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
    208   }
    209 
    210   // Check that what we are writing matches the expectation.
    211   // Then give the mocked return value.
    212   MockWrite* w = &writes_[write_index_++];
    213   w->time_stamp = base::Time::Now();
    214   int result = w->result;
    215   if (w->data) {
    216     // Note - we can simulate a partial write here.  If the expected data
    217     // is a match, but shorter than the write actually written, that is legal.
    218     // Example:
    219     //   Application writes "foobarbaz" (9 bytes)
    220     //   Expected write was "foo" (3 bytes)
    221     //   This is a success, and we return 3 to the application.
    222     std::string expected_data(w->data, w->data_len);
    223     EXPECT_GE(data.length(), expected_data.length());
    224     std::string actual_data(data.substr(0, w->data_len));
    225     EXPECT_EQ(expected_data, actual_data);
    226     if (expected_data != actual_data)
    227       return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
    228     if (result == OK)
    229       result = w->data_len;
    230   }
    231   return MockWriteResult(w->mode, result);
    232 }
    233 
    234 void StaticSocketDataProvider::Reset() {
    235   read_index_ = 0;
    236   write_index_ = 0;
    237 }
    238 
    239 DynamicSocketDataProvider::DynamicSocketDataProvider()
    240     : short_read_limit_(0),
    241       allow_unconsumed_reads_(false) {
    242 }
    243 
    244 DynamicSocketDataProvider::~DynamicSocketDataProvider() {}
    245 
    246 MockRead DynamicSocketDataProvider::GetNextRead() {
    247   if (reads_.empty())
    248     return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
    249   MockRead result = reads_.front();
    250   if (short_read_limit_ == 0 || result.data_len <= short_read_limit_) {
    251     reads_.pop_front();
    252   } else {
    253     result.data_len = short_read_limit_;
    254     reads_.front().data += result.data_len;
    255     reads_.front().data_len -= result.data_len;
    256   }
    257   return result;
    258 }
    259 
    260 void DynamicSocketDataProvider::Reset() {
    261   reads_.clear();
    262 }
    263 
    264 void DynamicSocketDataProvider::SimulateRead(const char* data,
    265                                              const size_t length) {
    266   if (!allow_unconsumed_reads_) {
    267     EXPECT_TRUE(reads_.empty()) << "Unconsumed read: " << reads_.front().data;
    268   }
    269   reads_.push_back(MockRead(ASYNC, data, length));
    270 }
    271 
    272 SSLSocketDataProvider::SSLSocketDataProvider(IoMode mode, int result)
    273     : connect(mode, result),
    274       next_proto_status(SSLClientSocket::kNextProtoUnsupported),
    275       was_npn_negotiated(false),
    276       protocol_negotiated(kProtoUnknown),
    277       client_cert_sent(false),
    278       cert_request_info(NULL),
    279       channel_id_sent(false),
    280       connection_status(0) {
    281   SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2,
    282                                 &connection_status);
    283   // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
    284   SSLConnectionStatusSetCipherSuite(0xcc14, &connection_status);
    285 }
    286 
    287 SSLSocketDataProvider::~SSLSocketDataProvider() {
    288 }
    289 
    290 void SSLSocketDataProvider::SetNextProto(NextProto proto) {
    291   was_npn_negotiated = true;
    292   next_proto_status = SSLClientSocket::kNextProtoNegotiated;
    293   protocol_negotiated = proto;
    294   next_proto = SSLClientSocket::NextProtoToString(proto);
    295 }
    296 
    297 DelayedSocketData::DelayedSocketData(
    298     int write_delay, MockRead* reads, size_t reads_count,
    299     MockWrite* writes, size_t writes_count)
    300     : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
    301       write_delay_(write_delay),
    302       read_in_progress_(false),
    303       weak_factory_(this) {
    304   DCHECK_GE(write_delay_, 0);
    305 }
    306 
    307 DelayedSocketData::DelayedSocketData(
    308     const MockConnect& connect, int write_delay, MockRead* reads,
    309     size_t reads_count, MockWrite* writes, size_t writes_count)
    310     : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
    311       write_delay_(write_delay),
    312       read_in_progress_(false),
    313       weak_factory_(this) {
    314   DCHECK_GE(write_delay_, 0);
    315   set_connect_data(connect);
    316 }
    317 
    318 DelayedSocketData::~DelayedSocketData() {
    319 }
    320 
    321 void DelayedSocketData::ForceNextRead() {
    322   DCHECK(read_in_progress_);
    323   write_delay_ = 0;
    324   CompleteRead();
    325 }
    326 
    327 MockRead DelayedSocketData::GetNextRead() {
    328   MockRead out = MockRead(ASYNC, ERR_IO_PENDING);
    329   if (write_delay_ <= 0)
    330     out = StaticSocketDataProvider::GetNextRead();
    331   read_in_progress_ = (out.result == ERR_IO_PENDING);
    332   return out;
    333 }
    334 
    335 MockWriteResult DelayedSocketData::OnWrite(const std::string& data) {
    336   MockWriteResult rv = StaticSocketDataProvider::OnWrite(data);
    337   // Now that our write has completed, we can allow reads to continue.
    338   if (!--write_delay_ && read_in_progress_)
    339     base::MessageLoop::current()->PostDelayedTask(
    340         FROM_HERE,
    341         base::Bind(&DelayedSocketData::CompleteRead,
    342                    weak_factory_.GetWeakPtr()),
    343         base::TimeDelta::FromMilliseconds(100));
    344   return rv;
    345 }
    346 
    347 void DelayedSocketData::Reset() {
    348   set_socket(NULL);
    349   read_in_progress_ = false;
    350   weak_factory_.InvalidateWeakPtrs();
    351   StaticSocketDataProvider::Reset();
    352 }
    353 
    354 void DelayedSocketData::CompleteRead() {
    355   if (socket() && read_in_progress_)
    356     socket()->OnReadComplete(GetNextRead());
    357 }
    358 
    359 OrderedSocketData::OrderedSocketData(
    360     MockRead* reads, size_t reads_count, MockWrite* writes, size_t writes_count)
    361     : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
    362       sequence_number_(0), loop_stop_stage_(0),
    363       blocked_(false), weak_factory_(this) {
    364 }
    365 
    366 OrderedSocketData::OrderedSocketData(
    367     const MockConnect& connect,
    368     MockRead* reads, size_t reads_count,
    369     MockWrite* writes, size_t writes_count)
    370     : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
    371       sequence_number_(0), loop_stop_stage_(0),
    372       blocked_(false), weak_factory_(this) {
    373   set_connect_data(connect);
    374 }
    375 
    376 void OrderedSocketData::EndLoop() {
    377   // If we've already stopped the loop, don't do it again until we've advanced
    378   // to the next sequence_number.
    379   NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_ << ": EndLoop()";
    380   if (loop_stop_stage_ > 0) {
    381     const MockRead& next_read = StaticSocketDataProvider::PeekRead();
    382     if ((next_read.sequence_number & ~MockRead::STOPLOOP) >
    383         loop_stop_stage_) {
    384       NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_
    385                                 << ": Clearing stop index";
    386       loop_stop_stage_ = 0;
    387     } else {
    388       return;
    389     }
    390   }
    391   // Record the sequence_number at which we stopped the loop.
    392   NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_
    393                             << ": Posting Quit at read " << read_index();
    394   loop_stop_stage_ = sequence_number_;
    395 }
    396 
    397 MockRead OrderedSocketData::GetNextRead() {
    398   weak_factory_.InvalidateWeakPtrs();
    399   blocked_ = false;
    400   const MockRead& next_read = StaticSocketDataProvider::PeekRead();
    401   if (next_read.sequence_number & MockRead::STOPLOOP)
    402     EndLoop();
    403   if ((next_read.sequence_number & ~MockRead::STOPLOOP) <=
    404       sequence_number_++) {
    405     NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_ - 1
    406                               << ": Read " << read_index();
    407     DumpMockReadWrite(next_read);
    408     blocked_ = (next_read.result == ERR_IO_PENDING);
    409     return StaticSocketDataProvider::GetNextRead();
    410   }
    411   NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_ - 1
    412                             << ": I/O Pending";
    413   MockRead result = MockRead(ASYNC, ERR_IO_PENDING);
    414   DumpMockReadWrite(result);
    415   blocked_ = true;
    416   return result;
    417 }
    418 
    419 MockWriteResult OrderedSocketData::OnWrite(const std::string& data) {
    420   NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_
    421                             << ": Write " << write_index();
    422   DumpMockReadWrite(PeekWrite());
    423   ++sequence_number_;
    424   if (blocked_) {
    425     // TODO(willchan): This 100ms delay seems to work around some weirdness.  We
    426     // should probably fix the weirdness.  One example is in SpdyStream,
    427     // DoSendRequest() will return ERR_IO_PENDING, and there's a race.  If the
    428     // SYN_REPLY causes OnResponseReceived() to get called before
    429     // SpdyStream::ReadResponseHeaders() is called, we hit a NOTREACHED().
    430     base::MessageLoop::current()->PostDelayedTask(
    431         FROM_HERE,
    432         base::Bind(&OrderedSocketData::CompleteRead,
    433                    weak_factory_.GetWeakPtr()),
    434         base::TimeDelta::FromMilliseconds(100));
    435   }
    436   return StaticSocketDataProvider::OnWrite(data);
    437 }
    438 
    439 void OrderedSocketData::Reset() {
    440   NET_TRACE(INFO, "  *** ") << "Stage "
    441                             << sequence_number_ << ": Reset()";
    442   sequence_number_ = 0;
    443   loop_stop_stage_ = 0;
    444   set_socket(NULL);
    445   weak_factory_.InvalidateWeakPtrs();
    446   StaticSocketDataProvider::Reset();
    447 }
    448 
    449 void OrderedSocketData::CompleteRead() {
    450   if (socket() && blocked_) {
    451     NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_;
    452     socket()->OnReadComplete(GetNextRead());
    453   }
    454 }
    455 
    456 OrderedSocketData::~OrderedSocketData() {}
    457 
    458 DeterministicSocketData::DeterministicSocketData(MockRead* reads,
    459     size_t reads_count, MockWrite* writes, size_t writes_count)
    460     : StaticSocketDataProvider(reads, reads_count, writes, writes_count),
    461       sequence_number_(0),
    462       current_read_(),
    463       current_write_(),
    464       stopping_sequence_number_(0),
    465       stopped_(false),
    466       print_debug_(false),
    467       is_running_(false) {
    468   VerifyCorrectSequenceNumbers(reads, reads_count, writes, writes_count);
    469 }
    470 
    471 DeterministicSocketData::~DeterministicSocketData() {}
    472 
    473 void DeterministicSocketData::Run() {
    474   DCHECK(!is_running_);
    475   is_running_ = true;
    476 
    477   SetStopped(false);
    478   int counter = 0;
    479   // Continue to consume data until all data has run out, or the stopped_ flag
    480   // has been set. Consuming data requires two separate operations -- running
    481   // the tasks in the message loop, and explicitly invoking the read/write
    482   // callbacks (simulating network I/O). We check our conditions between each,
    483   // since they can change in either.
    484   while ((!at_write_eof() || !at_read_eof()) && !stopped()) {
    485     if (counter % 2 == 0)
    486       base::RunLoop().RunUntilIdle();
    487     if (counter % 2 == 1) {
    488       InvokeCallbacks();
    489     }
    490     counter++;
    491   }
    492   // We're done consuming new data, but it is possible there are still some
    493   // pending callbacks which we expect to complete before returning.
    494   while (delegate_.get() &&
    495          (delegate_->WritePending() || delegate_->ReadPending()) &&
    496          !stopped()) {
    497     InvokeCallbacks();
    498     base::RunLoop().RunUntilIdle();
    499   }
    500   SetStopped(false);
    501   is_running_ = false;
    502 }
    503 
    504 void DeterministicSocketData::RunFor(int steps) {
    505   StopAfter(steps);
    506   Run();
    507 }
    508 
    509 void DeterministicSocketData::SetStop(int seq) {
    510   DCHECK_LT(sequence_number_, seq);
    511   stopping_sequence_number_ = seq;
    512   stopped_ = false;
    513 }
    514 
    515 void DeterministicSocketData::StopAfter(int seq) {
    516   SetStop(sequence_number_ + seq);
    517 }
    518 
    519 MockRead DeterministicSocketData::GetNextRead() {
    520   current_read_ = StaticSocketDataProvider::PeekRead();
    521 
    522   // Synchronous read while stopped is an error
    523   if (stopped() && current_read_.mode == SYNCHRONOUS) {
    524     LOG(ERROR) << "Unable to perform synchronous IO while stopped";
    525     return MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
    526   }
    527 
    528   // Async read which will be called back in a future step.
    529   if (sequence_number_ < current_read_.sequence_number) {
    530     NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_
    531                               << ": I/O Pending";
    532     MockRead result = MockRead(SYNCHRONOUS, ERR_IO_PENDING);
    533     if (current_read_.mode == SYNCHRONOUS) {
    534       LOG(ERROR) << "Unable to perform synchronous read: "
    535           << current_read_.sequence_number
    536           << " at stage: " << sequence_number_;
    537       result = MockRead(SYNCHRONOUS, ERR_UNEXPECTED);
    538     }
    539     if (print_debug_)
    540       DumpMockReadWrite(result);
    541     return result;
    542   }
    543 
    544   NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_
    545                             << ": Read " << read_index();
    546   if (print_debug_)
    547     DumpMockReadWrite(current_read_);
    548 
    549   // Increment the sequence number if IO is complete
    550   if (current_read_.mode == SYNCHRONOUS)
    551     NextStep();
    552 
    553   DCHECK_NE(ERR_IO_PENDING, current_read_.result);
    554   StaticSocketDataProvider::GetNextRead();
    555 
    556   return current_read_;
    557 }
    558 
    559 MockWriteResult DeterministicSocketData::OnWrite(const std::string& data) {
    560   const MockWrite& next_write = StaticSocketDataProvider::PeekWrite();
    561   current_write_ = next_write;
    562 
    563   // Synchronous write while stopped is an error
    564   if (stopped() && next_write.mode == SYNCHRONOUS) {
    565     LOG(ERROR) << "Unable to perform synchronous IO while stopped";
    566     return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
    567   }
    568 
    569   // Async write which will be called back in a future step.
    570   if (sequence_number_ < next_write.sequence_number) {
    571     NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_
    572                               << ": I/O Pending";
    573     if (next_write.mode == SYNCHRONOUS) {
    574       LOG(ERROR) << "Unable to perform synchronous write: "
    575           << next_write.sequence_number << " at stage: " << sequence_number_;
    576       return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
    577     }
    578   } else {
    579     NET_TRACE(INFO, "  *** ") << "Stage " << sequence_number_
    580                               << ": Write " << write_index();
    581   }
    582 
    583   if (print_debug_)
    584     DumpMockReadWrite(next_write);
    585 
    586   // Move to the next step if I/O is synchronous, since the operation will
    587   // complete when this method returns.
    588   if (next_write.mode == SYNCHRONOUS)
    589     NextStep();
    590 
    591   // This is either a sync write for this step, or an async write.
    592   return StaticSocketDataProvider::OnWrite(data);
    593 }
    594 
    595 void DeterministicSocketData::Reset() {
    596   NET_TRACE(INFO, "  *** ") << "Stage "
    597                             << sequence_number_ << ": Reset()";
    598   sequence_number_ = 0;
    599   StaticSocketDataProvider::Reset();
    600   NOTREACHED();
    601 }
    602 
    603 void DeterministicSocketData::InvokeCallbacks() {
    604   if (delegate_.get() && delegate_->WritePending() &&
    605       (current_write().sequence_number == sequence_number())) {
    606     NextStep();
    607     delegate_->CompleteWrite();
    608     return;
    609   }
    610   if (delegate_.get() && delegate_->ReadPending() &&
    611       (current_read().sequence_number == sequence_number())) {
    612     NextStep();
    613     delegate_->CompleteRead();
    614     return;
    615   }
    616 }
    617 
    618 void DeterministicSocketData::NextStep() {
    619   // Invariant: Can never move *past* the stopping step.
    620   DCHECK_LT(sequence_number_, stopping_sequence_number_);
    621   sequence_number_++;
    622   if (sequence_number_ == stopping_sequence_number_)
    623     SetStopped(true);
    624 }
    625 
    626 void DeterministicSocketData::VerifyCorrectSequenceNumbers(
    627     MockRead* reads, size_t reads_count,
    628     MockWrite* writes, size_t writes_count) {
    629   size_t read = 0;
    630   size_t write = 0;
    631   int expected = 0;
    632   while (read < reads_count || write < writes_count) {
    633     // Check to see that we have a read or write at the expected
    634     // state.
    635     if (read < reads_count  && reads[read].sequence_number == expected) {
    636       ++read;
    637       ++expected;
    638       continue;
    639     }
    640     if (write < writes_count && writes[write].sequence_number == expected) {
    641       ++write;
    642       ++expected;
    643       continue;
    644     }
    645     NOTREACHED() << "Missing sequence number: " << expected;
    646     return;
    647   }
    648   DCHECK_EQ(read, reads_count);
    649   DCHECK_EQ(write, writes_count);
    650 }
    651 
    652 MockClientSocketFactory::MockClientSocketFactory() {}
    653 
    654 MockClientSocketFactory::~MockClientSocketFactory() {}
    655 
    656 void MockClientSocketFactory::AddSocketDataProvider(
    657     SocketDataProvider* data) {
    658   mock_data_.Add(data);
    659 }
    660 
    661 void MockClientSocketFactory::AddSSLSocketDataProvider(
    662     SSLSocketDataProvider* data) {
    663   mock_ssl_data_.Add(data);
    664 }
    665 
    666 void MockClientSocketFactory::ResetNextMockIndexes() {
    667   mock_data_.ResetNextIndex();
    668   mock_ssl_data_.ResetNextIndex();
    669 }
    670 
    671 scoped_ptr<DatagramClientSocket>
    672 MockClientSocketFactory::CreateDatagramClientSocket(
    673     DatagramSocket::BindType bind_type,
    674     const RandIntCallback& rand_int_cb,
    675     net::NetLog* net_log,
    676     const net::NetLog::Source& source) {
    677   SocketDataProvider* data_provider = mock_data_.GetNext();
    678   scoped_ptr<MockUDPClientSocket> socket(
    679       new MockUDPClientSocket(data_provider, net_log));
    680   data_provider->set_socket(socket.get());
    681   if (bind_type == DatagramSocket::RANDOM_BIND)
    682     socket->set_source_port(rand_int_cb.Run(1025, 65535));
    683   return socket.PassAs<DatagramClientSocket>();
    684 }
    685 
    686 scoped_ptr<StreamSocket> MockClientSocketFactory::CreateTransportClientSocket(
    687     const AddressList& addresses,
    688     net::NetLog* net_log,
    689     const net::NetLog::Source& source) {
    690   SocketDataProvider* data_provider = mock_data_.GetNext();
    691   scoped_ptr<MockTCPClientSocket> socket(
    692       new MockTCPClientSocket(addresses, net_log, data_provider));
    693   data_provider->set_socket(socket.get());
    694   return socket.PassAs<StreamSocket>();
    695 }
    696 
    697 scoped_ptr<SSLClientSocket> MockClientSocketFactory::CreateSSLClientSocket(
    698     scoped_ptr<ClientSocketHandle> transport_socket,
    699     const HostPortPair& host_and_port,
    700     const SSLConfig& ssl_config,
    701     const SSLClientSocketContext& context) {
    702   return scoped_ptr<SSLClientSocket>(
    703       new MockSSLClientSocket(transport_socket.Pass(),
    704                               host_and_port, ssl_config,
    705                               mock_ssl_data_.GetNext()));
    706 }
    707 
    708 void MockClientSocketFactory::ClearSSLSessionCache() {
    709 }
    710 
    711 const char MockClientSocket::kTlsUnique[] = "MOCK_TLSUNIQ";
    712 
    713 MockClientSocket::MockClientSocket(const BoundNetLog& net_log)
    714     : connected_(false),
    715       net_log_(net_log),
    716       weak_factory_(this) {
    717   IPAddressNumber ip;
    718   CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip));
    719   peer_addr_ = IPEndPoint(ip, 0);
    720 }
    721 
    722 int MockClientSocket::SetReceiveBufferSize(int32 size) {
    723   return OK;
    724 }
    725 
    726 int MockClientSocket::SetSendBufferSize(int32 size) {
    727   return OK;
    728 }
    729 
    730 void MockClientSocket::Disconnect() {
    731   connected_ = false;
    732 }
    733 
    734 bool MockClientSocket::IsConnected() const {
    735   return connected_;
    736 }
    737 
    738 bool MockClientSocket::IsConnectedAndIdle() const {
    739   return connected_;
    740 }
    741 
    742 int MockClientSocket::GetPeerAddress(IPEndPoint* address) const {
    743   if (!IsConnected())
    744     return ERR_SOCKET_NOT_CONNECTED;
    745   *address = peer_addr_;
    746   return OK;
    747 }
    748 
    749 int MockClientSocket::GetLocalAddress(IPEndPoint* address) const {
    750   IPAddressNumber ip;
    751   bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
    752   CHECK(rv);
    753   *address = IPEndPoint(ip, 123);
    754   return OK;
    755 }
    756 
    757 const BoundNetLog& MockClientSocket::NetLog() const {
    758   return net_log_;
    759 }
    760 
    761 void MockClientSocket::GetSSLCertRequestInfo(
    762   SSLCertRequestInfo* cert_request_info) {
    763 }
    764 
    765 int MockClientSocket::ExportKeyingMaterial(const base::StringPiece& label,
    766                                            bool has_context,
    767                                            const base::StringPiece& context,
    768                                            unsigned char* out,
    769                                            unsigned int outlen) {
    770   memset(out, 'A', outlen);
    771   return OK;
    772 }
    773 
    774 int MockClientSocket::GetTLSUniqueChannelBinding(std::string* out) {
    775   out->assign(MockClientSocket::kTlsUnique);
    776   return OK;
    777 }
    778 
    779 ServerBoundCertService* MockClientSocket::GetServerBoundCertService() const {
    780   NOTREACHED();
    781   return NULL;
    782 }
    783 
    784 SSLClientSocket::NextProtoStatus
    785 MockClientSocket::GetNextProto(std::string* proto, std::string* server_protos) {
    786   proto->clear();
    787   server_protos->clear();
    788   return SSLClientSocket::kNextProtoUnsupported;
    789 }
    790 
    791 scoped_refptr<X509Certificate>
    792 MockClientSocket::GetUnverifiedServerCertificateChain() const {
    793   NOTREACHED();
    794   return NULL;
    795 }
    796 
    797 MockClientSocket::~MockClientSocket() {}
    798 
    799 void MockClientSocket::RunCallbackAsync(const CompletionCallback& callback,
    800                                         int result) {
    801   base::MessageLoop::current()->PostTask(
    802       FROM_HERE,
    803       base::Bind(&MockClientSocket::RunCallback,
    804                  weak_factory_.GetWeakPtr(),
    805                  callback,
    806                  result));
    807 }
    808 
    809 void MockClientSocket::RunCallback(const net::CompletionCallback& callback,
    810                                    int result) {
    811   if (!callback.is_null())
    812     callback.Run(result);
    813 }
    814 
    815 MockTCPClientSocket::MockTCPClientSocket(const AddressList& addresses,
    816                                          net::NetLog* net_log,
    817                                          SocketDataProvider* data)
    818     : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
    819       addresses_(addresses),
    820       data_(data),
    821       read_offset_(0),
    822       read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
    823       need_read_data_(true),
    824       peer_closed_connection_(false),
    825       pending_buf_(NULL),
    826       pending_buf_len_(0),
    827       was_used_to_convey_data_(false) {
    828   DCHECK(data_);
    829   peer_addr_ = data->connect_data().peer_addr;
    830   data_->Reset();
    831 }
    832 
    833 MockTCPClientSocket::~MockTCPClientSocket() {}
    834 
    835 int MockTCPClientSocket::Read(IOBuffer* buf, int buf_len,
    836                               const CompletionCallback& callback) {
    837   if (!connected_)
    838     return ERR_UNEXPECTED;
    839 
    840   // If the buffer is already in use, a read is already in progress!
    841   DCHECK(pending_buf_ == NULL);
    842 
    843   // Store our async IO data.
    844   pending_buf_ = buf;
    845   pending_buf_len_ = buf_len;
    846   pending_callback_ = callback;
    847 
    848   if (need_read_data_) {
    849     read_data_ = data_->GetNextRead();
    850     if (read_data_.result == ERR_CONNECTION_CLOSED) {
    851       // This MockRead is just a marker to instruct us to set
    852       // peer_closed_connection_.
    853       peer_closed_connection_ = true;
    854     }
    855     if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
    856       // This MockRead is just a marker to instruct us to set
    857       // peer_closed_connection_.  Skip it and get the next one.
    858       read_data_ = data_->GetNextRead();
    859       peer_closed_connection_ = true;
    860     }
    861     // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
    862     // to complete the async IO manually later (via OnReadComplete).
    863     if (read_data_.result == ERR_IO_PENDING) {
    864       // We need to be using async IO in this case.
    865       DCHECK(!callback.is_null());
    866       return ERR_IO_PENDING;
    867     }
    868     need_read_data_ = false;
    869   }
    870 
    871   return CompleteRead();
    872 }
    873 
    874 int MockTCPClientSocket::Write(IOBuffer* buf, int buf_len,
    875                                const CompletionCallback& callback) {
    876   DCHECK(buf);
    877   DCHECK_GT(buf_len, 0);
    878 
    879   if (!connected_)
    880     return ERR_UNEXPECTED;
    881 
    882   std::string data(buf->data(), buf_len);
    883   MockWriteResult write_result = data_->OnWrite(data);
    884 
    885   was_used_to_convey_data_ = true;
    886 
    887   if (write_result.mode == ASYNC) {
    888     RunCallbackAsync(callback, write_result.result);
    889     return ERR_IO_PENDING;
    890   }
    891 
    892   return write_result.result;
    893 }
    894 
    895 int MockTCPClientSocket::Connect(const CompletionCallback& callback) {
    896   if (connected_)
    897     return OK;
    898   connected_ = true;
    899   peer_closed_connection_ = false;
    900   if (data_->connect_data().mode == ASYNC) {
    901     if (data_->connect_data().result == ERR_IO_PENDING)
    902       pending_callback_ = callback;
    903     else
    904       RunCallbackAsync(callback, data_->connect_data().result);
    905     return ERR_IO_PENDING;
    906   }
    907   return data_->connect_data().result;
    908 }
    909 
    910 void MockTCPClientSocket::Disconnect() {
    911   MockClientSocket::Disconnect();
    912   pending_callback_.Reset();
    913 }
    914 
    915 bool MockTCPClientSocket::IsConnected() const {
    916   return connected_ && !peer_closed_connection_;
    917 }
    918 
    919 bool MockTCPClientSocket::IsConnectedAndIdle() const {
    920   return IsConnected();
    921 }
    922 
    923 int MockTCPClientSocket::GetPeerAddress(IPEndPoint* address) const {
    924   if (addresses_.empty())
    925     return MockClientSocket::GetPeerAddress(address);
    926 
    927   *address = addresses_[0];
    928   return OK;
    929 }
    930 
    931 bool MockTCPClientSocket::WasEverUsed() const {
    932   return was_used_to_convey_data_;
    933 }
    934 
    935 bool MockTCPClientSocket::UsingTCPFastOpen() const {
    936   return false;
    937 }
    938 
    939 bool MockTCPClientSocket::WasNpnNegotiated() const {
    940   return false;
    941 }
    942 
    943 bool MockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
    944   return false;
    945 }
    946 
    947 void MockTCPClientSocket::OnReadComplete(const MockRead& data) {
    948   // There must be a read pending.
    949   DCHECK(pending_buf_);
    950   // You can't complete a read with another ERR_IO_PENDING status code.
    951   DCHECK_NE(ERR_IO_PENDING, data.result);
    952   // Since we've been waiting for data, need_read_data_ should be true.
    953   DCHECK(need_read_data_);
    954 
    955   read_data_ = data;
    956   need_read_data_ = false;
    957 
    958   // The caller is simulating that this IO completes right now.  Don't
    959   // let CompleteRead() schedule a callback.
    960   read_data_.mode = SYNCHRONOUS;
    961 
    962   CompletionCallback callback = pending_callback_;
    963   int rv = CompleteRead();
    964   RunCallback(callback, rv);
    965 }
    966 
    967 void MockTCPClientSocket::OnConnectComplete(const MockConnect& data) {
    968   CompletionCallback callback = pending_callback_;
    969   RunCallback(callback, data.result);
    970 }
    971 
    972 int MockTCPClientSocket::CompleteRead() {
    973   DCHECK(pending_buf_);
    974   DCHECK(pending_buf_len_ > 0);
    975 
    976   was_used_to_convey_data_ = true;
    977 
    978   // Save the pending async IO data and reset our |pending_| state.
    979   scoped_refptr<IOBuffer> buf = pending_buf_;
    980   int buf_len = pending_buf_len_;
    981   CompletionCallback callback = pending_callback_;
    982   pending_buf_ = NULL;
    983   pending_buf_len_ = 0;
    984   pending_callback_.Reset();
    985 
    986   int result = read_data_.result;
    987   DCHECK(result != ERR_IO_PENDING);
    988 
    989   if (read_data_.data) {
    990     if (read_data_.data_len - read_offset_ > 0) {
    991       result = std::min(buf_len, read_data_.data_len - read_offset_);
    992       memcpy(buf->data(), read_data_.data + read_offset_, result);
    993       read_offset_ += result;
    994       if (read_offset_ == read_data_.data_len) {
    995         need_read_data_ = true;
    996         read_offset_ = 0;
    997       }
    998     } else {
    999       result = 0;  // EOF
   1000     }
   1001   }
   1002 
   1003   if (read_data_.mode == ASYNC) {
   1004     DCHECK(!callback.is_null());
   1005     RunCallbackAsync(callback, result);
   1006     return ERR_IO_PENDING;
   1007   }
   1008   return result;
   1009 }
   1010 
   1011 DeterministicSocketHelper::DeterministicSocketHelper(
   1012     net::NetLog* net_log,
   1013     DeterministicSocketData* data)
   1014     : write_pending_(false),
   1015       write_result_(0),
   1016       read_data_(),
   1017       read_buf_(NULL),
   1018       read_buf_len_(0),
   1019       read_pending_(false),
   1020       data_(data),
   1021       was_used_to_convey_data_(false),
   1022       peer_closed_connection_(false),
   1023       net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)) {
   1024 }
   1025 
   1026 DeterministicSocketHelper::~DeterministicSocketHelper() {}
   1027 
   1028 void DeterministicSocketHelper::CompleteWrite() {
   1029   was_used_to_convey_data_ = true;
   1030   write_pending_ = false;
   1031   write_callback_.Run(write_result_);
   1032 }
   1033 
   1034 int DeterministicSocketHelper::CompleteRead() {
   1035   DCHECK_GT(read_buf_len_, 0);
   1036   DCHECK_LE(read_data_.data_len, read_buf_len_);
   1037   DCHECK(read_buf_);
   1038 
   1039   was_used_to_convey_data_ = true;
   1040 
   1041   if (read_data_.result == ERR_IO_PENDING)
   1042     read_data_ = data_->GetNextRead();
   1043   DCHECK_NE(ERR_IO_PENDING, read_data_.result);
   1044   // If read_data_.mode is ASYNC, we do not need to wait, since this is already
   1045   // the callback. Therefore we don't even bother to check it.
   1046   int result = read_data_.result;
   1047 
   1048   if (read_data_.data_len > 0) {
   1049     DCHECK(read_data_.data);
   1050     result = std::min(read_buf_len_, read_data_.data_len);
   1051     memcpy(read_buf_->data(), read_data_.data, result);
   1052   }
   1053 
   1054   if (read_pending_) {
   1055     read_pending_ = false;
   1056     read_callback_.Run(result);
   1057   }
   1058 
   1059   return result;
   1060 }
   1061 
   1062 int DeterministicSocketHelper::Write(
   1063     IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
   1064   DCHECK(buf);
   1065   DCHECK_GT(buf_len, 0);
   1066 
   1067   std::string data(buf->data(), buf_len);
   1068   MockWriteResult write_result = data_->OnWrite(data);
   1069 
   1070   if (write_result.mode == ASYNC) {
   1071     write_callback_ = callback;
   1072     write_result_ = write_result.result;
   1073     DCHECK(!write_callback_.is_null());
   1074     write_pending_ = true;
   1075     return ERR_IO_PENDING;
   1076   }
   1077 
   1078   was_used_to_convey_data_ = true;
   1079   write_pending_ = false;
   1080   return write_result.result;
   1081 }
   1082 
   1083 int DeterministicSocketHelper::Read(
   1084     IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
   1085 
   1086   read_data_ = data_->GetNextRead();
   1087   // The buffer should always be big enough to contain all the MockRead data. To
   1088   // use small buffers, split the data into multiple MockReads.
   1089   DCHECK_LE(read_data_.data_len, buf_len);
   1090 
   1091   if (read_data_.result == ERR_CONNECTION_CLOSED) {
   1092     // This MockRead is just a marker to instruct us to set
   1093     // peer_closed_connection_.
   1094     peer_closed_connection_ = true;
   1095   }
   1096   if (read_data_.result == ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ) {
   1097     // This MockRead is just a marker to instruct us to set
   1098     // peer_closed_connection_.  Skip it and get the next one.
   1099     read_data_ = data_->GetNextRead();
   1100     peer_closed_connection_ = true;
   1101   }
   1102 
   1103   read_buf_ = buf;
   1104   read_buf_len_ = buf_len;
   1105   read_callback_ = callback;
   1106 
   1107   if (read_data_.mode == ASYNC || (read_data_.result == ERR_IO_PENDING)) {
   1108     read_pending_ = true;
   1109     DCHECK(!read_callback_.is_null());
   1110     return ERR_IO_PENDING;
   1111   }
   1112 
   1113   was_used_to_convey_data_ = true;
   1114   return CompleteRead();
   1115 }
   1116 
   1117 DeterministicMockUDPClientSocket::DeterministicMockUDPClientSocket(
   1118     net::NetLog* net_log,
   1119     DeterministicSocketData* data)
   1120     : connected_(false),
   1121       helper_(net_log, data),
   1122       source_port_(123) {
   1123 }
   1124 
   1125 DeterministicMockUDPClientSocket::~DeterministicMockUDPClientSocket() {}
   1126 
   1127 bool DeterministicMockUDPClientSocket::WritePending() const {
   1128   return helper_.write_pending();
   1129 }
   1130 
   1131 bool DeterministicMockUDPClientSocket::ReadPending() const {
   1132   return helper_.read_pending();
   1133 }
   1134 
   1135 void DeterministicMockUDPClientSocket::CompleteWrite() {
   1136   helper_.CompleteWrite();
   1137 }
   1138 
   1139 int DeterministicMockUDPClientSocket::CompleteRead() {
   1140   return helper_.CompleteRead();
   1141 }
   1142 
   1143 int DeterministicMockUDPClientSocket::Connect(const IPEndPoint& address) {
   1144   if (connected_)
   1145     return OK;
   1146   connected_ = true;
   1147   peer_address_ = address;
   1148   return helper_.data()->connect_data().result;
   1149 };
   1150 
   1151 int DeterministicMockUDPClientSocket::Write(
   1152     IOBuffer* buf,
   1153     int buf_len,
   1154     const CompletionCallback& callback) {
   1155   if (!connected_)
   1156     return ERR_UNEXPECTED;
   1157 
   1158   return helper_.Write(buf, buf_len, callback);
   1159 }
   1160 
   1161 int DeterministicMockUDPClientSocket::Read(
   1162     IOBuffer* buf,
   1163     int buf_len,
   1164     const CompletionCallback& callback) {
   1165   if (!connected_)
   1166     return ERR_UNEXPECTED;
   1167 
   1168   return helper_.Read(buf, buf_len, callback);
   1169 }
   1170 
   1171 int DeterministicMockUDPClientSocket::SetReceiveBufferSize(int32 size) {
   1172   return OK;
   1173 }
   1174 
   1175 int DeterministicMockUDPClientSocket::SetSendBufferSize(int32 size) {
   1176   return OK;
   1177 }
   1178 
   1179 void DeterministicMockUDPClientSocket::Close() {
   1180   connected_ = false;
   1181 }
   1182 
   1183 int DeterministicMockUDPClientSocket::GetPeerAddress(
   1184     IPEndPoint* address) const {
   1185   *address = peer_address_;
   1186   return OK;
   1187 }
   1188 
   1189 int DeterministicMockUDPClientSocket::GetLocalAddress(
   1190     IPEndPoint* address) const {
   1191   IPAddressNumber ip;
   1192   bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
   1193   CHECK(rv);
   1194   *address = IPEndPoint(ip, source_port_);
   1195   return OK;
   1196 }
   1197 
   1198 const BoundNetLog& DeterministicMockUDPClientSocket::NetLog() const {
   1199   return helper_.net_log();
   1200 }
   1201 
   1202 void DeterministicMockUDPClientSocket::OnReadComplete(const MockRead& data) {}
   1203 
   1204 void DeterministicMockUDPClientSocket::OnConnectComplete(
   1205     const MockConnect& data) {
   1206   NOTIMPLEMENTED();
   1207 }
   1208 
   1209 DeterministicMockTCPClientSocket::DeterministicMockTCPClientSocket(
   1210     net::NetLog* net_log,
   1211     DeterministicSocketData* data)
   1212     : MockClientSocket(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
   1213       helper_(net_log, data) {
   1214   peer_addr_ = data->connect_data().peer_addr;
   1215 }
   1216 
   1217 DeterministicMockTCPClientSocket::~DeterministicMockTCPClientSocket() {}
   1218 
   1219 bool DeterministicMockTCPClientSocket::WritePending() const {
   1220   return helper_.write_pending();
   1221 }
   1222 
   1223 bool DeterministicMockTCPClientSocket::ReadPending() const {
   1224   return helper_.read_pending();
   1225 }
   1226 
   1227 void DeterministicMockTCPClientSocket::CompleteWrite() {
   1228   helper_.CompleteWrite();
   1229 }
   1230 
   1231 int DeterministicMockTCPClientSocket::CompleteRead() {
   1232   return helper_.CompleteRead();
   1233 }
   1234 
   1235 int DeterministicMockTCPClientSocket::Write(
   1236     IOBuffer* buf,
   1237     int buf_len,
   1238     const CompletionCallback& callback) {
   1239   if (!connected_)
   1240     return ERR_UNEXPECTED;
   1241 
   1242   return helper_.Write(buf, buf_len, callback);
   1243 }
   1244 
   1245 int DeterministicMockTCPClientSocket::Read(
   1246     IOBuffer* buf,
   1247     int buf_len,
   1248     const CompletionCallback& callback) {
   1249   if (!connected_)
   1250     return ERR_UNEXPECTED;
   1251 
   1252   return helper_.Read(buf, buf_len, callback);
   1253 }
   1254 
   1255 // TODO(erikchen): Support connect sequencing.
   1256 int DeterministicMockTCPClientSocket::Connect(
   1257     const CompletionCallback& callback) {
   1258   if (connected_)
   1259     return OK;
   1260   connected_ = true;
   1261   if (helper_.data()->connect_data().mode == ASYNC) {
   1262     RunCallbackAsync(callback, helper_.data()->connect_data().result);
   1263     return ERR_IO_PENDING;
   1264   }
   1265   return helper_.data()->connect_data().result;
   1266 }
   1267 
   1268 void DeterministicMockTCPClientSocket::Disconnect() {
   1269   MockClientSocket::Disconnect();
   1270 }
   1271 
   1272 bool DeterministicMockTCPClientSocket::IsConnected() const {
   1273   return connected_ && !helper_.peer_closed_connection();
   1274 }
   1275 
   1276 bool DeterministicMockTCPClientSocket::IsConnectedAndIdle() const {
   1277   return IsConnected();
   1278 }
   1279 
   1280 bool DeterministicMockTCPClientSocket::WasEverUsed() const {
   1281   return helper_.was_used_to_convey_data();
   1282 }
   1283 
   1284 bool DeterministicMockTCPClientSocket::UsingTCPFastOpen() const {
   1285   return false;
   1286 }
   1287 
   1288 bool DeterministicMockTCPClientSocket::WasNpnNegotiated() const {
   1289   return false;
   1290 }
   1291 
   1292 bool DeterministicMockTCPClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
   1293   return false;
   1294 }
   1295 
   1296 void DeterministicMockTCPClientSocket::OnReadComplete(const MockRead& data) {}
   1297 
   1298 void DeterministicMockTCPClientSocket::OnConnectComplete(
   1299     const MockConnect& data) {}
   1300 
   1301 // static
   1302 void MockSSLClientSocket::ConnectCallback(
   1303     MockSSLClientSocket* ssl_client_socket,
   1304     const CompletionCallback& callback,
   1305     int rv) {
   1306   if (rv == OK)
   1307     ssl_client_socket->connected_ = true;
   1308   callback.Run(rv);
   1309 }
   1310 
   1311 MockSSLClientSocket::MockSSLClientSocket(
   1312     scoped_ptr<ClientSocketHandle> transport_socket,
   1313     const HostPortPair& host_port_pair,
   1314     const SSLConfig& ssl_config,
   1315     SSLSocketDataProvider* data)
   1316     : MockClientSocket(
   1317          // Have to use the right BoundNetLog for LoadTimingInfo regression
   1318          // tests.
   1319          transport_socket->socket()->NetLog()),
   1320       transport_(transport_socket.Pass()),
   1321       data_(data),
   1322       is_npn_state_set_(false),
   1323       new_npn_value_(false),
   1324       is_protocol_negotiated_set_(false),
   1325       protocol_negotiated_(kProtoUnknown) {
   1326   DCHECK(data_);
   1327   peer_addr_ = data->connect.peer_addr;
   1328 }
   1329 
   1330 MockSSLClientSocket::~MockSSLClientSocket() {
   1331   Disconnect();
   1332 }
   1333 
   1334 int MockSSLClientSocket::Read(IOBuffer* buf, int buf_len,
   1335                               const CompletionCallback& callback) {
   1336   return transport_->socket()->Read(buf, buf_len, callback);
   1337 }
   1338 
   1339 int MockSSLClientSocket::Write(IOBuffer* buf, int buf_len,
   1340                                const CompletionCallback& callback) {
   1341   return transport_->socket()->Write(buf, buf_len, callback);
   1342 }
   1343 
   1344 int MockSSLClientSocket::Connect(const CompletionCallback& callback) {
   1345   int rv = transport_->socket()->Connect(
   1346       base::Bind(&ConnectCallback, base::Unretained(this), callback));
   1347   if (rv == OK) {
   1348     if (data_->connect.result == OK)
   1349       connected_ = true;
   1350     if (data_->connect.mode == ASYNC) {
   1351       RunCallbackAsync(callback, data_->connect.result);
   1352       return ERR_IO_PENDING;
   1353     }
   1354     return data_->connect.result;
   1355   }
   1356   return rv;
   1357 }
   1358 
   1359 void MockSSLClientSocket::Disconnect() {
   1360   MockClientSocket::Disconnect();
   1361   if (transport_->socket() != NULL)
   1362     transport_->socket()->Disconnect();
   1363 }
   1364 
   1365 bool MockSSLClientSocket::IsConnected() const {
   1366   return transport_->socket()->IsConnected();
   1367 }
   1368 
   1369 bool MockSSLClientSocket::WasEverUsed() const {
   1370   return transport_->socket()->WasEverUsed();
   1371 }
   1372 
   1373 bool MockSSLClientSocket::UsingTCPFastOpen() const {
   1374   return transport_->socket()->UsingTCPFastOpen();
   1375 }
   1376 
   1377 int MockSSLClientSocket::GetPeerAddress(IPEndPoint* address) const {
   1378   return transport_->socket()->GetPeerAddress(address);
   1379 }
   1380 
   1381 bool MockSSLClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
   1382   ssl_info->Reset();
   1383   ssl_info->cert = data_->cert;
   1384   ssl_info->client_cert_sent = data_->client_cert_sent;
   1385   ssl_info->channel_id_sent = data_->channel_id_sent;
   1386   ssl_info->connection_status = data_->connection_status;
   1387   return true;
   1388 }
   1389 
   1390 void MockSSLClientSocket::GetSSLCertRequestInfo(
   1391     SSLCertRequestInfo* cert_request_info) {
   1392   DCHECK(cert_request_info);
   1393   if (data_->cert_request_info) {
   1394     cert_request_info->host_and_port =
   1395         data_->cert_request_info->host_and_port;
   1396     cert_request_info->client_certs = data_->cert_request_info->client_certs;
   1397   } else {
   1398     cert_request_info->Reset();
   1399   }
   1400 }
   1401 
   1402 SSLClientSocket::NextProtoStatus MockSSLClientSocket::GetNextProto(
   1403     std::string* proto, std::string* server_protos) {
   1404   *proto = data_->next_proto;
   1405   *server_protos = data_->server_protos;
   1406   return data_->next_proto_status;
   1407 }
   1408 
   1409 bool MockSSLClientSocket::set_was_npn_negotiated(bool negotiated) {
   1410   is_npn_state_set_ = true;
   1411   return new_npn_value_ = negotiated;
   1412 }
   1413 
   1414 bool MockSSLClientSocket::WasNpnNegotiated() const {
   1415   if (is_npn_state_set_)
   1416     return new_npn_value_;
   1417   return data_->was_npn_negotiated;
   1418 }
   1419 
   1420 NextProto MockSSLClientSocket::GetNegotiatedProtocol() const {
   1421   if (is_protocol_negotiated_set_)
   1422     return protocol_negotiated_;
   1423   return data_->protocol_negotiated;
   1424 }
   1425 
   1426 void MockSSLClientSocket::set_protocol_negotiated(
   1427     NextProto protocol_negotiated) {
   1428   is_protocol_negotiated_set_ = true;
   1429   protocol_negotiated_ = protocol_negotiated;
   1430 }
   1431 
   1432 bool MockSSLClientSocket::WasChannelIDSent() const {
   1433   return data_->channel_id_sent;
   1434 }
   1435 
   1436 void MockSSLClientSocket::set_channel_id_sent(bool channel_id_sent) {
   1437   data_->channel_id_sent = channel_id_sent;
   1438 }
   1439 
   1440 ServerBoundCertService* MockSSLClientSocket::GetServerBoundCertService() const {
   1441   return data_->server_bound_cert_service;
   1442 }
   1443 
   1444 void MockSSLClientSocket::OnReadComplete(const MockRead& data) {
   1445   NOTIMPLEMENTED();
   1446 }
   1447 
   1448 void MockSSLClientSocket::OnConnectComplete(const MockConnect& data) {
   1449   NOTIMPLEMENTED();
   1450 }
   1451 
   1452 MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data,
   1453                                          net::NetLog* net_log)
   1454     : connected_(false),
   1455       data_(data),
   1456       read_offset_(0),
   1457       read_data_(SYNCHRONOUS, ERR_UNEXPECTED),
   1458       need_read_data_(true),
   1459       source_port_(123),
   1460       pending_buf_(NULL),
   1461       pending_buf_len_(0),
   1462       net_log_(BoundNetLog::Make(net_log, net::NetLog::SOURCE_NONE)),
   1463       weak_factory_(this) {
   1464   DCHECK(data_);
   1465   data_->Reset();
   1466   peer_addr_ = data->connect_data().peer_addr;
   1467 }
   1468 
   1469 MockUDPClientSocket::~MockUDPClientSocket() {}
   1470 
   1471 int MockUDPClientSocket::Read(IOBuffer* buf,
   1472                               int buf_len,
   1473                               const CompletionCallback& callback) {
   1474   if (!connected_)
   1475     return ERR_UNEXPECTED;
   1476 
   1477   // If the buffer is already in use, a read is already in progress!
   1478   DCHECK(pending_buf_ == NULL);
   1479 
   1480   // Store our async IO data.
   1481   pending_buf_ = buf;
   1482   pending_buf_len_ = buf_len;
   1483   pending_callback_ = callback;
   1484 
   1485   if (need_read_data_) {
   1486     read_data_ = data_->GetNextRead();
   1487     // ERR_IO_PENDING means that the SocketDataProvider is taking responsibility
   1488     // to complete the async IO manually later (via OnReadComplete).
   1489     if (read_data_.result == ERR_IO_PENDING) {
   1490       // We need to be using async IO in this case.
   1491       DCHECK(!callback.is_null());
   1492       return ERR_IO_PENDING;
   1493     }
   1494     need_read_data_ = false;
   1495   }
   1496 
   1497   return CompleteRead();
   1498 }
   1499 
   1500 int MockUDPClientSocket::Write(IOBuffer* buf, int buf_len,
   1501                                const CompletionCallback& callback) {
   1502   DCHECK(buf);
   1503   DCHECK_GT(buf_len, 0);
   1504 
   1505   if (!connected_)
   1506     return ERR_UNEXPECTED;
   1507 
   1508   std::string data(buf->data(), buf_len);
   1509   MockWriteResult write_result = data_->OnWrite(data);
   1510 
   1511   if (write_result.mode == ASYNC) {
   1512     RunCallbackAsync(callback, write_result.result);
   1513     return ERR_IO_PENDING;
   1514   }
   1515   return write_result.result;
   1516 }
   1517 
   1518 int MockUDPClientSocket::SetReceiveBufferSize(int32 size) {
   1519   return OK;
   1520 }
   1521 
   1522 int MockUDPClientSocket::SetSendBufferSize(int32 size) {
   1523   return OK;
   1524 }
   1525 
   1526 void MockUDPClientSocket::Close() {
   1527   connected_ = false;
   1528 }
   1529 
   1530 int MockUDPClientSocket::GetPeerAddress(IPEndPoint* address) const {
   1531   *address = peer_addr_;
   1532   return OK;
   1533 }
   1534 
   1535 int MockUDPClientSocket::GetLocalAddress(IPEndPoint* address) const {
   1536   IPAddressNumber ip;
   1537   bool rv = ParseIPLiteralToNumber("192.0.2.33", &ip);
   1538   CHECK(rv);
   1539   *address = IPEndPoint(ip, source_port_);
   1540   return OK;
   1541 }
   1542 
   1543 const BoundNetLog& MockUDPClientSocket::NetLog() const {
   1544   return net_log_;
   1545 }
   1546 
   1547 int MockUDPClientSocket::Connect(const IPEndPoint& address) {
   1548   connected_ = true;
   1549   peer_addr_ = address;
   1550   return data_->connect_data().result;
   1551 }
   1552 
   1553 void MockUDPClientSocket::OnReadComplete(const MockRead& data) {
   1554   // There must be a read pending.
   1555   DCHECK(pending_buf_);
   1556   // You can't complete a read with another ERR_IO_PENDING status code.
   1557   DCHECK_NE(ERR_IO_PENDING, data.result);
   1558   // Since we've been waiting for data, need_read_data_ should be true.
   1559   DCHECK(need_read_data_);
   1560 
   1561   read_data_ = data;
   1562   need_read_data_ = false;
   1563 
   1564   // The caller is simulating that this IO completes right now.  Don't
   1565   // let CompleteRead() schedule a callback.
   1566   read_data_.mode = SYNCHRONOUS;
   1567 
   1568   net::CompletionCallback callback = pending_callback_;
   1569   int rv = CompleteRead();
   1570   RunCallback(callback, rv);
   1571 }
   1572 
   1573 void MockUDPClientSocket::OnConnectComplete(const MockConnect& data) {
   1574   NOTIMPLEMENTED();
   1575 }
   1576 
   1577 int MockUDPClientSocket::CompleteRead() {
   1578   DCHECK(pending_buf_);
   1579   DCHECK(pending_buf_len_ > 0);
   1580 
   1581   // Save the pending async IO data and reset our |pending_| state.
   1582   scoped_refptr<IOBuffer> buf = pending_buf_;
   1583   int buf_len = pending_buf_len_;
   1584   CompletionCallback callback = pending_callback_;
   1585   pending_buf_ = NULL;
   1586   pending_buf_len_ = 0;
   1587   pending_callback_.Reset();
   1588 
   1589   int result = read_data_.result;
   1590   DCHECK(result != ERR_IO_PENDING);
   1591 
   1592   if (read_data_.data) {
   1593     if (read_data_.data_len - read_offset_ > 0) {
   1594       result = std::min(buf_len, read_data_.data_len - read_offset_);
   1595       memcpy(buf->data(), read_data_.data + read_offset_, result);
   1596       read_offset_ += result;
   1597       if (read_offset_ == read_data_.data_len) {
   1598         need_read_data_ = true;
   1599         read_offset_ = 0;
   1600       }
   1601     } else {
   1602       result = 0;  // EOF
   1603     }
   1604   }
   1605 
   1606   if (read_data_.mode == ASYNC) {
   1607     DCHECK(!callback.is_null());
   1608     RunCallbackAsync(callback, result);
   1609     return ERR_IO_PENDING;
   1610   }
   1611   return result;
   1612 }
   1613 
   1614 void MockUDPClientSocket::RunCallbackAsync(const CompletionCallback& callback,
   1615                                            int result) {
   1616   base::MessageLoop::current()->PostTask(
   1617       FROM_HERE,
   1618       base::Bind(&MockUDPClientSocket::RunCallback,
   1619                  weak_factory_.GetWeakPtr(),
   1620                  callback,
   1621                  result));
   1622 }
   1623 
   1624 void MockUDPClientSocket::RunCallback(const CompletionCallback& callback,
   1625                                       int result) {
   1626   if (!callback.is_null())
   1627     callback.Run(result);
   1628 }
   1629 
   1630 TestSocketRequest::TestSocketRequest(
   1631     std::vector<TestSocketRequest*>* request_order, size_t* completion_count)
   1632     : request_order_(request_order),
   1633       completion_count_(completion_count),
   1634       callback_(base::Bind(&TestSocketRequest::OnComplete,
   1635                            base::Unretained(this))) {
   1636   DCHECK(request_order);
   1637   DCHECK(completion_count);
   1638 }
   1639 
   1640 TestSocketRequest::~TestSocketRequest() {
   1641 }
   1642 
   1643 void TestSocketRequest::OnComplete(int result) {
   1644   SetResult(result);
   1645   (*completion_count_)++;
   1646   request_order_->push_back(this);
   1647 }
   1648 
   1649 // static
   1650 const int ClientSocketPoolTest::kIndexOutOfBounds = -1;
   1651 
   1652 // static
   1653 const int ClientSocketPoolTest::kRequestNotFound = -2;
   1654 
   1655 ClientSocketPoolTest::ClientSocketPoolTest() : completion_count_(0) {}
   1656 ClientSocketPoolTest::~ClientSocketPoolTest() {}
   1657 
   1658 int ClientSocketPoolTest::GetOrderOfRequest(size_t index) const {
   1659   index--;
   1660   if (index >= requests_.size())
   1661     return kIndexOutOfBounds;
   1662 
   1663   for (size_t i = 0; i < request_order_.size(); i++)
   1664     if (requests_[index] == request_order_[i])
   1665       return i + 1;
   1666 
   1667   return kRequestNotFound;
   1668 }
   1669 
   1670 bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
   1671   ScopedVector<TestSocketRequest>::iterator i;
   1672   for (i = requests_.begin(); i != requests_.end(); ++i) {
   1673     if ((*i)->handle()->is_initialized()) {
   1674       if (keep_alive == NO_KEEP_ALIVE)
   1675         (*i)->handle()->socket()->Disconnect();
   1676       (*i)->handle()->Reset();
   1677       base::RunLoop().RunUntilIdle();
   1678       return true;
   1679     }
   1680   }
   1681   return false;
   1682 }
   1683 
   1684 void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
   1685   bool released_one;
   1686   do {
   1687     released_one = ReleaseOneConnection(keep_alive);
   1688   } while (released_one);
   1689 }
   1690 
   1691 MockTransportClientSocketPool::MockConnectJob::MockConnectJob(
   1692     scoped_ptr<StreamSocket> socket,
   1693     ClientSocketHandle* handle,
   1694     const CompletionCallback& callback)
   1695     : socket_(socket.Pass()),
   1696       handle_(handle),
   1697       user_callback_(callback) {
   1698 }
   1699 
   1700 MockTransportClientSocketPool::MockConnectJob::~MockConnectJob() {}
   1701 
   1702 int MockTransportClientSocketPool::MockConnectJob::Connect() {
   1703   int rv = socket_->Connect(base::Bind(&MockConnectJob::OnConnect,
   1704                                        base::Unretained(this)));
   1705   if (rv == OK) {
   1706     user_callback_.Reset();
   1707     OnConnect(OK);
   1708   }
   1709   return rv;
   1710 }
   1711 
   1712 bool MockTransportClientSocketPool::MockConnectJob::CancelHandle(
   1713     const ClientSocketHandle* handle) {
   1714   if (handle != handle_)
   1715     return false;
   1716   socket_.reset();
   1717   handle_ = NULL;
   1718   user_callback_.Reset();
   1719   return true;
   1720 }
   1721 
   1722 void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) {
   1723   if (!socket_.get())
   1724     return;
   1725   if (rv == OK) {
   1726     handle_->SetSocket(socket_.Pass());
   1727 
   1728     // Needed for socket pool tests that layer other sockets on top of mock
   1729     // sockets.
   1730     LoadTimingInfo::ConnectTiming connect_timing;
   1731     base::TimeTicks now = base::TimeTicks::Now();
   1732     connect_timing.dns_start = now;
   1733     connect_timing.dns_end = now;
   1734     connect_timing.connect_start = now;
   1735     connect_timing.connect_end = now;
   1736     handle_->set_connect_timing(connect_timing);
   1737   } else {
   1738     socket_.reset();
   1739   }
   1740 
   1741   handle_ = NULL;
   1742 
   1743   if (!user_callback_.is_null()) {
   1744     CompletionCallback callback = user_callback_;
   1745     user_callback_.Reset();
   1746     callback.Run(rv);
   1747   }
   1748 }
   1749 
   1750 MockTransportClientSocketPool::MockTransportClientSocketPool(
   1751     int max_sockets,
   1752     int max_sockets_per_group,
   1753     ClientSocketPoolHistograms* histograms,
   1754     ClientSocketFactory* socket_factory)
   1755     : TransportClientSocketPool(max_sockets, max_sockets_per_group, histograms,
   1756                                 NULL, NULL, NULL),
   1757       client_socket_factory_(socket_factory),
   1758       last_request_priority_(DEFAULT_PRIORITY),
   1759       release_count_(0),
   1760       cancel_count_(0) {
   1761 }
   1762 
   1763 MockTransportClientSocketPool::~MockTransportClientSocketPool() {}
   1764 
   1765 int MockTransportClientSocketPool::RequestSocket(
   1766     const std::string& group_name, const void* socket_params,
   1767     RequestPriority priority, ClientSocketHandle* handle,
   1768     const CompletionCallback& callback, const BoundNetLog& net_log) {
   1769   last_request_priority_ = priority;
   1770   scoped_ptr<StreamSocket> socket =
   1771       client_socket_factory_->CreateTransportClientSocket(
   1772           AddressList(), net_log.net_log(), net::NetLog::Source());
   1773   MockConnectJob* job = new MockConnectJob(socket.Pass(), handle, callback);
   1774   job_list_.push_back(job);
   1775   handle->set_pool_id(1);
   1776   return job->Connect();
   1777 }
   1778 
   1779 void MockTransportClientSocketPool::CancelRequest(const std::string& group_name,
   1780                                                   ClientSocketHandle* handle) {
   1781   std::vector<MockConnectJob*>::iterator i;
   1782   for (i = job_list_.begin(); i != job_list_.end(); ++i) {
   1783     if ((*i)->CancelHandle(handle)) {
   1784       cancel_count_++;
   1785       break;
   1786     }
   1787   }
   1788 }
   1789 
   1790 void MockTransportClientSocketPool::ReleaseSocket(
   1791     const std::string& group_name,
   1792     scoped_ptr<StreamSocket> socket,
   1793     int id) {
   1794   EXPECT_EQ(1, id);
   1795   release_count_++;
   1796 }
   1797 
   1798 DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {}
   1799 
   1800 DeterministicMockClientSocketFactory::~DeterministicMockClientSocketFactory() {}
   1801 
   1802 void DeterministicMockClientSocketFactory::AddSocketDataProvider(
   1803     DeterministicSocketData* data) {
   1804   mock_data_.Add(data);
   1805 }
   1806 
   1807 void DeterministicMockClientSocketFactory::AddSSLSocketDataProvider(
   1808     SSLSocketDataProvider* data) {
   1809   mock_ssl_data_.Add(data);
   1810 }
   1811 
   1812 void DeterministicMockClientSocketFactory::ResetNextMockIndexes() {
   1813   mock_data_.ResetNextIndex();
   1814   mock_ssl_data_.ResetNextIndex();
   1815 }
   1816 
   1817 MockSSLClientSocket* DeterministicMockClientSocketFactory::
   1818     GetMockSSLClientSocket(size_t index) const {
   1819   DCHECK_LT(index, ssl_client_sockets_.size());
   1820   return ssl_client_sockets_[index];
   1821 }
   1822 
   1823 scoped_ptr<DatagramClientSocket>
   1824 DeterministicMockClientSocketFactory::CreateDatagramClientSocket(
   1825     DatagramSocket::BindType bind_type,
   1826     const RandIntCallback& rand_int_cb,
   1827     net::NetLog* net_log,
   1828     const NetLog::Source& source) {
   1829   DeterministicSocketData* data_provider = mock_data().GetNext();
   1830   scoped_ptr<DeterministicMockUDPClientSocket> socket(
   1831       new DeterministicMockUDPClientSocket(net_log, data_provider));
   1832   data_provider->set_delegate(socket->AsWeakPtr());
   1833   udp_client_sockets().push_back(socket.get());
   1834   if (bind_type == DatagramSocket::RANDOM_BIND)
   1835     socket->set_source_port(rand_int_cb.Run(1025, 65535));
   1836   return socket.PassAs<DatagramClientSocket>();
   1837 }
   1838 
   1839 scoped_ptr<StreamSocket>
   1840 DeterministicMockClientSocketFactory::CreateTransportClientSocket(
   1841     const AddressList& addresses,
   1842     net::NetLog* net_log,
   1843     const net::NetLog::Source& source) {
   1844   DeterministicSocketData* data_provider = mock_data().GetNext();
   1845   scoped_ptr<DeterministicMockTCPClientSocket> socket(
   1846       new DeterministicMockTCPClientSocket(net_log, data_provider));
   1847   data_provider->set_delegate(socket->AsWeakPtr());
   1848   tcp_client_sockets().push_back(socket.get());
   1849   return socket.PassAs<StreamSocket>();
   1850 }
   1851 
   1852 scoped_ptr<SSLClientSocket>
   1853 DeterministicMockClientSocketFactory::CreateSSLClientSocket(
   1854     scoped_ptr<ClientSocketHandle> transport_socket,
   1855     const HostPortPair& host_and_port,
   1856     const SSLConfig& ssl_config,
   1857     const SSLClientSocketContext& context) {
   1858   scoped_ptr<MockSSLClientSocket> socket(
   1859       new MockSSLClientSocket(transport_socket.Pass(),
   1860                               host_and_port, ssl_config,
   1861                               mock_ssl_data_.GetNext()));
   1862   ssl_client_sockets_.push_back(socket.get());
   1863   return socket.PassAs<SSLClientSocket>();
   1864 }
   1865 
   1866 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
   1867 }
   1868 
   1869 MockSOCKSClientSocketPool::MockSOCKSClientSocketPool(
   1870     int max_sockets,
   1871     int max_sockets_per_group,
   1872     ClientSocketPoolHistograms* histograms,
   1873     TransportClientSocketPool* transport_pool)
   1874     : SOCKSClientSocketPool(max_sockets, max_sockets_per_group, histograms,
   1875                             NULL, transport_pool, NULL),
   1876       transport_pool_(transport_pool) {
   1877 }
   1878 
   1879 MockSOCKSClientSocketPool::~MockSOCKSClientSocketPool() {}
   1880 
   1881 int MockSOCKSClientSocketPool::RequestSocket(
   1882     const std::string& group_name, const void* socket_params,
   1883     RequestPriority priority, ClientSocketHandle* handle,
   1884     const CompletionCallback& callback, const BoundNetLog& net_log) {
   1885   return transport_pool_->RequestSocket(
   1886       group_name, socket_params, priority, handle, callback, net_log);
   1887 }
   1888 
   1889 void MockSOCKSClientSocketPool::CancelRequest(
   1890     const std::string& group_name,
   1891     ClientSocketHandle* handle) {
   1892   return transport_pool_->CancelRequest(group_name, handle);
   1893 }
   1894 
   1895 void MockSOCKSClientSocketPool::ReleaseSocket(const std::string& group_name,
   1896                                               scoped_ptr<StreamSocket> socket,
   1897                                               int id) {
   1898   return transport_pool_->ReleaseSocket(group_name, socket.Pass(), id);
   1899 }
   1900 
   1901 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
   1902 const int kSOCKS5GreetRequestLength = arraysize(kSOCKS5GreetRequest);
   1903 
   1904 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
   1905 const int kSOCKS5GreetResponseLength = arraysize(kSOCKS5GreetResponse);
   1906 
   1907 const char kSOCKS5OkRequest[] =
   1908     { 0x05, 0x01, 0x00, 0x03, 0x04, 'h', 'o', 's', 't', 0x00, 0x50 };
   1909 const int kSOCKS5OkRequestLength = arraysize(kSOCKS5OkRequest);
   1910 
   1911 const char kSOCKS5OkResponse[] =
   1912     { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
   1913 const int kSOCKS5OkResponseLength = arraysize(kSOCKS5OkResponse);
   1914 
   1915 }  // namespace net
   1916