1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef NET_SOCKET_SOCKET_TEST_UTIL_H_
6 #define NET_SOCKET_SOCKET_TEST_UTIL_H_
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 "base/time/time.h"
22 #include "net/base/address_list.h"
23 #include "net/base/io_buffer.h"
24 #include "net/base/net_errors.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/log/net_log.h"
29 #include "net/socket/client_socket_factory.h"
30 #include "net/socket/client_socket_handle.h"
31 #include "net/socket/socks_client_socket_pool.h"
32 #include "net/socket/ssl_client_socket.h"
33 #include "net/socket/ssl_client_socket_pool.h"
34 #include "net/socket/transport_client_socket_pool.h"
35 #include "net/ssl/ssl_config_service.h"
36 #include "net/udp/datagram_client_socket.h"
37 #include "testing/gtest/include/gtest/gtest.h"
42 // A private network error code used by the socket test utility classes.
43 // If the |result| member of a MockRead is
44 // ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ, that MockRead is just a
45 // marker that indicates the peer will close the connection after the next
46 // MockRead. The other members of that MockRead are ignored.
47 ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ
= -10000,
51 class ChannelIDService
;
52 class MockClientSocket
;
53 class SSLClientSocket
;
62 // Asynchronous connection success.
63 // Creates a MockConnect with |mode| ASYC, |result| OK, and
64 // |peer_addr| 192.0.2.33.
66 // Creates a MockConnect with the specified mode and result, with
67 // |peer_addr| 192.0.2.33.
68 MockConnect(IoMode io_mode
, int r
);
69 MockConnect(IoMode io_mode
, int r
, IPEndPoint addr
);
77 // MockRead and MockWrite shares the same interface and members, but we'd like
78 // to have distinct types because we don't want to have them used
79 // interchangably. To do this, a struct template is defined, and MockRead and
80 // MockWrite are instantiated by using this template. Template parameter |type|
81 // is not used in the struct definition (it purely exists for creating a new
84 // |data| in MockRead and MockWrite has different meanings: |data| in MockRead
85 // is the data returned from the socket when MockTCPClientSocket::Read() is
86 // attempted, while |data| in MockWrite is the expected data that should be
87 // given in MockTCPClientSocket::Write().
88 enum MockReadWriteType
{
93 template <MockReadWriteType type
>
94 struct MockReadWrite
{
95 // Flag to indicate that the message loop should be terminated.
106 sequence_number(0) {}
108 // Read/write failure (no data).
109 MockReadWrite(IoMode io_mode
, int result
)
114 sequence_number(0) {}
116 // Read/write failure (no data), with sequence information.
117 MockReadWrite(IoMode io_mode
, int result
, int seq
)
122 sequence_number(seq
) {}
124 // Asynchronous read/write success (inferred data length).
125 explicit MockReadWrite(const char* data
)
129 data_len(strlen(data
)),
130 sequence_number(0) {}
132 // Read/write success (inferred data length).
133 MockReadWrite(IoMode io_mode
, const char* data
)
137 data_len(strlen(data
)),
138 sequence_number(0) {}
140 // Read/write success.
141 MockReadWrite(IoMode io_mode
, const char* data
, int data_len
)
146 sequence_number(0) {}
148 // Read/write success (inferred data length) with sequence information.
149 MockReadWrite(IoMode io_mode
, int seq
, const char* data
)
153 data_len(strlen(data
)),
154 sequence_number(seq
) {}
156 // Read/write success with sequence information.
157 MockReadWrite(IoMode io_mode
, const char* data
, int data_len
, int seq
)
162 sequence_number(seq
) {}
169 // For OrderedSocketData, which only allows reads to occur in a particular
170 // sequence. If a read occurs before the given |sequence_number| is reached,
171 // an ERR_IO_PENDING is returned.
172 int sequence_number
; // The sequence number at which a read is allowed
176 typedef MockReadWrite
<MOCK_READ
> MockRead
;
177 typedef MockReadWrite
<MOCK_WRITE
> MockWrite
;
179 struct MockWriteResult
{
180 MockWriteResult(IoMode io_mode
, int result
) : mode(io_mode
), result(result
) {}
186 // The SocketDataProvider is an interface used by the MockClientSocket
187 // for getting data about individual reads and writes on the socket.
188 class SocketDataProvider
{
190 SocketDataProvider() : socket_(NULL
) {}
192 virtual ~SocketDataProvider() {}
194 // Returns the buffer and result code for the next simulated read.
195 // If the |MockRead.result| is ERR_IO_PENDING, it informs the caller
196 // that it will be called via the AsyncSocket::OnReadComplete()
197 // function at a later time.
198 virtual MockRead
OnRead() = 0;
199 virtual MockWriteResult
OnWrite(const std::string
& data
) = 0;
200 virtual void Reset() = 0;
202 // Accessor for the socket which is using the SocketDataProvider.
203 AsyncSocket
* socket() { return socket_
; }
204 void set_socket(AsyncSocket
* socket
) { socket_
= socket
; }
206 MockConnect
connect_data() const { return connect_
; }
207 void set_connect_data(const MockConnect
& connect
) { connect_
= connect
; }
210 MockConnect connect_
;
211 AsyncSocket
* socket_
;
213 DISALLOW_COPY_AND_ASSIGN(SocketDataProvider
);
216 // The AsyncSocket is an interface used by the SocketDataProvider to
217 // complete the asynchronous read operation.
220 // If an async IO is pending because the SocketDataProvider returned
221 // ERR_IO_PENDING, then the AsyncSocket waits until this OnReadComplete
222 // is called to complete the asynchronous read operation.
223 // data.async is ignored, and this read is completed synchronously as
224 // part of this call.
225 // TODO(rch): this should take a StringPiece since most of the fields
227 virtual void OnReadComplete(const MockRead
& data
) = 0;
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 virtual void OnWriteComplete(int rv
) = 0;
232 virtual void OnConnectComplete(const MockConnect
& data
) = 0;
235 // StaticSocketDataHelper manages a list of reads and writes.
236 class StaticSocketDataHelper
{
238 StaticSocketDataHelper(MockRead
* reads
,
241 size_t writes_count
);
242 ~StaticSocketDataHelper();
244 // These functions get access to the next available read and write data,
245 // or null if there is no more data available.
246 const MockRead
& PeekRead() const;
247 const MockWrite
& PeekWrite() const;
249 // Returns the current read or write , and then advances to the next one.
250 const MockRead
& AdvanceRead();
251 const MockWrite
& AdvanceWrite();
253 // Resets the read and write indexes to 0.
256 // Returns true if |data| is valid data for the next write. In order
257 // to support short writes, the next write may be longer than |data|
258 // in which case this method will still return true.
259 bool VerifyWriteData(const std::string
& data
);
261 size_t read_index() const { return read_index_
; }
262 size_t write_index() const { return write_index_
; }
263 size_t read_count() const { return read_count_
; }
264 size_t write_count() const { return write_count_
; }
266 bool at_read_eof() const { return read_index_
>= read_count_
; }
267 bool at_write_eof() const { return write_index_
>= write_count_
; }
277 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataHelper
);
280 // SocketDataProvider which responds based on static tables of mock reads and
282 class StaticSocketDataProvider
: public SocketDataProvider
{
284 StaticSocketDataProvider();
285 StaticSocketDataProvider(MockRead
* reads
,
288 size_t writes_count
);
289 ~StaticSocketDataProvider() override
;
291 virtual void CompleteRead() {}
293 // SocketDataProvider implementation.
294 MockRead
OnRead() override
;
295 MockWriteResult
OnWrite(const std::string
& data
) override
;
296 void Reset() override
;
298 size_t read_index() const { return helper_
.read_index(); }
299 size_t write_index() const { return helper_
.write_index(); }
300 size_t read_count() const { return helper_
.read_count(); }
301 size_t write_count() const { return helper_
.write_count(); }
303 bool at_read_eof() const { return helper_
.at_read_eof(); }
304 bool at_write_eof() const { return helper_
.at_write_eof(); }
307 StaticSocketDataHelper
* helper() { return &helper_
; }
310 StaticSocketDataHelper helper_
;
312 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataProvider
);
315 // SocketDataProvider which can make decisions about next mock reads based on
316 // received writes. It can also be used to enforce order of operations, for
317 // example that tested code must send the "Hello!" message before receiving
318 // response. This is useful for testing conversation-like protocols like FTP.
319 class DynamicSocketDataProvider
: public SocketDataProvider
{
321 DynamicSocketDataProvider();
322 ~DynamicSocketDataProvider() override
;
324 int short_read_limit() const { return short_read_limit_
; }
325 void set_short_read_limit(int limit
) { short_read_limit_
= limit
; }
327 void allow_unconsumed_reads(bool allow
) { allow_unconsumed_reads_
= allow
; }
329 // SocketDataProvider implementation.
330 MockRead
OnRead() override
;
331 MockWriteResult
OnWrite(const std::string
& data
) override
= 0;
332 void Reset() override
;
335 // The next time there is a read from this socket, it will return |data|.
336 // Before calling SimulateRead next time, the previous data must be consumed.
337 void SimulateRead(const char* data
, size_t length
);
338 void SimulateRead(const char* data
) { SimulateRead(data
, std::strlen(data
)); }
341 std::deque
<MockRead
> reads_
;
343 // Max number of bytes we will read at a time. 0 means no limit.
344 int short_read_limit_
;
346 // If true, we'll not require the client to consume all data before we
347 // mock the next read.
348 bool allow_unconsumed_reads_
;
350 DISALLOW_COPY_AND_ASSIGN(DynamicSocketDataProvider
);
353 // SSLSocketDataProviders only need to keep track of the return code from calls
355 struct SSLSocketDataProvider
{
356 SSLSocketDataProvider(IoMode mode
, int result
);
357 ~SSLSocketDataProvider();
359 void SetNextProto(NextProto proto
);
362 SSLClientSocket::NextProtoStatus next_proto_status
;
363 std::string next_proto
;
364 bool was_npn_negotiated
;
365 NextProto protocol_negotiated
;
366 NextProtoVector next_protos_expected_in_ssl_config
;
367 bool client_cert_sent
;
368 SSLCertRequestInfo
* cert_request_info
;
369 scoped_refptr
<X509Certificate
> cert
;
370 bool channel_id_sent
;
371 ChannelIDService
* channel_id_service
;
372 int connection_status
;
375 // A DataProvider where the client must write a request before the reads (e.g.
376 // the response) will complete.
377 class DelayedSocketData
: public StaticSocketDataProvider
{
379 // |write_delay| the number of MockWrites to complete before allowing
380 // a MockRead to complete.
381 // |reads| the list of MockRead completions.
382 // |writes| the list of MockWrite completions.
383 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
384 // MockRead(true, 0, 0);
385 DelayedSocketData(int write_delay
,
389 size_t writes_count
);
391 // |connect| the result for the connect phase.
392 // |reads| the list of MockRead completions.
393 // |write_delay| the number of MockWrites to complete before allowing
394 // a MockRead to complete.
395 // |writes| the list of MockWrite completions.
396 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
397 // MockRead(true, 0, 0);
398 DelayedSocketData(const MockConnect
& connect
,
403 size_t writes_count
);
404 ~DelayedSocketData() override
;
406 void ForceNextRead();
408 // StaticSocketDataProvider:
409 MockRead
OnRead() override
;
410 MockWriteResult
OnWrite(const std::string
& data
) override
;
411 void Reset() override
;
412 void CompleteRead() override
;
416 bool read_in_progress_
;
418 base::WeakPtrFactory
<DelayedSocketData
> weak_factory_
;
420 DISALLOW_COPY_AND_ASSIGN(DelayedSocketData
);
423 // A DataProvider where the reads are ordered.
424 // If a read is requested before its sequence number is reached, we return an
425 // ERR_IO_PENDING (that way we don't have to explicitly add a MockRead just to
427 // The sequence number is incremented on every read and write operation.
428 // The message loop may be interrupted by setting the high bit of the sequence
429 // number in the MockRead's sequence number. When that MockRead is reached,
430 // we post a Quit message to the loop. This allows us to interrupt the reading
431 // of data before a complete message has arrived, and provides support for
432 // testing server push when the request is issued while the response is in the
433 // middle of being received.
434 class OrderedSocketData
: public StaticSocketDataProvider
{
436 // |reads| the list of MockRead completions.
437 // |writes| the list of MockWrite completions.
438 // Note: All MockReads and MockWrites must be async.
439 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
440 // MockRead(true, 0, 0);
441 OrderedSocketData(MockRead
* reads
,
444 size_t writes_count
);
445 ~OrderedSocketData() override
;
447 // |connect| the result for the connect phase.
448 // |reads| the list of MockRead completions.
449 // |writes| the list of MockWrite completions.
450 // Note: All MockReads and MockWrites must be async.
451 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
452 // MockRead(true, 0, 0);
453 OrderedSocketData(const MockConnect
& connect
,
457 size_t writes_count
);
459 // Posts a quit message to the current message loop, if one is running.
462 // StaticSocketDataProvider:
463 MockRead
OnRead() override
;
464 MockWriteResult
OnWrite(const std::string
& data
) override
;
465 void Reset() override
;
466 void CompleteRead() override
;
469 int sequence_number_
;
470 int loop_stop_stage_
;
473 base::WeakPtrFactory
<OrderedSocketData
> weak_factory_
;
475 DISALLOW_COPY_AND_ASSIGN(OrderedSocketData
);
478 // Uses the sequence_number field in the mock reads and writes to
479 // complete the operations in a specified order.
480 class SequencedSocketData
: public SocketDataProvider
{
482 // |reads| is the list of MockRead completions.
483 // |writes| is the list of MockWrite completions.
484 SequencedSocketData(MockRead
* reads
,
487 size_t writes_count
);
489 // |connect| is the result for the connect phase.
490 // |reads| is the list of MockRead completions.
491 // |writes| is the list of MockWrite completions.
492 SequencedSocketData(const MockConnect
& connect
,
496 size_t writes_count
);
498 ~SequencedSocketData() override
;
500 // SocketDataProviderBase implementation.
501 MockRead
OnRead() override
;
502 MockWriteResult
OnWrite(const std::string
& data
) override
;
503 void Reset() override
;
505 // Returns true if all data has been read.
508 // Returns true if all data has been written.
512 // Defines the state for the read or write path.
514 IDLE
, // No async operation is in progress.
515 PENDING
, // An async operation in waiting for another opteration to
517 COMPLETING
, // A task has been posted to complet an async operation.
519 void OnReadComplete();
520 void OnWriteComplete();
522 void MaybePostReadCompleteTask();
523 void MaybePostWriteCompleteTask();
525 StaticSocketDataHelper helper_
;
526 int sequence_number_
;
528 IoState write_state_
;
530 base::WeakPtrFactory
<SequencedSocketData
> weak_factory_
;
532 DISALLOW_COPY_AND_ASSIGN(SequencedSocketData
);
535 class DeterministicMockTCPClientSocket
;
537 // This class gives the user full control over the network activity,
538 // specifically the timing of the COMPLETION of I/O operations. Regardless of
539 // the order in which I/O operations are initiated, this class ensures that they
540 // complete in the correct order.
542 // Network activity is modeled as a sequence of numbered steps which is
543 // incremented whenever an I/O operation completes. This can happen under two
544 // different circumstances:
546 // 1) Performing a synchronous I/O operation. (Invoking Read() or Write()
547 // when the corresponding MockRead or MockWrite is marked !async).
548 // 2) Running the Run() method of this class. The run method will invoke
549 // the current MessageLoop, running all pending events, and will then
550 // invoke any pending IO callbacks.
552 // In addition, this class allows for I/O processing to "stop" at a specified
553 // step, by calling SetStop(int) or StopAfter(int). Initiating an I/O operation
554 // by calling Read() or Write() while stopped is permitted if the operation is
555 // asynchronous. It is an error to perform synchronous I/O while stopped.
557 // When creating the MockReads and MockWrites, note that the sequence number
558 // refers to the number of the step in which the I/O will complete. In the
559 // case of synchronous I/O, this will be the same step as the I/O is initiated.
560 // However, in the case of asynchronous I/O, this I/O may be initiated in
561 // a much earlier step. Furthermore, when the a Read() or Write() is separated
562 // from its completion by other Read() or Writes()'s, it can not be marked
563 // synchronous. If it is, ERR_UNUEXPECTED will be returned indicating that a
564 // synchronous Read() or Write() could not be completed synchronously because of
565 // the specific ordering constraints.
567 // Sequence numbers are preserved across both reads and writes. There should be
568 // no gaps in sequence numbers, and no repeated sequence numbers. i.e.
569 // MockRead reads[] = {
570 // MockRead(false, "first read", length, 0) // sync
571 // MockRead(true, "second read", length, 2) // async
573 // MockWrite writes[] = {
574 // MockWrite(true, "first write", length, 1), // async
575 // MockWrite(false, "second write", length, 3), // sync
578 // Example control flow:
579 // Read() is called. The current step is 0. The first available read is
580 // synchronous, so the call to Read() returns length. The current step is
581 // now 1. Next, Read() is called again. The next available read can
582 // not be completed until step 2, so Read() returns ERR_IO_PENDING. The current
583 // step is still 1. Write is called(). The first available write is able to
584 // complete in this step, but is marked asynchronous. Write() returns
585 // ERR_IO_PENDING. The current step is still 1. At this point RunFor(1) is
586 // called which will cause the write callback to be invoked, and will then
587 // stop. The current state is now 2. RunFor(1) is called again, which
588 // causes the read callback to be invoked, and will then stop. Then current
589 // step is 2. Write() is called again. Then next available write is
590 // synchronous so the call to Write() returns length.
592 // For examples of how to use this class, see:
593 // deterministic_socket_data_unittests.cc
594 class DeterministicSocketData
: public StaticSocketDataProvider
{
596 // The Delegate is an abstract interface which handles the communication from
597 // the DeterministicSocketData to the Deterministic MockSocket. The
598 // MockSockets directly store a pointer to the DeterministicSocketData,
599 // whereas the DeterministicSocketData only stores a pointer to the
600 // abstract Delegate interface.
603 // Returns true if there is currently a write pending. That is to say, if
604 // an asynchronous write has been started but the callback has not been
606 virtual bool WritePending() const = 0;
607 // Returns true if there is currently a read pending. That is to say, if
608 // an asynchronous read has been started but the callback has not been
610 virtual bool ReadPending() const = 0;
611 // Called to complete an asynchronous write to execute the write callback.
612 virtual void CompleteWrite() = 0;
613 // Called to complete an asynchronous read to execute the read callback.
614 virtual int CompleteRead() = 0;
617 virtual ~Delegate() {}
620 // |reads| the list of MockRead completions.
621 // |writes| the list of MockWrite completions.
622 DeterministicSocketData(MockRead
* reads
,
625 size_t writes_count
);
626 ~DeterministicSocketData() override
;
628 // Consume all the data up to the give stop point (via SetStop()).
631 // Set the stop point to be |steps| from now, and then invoke Run().
632 void RunFor(int steps
);
634 // Stop at step |seq|, which must be in the future.
635 virtual void SetStop(int seq
);
637 // Stop |seq| steps after the current step.
638 virtual void StopAfter(int seq
);
639 bool stopped() const { return stopped_
; }
640 void SetStopped(bool val
) { stopped_
= val
; }
641 MockRead
& current_read() { return current_read_
; }
642 MockWrite
& current_write() { return current_write_
; }
643 int sequence_number() const { return sequence_number_
; }
644 void set_delegate(base::WeakPtr
<Delegate
> delegate
) { delegate_
= delegate
; }
646 // StaticSocketDataProvider:
648 // When the socket calls Read(), that calls OnRead(), and expects either
649 // ERR_IO_PENDING or data.
650 MockRead
OnRead() override
;
652 // When the socket calls Write(), it always completes synchronously. OnWrite()
653 // checks to make sure the written data matches the expected data. The
654 // callback will not be invoked until its sequence number is reached.
655 MockWriteResult
OnWrite(const std::string
& data
) override
;
656 void Reset() override
;
657 void CompleteRead() override
{}
660 // Invoke the read and write callbacks, if the timing is appropriate.
661 void InvokeCallbacks();
665 void VerifyCorrectSequenceNumbers(MockRead
* reads
,
668 size_t writes_count
);
670 int sequence_number_
;
671 MockRead current_read_
;
672 MockWrite current_write_
;
673 int stopping_sequence_number_
;
675 base::WeakPtr
<Delegate
> delegate_
;
680 // Holds an array of SocketDataProvider elements. As Mock{TCP,SSL}StreamSocket
681 // objects get instantiated, they take their data from the i'th element of this
683 template <typename T
>
684 class SocketDataProviderArray
{
686 SocketDataProviderArray() : next_index_(0) {}
689 DCHECK_LT(next_index_
, data_providers_
.size());
690 return data_providers_
[next_index_
++];
693 void Add(T
* data_provider
) {
694 DCHECK(data_provider
);
695 data_providers_
.push_back(data_provider
);
698 size_t next_index() { return next_index_
; }
700 void ResetNextIndex() { next_index_
= 0; }
703 // Index of the next |data_providers_| element to use. Not an iterator
704 // because those are invalidated on vector reallocation.
707 // SocketDataProviders to be returned.
708 std::vector
<T
*> data_providers_
;
711 class MockUDPClientSocket
;
712 class MockTCPClientSocket
;
713 class MockSSLClientSocket
;
715 // ClientSocketFactory which contains arrays of sockets of each type.
716 // You should first fill the arrays using AddMock{SSL,}Socket. When the factory
717 // is asked to create a socket, it takes next entry from appropriate array.
718 // You can use ResetNextMockIndexes to reset that next entry index for all mock
720 class MockClientSocketFactory
: public ClientSocketFactory
{
722 MockClientSocketFactory();
723 ~MockClientSocketFactory() override
;
725 void AddSocketDataProvider(SocketDataProvider
* socket
);
726 void AddSSLSocketDataProvider(SSLSocketDataProvider
* socket
);
727 void ResetNextMockIndexes();
729 SocketDataProviderArray
<SocketDataProvider
>& mock_data() {
733 // ClientSocketFactory
734 scoped_ptr
<DatagramClientSocket
> CreateDatagramClientSocket(
735 DatagramSocket::BindType bind_type
,
736 const RandIntCallback
& rand_int_cb
,
738 const NetLog::Source
& source
) override
;
739 scoped_ptr
<StreamSocket
> CreateTransportClientSocket(
740 const AddressList
& addresses
,
742 const NetLog::Source
& source
) override
;
743 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
744 scoped_ptr
<ClientSocketHandle
> transport_socket
,
745 const HostPortPair
& host_and_port
,
746 const SSLConfig
& ssl_config
,
747 const SSLClientSocketContext
& context
) override
;
748 void ClearSSLSessionCache() override
;
751 SocketDataProviderArray
<SocketDataProvider
> mock_data_
;
752 SocketDataProviderArray
<SSLSocketDataProvider
> mock_ssl_data_
;
755 class MockClientSocket
: public SSLClientSocket
{
757 // Value returned by GetTLSUniqueChannelBinding().
758 static const char kTlsUnique
[];
760 // The BoundNetLog is needed to test LoadTimingInfo, which uses NetLog IDs as
761 // unique socket IDs.
762 explicit MockClientSocket(const BoundNetLog
& net_log
);
764 // Socket implementation.
765 int Read(IOBuffer
* buf
,
767 const CompletionCallback
& callback
) override
= 0;
768 int Write(IOBuffer
* buf
,
770 const CompletionCallback
& callback
) override
= 0;
771 int SetReceiveBufferSize(int32 size
) override
;
772 int SetSendBufferSize(int32 size
) override
;
774 // StreamSocket implementation.
775 int Connect(const CompletionCallback
& callback
) override
= 0;
776 void Disconnect() override
;
777 bool IsConnected() const override
;
778 bool IsConnectedAndIdle() const override
;
779 int GetPeerAddress(IPEndPoint
* address
) const override
;
780 int GetLocalAddress(IPEndPoint
* address
) const override
;
781 const BoundNetLog
& NetLog() const override
;
782 void SetSubresourceSpeculation() override
{}
783 void SetOmniboxSpeculation() override
{}
785 // SSLClientSocket implementation.
786 void GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
) override
;
787 int ExportKeyingMaterial(const base::StringPiece
& label
,
789 const base::StringPiece
& context
,
791 unsigned int outlen
) override
;
792 int GetTLSUniqueChannelBinding(std::string
* out
) override
;
793 NextProtoStatus
GetNextProto(std::string
* proto
) override
;
794 ChannelIDService
* GetChannelIDService() const override
;
797 ~MockClientSocket() override
;
798 void RunCallbackAsync(const CompletionCallback
& callback
, int result
);
799 void RunCallback(const CompletionCallback
& callback
, int result
);
801 // SSLClientSocket implementation.
802 scoped_refptr
<X509Certificate
> GetUnverifiedServerCertificateChain()
805 // True if Connect completed successfully and Disconnect hasn't been called.
808 // Address of the "remote" peer we're connected to.
809 IPEndPoint peer_addr_
;
811 BoundNetLog net_log_
;
814 base::WeakPtrFactory
<MockClientSocket
> weak_factory_
;
816 DISALLOW_COPY_AND_ASSIGN(MockClientSocket
);
819 class MockTCPClientSocket
: public MockClientSocket
, public AsyncSocket
{
821 MockTCPClientSocket(const AddressList
& addresses
,
822 net::NetLog
* net_log
,
823 SocketDataProvider
* socket
);
824 ~MockTCPClientSocket() override
;
826 const AddressList
& addresses() const { return addresses_
; }
828 // Socket implementation.
829 int Read(IOBuffer
* buf
,
831 const CompletionCallback
& callback
) override
;
832 int Write(IOBuffer
* buf
,
834 const CompletionCallback
& callback
) override
;
836 // StreamSocket implementation.
837 int Connect(const CompletionCallback
& callback
) override
;
838 void Disconnect() override
;
839 bool IsConnected() const override
;
840 bool IsConnectedAndIdle() const override
;
841 int GetPeerAddress(IPEndPoint
* address
) const override
;
842 bool WasEverUsed() const override
;
843 bool UsingTCPFastOpen() const override
;
844 bool WasNpnNegotiated() const override
;
845 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
848 void OnReadComplete(const MockRead
& data
) override
;
849 void OnWriteComplete(int rv
) override
;
850 void OnConnectComplete(const MockConnect
& data
) override
;
855 AddressList addresses_
;
857 SocketDataProvider
* data_
;
860 bool need_read_data_
;
862 // True if the peer has closed the connection. This allows us to simulate
863 // the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real
865 bool peer_closed_connection_
;
867 // While an asynchronous read is pending, we save our user-buffer state.
868 scoped_refptr
<IOBuffer
> pending_read_buf_
;
869 int pending_read_buf_len_
;
870 CompletionCallback pending_read_callback_
;
871 CompletionCallback pending_write_callback_
;
872 bool was_used_to_convey_data_
;
874 DISALLOW_COPY_AND_ASSIGN(MockTCPClientSocket
);
877 // DeterministicSocketHelper is a helper class that can be used
878 // to simulate Socket::Read() and Socket::Write()
879 // using deterministic |data|.
880 // Note: This is provided as a common helper class because
881 // of the inheritance hierarchy of DeterministicMock[UDP,TCP]ClientSocket and a
882 // desire not to introduce an additional common base class.
883 class DeterministicSocketHelper
{
885 DeterministicSocketHelper(NetLog
* net_log
, DeterministicSocketData
* data
);
886 virtual ~DeterministicSocketHelper();
888 bool write_pending() const { return write_pending_
; }
889 bool read_pending() const { return read_pending_
; }
891 void CompleteWrite();
894 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
895 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
897 const BoundNetLog
& net_log() const { return net_log_
; }
899 bool was_used_to_convey_data() const { return was_used_to_convey_data_
; }
901 bool peer_closed_connection() const { return peer_closed_connection_
; }
903 DeterministicSocketData
* data() const { return data_
; }
907 CompletionCallback write_callback_
;
915 CompletionCallback read_callback_
;
916 DeterministicSocketData
* data_
;
917 bool was_used_to_convey_data_
;
918 bool peer_closed_connection_
;
919 BoundNetLog net_log_
;
922 // Mock UDP socket to be used in conjunction with DeterministicSocketData.
923 class DeterministicMockUDPClientSocket
924 : public DatagramClientSocket
,
926 public DeterministicSocketData::Delegate
,
927 public base::SupportsWeakPtr
<DeterministicMockUDPClientSocket
> {
929 DeterministicMockUDPClientSocket(net::NetLog
* net_log
,
930 DeterministicSocketData
* data
);
931 ~DeterministicMockUDPClientSocket() override
;
933 // DeterministicSocketData::Delegate:
934 bool WritePending() const override
;
935 bool ReadPending() const override
;
936 void CompleteWrite() override
;
937 int CompleteRead() override
;
939 // Socket implementation.
940 int Read(IOBuffer
* buf
,
942 const CompletionCallback
& callback
) override
;
943 int Write(IOBuffer
* buf
,
945 const CompletionCallback
& callback
) override
;
946 int SetReceiveBufferSize(int32 size
) override
;
947 int SetSendBufferSize(int32 size
) override
;
949 // DatagramSocket implementation.
950 void Close() override
;
951 int GetPeerAddress(IPEndPoint
* address
) const override
;
952 int GetLocalAddress(IPEndPoint
* address
) const override
;
953 const BoundNetLog
& NetLog() const override
;
955 // DatagramClientSocket implementation.
956 int Connect(const IPEndPoint
& address
) override
;
958 // AsyncSocket implementation.
959 void OnReadComplete(const MockRead
& data
) override
;
960 void OnWriteComplete(int rv
) override
;
961 void OnConnectComplete(const MockConnect
& data
) override
;
963 void set_source_port(uint16 port
) { source_port_
= port
; }
967 IPEndPoint peer_address_
;
968 DeterministicSocketHelper helper_
;
969 uint16 source_port_
; // Ephemeral source port.
971 DISALLOW_COPY_AND_ASSIGN(DeterministicMockUDPClientSocket
);
974 // Mock TCP socket to be used in conjunction with DeterministicSocketData.
975 class DeterministicMockTCPClientSocket
976 : public MockClientSocket
,
978 public DeterministicSocketData::Delegate
,
979 public base::SupportsWeakPtr
<DeterministicMockTCPClientSocket
> {
981 DeterministicMockTCPClientSocket(net::NetLog
* net_log
,
982 DeterministicSocketData
* data
);
983 ~DeterministicMockTCPClientSocket() override
;
985 // DeterministicSocketData::Delegate:
986 bool WritePending() const override
;
987 bool ReadPending() const override
;
988 void CompleteWrite() override
;
989 int CompleteRead() override
;
992 int Write(IOBuffer
* buf
,
994 const CompletionCallback
& callback
) override
;
995 int Read(IOBuffer
* buf
,
997 const CompletionCallback
& callback
) override
;
1000 int Connect(const CompletionCallback
& callback
) override
;
1001 void Disconnect() override
;
1002 bool IsConnected() const override
;
1003 bool IsConnectedAndIdle() const override
;
1004 bool WasEverUsed() const override
;
1005 bool UsingTCPFastOpen() const override
;
1006 bool WasNpnNegotiated() const override
;
1007 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
1010 void OnReadComplete(const MockRead
& data
) override
;
1011 void OnWriteComplete(int rv
) override
;
1012 void OnConnectComplete(const MockConnect
& data
) override
;
1015 DeterministicSocketHelper helper_
;
1017 DISALLOW_COPY_AND_ASSIGN(DeterministicMockTCPClientSocket
);
1020 class MockSSLClientSocket
: public MockClientSocket
, public AsyncSocket
{
1022 MockSSLClientSocket(scoped_ptr
<ClientSocketHandle
> transport_socket
,
1023 const HostPortPair
& host_and_port
,
1024 const SSLConfig
& ssl_config
,
1025 SSLSocketDataProvider
* socket
);
1026 ~MockSSLClientSocket() override
;
1028 // Socket implementation.
1029 int Read(IOBuffer
* buf
,
1031 const CompletionCallback
& callback
) override
;
1032 int Write(IOBuffer
* buf
,
1034 const CompletionCallback
& callback
) override
;
1036 // StreamSocket implementation.
1037 int Connect(const CompletionCallback
& callback
) override
;
1038 void Disconnect() override
;
1039 bool IsConnected() const override
;
1040 bool WasEverUsed() const override
;
1041 bool UsingTCPFastOpen() const override
;
1042 int GetPeerAddress(IPEndPoint
* address
) const override
;
1043 bool WasNpnNegotiated() const override
;
1044 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
1046 // SSLClientSocket implementation.
1047 void GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
) override
;
1048 NextProtoStatus
GetNextProto(std::string
* proto
) override
;
1049 bool set_was_npn_negotiated(bool negotiated
) override
;
1050 void set_protocol_negotiated(NextProto protocol_negotiated
) override
;
1051 NextProto
GetNegotiatedProtocol() const override
;
1053 // This MockSocket does not implement the manual async IO feature.
1054 void OnReadComplete(const MockRead
& data
) override
;
1055 void OnWriteComplete(int rv
) override
;
1056 void OnConnectComplete(const MockConnect
& data
) override
;
1058 bool WasChannelIDSent() const override
;
1059 void set_channel_id_sent(bool channel_id_sent
) override
;
1060 ChannelIDService
* GetChannelIDService() const override
;
1063 static void ConnectCallback(MockSSLClientSocket
* ssl_client_socket
,
1064 const CompletionCallback
& callback
,
1067 scoped_ptr
<ClientSocketHandle
> transport_
;
1068 SSLSocketDataProvider
* data_
;
1069 bool is_npn_state_set_
;
1070 bool new_npn_value_
;
1071 bool is_protocol_negotiated_set_
;
1072 NextProto protocol_negotiated_
;
1074 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket
);
1077 class MockUDPClientSocket
: public DatagramClientSocket
, public AsyncSocket
{
1079 MockUDPClientSocket(SocketDataProvider
* data
, net::NetLog
* net_log
);
1080 ~MockUDPClientSocket() override
;
1082 // Socket implementation.
1083 int Read(IOBuffer
* buf
,
1085 const CompletionCallback
& callback
) override
;
1086 int Write(IOBuffer
* buf
,
1088 const CompletionCallback
& callback
) override
;
1089 int SetReceiveBufferSize(int32 size
) override
;
1090 int SetSendBufferSize(int32 size
) override
;
1092 // DatagramSocket implementation.
1093 void Close() override
;
1094 int GetPeerAddress(IPEndPoint
* address
) const override
;
1095 int GetLocalAddress(IPEndPoint
* address
) const override
;
1096 const BoundNetLog
& NetLog() const override
;
1098 // DatagramClientSocket implementation.
1099 int Connect(const IPEndPoint
& address
) override
;
1101 // AsyncSocket implementation.
1102 void OnReadComplete(const MockRead
& data
) override
;
1103 void OnWriteComplete(int rv
) override
;
1104 void OnConnectComplete(const MockConnect
& data
) override
;
1106 void set_source_port(uint16 port
) { source_port_
= port
;}
1111 void RunCallbackAsync(const CompletionCallback
& callback
, int result
);
1112 void RunCallback(const CompletionCallback
& callback
, int result
);
1115 SocketDataProvider
* data_
;
1117 MockRead read_data_
;
1118 bool need_read_data_
;
1119 uint16 source_port_
; // Ephemeral source port.
1121 // Address of the "remote" peer we're connected to.
1122 IPEndPoint peer_addr_
;
1124 // While an asynchronous IO is pending, we save our user-buffer state.
1125 scoped_refptr
<IOBuffer
> pending_read_buf_
;
1126 int pending_read_buf_len_
;
1127 CompletionCallback pending_read_callback_
;
1128 CompletionCallback pending_write_callback_
;
1130 BoundNetLog net_log_
;
1132 base::WeakPtrFactory
<MockUDPClientSocket
> weak_factory_
;
1134 DISALLOW_COPY_AND_ASSIGN(MockUDPClientSocket
);
1137 class TestSocketRequest
: public TestCompletionCallbackBase
{
1139 TestSocketRequest(std::vector
<TestSocketRequest
*>* request_order
,
1140 size_t* completion_count
);
1141 ~TestSocketRequest() override
;
1143 ClientSocketHandle
* handle() { return &handle_
; }
1145 const CompletionCallback
& callback() const { return callback_
; }
1148 void OnComplete(int result
);
1150 ClientSocketHandle handle_
;
1151 std::vector
<TestSocketRequest
*>* request_order_
;
1152 size_t* completion_count_
;
1153 CompletionCallback callback_
;
1155 DISALLOW_COPY_AND_ASSIGN(TestSocketRequest
);
1158 class ClientSocketPoolTest
{
1163 // A socket will be disconnected in addition to handle being reset.
1167 static const int kIndexOutOfBounds
;
1168 static const int kRequestNotFound
;
1170 ClientSocketPoolTest();
1171 ~ClientSocketPoolTest();
1173 template <typename PoolType
>
1174 int StartRequestUsingPool(
1175 PoolType
* socket_pool
,
1176 const std::string
& group_name
,
1177 RequestPriority priority
,
1178 const scoped_refptr
<typename
PoolType::SocketParams
>& socket_params
) {
1179 DCHECK(socket_pool
);
1180 TestSocketRequest
* request
=
1181 new TestSocketRequest(&request_order_
, &completion_count_
);
1182 requests_
.push_back(request
);
1183 int rv
= request
->handle()->Init(group_name
,
1186 request
->callback(),
1189 if (rv
!= ERR_IO_PENDING
)
1190 request_order_
.push_back(request
);
1194 // Provided there were n requests started, takes |index| in range 1..n
1195 // and returns order in which that request completed, in range 1..n,
1196 // or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound
1197 // if that request did not complete (for example was canceled).
1198 int GetOrderOfRequest(size_t index
) const;
1200 // Resets first initialized socket handle from |requests_|. If found such
1201 // a handle, returns true.
1202 bool ReleaseOneConnection(KeepAlive keep_alive
);
1204 // Releases connections until there is nothing to release.
1205 void ReleaseAllConnections(KeepAlive keep_alive
);
1207 // Note that this uses 0-based indices, while GetOrderOfRequest takes and
1208 // returns 0-based indices.
1209 TestSocketRequest
* request(int i
) { return requests_
[i
]; }
1211 size_t requests_size() const { return requests_
.size(); }
1212 ScopedVector
<TestSocketRequest
>* requests() { return &requests_
; }
1213 size_t completion_count() const { return completion_count_
; }
1216 ScopedVector
<TestSocketRequest
> requests_
;
1217 std::vector
<TestSocketRequest
*> request_order_
;
1218 size_t completion_count_
;
1220 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolTest
);
1223 class MockTransportSocketParams
1224 : public base::RefCounted
<MockTransportSocketParams
> {
1226 friend class base::RefCounted
<MockTransportSocketParams
>;
1227 ~MockTransportSocketParams() {}
1229 DISALLOW_COPY_AND_ASSIGN(MockTransportSocketParams
);
1232 class MockTransportClientSocketPool
: public TransportClientSocketPool
{
1234 typedef MockTransportSocketParams SocketParams
;
1236 class MockConnectJob
{
1238 MockConnectJob(scoped_ptr
<StreamSocket
> socket
,
1239 ClientSocketHandle
* handle
,
1240 const CompletionCallback
& callback
);
1244 bool CancelHandle(const ClientSocketHandle
* handle
);
1247 void OnConnect(int rv
);
1249 scoped_ptr
<StreamSocket
> socket_
;
1250 ClientSocketHandle
* handle_
;
1251 CompletionCallback user_callback_
;
1253 DISALLOW_COPY_AND_ASSIGN(MockConnectJob
);
1256 MockTransportClientSocketPool(int max_sockets
,
1257 int max_sockets_per_group
,
1258 ClientSocketFactory
* socket_factory
);
1260 ~MockTransportClientSocketPool() override
;
1262 RequestPriority
last_request_priority() const {
1263 return last_request_priority_
;
1265 int release_count() const { return release_count_
; }
1266 int cancel_count() const { return cancel_count_
; }
1268 // TransportClientSocketPool implementation.
1269 int RequestSocket(const std::string
& group_name
,
1270 const void* socket_params
,
1271 RequestPriority priority
,
1272 ClientSocketHandle
* handle
,
1273 const CompletionCallback
& callback
,
1274 const BoundNetLog
& net_log
) override
;
1276 void CancelRequest(const std::string
& group_name
,
1277 ClientSocketHandle
* handle
) override
;
1278 void ReleaseSocket(const std::string
& group_name
,
1279 scoped_ptr
<StreamSocket
> socket
,
1283 ClientSocketFactory
* client_socket_factory_
;
1284 ScopedVector
<MockConnectJob
> job_list_
;
1285 RequestPriority last_request_priority_
;
1289 DISALLOW_COPY_AND_ASSIGN(MockTransportClientSocketPool
);
1292 class DeterministicMockClientSocketFactory
: public ClientSocketFactory
{
1294 DeterministicMockClientSocketFactory();
1295 ~DeterministicMockClientSocketFactory() override
;
1297 void AddSocketDataProvider(DeterministicSocketData
* socket
);
1298 void AddSSLSocketDataProvider(SSLSocketDataProvider
* socket
);
1299 void ResetNextMockIndexes();
1301 // Return |index|-th MockSSLClientSocket (starting from 0) that the factory
1303 MockSSLClientSocket
* GetMockSSLClientSocket(size_t index
) const;
1305 SocketDataProviderArray
<DeterministicSocketData
>& mock_data() {
1308 std::vector
<DeterministicMockTCPClientSocket
*>& tcp_client_sockets() {
1309 return tcp_client_sockets_
;
1311 std::vector
<DeterministicMockUDPClientSocket
*>& udp_client_sockets() {
1312 return udp_client_sockets_
;
1315 // ClientSocketFactory
1316 scoped_ptr
<DatagramClientSocket
> CreateDatagramClientSocket(
1317 DatagramSocket::BindType bind_type
,
1318 const RandIntCallback
& rand_int_cb
,
1320 const NetLog::Source
& source
) override
;
1321 scoped_ptr
<StreamSocket
> CreateTransportClientSocket(
1322 const AddressList
& addresses
,
1324 const NetLog::Source
& source
) override
;
1325 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
1326 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1327 const HostPortPair
& host_and_port
,
1328 const SSLConfig
& ssl_config
,
1329 const SSLClientSocketContext
& context
) override
;
1330 void ClearSSLSessionCache() override
;
1333 SocketDataProviderArray
<DeterministicSocketData
> mock_data_
;
1334 SocketDataProviderArray
<SSLSocketDataProvider
> mock_ssl_data_
;
1336 // Store pointers to handed out sockets in case the test wants to get them.
1337 std::vector
<DeterministicMockTCPClientSocket
*> tcp_client_sockets_
;
1338 std::vector
<DeterministicMockUDPClientSocket
*> udp_client_sockets_
;
1339 std::vector
<MockSSLClientSocket
*> ssl_client_sockets_
;
1341 DISALLOW_COPY_AND_ASSIGN(DeterministicMockClientSocketFactory
);
1344 class MockSOCKSClientSocketPool
: public SOCKSClientSocketPool
{
1346 MockSOCKSClientSocketPool(int max_sockets
,
1347 int max_sockets_per_group
,
1348 TransportClientSocketPool
* transport_pool
);
1350 ~MockSOCKSClientSocketPool() override
;
1352 // SOCKSClientSocketPool implementation.
1353 int RequestSocket(const std::string
& group_name
,
1354 const void* socket_params
,
1355 RequestPriority priority
,
1356 ClientSocketHandle
* handle
,
1357 const CompletionCallback
& callback
,
1358 const BoundNetLog
& net_log
) override
;
1360 void CancelRequest(const std::string
& group_name
,
1361 ClientSocketHandle
* handle
) override
;
1362 void ReleaseSocket(const std::string
& group_name
,
1363 scoped_ptr
<StreamSocket
> socket
,
1367 TransportClientSocketPool
* const transport_pool_
;
1369 DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool
);
1372 // Convenience class to temporarily set the WebSocketEndpointLockManager unlock
1373 // delay to zero for testing purposes. Automatically restores the original value
1375 class ScopedWebSocketEndpointZeroUnlockDelay
{
1377 ScopedWebSocketEndpointZeroUnlockDelay();
1378 ~ScopedWebSocketEndpointZeroUnlockDelay();
1381 base::TimeDelta old_delay_
;
1384 // Constants for a successful SOCKS v5 handshake.
1385 extern const char kSOCKS5GreetRequest
[];
1386 extern const int kSOCKS5GreetRequestLength
;
1388 extern const char kSOCKS5GreetResponse
[];
1389 extern const int kSOCKS5GreetResponseLength
;
1391 extern const char kSOCKS5OkRequest
[];
1392 extern const int kSOCKS5OkRequestLength
;
1394 extern const char kSOCKS5OkResponse
[];
1395 extern const int kSOCKS5OkResponseLength
;
1399 #endif // NET_SOCKET_SOCKET_TEST_UTIL_H_