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 #ifndef NET_SOCKET_SOCKET_TEST_UTIL_H_
      6 #define NET_SOCKET_SOCKET_TEST_UTIL_H_
      7 
      8 #include <cstring>
      9 #include <deque>
     10 #include <string>
     11 #include <vector>
     12 
     13 #include "base/basictypes.h"
     14 #include "base/callback.h"
     15 #include "base/logging.h"
     16 #include "base/memory/ref_counted.h"
     17 #include "base/memory/scoped_ptr.h"
     18 #include "base/memory/scoped_vector.h"
     19 #include "base/memory/weak_ptr.h"
     20 #include "base/strings/string16.h"
     21 #include "net/base/address_list.h"
     22 #include "net/base/io_buffer.h"
     23 #include "net/base/net_errors.h"
     24 #include "net/base/net_log.h"
     25 #include "net/base/test_completion_callback.h"
     26 #include "net/http/http_auth_controller.h"
     27 #include "net/http/http_proxy_client_socket_pool.h"
     28 #include "net/socket/client_socket_factory.h"
     29 #include "net/socket/client_socket_handle.h"
     30 #include "net/socket/socks_client_socket_pool.h"
     31 #include "net/socket/ssl_client_socket.h"
     32 #include "net/socket/ssl_client_socket_pool.h"
     33 #include "net/socket/transport_client_socket_pool.h"
     34 #include "net/ssl/ssl_config_service.h"
     35 #include "net/udp/datagram_client_socket.h"
     36 #include "testing/gtest/include/gtest/gtest.h"
     37 
     38 namespace net {
     39 
     40 enum {
     41   // A private network error code used by the socket test utility classes.
     42   // If the |result| member of a MockRead is
     43   // ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ, that MockRead is just a
     44   // marker that indicates the peer will close the connection after the next
     45   // MockRead.  The other members of that MockRead are ignored.
     46   ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ = -10000,
     47 };
     48 
     49 class AsyncSocket;
     50 class MockClientSocket;
     51 class ServerBoundCertService;
     52 class SSLClientSocket;
     53 class StreamSocket;
     54 
     55 enum IoMode {
     56   ASYNC,
     57   SYNCHRONOUS
     58 };
     59 
     60 struct MockConnect {
     61   // Asynchronous connection success.
     62   // Creates a MockConnect with |mode| ASYC, |result| OK, and
     63   // |peer_addr| 192.0.2.33.
     64   MockConnect();
     65   // Creates a MockConnect with the specified mode and result, with
     66   // |peer_addr| 192.0.2.33.
     67   MockConnect(IoMode io_mode, int r);
     68   MockConnect(IoMode io_mode, int r, IPEndPoint addr);
     69   ~MockConnect();
     70 
     71   IoMode mode;
     72   int result;
     73   IPEndPoint peer_addr;
     74 };
     75 
     76 // MockRead and MockWrite shares the same interface and members, but we'd like
     77 // to have distinct types because we don't want to have them used
     78 // interchangably. To do this, a struct template is defined, and MockRead and
     79 // MockWrite are instantiated by using this template. Template parameter |type|
     80 // is not used in the struct definition (it purely exists for creating a new
     81 // type).
     82 //
     83 // |data| in MockRead and MockWrite has different meanings: |data| in MockRead
     84 // is the data returned from the socket when MockTCPClientSocket::Read() is
     85 // attempted, while |data| in MockWrite is the expected data that should be
     86 // given in MockTCPClientSocket::Write().
     87 enum MockReadWriteType {
     88   MOCK_READ,
     89   MOCK_WRITE
     90 };
     91 
     92 template <MockReadWriteType type>
     93 struct MockReadWrite {
     94   // Flag to indicate that the message loop should be terminated.
     95   enum {
     96     STOPLOOP = 1 << 31
     97   };
     98 
     99   // Default
    100   MockReadWrite()
    101       : mode(SYNCHRONOUS),
    102         result(0),
    103         data(NULL),
    104         data_len(0),
    105         sequence_number(0),
    106         time_stamp(base::Time::Now()) {}
    107 
    108   // Read/write failure (no data).
    109   MockReadWrite(IoMode io_mode, int result)
    110       : mode(io_mode),
    111         result(result),
    112         data(NULL),
    113         data_len(0),
    114         sequence_number(0),
    115         time_stamp(base::Time::Now()) {}
    116 
    117   // Read/write failure (no data), with sequence information.
    118   MockReadWrite(IoMode io_mode, int result, int seq)
    119       : mode(io_mode),
    120         result(result),
    121         data(NULL),
    122         data_len(0),
    123         sequence_number(seq),
    124         time_stamp(base::Time::Now()) {}
    125 
    126   // Asynchronous read/write success (inferred data length).
    127   explicit MockReadWrite(const char* data)
    128       : mode(ASYNC),
    129         result(0),
    130         data(data),
    131         data_len(strlen(data)),
    132         sequence_number(0),
    133         time_stamp(base::Time::Now()) {}
    134 
    135   // Read/write success (inferred data length).
    136   MockReadWrite(IoMode io_mode, const char* data)
    137       : mode(io_mode),
    138         result(0),
    139         data(data),
    140         data_len(strlen(data)),
    141         sequence_number(0),
    142         time_stamp(base::Time::Now()) {}
    143 
    144   // Read/write success.
    145   MockReadWrite(IoMode io_mode, const char* data, int data_len)
    146       : mode(io_mode),
    147         result(0),
    148         data(data),
    149         data_len(data_len),
    150         sequence_number(0),
    151         time_stamp(base::Time::Now()) {}
    152 
    153   // Read/write success (inferred data length) with sequence information.
    154   MockReadWrite(IoMode io_mode, int seq, const char* data)
    155       : mode(io_mode),
    156         result(0),
    157         data(data),
    158         data_len(strlen(data)),
    159         sequence_number(seq),
    160         time_stamp(base::Time::Now()) {}
    161 
    162   // Read/write success with sequence information.
    163   MockReadWrite(IoMode io_mode, const char* data, int data_len, int seq)
    164       : mode(io_mode),
    165         result(0),
    166         data(data),
    167         data_len(data_len),
    168         sequence_number(seq),
    169         time_stamp(base::Time::Now()) {}
    170 
    171   IoMode mode;
    172   int result;
    173   const char* data;
    174   int data_len;
    175 
    176   // For OrderedSocketData, which only allows reads to occur in a particular
    177   // sequence.  If a read occurs before the given |sequence_number| is reached,
    178   // an ERR_IO_PENDING is returned.
    179   int sequence_number;    // The sequence number at which a read is allowed
    180                           // to occur.
    181   base::Time time_stamp;  // The time stamp at which the operation occurred.
    182 };
    183 
    184 typedef MockReadWrite<MOCK_READ> MockRead;
    185 typedef MockReadWrite<MOCK_WRITE> MockWrite;
    186 
    187 struct MockWriteResult {
    188   MockWriteResult(IoMode io_mode, int result) : mode(io_mode), result(result) {}
    189 
    190   IoMode mode;
    191   int result;
    192 };
    193 
    194 // The SocketDataProvider is an interface used by the MockClientSocket
    195 // for getting data about individual reads and writes on the socket.
    196 class SocketDataProvider {
    197  public:
    198   SocketDataProvider() : socket_(NULL) {}
    199 
    200   virtual ~SocketDataProvider() {}
    201 
    202   // Returns the buffer and result code for the next simulated read.
    203   // If the |MockRead.result| is ERR_IO_PENDING, it informs the caller
    204   // that it will be called via the AsyncSocket::OnReadComplete()
    205   // function at a later time.
    206   virtual MockRead GetNextRead() = 0;
    207   virtual MockWriteResult OnWrite(const std::string& data) = 0;
    208   virtual void Reset() = 0;
    209 
    210   // Accessor for the socket which is using the SocketDataProvider.
    211   AsyncSocket* socket() { return socket_; }
    212   void set_socket(AsyncSocket* socket) { socket_ = socket; }
    213 
    214   MockConnect connect_data() const { return connect_; }
    215   void set_connect_data(const MockConnect& connect) { connect_ = connect; }
    216 
    217  private:
    218   MockConnect connect_;
    219   AsyncSocket* socket_;
    220 
    221   DISALLOW_COPY_AND_ASSIGN(SocketDataProvider);
    222 };
    223 
    224 // The AsyncSocket is an interface used by the SocketDataProvider to
    225 // complete the asynchronous read operation.
    226 class AsyncSocket {
    227  public:
    228   // If an async IO is pending because the SocketDataProvider returned
    229   // ERR_IO_PENDING, then the AsyncSocket waits until this OnReadComplete
    230   // is called to complete the asynchronous read operation.
    231   // data.async is ignored, and this read is completed synchronously as
    232   // part of this call.
    233   virtual void OnReadComplete(const MockRead& data) = 0;
    234   virtual void OnConnectComplete(const MockConnect& data) = 0;
    235 };
    236 
    237 // SocketDataProvider which responds based on static tables of mock reads and
    238 // writes.
    239 class StaticSocketDataProvider : public SocketDataProvider {
    240  public:
    241   StaticSocketDataProvider();
    242   StaticSocketDataProvider(MockRead* reads,
    243                            size_t reads_count,
    244                            MockWrite* writes,
    245                            size_t writes_count);
    246   virtual ~StaticSocketDataProvider();
    247 
    248   // These functions get access to the next available read and write data.
    249   const MockRead& PeekRead() const;
    250   const MockWrite& PeekWrite() const;
    251   // These functions get random access to the read and write data, for timing.
    252   const MockRead& PeekRead(size_t index) const;
    253   const MockWrite& PeekWrite(size_t index) const;
    254   size_t read_index() const { return read_index_; }
    255   size_t write_index() const { return write_index_; }
    256   size_t read_count() const { return read_count_; }
    257   size_t write_count() const { return write_count_; }
    258 
    259   bool at_read_eof() const { return read_index_ >= read_count_; }
    260   bool at_write_eof() const { return write_index_ >= write_count_; }
    261 
    262   virtual void CompleteRead() {}
    263 
    264   // SocketDataProvider implementation.
    265   virtual MockRead GetNextRead() OVERRIDE;
    266   virtual MockWriteResult OnWrite(const std::string& data) OVERRIDE;
    267   virtual void Reset() OVERRIDE;
    268 
    269  private:
    270   MockRead* reads_;
    271   size_t read_index_;
    272   size_t read_count_;
    273   MockWrite* writes_;
    274   size_t write_index_;
    275   size_t write_count_;
    276 
    277   DISALLOW_COPY_AND_ASSIGN(StaticSocketDataProvider);
    278 };
    279 
    280 // SocketDataProvider which can make decisions about next mock reads based on
    281 // received writes. It can also be used to enforce order of operations, for
    282 // example that tested code must send the "Hello!" message before receiving
    283 // response. This is useful for testing conversation-like protocols like FTP.
    284 class DynamicSocketDataProvider : public SocketDataProvider {
    285  public:
    286   DynamicSocketDataProvider();
    287   virtual ~DynamicSocketDataProvider();
    288 
    289   int short_read_limit() const { return short_read_limit_; }
    290   void set_short_read_limit(int limit) { short_read_limit_ = limit; }
    291 
    292   void allow_unconsumed_reads(bool allow) { allow_unconsumed_reads_ = allow; }
    293 
    294   // SocketDataProvider implementation.
    295   virtual MockRead GetNextRead() OVERRIDE;
    296   virtual MockWriteResult OnWrite(const std::string& data) = 0;
    297   virtual void Reset() OVERRIDE;
    298 
    299  protected:
    300   // The next time there is a read from this socket, it will return |data|.
    301   // Before calling SimulateRead next time, the previous data must be consumed.
    302   void SimulateRead(const char* data, size_t length);
    303   void SimulateRead(const char* data) { SimulateRead(data, std::strlen(data)); }
    304 
    305  private:
    306   std::deque<MockRead> reads_;
    307 
    308   // Max number of bytes we will read at a time. 0 means no limit.
    309   int short_read_limit_;
    310 
    311   // If true, we'll not require the client to consume all data before we
    312   // mock the next read.
    313   bool allow_unconsumed_reads_;
    314 
    315   DISALLOW_COPY_AND_ASSIGN(DynamicSocketDataProvider);
    316 };
    317 
    318 // SSLSocketDataProviders only need to keep track of the return code from calls
    319 // to Connect().
    320 struct SSLSocketDataProvider {
    321   SSLSocketDataProvider(IoMode mode, int result);
    322   ~SSLSocketDataProvider();
    323 
    324   void SetNextProto(NextProto proto);
    325 
    326   MockConnect connect;
    327   SSLClientSocket::NextProtoStatus next_proto_status;
    328   std::string next_proto;
    329   std::string server_protos;
    330   bool was_npn_negotiated;
    331   NextProto protocol_negotiated;
    332   bool client_cert_sent;
    333   SSLCertRequestInfo* cert_request_info;
    334   scoped_refptr<X509Certificate> cert;
    335   bool channel_id_sent;
    336   ServerBoundCertService* server_bound_cert_service;
    337   int connection_status;
    338 };
    339 
    340 // A DataProvider where the client must write a request before the reads (e.g.
    341 // the response) will complete.
    342 class DelayedSocketData : public StaticSocketDataProvider {
    343  public:
    344   // |write_delay| the number of MockWrites to complete before allowing
    345   //               a MockRead to complete.
    346   // |reads| the list of MockRead completions.
    347   // |writes| the list of MockWrite completions.
    348   // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
    349   //       MockRead(true, 0, 0);
    350   DelayedSocketData(int write_delay,
    351                     MockRead* reads,
    352                     size_t reads_count,
    353                     MockWrite* writes,
    354                     size_t writes_count);
    355 
    356   // |connect| the result for the connect phase.
    357   // |reads| the list of MockRead completions.
    358   // |write_delay| the number of MockWrites to complete before allowing
    359   //               a MockRead to complete.
    360   // |writes| the list of MockWrite completions.
    361   // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
    362   //       MockRead(true, 0, 0);
    363   DelayedSocketData(const MockConnect& connect,
    364                     int write_delay,
    365                     MockRead* reads,
    366                     size_t reads_count,
    367                     MockWrite* writes,
    368                     size_t writes_count);
    369   virtual ~DelayedSocketData();
    370 
    371   void ForceNextRead();
    372 
    373   // StaticSocketDataProvider:
    374   virtual MockRead GetNextRead() OVERRIDE;
    375   virtual MockWriteResult OnWrite(const std::string& data) OVERRIDE;
    376   virtual void Reset() OVERRIDE;
    377   virtual void CompleteRead() OVERRIDE;
    378 
    379  private:
    380   int write_delay_;
    381   bool read_in_progress_;
    382 
    383   base::WeakPtrFactory<DelayedSocketData> weak_factory_;
    384 
    385   DISALLOW_COPY_AND_ASSIGN(DelayedSocketData);
    386 };
    387 
    388 // A DataProvider where the reads are ordered.
    389 // If a read is requested before its sequence number is reached, we return an
    390 // ERR_IO_PENDING (that way we don't have to explicitly add a MockRead just to
    391 // wait).
    392 // The sequence number is incremented on every read and write operation.
    393 // The message loop may be interrupted by setting the high bit of the sequence
    394 // number in the MockRead's sequence number.  When that MockRead is reached,
    395 // we post a Quit message to the loop.  This allows us to interrupt the reading
    396 // of data before a complete message has arrived, and provides support for
    397 // testing server push when the request is issued while the response is in the
    398 // middle of being received.
    399 class OrderedSocketData : public StaticSocketDataProvider {
    400  public:
    401   // |reads| the list of MockRead completions.
    402   // |writes| the list of MockWrite completions.
    403   // Note: All MockReads and MockWrites must be async.
    404   // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
    405   //       MockRead(true, 0, 0);
    406   OrderedSocketData(MockRead* reads,
    407                     size_t reads_count,
    408                     MockWrite* writes,
    409                     size_t writes_count);
    410   virtual ~OrderedSocketData();
    411 
    412   // |connect| the result for the connect phase.
    413   // |reads| the list of MockRead completions.
    414   // |writes| the list of MockWrite completions.
    415   // Note: All MockReads and MockWrites must be async.
    416   // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
    417   //       MockRead(true, 0, 0);
    418   OrderedSocketData(const MockConnect& connect,
    419                     MockRead* reads,
    420                     size_t reads_count,
    421                     MockWrite* writes,
    422                     size_t writes_count);
    423 
    424   // Posts a quit message to the current message loop, if one is running.
    425   void EndLoop();
    426 
    427   // StaticSocketDataProvider:
    428   virtual MockRead GetNextRead() OVERRIDE;
    429   virtual MockWriteResult OnWrite(const std::string& data) OVERRIDE;
    430   virtual void Reset() OVERRIDE;
    431   virtual void CompleteRead() OVERRIDE;
    432 
    433  private:
    434   int sequence_number_;
    435   int loop_stop_stage_;
    436   bool blocked_;
    437 
    438   base::WeakPtrFactory<OrderedSocketData> weak_factory_;
    439 
    440   DISALLOW_COPY_AND_ASSIGN(OrderedSocketData);
    441 };
    442 
    443 class DeterministicMockTCPClientSocket;
    444 
    445 // This class gives the user full control over the network activity,
    446 // specifically the timing of the COMPLETION of I/O operations.  Regardless of
    447 // the order in which I/O operations are initiated, this class ensures that they
    448 // complete in the correct order.
    449 //
    450 // Network activity is modeled as a sequence of numbered steps which is
    451 // incremented whenever an I/O operation completes.  This can happen under two
    452 // different circumstances:
    453 //
    454 // 1) Performing a synchronous I/O operation.  (Invoking Read() or Write()
    455 //    when the corresponding MockRead or MockWrite is marked !async).
    456 // 2) Running the Run() method of this class.  The run method will invoke
    457 //    the current MessageLoop, running all pending events, and will then
    458 //    invoke any pending IO callbacks.
    459 //
    460 // In addition, this class allows for I/O processing to "stop" at a specified
    461 // step, by calling SetStop(int) or StopAfter(int).  Initiating an I/O operation
    462 // by calling Read() or Write() while stopped is permitted if the operation is
    463 // asynchronous.  It is an error to perform synchronous I/O while stopped.
    464 //
    465 // When creating the MockReads and MockWrites, note that the sequence number
    466 // refers to the number of the step in which the I/O will complete.  In the
    467 // case of synchronous I/O, this will be the same step as the I/O is initiated.
    468 // However, in the case of asynchronous I/O, this I/O may be initiated in
    469 // a much earlier step. Furthermore, when the a Read() or Write() is separated
    470 // from its completion by other Read() or Writes()'s, it can not be marked
    471 // synchronous.  If it is, ERR_UNUEXPECTED will be returned indicating that a
    472 // synchronous Read() or Write() could not be completed synchronously because of
    473 // the specific ordering constraints.
    474 //
    475 // Sequence numbers are preserved across both reads and writes. There should be
    476 // no gaps in sequence numbers, and no repeated sequence numbers. i.e.
    477 //  MockRead reads[] = {
    478 //    MockRead(false, "first read", length, 0)   // sync
    479 //    MockRead(true, "second read", length, 2)   // async
    480 //  };
    481 //  MockWrite writes[] = {
    482 //    MockWrite(true, "first write", length, 1),    // async
    483 //    MockWrite(false, "second write", length, 3),  // sync
    484 //  };
    485 //
    486 // Example control flow:
    487 // Read() is called.  The current step is 0.  The first available read is
    488 // synchronous, so the call to Read() returns length.  The current step is
    489 // now 1.  Next, Read() is called again.  The next available read can
    490 // not be completed until step 2, so Read() returns ERR_IO_PENDING.  The current
    491 // step is still 1.  Write is called().  The first available write is able to
    492 // complete in this step, but is marked asynchronous.  Write() returns
    493 // ERR_IO_PENDING.  The current step is still 1.  At this point RunFor(1) is
    494 // called which will cause the write callback to be invoked, and will then
    495 // stop.  The current state is now 2.  RunFor(1) is called again, which
    496 // causes the read callback to be invoked, and will then stop.  Then current
    497 // step is 2.  Write() is called again.  Then next available write is
    498 // synchronous so the call to Write() returns length.
    499 //
    500 // For examples of how to use this class, see:
    501 //   deterministic_socket_data_unittests.cc
    502 class DeterministicSocketData : public StaticSocketDataProvider {
    503  public:
    504   // The Delegate is an abstract interface which handles the communication from
    505   // the DeterministicSocketData to the Deterministic MockSocket.  The
    506   // MockSockets directly store a pointer to the DeterministicSocketData,
    507   // whereas the DeterministicSocketData only stores a pointer to the
    508   // abstract Delegate interface.
    509   class Delegate {
    510    public:
    511     // Returns true if there is currently a write pending. That is to say, if
    512     // an asynchronous write has been started but the callback has not been
    513     // invoked.
    514     virtual bool WritePending() const = 0;
    515     // Returns true if there is currently a read pending. That is to say, if
    516     // an asynchronous read has been started but the callback has not been
    517     // invoked.
    518     virtual bool ReadPending() const = 0;
    519     // Called to complete an asynchronous write to execute the write callback.
    520     virtual void CompleteWrite() = 0;
    521     // Called to complete an asynchronous read to execute the read callback.
    522     virtual int CompleteRead() = 0;
    523 
    524    protected:
    525     virtual ~Delegate() {}
    526   };
    527 
    528   // |reads| the list of MockRead completions.
    529   // |writes| the list of MockWrite completions.
    530   DeterministicSocketData(MockRead* reads,
    531                           size_t reads_count,
    532                           MockWrite* writes,
    533                           size_t writes_count);
    534   virtual ~DeterministicSocketData();
    535 
    536   // Consume all the data up to the give stop point (via SetStop()).
    537   void Run();
    538 
    539   // Set the stop point to be |steps| from now, and then invoke Run().
    540   void RunFor(int steps);
    541 
    542   // Stop at step |seq|, which must be in the future.
    543   virtual void SetStop(int seq);
    544 
    545   // Stop |seq| steps after the current step.
    546   virtual void StopAfter(int seq);
    547   bool stopped() const { return stopped_; }
    548   void SetStopped(bool val) { stopped_ = val; }
    549   MockRead& current_read() { return current_read_; }
    550   MockWrite& current_write() { return current_write_; }
    551   int sequence_number() const { return sequence_number_; }
    552   void set_delegate(base::WeakPtr<Delegate> delegate) { delegate_ = delegate; }
    553 
    554   // StaticSocketDataProvider:
    555 
    556   // When the socket calls Read(), that calls GetNextRead(), and expects either
    557   // ERR_IO_PENDING or data.
    558   virtual MockRead GetNextRead() OVERRIDE;
    559 
    560   // When the socket calls Write(), it always completes synchronously. OnWrite()
    561   // checks to make sure the written data matches the expected data. The
    562   // callback will not be invoked until its sequence number is reached.
    563   virtual MockWriteResult OnWrite(const std::string& data) OVERRIDE;
    564   virtual void Reset() OVERRIDE;
    565   virtual void CompleteRead() OVERRIDE {}
    566 
    567  private:
    568   // Invoke the read and write callbacks, if the timing is appropriate.
    569   void InvokeCallbacks();
    570 
    571   void NextStep();
    572 
    573   void VerifyCorrectSequenceNumbers(MockRead* reads,
    574                                     size_t reads_count,
    575                                     MockWrite* writes,
    576                                     size_t writes_count);
    577 
    578   int sequence_number_;
    579   MockRead current_read_;
    580   MockWrite current_write_;
    581   int stopping_sequence_number_;
    582   bool stopped_;
    583   base::WeakPtr<Delegate> delegate_;
    584   bool print_debug_;
    585   bool is_running_;
    586 };
    587 
    588 // Holds an array of SocketDataProvider elements.  As Mock{TCP,SSL}StreamSocket
    589 // objects get instantiated, they take their data from the i'th element of this
    590 // array.
    591 template <typename T>
    592 class SocketDataProviderArray {
    593  public:
    594   SocketDataProviderArray() : next_index_(0) {}
    595 
    596   T* GetNext() {
    597     DCHECK_LT(next_index_, data_providers_.size());
    598     return data_providers_[next_index_++];
    599   }
    600 
    601   void Add(T* data_provider) {
    602     DCHECK(data_provider);
    603     data_providers_.push_back(data_provider);
    604   }
    605 
    606   size_t next_index() { return next_index_; }
    607 
    608   void ResetNextIndex() { next_index_ = 0; }
    609 
    610  private:
    611   // Index of the next |data_providers_| element to use. Not an iterator
    612   // because those are invalidated on vector reallocation.
    613   size_t next_index_;
    614 
    615   // SocketDataProviders to be returned.
    616   std::vector<T*> data_providers_;
    617 };
    618 
    619 class MockUDPClientSocket;
    620 class MockTCPClientSocket;
    621 class MockSSLClientSocket;
    622 
    623 // ClientSocketFactory which contains arrays of sockets of each type.
    624 // You should first fill the arrays using AddMock{SSL,}Socket. When the factory
    625 // is asked to create a socket, it takes next entry from appropriate array.
    626 // You can use ResetNextMockIndexes to reset that next entry index for all mock
    627 // socket types.
    628 class MockClientSocketFactory : public ClientSocketFactory {
    629  public:
    630   MockClientSocketFactory();
    631   virtual ~MockClientSocketFactory();
    632 
    633   void AddSocketDataProvider(SocketDataProvider* socket);
    634   void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
    635   void ResetNextMockIndexes();
    636 
    637   SocketDataProviderArray<SocketDataProvider>& mock_data() {
    638     return mock_data_;
    639   }
    640 
    641   // ClientSocketFactory
    642   virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
    643       DatagramSocket::BindType bind_type,
    644       const RandIntCallback& rand_int_cb,
    645       NetLog* net_log,
    646       const NetLog::Source& source) OVERRIDE;
    647   virtual scoped_ptr<StreamSocket> CreateTransportClientSocket(
    648       const AddressList& addresses,
    649       NetLog* net_log,
    650       const NetLog::Source& source) OVERRIDE;
    651   virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
    652       scoped_ptr<ClientSocketHandle> transport_socket,
    653       const HostPortPair& host_and_port,
    654       const SSLConfig& ssl_config,
    655       const SSLClientSocketContext& context) OVERRIDE;
    656   virtual void ClearSSLSessionCache() OVERRIDE;
    657 
    658  private:
    659   SocketDataProviderArray<SocketDataProvider> mock_data_;
    660   SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
    661 };
    662 
    663 class MockClientSocket : public SSLClientSocket {
    664  public:
    665   // Value returned by GetTLSUniqueChannelBinding().
    666   static const char kTlsUnique[];
    667 
    668   // The BoundNetLog is needed to test LoadTimingInfo, which uses NetLog IDs as
    669   // unique socket IDs.
    670   explicit MockClientSocket(const BoundNetLog& net_log);
    671 
    672   // Socket implementation.
    673   virtual int Read(IOBuffer* buf,
    674                    int buf_len,
    675                    const CompletionCallback& callback) = 0;
    676   virtual int Write(IOBuffer* buf,
    677                     int buf_len,
    678                     const CompletionCallback& callback) = 0;
    679   virtual int SetReceiveBufferSize(int32 size) OVERRIDE;
    680   virtual int SetSendBufferSize(int32 size) OVERRIDE;
    681 
    682   // StreamSocket implementation.
    683   virtual int Connect(const CompletionCallback& callback) = 0;
    684   virtual void Disconnect() OVERRIDE;
    685   virtual bool IsConnected() const OVERRIDE;
    686   virtual bool IsConnectedAndIdle() const OVERRIDE;
    687   virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
    688   virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE;
    689   virtual const BoundNetLog& NetLog() const OVERRIDE;
    690   virtual void SetSubresourceSpeculation() OVERRIDE {}
    691   virtual void SetOmniboxSpeculation() OVERRIDE {}
    692 
    693   // SSLClientSocket implementation.
    694   virtual void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info)
    695       OVERRIDE;
    696   virtual int ExportKeyingMaterial(const base::StringPiece& label,
    697                                    bool has_context,
    698                                    const base::StringPiece& context,
    699                                    unsigned char* out,
    700                                    unsigned int outlen) OVERRIDE;
    701   virtual int GetTLSUniqueChannelBinding(std::string* out) OVERRIDE;
    702   virtual NextProtoStatus GetNextProto(std::string* proto,
    703                                        std::string* server_protos) OVERRIDE;
    704   virtual ServerBoundCertService* GetServerBoundCertService() const OVERRIDE;
    705 
    706  protected:
    707   virtual ~MockClientSocket();
    708   void RunCallbackAsync(const CompletionCallback& callback, int result);
    709   void RunCallback(const CompletionCallback& callback, int result);
    710 
    711   // SSLClientSocket implementation.
    712   virtual scoped_refptr<X509Certificate> GetUnverifiedServerCertificateChain()
    713       const OVERRIDE;
    714 
    715   // True if Connect completed successfully and Disconnect hasn't been called.
    716   bool connected_;
    717 
    718   // Address of the "remote" peer we're connected to.
    719   IPEndPoint peer_addr_;
    720 
    721   BoundNetLog net_log_;
    722 
    723   base::WeakPtrFactory<MockClientSocket> weak_factory_;
    724 
    725   DISALLOW_COPY_AND_ASSIGN(MockClientSocket);
    726 };
    727 
    728 class MockTCPClientSocket : public MockClientSocket, public AsyncSocket {
    729  public:
    730   MockTCPClientSocket(const AddressList& addresses,
    731                       net::NetLog* net_log,
    732                       SocketDataProvider* socket);
    733   virtual ~MockTCPClientSocket();
    734 
    735   const AddressList& addresses() const { return addresses_; }
    736 
    737   // Socket implementation.
    738   virtual int Read(IOBuffer* buf,
    739                    int buf_len,
    740                    const CompletionCallback& callback) OVERRIDE;
    741   virtual int Write(IOBuffer* buf,
    742                     int buf_len,
    743                     const CompletionCallback& callback) OVERRIDE;
    744 
    745   // StreamSocket implementation.
    746   virtual int Connect(const CompletionCallback& callback) OVERRIDE;
    747   virtual void Disconnect() OVERRIDE;
    748   virtual bool IsConnected() const OVERRIDE;
    749   virtual bool IsConnectedAndIdle() const OVERRIDE;
    750   virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
    751   virtual bool WasEverUsed() const OVERRIDE;
    752   virtual bool UsingTCPFastOpen() const OVERRIDE;
    753   virtual bool WasNpnNegotiated() const OVERRIDE;
    754   virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE;
    755 
    756   // AsyncSocket:
    757   virtual void OnReadComplete(const MockRead& data) OVERRIDE;
    758   virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
    759 
    760  private:
    761   int CompleteRead();
    762 
    763   AddressList addresses_;
    764 
    765   SocketDataProvider* data_;
    766   int read_offset_;
    767   MockRead read_data_;
    768   bool need_read_data_;
    769 
    770   // True if the peer has closed the connection.  This allows us to simulate
    771   // the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real
    772   // TCPClientSocket.
    773   bool peer_closed_connection_;
    774 
    775   // While an asynchronous IO is pending, we save our user-buffer state.
    776   scoped_refptr<IOBuffer> pending_buf_;
    777   int pending_buf_len_;
    778   CompletionCallback pending_callback_;
    779   bool was_used_to_convey_data_;
    780 
    781   DISALLOW_COPY_AND_ASSIGN(MockTCPClientSocket);
    782 };
    783 
    784 // DeterministicSocketHelper is a helper class that can be used
    785 // to simulate net::Socket::Read() and net::Socket::Write()
    786 // using deterministic |data|.
    787 // Note: This is provided as a common helper class because
    788 // of the inheritance hierarchy of DeterministicMock[UDP,TCP]ClientSocket and a
    789 // desire not to introduce an additional common base class.
    790 class DeterministicSocketHelper {
    791  public:
    792   DeterministicSocketHelper(net::NetLog* net_log,
    793                             DeterministicSocketData* data);
    794   virtual ~DeterministicSocketHelper();
    795 
    796   bool write_pending() const { return write_pending_; }
    797   bool read_pending() const { return read_pending_; }
    798 
    799   void CompleteWrite();
    800   int CompleteRead();
    801 
    802   int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
    803   int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
    804 
    805   const BoundNetLog& net_log() const { return net_log_; }
    806 
    807   bool was_used_to_convey_data() const { return was_used_to_convey_data_; }
    808 
    809   bool peer_closed_connection() const { return peer_closed_connection_; }
    810 
    811   DeterministicSocketData* data() const { return data_; }
    812 
    813  private:
    814   bool write_pending_;
    815   CompletionCallback write_callback_;
    816   int write_result_;
    817 
    818   MockRead read_data_;
    819 
    820   IOBuffer* read_buf_;
    821   int read_buf_len_;
    822   bool read_pending_;
    823   CompletionCallback read_callback_;
    824   DeterministicSocketData* data_;
    825   bool was_used_to_convey_data_;
    826   bool peer_closed_connection_;
    827   BoundNetLog net_log_;
    828 };
    829 
    830 // Mock UDP socket to be used in conjunction with DeterministicSocketData.
    831 class DeterministicMockUDPClientSocket
    832     : public DatagramClientSocket,
    833       public AsyncSocket,
    834       public DeterministicSocketData::Delegate,
    835       public base::SupportsWeakPtr<DeterministicMockUDPClientSocket> {
    836  public:
    837   DeterministicMockUDPClientSocket(net::NetLog* net_log,
    838                                    DeterministicSocketData* data);
    839   virtual ~DeterministicMockUDPClientSocket();
    840 
    841   // DeterministicSocketData::Delegate:
    842   virtual bool WritePending() const OVERRIDE;
    843   virtual bool ReadPending() const OVERRIDE;
    844   virtual void CompleteWrite() OVERRIDE;
    845   virtual int CompleteRead() OVERRIDE;
    846 
    847   // Socket implementation.
    848   virtual int Read(IOBuffer* buf,
    849                    int buf_len,
    850                    const CompletionCallback& callback) OVERRIDE;
    851   virtual int Write(IOBuffer* buf,
    852                     int buf_len,
    853                     const CompletionCallback& callback) OVERRIDE;
    854   virtual int SetReceiveBufferSize(int32 size) OVERRIDE;
    855   virtual int SetSendBufferSize(int32 size) OVERRIDE;
    856 
    857   // DatagramSocket implementation.
    858   virtual void Close() OVERRIDE;
    859   virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
    860   virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE;
    861   virtual const BoundNetLog& NetLog() const OVERRIDE;
    862 
    863   // DatagramClientSocket implementation.
    864   virtual int Connect(const IPEndPoint& address) OVERRIDE;
    865 
    866   // AsyncSocket implementation.
    867   virtual void OnReadComplete(const MockRead& data) OVERRIDE;
    868   virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
    869 
    870   void set_source_port(int port) { source_port_ = port; }
    871 
    872  private:
    873   bool connected_;
    874   IPEndPoint peer_address_;
    875   DeterministicSocketHelper helper_;
    876   int source_port_;  // Ephemeral source port.
    877 
    878   DISALLOW_COPY_AND_ASSIGN(DeterministicMockUDPClientSocket);
    879 };
    880 
    881 // Mock TCP socket to be used in conjunction with DeterministicSocketData.
    882 class DeterministicMockTCPClientSocket
    883     : public MockClientSocket,
    884       public AsyncSocket,
    885       public DeterministicSocketData::Delegate,
    886       public base::SupportsWeakPtr<DeterministicMockTCPClientSocket> {
    887  public:
    888   DeterministicMockTCPClientSocket(net::NetLog* net_log,
    889                                    DeterministicSocketData* data);
    890   virtual ~DeterministicMockTCPClientSocket();
    891 
    892   // DeterministicSocketData::Delegate:
    893   virtual bool WritePending() const OVERRIDE;
    894   virtual bool ReadPending() const OVERRIDE;
    895   virtual void CompleteWrite() OVERRIDE;
    896   virtual int CompleteRead() OVERRIDE;
    897 
    898   // Socket:
    899   virtual int Write(IOBuffer* buf,
    900                     int buf_len,
    901                     const CompletionCallback& callback) OVERRIDE;
    902   virtual int Read(IOBuffer* buf,
    903                    int buf_len,
    904                    const CompletionCallback& callback) OVERRIDE;
    905 
    906   // StreamSocket:
    907   virtual int Connect(const CompletionCallback& callback) OVERRIDE;
    908   virtual void Disconnect() OVERRIDE;
    909   virtual bool IsConnected() const OVERRIDE;
    910   virtual bool IsConnectedAndIdle() const OVERRIDE;
    911   virtual bool WasEverUsed() const OVERRIDE;
    912   virtual bool UsingTCPFastOpen() const OVERRIDE;
    913   virtual bool WasNpnNegotiated() const OVERRIDE;
    914   virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE;
    915 
    916   // AsyncSocket:
    917   virtual void OnReadComplete(const MockRead& data) OVERRIDE;
    918   virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
    919 
    920  private:
    921   DeterministicSocketHelper helper_;
    922 
    923   DISALLOW_COPY_AND_ASSIGN(DeterministicMockTCPClientSocket);
    924 };
    925 
    926 class MockSSLClientSocket : public MockClientSocket, public AsyncSocket {
    927  public:
    928   MockSSLClientSocket(scoped_ptr<ClientSocketHandle> transport_socket,
    929                       const HostPortPair& host_and_port,
    930                       const SSLConfig& ssl_config,
    931                       SSLSocketDataProvider* socket);
    932   virtual ~MockSSLClientSocket();
    933 
    934   // Socket implementation.
    935   virtual int Read(IOBuffer* buf,
    936                    int buf_len,
    937                    const CompletionCallback& callback) OVERRIDE;
    938   virtual int Write(IOBuffer* buf,
    939                     int buf_len,
    940                     const CompletionCallback& callback) OVERRIDE;
    941 
    942   // StreamSocket implementation.
    943   virtual int Connect(const CompletionCallback& callback) OVERRIDE;
    944   virtual void Disconnect() OVERRIDE;
    945   virtual bool IsConnected() const OVERRIDE;
    946   virtual bool WasEverUsed() const OVERRIDE;
    947   virtual bool UsingTCPFastOpen() const OVERRIDE;
    948   virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
    949   virtual bool WasNpnNegotiated() const OVERRIDE;
    950   virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE;
    951 
    952   // SSLClientSocket implementation.
    953   virtual void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info)
    954       OVERRIDE;
    955   virtual NextProtoStatus GetNextProto(std::string* proto,
    956                                        std::string* server_protos) OVERRIDE;
    957   virtual bool set_was_npn_negotiated(bool negotiated) OVERRIDE;
    958   virtual void set_protocol_negotiated(NextProto protocol_negotiated) OVERRIDE;
    959   virtual NextProto GetNegotiatedProtocol() const OVERRIDE;
    960 
    961   // This MockSocket does not implement the manual async IO feature.
    962   virtual void OnReadComplete(const MockRead& data) OVERRIDE;
    963   virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
    964 
    965   virtual bool WasChannelIDSent() const OVERRIDE;
    966   virtual void set_channel_id_sent(bool channel_id_sent) OVERRIDE;
    967   virtual ServerBoundCertService* GetServerBoundCertService() const OVERRIDE;
    968 
    969  private:
    970   static void ConnectCallback(MockSSLClientSocket* ssl_client_socket,
    971                               const CompletionCallback& callback,
    972                               int rv);
    973 
    974   scoped_ptr<ClientSocketHandle> transport_;
    975   SSLSocketDataProvider* data_;
    976   bool is_npn_state_set_;
    977   bool new_npn_value_;
    978   bool is_protocol_negotiated_set_;
    979   NextProto protocol_negotiated_;
    980 
    981   DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket);
    982 };
    983 
    984 class MockUDPClientSocket : public DatagramClientSocket, public AsyncSocket {
    985  public:
    986   MockUDPClientSocket(SocketDataProvider* data, net::NetLog* net_log);
    987   virtual ~MockUDPClientSocket();
    988 
    989   // Socket implementation.
    990   virtual int Read(IOBuffer* buf,
    991                    int buf_len,
    992                    const CompletionCallback& callback) OVERRIDE;
    993   virtual int Write(IOBuffer* buf,
    994                     int buf_len,
    995                     const CompletionCallback& callback) OVERRIDE;
    996   virtual int SetReceiveBufferSize(int32 size) OVERRIDE;
    997   virtual int SetSendBufferSize(int32 size) OVERRIDE;
    998 
    999   // DatagramSocket implementation.
   1000   virtual void Close() OVERRIDE;
   1001   virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
   1002   virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE;
   1003   virtual const BoundNetLog& NetLog() const OVERRIDE;
   1004 
   1005   // DatagramClientSocket implementation.
   1006   virtual int Connect(const IPEndPoint& address) OVERRIDE;
   1007 
   1008   // AsyncSocket implementation.
   1009   virtual void OnReadComplete(const MockRead& data) OVERRIDE;
   1010   virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
   1011 
   1012   void set_source_port(int port) { source_port_ = port;}
   1013 
   1014  private:
   1015   int CompleteRead();
   1016 
   1017   void RunCallbackAsync(const CompletionCallback& callback, int result);
   1018   void RunCallback(const CompletionCallback& callback, int result);
   1019 
   1020   bool connected_;
   1021   SocketDataProvider* data_;
   1022   int read_offset_;
   1023   MockRead read_data_;
   1024   bool need_read_data_;
   1025   int source_port_;  // Ephemeral source port.
   1026 
   1027   // Address of the "remote" peer we're connected to.
   1028   IPEndPoint peer_addr_;
   1029 
   1030   // While an asynchronous IO is pending, we save our user-buffer state.
   1031   scoped_refptr<IOBuffer> pending_buf_;
   1032   int pending_buf_len_;
   1033   CompletionCallback pending_callback_;
   1034 
   1035   BoundNetLog net_log_;
   1036 
   1037   base::WeakPtrFactory<MockUDPClientSocket> weak_factory_;
   1038 
   1039   DISALLOW_COPY_AND_ASSIGN(MockUDPClientSocket);
   1040 };
   1041 
   1042 class TestSocketRequest : public TestCompletionCallbackBase {
   1043  public:
   1044   TestSocketRequest(std::vector<TestSocketRequest*>* request_order,
   1045                     size_t* completion_count);
   1046   virtual ~TestSocketRequest();
   1047 
   1048   ClientSocketHandle* handle() { return &handle_; }
   1049 
   1050   const net::CompletionCallback& callback() const { return callback_; }
   1051 
   1052  private:
   1053   void OnComplete(int result);
   1054 
   1055   ClientSocketHandle handle_;
   1056   std::vector<TestSocketRequest*>* request_order_;
   1057   size_t* completion_count_;
   1058   CompletionCallback callback_;
   1059 
   1060   DISALLOW_COPY_AND_ASSIGN(TestSocketRequest);
   1061 };
   1062 
   1063 class ClientSocketPoolTest {
   1064  public:
   1065   enum KeepAlive {
   1066     KEEP_ALIVE,
   1067 
   1068     // A socket will be disconnected in addition to handle being reset.
   1069     NO_KEEP_ALIVE,
   1070   };
   1071 
   1072   static const int kIndexOutOfBounds;
   1073   static const int kRequestNotFound;
   1074 
   1075   ClientSocketPoolTest();
   1076   ~ClientSocketPoolTest();
   1077 
   1078   template <typename PoolType>
   1079   int StartRequestUsingPool(
   1080       PoolType* socket_pool,
   1081       const std::string& group_name,
   1082       RequestPriority priority,
   1083       const scoped_refptr<typename PoolType::SocketParams>& socket_params) {
   1084     DCHECK(socket_pool);
   1085     TestSocketRequest* request =
   1086         new TestSocketRequest(&request_order_, &completion_count_);
   1087     requests_.push_back(request);
   1088     int rv = request->handle()->Init(group_name,
   1089                                      socket_params,
   1090                                      priority,
   1091                                      request->callback(),
   1092                                      socket_pool,
   1093                                      BoundNetLog());
   1094     if (rv != ERR_IO_PENDING)
   1095       request_order_.push_back(request);
   1096     return rv;
   1097   }
   1098 
   1099   // Provided there were n requests started, takes |index| in range 1..n
   1100   // and returns order in which that request completed, in range 1..n,
   1101   // or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound
   1102   // if that request did not complete (for example was canceled).
   1103   int GetOrderOfRequest(size_t index) const;
   1104 
   1105   // Resets first initialized socket handle from |requests_|. If found such
   1106   // a handle, returns true.
   1107   bool ReleaseOneConnection(KeepAlive keep_alive);
   1108 
   1109   // Releases connections until there is nothing to release.
   1110   void ReleaseAllConnections(KeepAlive keep_alive);
   1111 
   1112   // Note that this uses 0-based indices, while GetOrderOfRequest takes and
   1113   // returns 0-based indices.
   1114   TestSocketRequest* request(int i) { return requests_[i]; }
   1115 
   1116   size_t requests_size() const { return requests_.size(); }
   1117   ScopedVector<TestSocketRequest>* requests() { return &requests_; }
   1118   size_t completion_count() const { return completion_count_; }
   1119 
   1120  private:
   1121   ScopedVector<TestSocketRequest> requests_;
   1122   std::vector<TestSocketRequest*> request_order_;
   1123   size_t completion_count_;
   1124 
   1125   DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolTest);
   1126 };
   1127 
   1128 class MockTransportSocketParams
   1129     : public base::RefCounted<MockTransportSocketParams> {
   1130  private:
   1131   friend class base::RefCounted<MockTransportSocketParams>;
   1132   ~MockTransportSocketParams() {}
   1133 
   1134   DISALLOW_COPY_AND_ASSIGN(MockTransportSocketParams);
   1135 };
   1136 
   1137 class MockTransportClientSocketPool : public TransportClientSocketPool {
   1138  public:
   1139   typedef MockTransportSocketParams SocketParams;
   1140 
   1141   class MockConnectJob {
   1142    public:
   1143     MockConnectJob(scoped_ptr<StreamSocket> socket,
   1144                    ClientSocketHandle* handle,
   1145                    const CompletionCallback& callback);
   1146     ~MockConnectJob();
   1147 
   1148     int Connect();
   1149     bool CancelHandle(const ClientSocketHandle* handle);
   1150 
   1151    private:
   1152     void OnConnect(int rv);
   1153 
   1154     scoped_ptr<StreamSocket> socket_;
   1155     ClientSocketHandle* handle_;
   1156     CompletionCallback user_callback_;
   1157 
   1158     DISALLOW_COPY_AND_ASSIGN(MockConnectJob);
   1159   };
   1160 
   1161   MockTransportClientSocketPool(int max_sockets,
   1162                                 int max_sockets_per_group,
   1163                                 ClientSocketPoolHistograms* histograms,
   1164                                 ClientSocketFactory* socket_factory);
   1165 
   1166   virtual ~MockTransportClientSocketPool();
   1167 
   1168   RequestPriority last_request_priority() const {
   1169     return last_request_priority_;
   1170   }
   1171   int release_count() const { return release_count_; }
   1172   int cancel_count() const { return cancel_count_; }
   1173 
   1174   // TransportClientSocketPool implementation.
   1175   virtual int RequestSocket(const std::string& group_name,
   1176                             const void* socket_params,
   1177                             RequestPriority priority,
   1178                             ClientSocketHandle* handle,
   1179                             const CompletionCallback& callback,
   1180                             const BoundNetLog& net_log) OVERRIDE;
   1181 
   1182   virtual void CancelRequest(const std::string& group_name,
   1183                              ClientSocketHandle* handle) OVERRIDE;
   1184   virtual void ReleaseSocket(const std::string& group_name,
   1185                              scoped_ptr<StreamSocket> socket,
   1186                              int id) OVERRIDE;
   1187 
   1188  private:
   1189   ClientSocketFactory* client_socket_factory_;
   1190   ScopedVector<MockConnectJob> job_list_;
   1191   RequestPriority last_request_priority_;
   1192   int release_count_;
   1193   int cancel_count_;
   1194 
   1195   DISALLOW_COPY_AND_ASSIGN(MockTransportClientSocketPool);
   1196 };
   1197 
   1198 class DeterministicMockClientSocketFactory : public ClientSocketFactory {
   1199  public:
   1200   DeterministicMockClientSocketFactory();
   1201   virtual ~DeterministicMockClientSocketFactory();
   1202 
   1203   void AddSocketDataProvider(DeterministicSocketData* socket);
   1204   void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
   1205   void ResetNextMockIndexes();
   1206 
   1207   // Return |index|-th MockSSLClientSocket (starting from 0) that the factory
   1208   // created.
   1209   MockSSLClientSocket* GetMockSSLClientSocket(size_t index) const;
   1210 
   1211   SocketDataProviderArray<DeterministicSocketData>& mock_data() {
   1212     return mock_data_;
   1213   }
   1214   std::vector<DeterministicMockTCPClientSocket*>& tcp_client_sockets() {
   1215     return tcp_client_sockets_;
   1216   }
   1217   std::vector<DeterministicMockUDPClientSocket*>& udp_client_sockets() {
   1218     return udp_client_sockets_;
   1219   }
   1220 
   1221   // ClientSocketFactory
   1222   virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
   1223       DatagramSocket::BindType bind_type,
   1224       const RandIntCallback& rand_int_cb,
   1225       NetLog* net_log,
   1226       const NetLog::Source& source) OVERRIDE;
   1227   virtual scoped_ptr<StreamSocket> CreateTransportClientSocket(
   1228       const AddressList& addresses,
   1229       NetLog* net_log,
   1230       const NetLog::Source& source) OVERRIDE;
   1231   virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
   1232       scoped_ptr<ClientSocketHandle> transport_socket,
   1233       const HostPortPair& host_and_port,
   1234       const SSLConfig& ssl_config,
   1235       const SSLClientSocketContext& context) OVERRIDE;
   1236   virtual void ClearSSLSessionCache() OVERRIDE;
   1237 
   1238  private:
   1239   SocketDataProviderArray<DeterministicSocketData> mock_data_;
   1240   SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
   1241 
   1242   // Store pointers to handed out sockets in case the test wants to get them.
   1243   std::vector<DeterministicMockTCPClientSocket*> tcp_client_sockets_;
   1244   std::vector<DeterministicMockUDPClientSocket*> udp_client_sockets_;
   1245   std::vector<MockSSLClientSocket*> ssl_client_sockets_;
   1246 
   1247   DISALLOW_COPY_AND_ASSIGN(DeterministicMockClientSocketFactory);
   1248 };
   1249 
   1250 class MockSOCKSClientSocketPool : public SOCKSClientSocketPool {
   1251  public:
   1252   MockSOCKSClientSocketPool(int max_sockets,
   1253                             int max_sockets_per_group,
   1254                             ClientSocketPoolHistograms* histograms,
   1255                             TransportClientSocketPool* transport_pool);
   1256 
   1257   virtual ~MockSOCKSClientSocketPool();
   1258 
   1259   // SOCKSClientSocketPool implementation.
   1260   virtual int RequestSocket(const std::string& group_name,
   1261                             const void* socket_params,
   1262                             RequestPriority priority,
   1263                             ClientSocketHandle* handle,
   1264                             const CompletionCallback& callback,
   1265                             const BoundNetLog& net_log) OVERRIDE;
   1266 
   1267   virtual void CancelRequest(const std::string& group_name,
   1268                              ClientSocketHandle* handle) OVERRIDE;
   1269   virtual void ReleaseSocket(const std::string& group_name,
   1270                              scoped_ptr<StreamSocket> socket,
   1271                              int id) OVERRIDE;
   1272 
   1273  private:
   1274   TransportClientSocketPool* const transport_pool_;
   1275 
   1276   DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool);
   1277 };
   1278 
   1279 // Constants for a successful SOCKS v5 handshake.
   1280 extern const char kSOCKS5GreetRequest[];
   1281 extern const int kSOCKS5GreetRequestLength;
   1282 
   1283 extern const char kSOCKS5GreetResponse[];
   1284 extern const int kSOCKS5GreetResponseLength;
   1285 
   1286 extern const char kSOCKS5OkRequest[];
   1287 extern const int kSOCKS5OkRequestLength;
   1288 
   1289 extern const char kSOCKS5OkResponse[];
   1290 extern const int kSOCKS5OkResponseLength;
   1291 
   1292 }  // namespace net
   1293 
   1294 #endif  // NET_SOCKET_SOCKET_TEST_UTIL_H_
   1295