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