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 NextProtoVector next_protos_expected_in_ssl_config
;
365 bool client_cert_sent
;
366 SSLCertRequestInfo
* cert_request_info
;
367 scoped_refptr
<X509Certificate
> cert
;
368 bool channel_id_sent
;
369 ChannelIDService
* channel_id_service
;
370 int connection_status
;
373 // A DataProvider where the client must write a request before the reads (e.g.
374 // the response) will complete.
375 class DelayedSocketData
: public StaticSocketDataProvider
{
377 // |write_delay| the number of MockWrites to complete before allowing
378 // a MockRead to complete.
379 // |reads| the list of MockRead completions.
380 // |writes| the list of MockWrite completions.
381 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
382 // MockRead(true, 0, 0);
383 DelayedSocketData(int write_delay
,
387 size_t writes_count
);
389 // |connect| the result for the connect phase.
390 // |reads| the list of MockRead completions.
391 // |write_delay| the number of MockWrites to complete before allowing
392 // a MockRead to complete.
393 // |writes| the list of MockWrite completions.
394 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
395 // MockRead(true, 0, 0);
396 DelayedSocketData(const MockConnect
& connect
,
401 size_t writes_count
);
402 ~DelayedSocketData() override
;
404 void ForceNextRead();
406 // StaticSocketDataProvider:
407 MockRead
OnRead() override
;
408 MockWriteResult
OnWrite(const std::string
& data
) override
;
409 void Reset() override
;
410 void CompleteRead() override
;
414 bool read_in_progress_
;
416 base::WeakPtrFactory
<DelayedSocketData
> weak_factory_
;
418 DISALLOW_COPY_AND_ASSIGN(DelayedSocketData
);
421 // A DataProvider where the reads are ordered.
422 // If a read is requested before its sequence number is reached, we return an
423 // ERR_IO_PENDING (that way we don't have to explicitly add a MockRead just to
425 // The sequence number is incremented on every read and write operation.
426 // The message loop may be interrupted by setting the high bit of the sequence
427 // number in the MockRead's sequence number. When that MockRead is reached,
428 // we post a Quit message to the loop. This allows us to interrupt the reading
429 // of data before a complete message has arrived, and provides support for
430 // testing server push when the request is issued while the response is in the
431 // middle of being received.
432 class OrderedSocketData
: public StaticSocketDataProvider
{
434 // |reads| the list of MockRead completions.
435 // |writes| the list of MockWrite completions.
436 // Note: All MockReads and MockWrites must be async.
437 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
438 // MockRead(true, 0, 0);
439 OrderedSocketData(MockRead
* reads
,
442 size_t writes_count
);
443 ~OrderedSocketData() override
;
445 // |connect| the result for the connect phase.
446 // |reads| the list of MockRead completions.
447 // |writes| the list of MockWrite completions.
448 // Note: All MockReads and MockWrites must be async.
449 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
450 // MockRead(true, 0, 0);
451 OrderedSocketData(const MockConnect
& connect
,
455 size_t writes_count
);
457 // Posts a quit message to the current message loop, if one is running.
460 // StaticSocketDataProvider:
461 MockRead
OnRead() override
;
462 MockWriteResult
OnWrite(const std::string
& data
) override
;
463 void Reset() override
;
464 void CompleteRead() override
;
467 int sequence_number_
;
468 int loop_stop_stage_
;
471 base::WeakPtrFactory
<OrderedSocketData
> weak_factory_
;
473 DISALLOW_COPY_AND_ASSIGN(OrderedSocketData
);
476 // Uses the sequence_number field in the mock reads and writes to
477 // complete the operations in a specified order.
478 class SequencedSocketData
: public SocketDataProvider
{
480 // |reads| is the list of MockRead completions.
481 // |writes| is the list of MockWrite completions.
482 SequencedSocketData(MockRead
* reads
,
485 size_t writes_count
);
487 // |connect| is the result for the connect phase.
488 // |reads| is the list of MockRead completions.
489 // |writes| is the list of MockWrite completions.
490 SequencedSocketData(const MockConnect
& connect
,
494 size_t writes_count
);
496 ~SequencedSocketData() override
;
498 // SocketDataProviderBase implementation.
499 MockRead
OnRead() override
;
500 MockWriteResult
OnWrite(const std::string
& data
) override
;
501 void Reset() override
;
503 // Returns true if all data has been read.
504 bool at_read_eof() const;
506 // Returns true if all data has been written.
507 bool at_write_eof() const;
510 // Defines the state for the read or write path.
512 IDLE
, // No async operation is in progress.
513 PENDING
, // An async operation in waiting for another opteration to
515 COMPLETING
, // A task has been posted to complet an async operation.
517 void OnReadComplete();
518 void OnWriteComplete();
520 void MaybePostReadCompleteTask();
521 void MaybePostWriteCompleteTask();
523 StaticSocketDataHelper helper_
;
524 int sequence_number_
;
526 IoState write_state_
;
528 base::WeakPtrFactory
<SequencedSocketData
> weak_factory_
;
530 DISALLOW_COPY_AND_ASSIGN(SequencedSocketData
);
533 class DeterministicMockTCPClientSocket
;
535 // This class gives the user full control over the network activity,
536 // specifically the timing of the COMPLETION of I/O operations. Regardless of
537 // the order in which I/O operations are initiated, this class ensures that they
538 // complete in the correct order.
540 // Network activity is modeled as a sequence of numbered steps which is
541 // incremented whenever an I/O operation completes. This can happen under two
542 // different circumstances:
544 // 1) Performing a synchronous I/O operation. (Invoking Read() or Write()
545 // when the corresponding MockRead or MockWrite is marked !async).
546 // 2) Running the Run() method of this class. The run method will invoke
547 // the current MessageLoop, running all pending events, and will then
548 // invoke any pending IO callbacks.
550 // In addition, this class allows for I/O processing to "stop" at a specified
551 // step, by calling SetStop(int) or StopAfter(int). Initiating an I/O operation
552 // by calling Read() or Write() while stopped is permitted if the operation is
553 // asynchronous. It is an error to perform synchronous I/O while stopped.
555 // When creating the MockReads and MockWrites, note that the sequence number
556 // refers to the number of the step in which the I/O will complete. In the
557 // case of synchronous I/O, this will be the same step as the I/O is initiated.
558 // However, in the case of asynchronous I/O, this I/O may be initiated in
559 // a much earlier step. Furthermore, when the a Read() or Write() is separated
560 // from its completion by other Read() or Writes()'s, it can not be marked
561 // synchronous. If it is, ERR_UNUEXPECTED will be returned indicating that a
562 // synchronous Read() or Write() could not be completed synchronously because of
563 // the specific ordering constraints.
565 // Sequence numbers are preserved across both reads and writes. There should be
566 // no gaps in sequence numbers, and no repeated sequence numbers. i.e.
567 // MockRead reads[] = {
568 // MockRead(false, "first read", length, 0) // sync
569 // MockRead(true, "second read", length, 2) // async
571 // MockWrite writes[] = {
572 // MockWrite(true, "first write", length, 1), // async
573 // MockWrite(false, "second write", length, 3), // sync
576 // Example control flow:
577 // Read() is called. The current step is 0. The first available read is
578 // synchronous, so the call to Read() returns length. The current step is
579 // now 1. Next, Read() is called again. The next available read can
580 // not be completed until step 2, so Read() returns ERR_IO_PENDING. The current
581 // step is still 1. Write is called(). The first available write is able to
582 // complete in this step, but is marked asynchronous. Write() returns
583 // ERR_IO_PENDING. The current step is still 1. At this point RunFor(1) is
584 // called which will cause the write callback to be invoked, and will then
585 // stop. The current state is now 2. RunFor(1) is called again, which
586 // causes the read callback to be invoked, and will then stop. Then current
587 // step is 2. Write() is called again. Then next available write is
588 // synchronous so the call to Write() returns length.
590 // For examples of how to use this class, see:
591 // deterministic_socket_data_unittests.cc
592 class DeterministicSocketData
: public StaticSocketDataProvider
{
594 // The Delegate is an abstract interface which handles the communication from
595 // the DeterministicSocketData to the Deterministic MockSocket. The
596 // MockSockets directly store a pointer to the DeterministicSocketData,
597 // whereas the DeterministicSocketData only stores a pointer to the
598 // abstract Delegate interface.
601 // Returns true if there is currently a write pending. That is to say, if
602 // an asynchronous write has been started but the callback has not been
604 virtual bool WritePending() const = 0;
605 // Returns true if there is currently a read pending. That is to say, if
606 // an asynchronous read has been started but the callback has not been
608 virtual bool ReadPending() const = 0;
609 // Called to complete an asynchronous write to execute the write callback.
610 virtual void CompleteWrite() = 0;
611 // Called to complete an asynchronous read to execute the read callback.
612 virtual int CompleteRead() = 0;
615 virtual ~Delegate() {}
618 // |reads| the list of MockRead completions.
619 // |writes| the list of MockWrite completions.
620 DeterministicSocketData(MockRead
* reads
,
623 size_t writes_count
);
624 ~DeterministicSocketData() override
;
626 // Consume all the data up to the give stop point (via SetStop()).
629 // Set the stop point to be |steps| from now, and then invoke Run().
630 void RunFor(int steps
);
632 // Stop at step |seq|, which must be in the future.
633 virtual void SetStop(int seq
);
635 // Stop |seq| steps after the current step.
636 virtual void StopAfter(int seq
);
637 bool stopped() const { return stopped_
; }
638 void SetStopped(bool val
) { stopped_
= val
; }
639 MockRead
& current_read() { return current_read_
; }
640 MockWrite
& current_write() { return current_write_
; }
641 int sequence_number() const { return sequence_number_
; }
642 void set_delegate(base::WeakPtr
<Delegate
> delegate
) { delegate_
= delegate
; }
644 // StaticSocketDataProvider:
646 // When the socket calls Read(), that calls OnRead(), and expects either
647 // ERR_IO_PENDING or data.
648 MockRead
OnRead() override
;
650 // When the socket calls Write(), it always completes synchronously. OnWrite()
651 // checks to make sure the written data matches the expected data. The
652 // callback will not be invoked until its sequence number is reached.
653 MockWriteResult
OnWrite(const std::string
& data
) override
;
654 void Reset() override
;
655 void CompleteRead() override
{}
658 // Invoke the read and write callbacks, if the timing is appropriate.
659 void InvokeCallbacks();
663 void VerifyCorrectSequenceNumbers(MockRead
* reads
,
666 size_t writes_count
);
668 int sequence_number_
;
669 MockRead current_read_
;
670 MockWrite current_write_
;
671 int stopping_sequence_number_
;
673 base::WeakPtr
<Delegate
> delegate_
;
678 // Holds an array of SocketDataProvider elements. As Mock{TCP,SSL}StreamSocket
679 // objects get instantiated, they take their data from the i'th element of this
681 template <typename T
>
682 class SocketDataProviderArray
{
684 SocketDataProviderArray() : next_index_(0) {}
687 DCHECK_LT(next_index_
, data_providers_
.size());
688 return data_providers_
[next_index_
++];
691 void Add(T
* data_provider
) {
692 DCHECK(data_provider
);
693 data_providers_
.push_back(data_provider
);
696 size_t next_index() { return next_index_
; }
698 void ResetNextIndex() { next_index_
= 0; }
701 // Index of the next |data_providers_| element to use. Not an iterator
702 // because those are invalidated on vector reallocation.
705 // SocketDataProviders to be returned.
706 std::vector
<T
*> data_providers_
;
709 class MockUDPClientSocket
;
710 class MockTCPClientSocket
;
711 class MockSSLClientSocket
;
713 // ClientSocketFactory which contains arrays of sockets of each type.
714 // You should first fill the arrays using AddMock{SSL,}Socket. When the factory
715 // is asked to create a socket, it takes next entry from appropriate array.
716 // You can use ResetNextMockIndexes to reset that next entry index for all mock
718 class MockClientSocketFactory
: public ClientSocketFactory
{
720 MockClientSocketFactory();
721 ~MockClientSocketFactory() override
;
723 void AddSocketDataProvider(SocketDataProvider
* socket
);
724 void AddSSLSocketDataProvider(SSLSocketDataProvider
* socket
);
725 void ResetNextMockIndexes();
727 SocketDataProviderArray
<SocketDataProvider
>& mock_data() {
731 // ClientSocketFactory
732 scoped_ptr
<DatagramClientSocket
> CreateDatagramClientSocket(
733 DatagramSocket::BindType bind_type
,
734 const RandIntCallback
& rand_int_cb
,
736 const NetLog::Source
& source
) override
;
737 scoped_ptr
<StreamSocket
> CreateTransportClientSocket(
738 const AddressList
& addresses
,
740 const NetLog::Source
& source
) override
;
741 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
742 scoped_ptr
<ClientSocketHandle
> transport_socket
,
743 const HostPortPair
& host_and_port
,
744 const SSLConfig
& ssl_config
,
745 const SSLClientSocketContext
& context
) override
;
746 void ClearSSLSessionCache() override
;
749 SocketDataProviderArray
<SocketDataProvider
> mock_data_
;
750 SocketDataProviderArray
<SSLSocketDataProvider
> mock_ssl_data_
;
753 class MockClientSocket
: public SSLClientSocket
{
755 // Value returned by GetTLSUniqueChannelBinding().
756 static const char kTlsUnique
[];
758 // The BoundNetLog is needed to test LoadTimingInfo, which uses NetLog IDs as
759 // unique socket IDs.
760 explicit MockClientSocket(const BoundNetLog
& net_log
);
762 // Socket implementation.
763 int Read(IOBuffer
* buf
,
765 const CompletionCallback
& callback
) override
= 0;
766 int Write(IOBuffer
* buf
,
768 const CompletionCallback
& callback
) override
= 0;
769 int SetReceiveBufferSize(int32 size
) override
;
770 int SetSendBufferSize(int32 size
) override
;
772 // StreamSocket implementation.
773 int Connect(const CompletionCallback
& callback
) override
= 0;
774 void Disconnect() override
;
775 bool IsConnected() const override
;
776 bool IsConnectedAndIdle() const override
;
777 int GetPeerAddress(IPEndPoint
* address
) const override
;
778 int GetLocalAddress(IPEndPoint
* address
) const override
;
779 const BoundNetLog
& NetLog() const override
;
780 void SetSubresourceSpeculation() override
{}
781 void SetOmniboxSpeculation() override
{}
783 // SSLClientSocket implementation.
784 void GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
) override
;
785 int ExportKeyingMaterial(const base::StringPiece
& label
,
787 const base::StringPiece
& context
,
789 unsigned int outlen
) override
;
790 int GetTLSUniqueChannelBinding(std::string
* out
) override
;
791 NextProtoStatus
GetNextProto(std::string
* proto
) const override
;
792 ChannelIDService
* GetChannelIDService() const override
;
795 ~MockClientSocket() override
;
796 void RunCallbackAsync(const CompletionCallback
& callback
, int result
);
797 void RunCallback(const CompletionCallback
& callback
, int result
);
799 // SSLClientSocket implementation.
800 scoped_refptr
<X509Certificate
> GetUnverifiedServerCertificateChain()
803 // True if Connect completed successfully and Disconnect hasn't been called.
806 // Address of the "remote" peer we're connected to.
807 IPEndPoint peer_addr_
;
809 BoundNetLog net_log_
;
812 base::WeakPtrFactory
<MockClientSocket
> weak_factory_
;
814 DISALLOW_COPY_AND_ASSIGN(MockClientSocket
);
817 class MockTCPClientSocket
: public MockClientSocket
, public AsyncSocket
{
819 MockTCPClientSocket(const AddressList
& addresses
,
820 net::NetLog
* net_log
,
821 SocketDataProvider
* socket
);
822 ~MockTCPClientSocket() override
;
824 const AddressList
& addresses() const { return addresses_
; }
826 // Socket implementation.
827 int Read(IOBuffer
* buf
,
829 const CompletionCallback
& callback
) override
;
830 int Write(IOBuffer
* buf
,
832 const CompletionCallback
& callback
) override
;
834 // StreamSocket implementation.
835 int Connect(const CompletionCallback
& callback
) override
;
836 void Disconnect() override
;
837 bool IsConnected() const override
;
838 bool IsConnectedAndIdle() const override
;
839 int GetPeerAddress(IPEndPoint
* address
) const override
;
840 bool WasEverUsed() const override
;
841 bool UsingTCPFastOpen() const override
;
842 bool WasNpnNegotiated() const override
;
843 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
846 void OnReadComplete(const MockRead
& data
) override
;
847 void OnWriteComplete(int rv
) override
;
848 void OnConnectComplete(const MockConnect
& data
) override
;
853 AddressList addresses_
;
855 SocketDataProvider
* data_
;
858 bool need_read_data_
;
860 // True if the peer has closed the connection. This allows us to simulate
861 // the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real
863 bool peer_closed_connection_
;
865 // While an asynchronous read is pending, we save our user-buffer state.
866 scoped_refptr
<IOBuffer
> pending_read_buf_
;
867 int pending_read_buf_len_
;
868 CompletionCallback pending_read_callback_
;
869 CompletionCallback pending_write_callback_
;
870 bool was_used_to_convey_data_
;
872 DISALLOW_COPY_AND_ASSIGN(MockTCPClientSocket
);
875 // DeterministicSocketHelper is a helper class that can be used
876 // to simulate Socket::Read() and Socket::Write()
877 // using deterministic |data|.
878 // Note: This is provided as a common helper class because
879 // of the inheritance hierarchy of DeterministicMock[UDP,TCP]ClientSocket and a
880 // desire not to introduce an additional common base class.
881 class DeterministicSocketHelper
{
883 DeterministicSocketHelper(NetLog
* net_log
, DeterministicSocketData
* data
);
884 virtual ~DeterministicSocketHelper();
886 bool write_pending() const { return write_pending_
; }
887 bool read_pending() const { return read_pending_
; }
889 void CompleteWrite();
892 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
893 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
895 const BoundNetLog
& net_log() const { return net_log_
; }
897 bool was_used_to_convey_data() const { return was_used_to_convey_data_
; }
899 bool peer_closed_connection() const { return peer_closed_connection_
; }
901 DeterministicSocketData
* data() const { return data_
; }
905 CompletionCallback write_callback_
;
913 CompletionCallback read_callback_
;
914 DeterministicSocketData
* data_
;
915 bool was_used_to_convey_data_
;
916 bool peer_closed_connection_
;
917 BoundNetLog net_log_
;
920 // Mock UDP socket to be used in conjunction with DeterministicSocketData.
921 class DeterministicMockUDPClientSocket
922 : public DatagramClientSocket
,
924 public DeterministicSocketData::Delegate
,
925 public base::SupportsWeakPtr
<DeterministicMockUDPClientSocket
> {
927 DeterministicMockUDPClientSocket(net::NetLog
* net_log
,
928 DeterministicSocketData
* data
);
929 ~DeterministicMockUDPClientSocket() override
;
931 // DeterministicSocketData::Delegate:
932 bool WritePending() const override
;
933 bool ReadPending() const override
;
934 void CompleteWrite() override
;
935 int CompleteRead() override
;
937 // Socket implementation.
938 int Read(IOBuffer
* buf
,
940 const CompletionCallback
& callback
) override
;
941 int Write(IOBuffer
* buf
,
943 const CompletionCallback
& callback
) override
;
944 int SetReceiveBufferSize(int32 size
) override
;
945 int SetSendBufferSize(int32 size
) override
;
947 // DatagramSocket implementation.
948 void Close() override
;
949 int GetPeerAddress(IPEndPoint
* address
) const override
;
950 int GetLocalAddress(IPEndPoint
* address
) const override
;
951 const BoundNetLog
& NetLog() const override
;
953 // DatagramClientSocket implementation.
954 int Connect(const IPEndPoint
& address
) override
;
956 // AsyncSocket implementation.
957 void OnReadComplete(const MockRead
& data
) override
;
958 void OnWriteComplete(int rv
) override
;
959 void OnConnectComplete(const MockConnect
& data
) override
;
961 void set_source_port(uint16 port
) { source_port_
= port
; }
965 IPEndPoint peer_address_
;
966 DeterministicSocketHelper helper_
;
967 uint16 source_port_
; // Ephemeral source port.
969 DISALLOW_COPY_AND_ASSIGN(DeterministicMockUDPClientSocket
);
972 // Mock TCP socket to be used in conjunction with DeterministicSocketData.
973 class DeterministicMockTCPClientSocket
974 : public MockClientSocket
,
976 public DeterministicSocketData::Delegate
,
977 public base::SupportsWeakPtr
<DeterministicMockTCPClientSocket
> {
979 DeterministicMockTCPClientSocket(net::NetLog
* net_log
,
980 DeterministicSocketData
* data
);
981 ~DeterministicMockTCPClientSocket() override
;
983 // DeterministicSocketData::Delegate:
984 bool WritePending() const override
;
985 bool ReadPending() const override
;
986 void CompleteWrite() override
;
987 int CompleteRead() override
;
990 int Write(IOBuffer
* buf
,
992 const CompletionCallback
& callback
) override
;
993 int Read(IOBuffer
* buf
,
995 const CompletionCallback
& callback
) override
;
998 int Connect(const CompletionCallback
& callback
) override
;
999 void Disconnect() override
;
1000 bool IsConnected() const override
;
1001 bool IsConnectedAndIdle() const override
;
1002 bool WasEverUsed() const override
;
1003 bool UsingTCPFastOpen() const override
;
1004 bool WasNpnNegotiated() const override
;
1005 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
1008 void OnReadComplete(const MockRead
& data
) override
;
1009 void OnWriteComplete(int rv
) override
;
1010 void OnConnectComplete(const MockConnect
& data
) override
;
1013 DeterministicSocketHelper helper_
;
1015 DISALLOW_COPY_AND_ASSIGN(DeterministicMockTCPClientSocket
);
1018 class MockSSLClientSocket
: public MockClientSocket
, public AsyncSocket
{
1020 MockSSLClientSocket(scoped_ptr
<ClientSocketHandle
> transport_socket
,
1021 const HostPortPair
& host_and_port
,
1022 const SSLConfig
& ssl_config
,
1023 SSLSocketDataProvider
* socket
);
1024 ~MockSSLClientSocket() override
;
1026 // Socket implementation.
1027 int Read(IOBuffer
* buf
,
1029 const CompletionCallback
& callback
) override
;
1030 int Write(IOBuffer
* buf
,
1032 const CompletionCallback
& callback
) override
;
1034 // StreamSocket implementation.
1035 int Connect(const CompletionCallback
& callback
) override
;
1036 void Disconnect() override
;
1037 bool IsConnected() const override
;
1038 bool WasEverUsed() const override
;
1039 bool UsingTCPFastOpen() const override
;
1040 int GetPeerAddress(IPEndPoint
* address
) const override
;
1041 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
1043 // SSLClientSocket implementation.
1044 void GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
) override
;
1045 NextProtoStatus
GetNextProto(std::string
* proto
) const override
;
1047 // This MockSocket does not implement the manual async IO feature.
1048 void OnReadComplete(const MockRead
& data
) override
;
1049 void OnWriteComplete(int rv
) override
;
1050 void OnConnectComplete(const MockConnect
& data
) override
;
1052 ChannelIDService
* GetChannelIDService() const override
;
1055 static void ConnectCallback(MockSSLClientSocket
* ssl_client_socket
,
1056 const CompletionCallback
& callback
,
1059 scoped_ptr
<ClientSocketHandle
> transport_
;
1060 SSLSocketDataProvider
* data_
;
1062 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket
);
1065 class MockUDPClientSocket
: public DatagramClientSocket
, public AsyncSocket
{
1067 MockUDPClientSocket(SocketDataProvider
* data
, net::NetLog
* net_log
);
1068 ~MockUDPClientSocket() override
;
1070 // Socket implementation.
1071 int Read(IOBuffer
* buf
,
1073 const CompletionCallback
& callback
) override
;
1074 int Write(IOBuffer
* buf
,
1076 const CompletionCallback
& callback
) override
;
1077 int SetReceiveBufferSize(int32 size
) override
;
1078 int SetSendBufferSize(int32 size
) override
;
1080 // DatagramSocket implementation.
1081 void Close() override
;
1082 int GetPeerAddress(IPEndPoint
* address
) const override
;
1083 int GetLocalAddress(IPEndPoint
* address
) const override
;
1084 const BoundNetLog
& NetLog() const override
;
1086 // DatagramClientSocket implementation.
1087 int Connect(const IPEndPoint
& address
) override
;
1089 // AsyncSocket implementation.
1090 void OnReadComplete(const MockRead
& data
) override
;
1091 void OnWriteComplete(int rv
) override
;
1092 void OnConnectComplete(const MockConnect
& data
) override
;
1094 void set_source_port(uint16 port
) { source_port_
= port
;}
1099 void RunCallbackAsync(const CompletionCallback
& callback
, int result
);
1100 void RunCallback(const CompletionCallback
& callback
, int result
);
1103 SocketDataProvider
* data_
;
1105 MockRead read_data_
;
1106 bool need_read_data_
;
1107 uint16 source_port_
; // Ephemeral source port.
1109 // Address of the "remote" peer we're connected to.
1110 IPEndPoint peer_addr_
;
1112 // While an asynchronous IO is pending, we save our user-buffer state.
1113 scoped_refptr
<IOBuffer
> pending_read_buf_
;
1114 int pending_read_buf_len_
;
1115 CompletionCallback pending_read_callback_
;
1116 CompletionCallback pending_write_callback_
;
1118 BoundNetLog net_log_
;
1120 base::WeakPtrFactory
<MockUDPClientSocket
> weak_factory_
;
1122 DISALLOW_COPY_AND_ASSIGN(MockUDPClientSocket
);
1125 class TestSocketRequest
: public TestCompletionCallbackBase
{
1127 TestSocketRequest(std::vector
<TestSocketRequest
*>* request_order
,
1128 size_t* completion_count
);
1129 ~TestSocketRequest() override
;
1131 ClientSocketHandle
* handle() { return &handle_
; }
1133 const CompletionCallback
& callback() const { return callback_
; }
1136 void OnComplete(int result
);
1138 ClientSocketHandle handle_
;
1139 std::vector
<TestSocketRequest
*>* request_order_
;
1140 size_t* completion_count_
;
1141 CompletionCallback callback_
;
1143 DISALLOW_COPY_AND_ASSIGN(TestSocketRequest
);
1146 class ClientSocketPoolTest
{
1151 // A socket will be disconnected in addition to handle being reset.
1155 static const int kIndexOutOfBounds
;
1156 static const int kRequestNotFound
;
1158 ClientSocketPoolTest();
1159 ~ClientSocketPoolTest();
1161 template <typename PoolType
>
1162 int StartRequestUsingPool(
1163 PoolType
* socket_pool
,
1164 const std::string
& group_name
,
1165 RequestPriority priority
,
1166 const scoped_refptr
<typename
PoolType::SocketParams
>& socket_params
) {
1167 DCHECK(socket_pool
);
1168 TestSocketRequest
* request
=
1169 new TestSocketRequest(&request_order_
, &completion_count_
);
1170 requests_
.push_back(request
);
1171 int rv
= request
->handle()->Init(group_name
,
1174 request
->callback(),
1177 if (rv
!= ERR_IO_PENDING
)
1178 request_order_
.push_back(request
);
1182 // Provided there were n requests started, takes |index| in range 1..n
1183 // and returns order in which that request completed, in range 1..n,
1184 // or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound
1185 // if that request did not complete (for example was canceled).
1186 int GetOrderOfRequest(size_t index
) const;
1188 // Resets first initialized socket handle from |requests_|. If found such
1189 // a handle, returns true.
1190 bool ReleaseOneConnection(KeepAlive keep_alive
);
1192 // Releases connections until there is nothing to release.
1193 void ReleaseAllConnections(KeepAlive keep_alive
);
1195 // Note that this uses 0-based indices, while GetOrderOfRequest takes and
1196 // returns 0-based indices.
1197 TestSocketRequest
* request(int i
) { return requests_
[i
]; }
1199 size_t requests_size() const { return requests_
.size(); }
1200 ScopedVector
<TestSocketRequest
>* requests() { return &requests_
; }
1201 size_t completion_count() const { return completion_count_
; }
1204 ScopedVector
<TestSocketRequest
> requests_
;
1205 std::vector
<TestSocketRequest
*> request_order_
;
1206 size_t completion_count_
;
1208 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolTest
);
1211 class MockTransportSocketParams
1212 : public base::RefCounted
<MockTransportSocketParams
> {
1214 friend class base::RefCounted
<MockTransportSocketParams
>;
1215 ~MockTransportSocketParams() {}
1217 DISALLOW_COPY_AND_ASSIGN(MockTransportSocketParams
);
1220 class MockTransportClientSocketPool
: public TransportClientSocketPool
{
1222 typedef MockTransportSocketParams SocketParams
;
1224 class MockConnectJob
{
1226 MockConnectJob(scoped_ptr
<StreamSocket
> socket
,
1227 ClientSocketHandle
* handle
,
1228 const CompletionCallback
& callback
);
1232 bool CancelHandle(const ClientSocketHandle
* handle
);
1235 void OnConnect(int rv
);
1237 scoped_ptr
<StreamSocket
> socket_
;
1238 ClientSocketHandle
* handle_
;
1239 CompletionCallback user_callback_
;
1241 DISALLOW_COPY_AND_ASSIGN(MockConnectJob
);
1244 MockTransportClientSocketPool(int max_sockets
,
1245 int max_sockets_per_group
,
1246 ClientSocketFactory
* socket_factory
);
1248 ~MockTransportClientSocketPool() override
;
1250 RequestPriority
last_request_priority() const {
1251 return last_request_priority_
;
1253 int release_count() const { return release_count_
; }
1254 int cancel_count() const { return cancel_count_
; }
1256 // TransportClientSocketPool implementation.
1257 int RequestSocket(const std::string
& group_name
,
1258 const void* socket_params
,
1259 RequestPriority priority
,
1260 ClientSocketHandle
* handle
,
1261 const CompletionCallback
& callback
,
1262 const BoundNetLog
& net_log
) override
;
1264 void CancelRequest(const std::string
& group_name
,
1265 ClientSocketHandle
* handle
) override
;
1266 void ReleaseSocket(const std::string
& group_name
,
1267 scoped_ptr
<StreamSocket
> socket
,
1271 ClientSocketFactory
* client_socket_factory_
;
1272 ScopedVector
<MockConnectJob
> job_list_
;
1273 RequestPriority last_request_priority_
;
1277 DISALLOW_COPY_AND_ASSIGN(MockTransportClientSocketPool
);
1280 class DeterministicMockClientSocketFactory
: public ClientSocketFactory
{
1282 DeterministicMockClientSocketFactory();
1283 ~DeterministicMockClientSocketFactory() override
;
1285 void AddSocketDataProvider(DeterministicSocketData
* socket
);
1286 void AddSSLSocketDataProvider(SSLSocketDataProvider
* socket
);
1287 void ResetNextMockIndexes();
1289 // Return |index|-th MockSSLClientSocket (starting from 0) that the factory
1291 MockSSLClientSocket
* GetMockSSLClientSocket(size_t index
) const;
1293 SocketDataProviderArray
<DeterministicSocketData
>& mock_data() {
1296 std::vector
<DeterministicMockTCPClientSocket
*>& tcp_client_sockets() {
1297 return tcp_client_sockets_
;
1299 std::vector
<DeterministicMockUDPClientSocket
*>& udp_client_sockets() {
1300 return udp_client_sockets_
;
1303 // ClientSocketFactory
1304 scoped_ptr
<DatagramClientSocket
> CreateDatagramClientSocket(
1305 DatagramSocket::BindType bind_type
,
1306 const RandIntCallback
& rand_int_cb
,
1308 const NetLog::Source
& source
) override
;
1309 scoped_ptr
<StreamSocket
> CreateTransportClientSocket(
1310 const AddressList
& addresses
,
1312 const NetLog::Source
& source
) override
;
1313 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
1314 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1315 const HostPortPair
& host_and_port
,
1316 const SSLConfig
& ssl_config
,
1317 const SSLClientSocketContext
& context
) override
;
1318 void ClearSSLSessionCache() override
;
1321 SocketDataProviderArray
<DeterministicSocketData
> mock_data_
;
1322 SocketDataProviderArray
<SSLSocketDataProvider
> mock_ssl_data_
;
1324 // Store pointers to handed out sockets in case the test wants to get them.
1325 std::vector
<DeterministicMockTCPClientSocket
*> tcp_client_sockets_
;
1326 std::vector
<DeterministicMockUDPClientSocket
*> udp_client_sockets_
;
1327 std::vector
<MockSSLClientSocket
*> ssl_client_sockets_
;
1329 DISALLOW_COPY_AND_ASSIGN(DeterministicMockClientSocketFactory
);
1332 class MockSOCKSClientSocketPool
: public SOCKSClientSocketPool
{
1334 MockSOCKSClientSocketPool(int max_sockets
,
1335 int max_sockets_per_group
,
1336 TransportClientSocketPool
* transport_pool
);
1338 ~MockSOCKSClientSocketPool() override
;
1340 // SOCKSClientSocketPool implementation.
1341 int RequestSocket(const std::string
& group_name
,
1342 const void* socket_params
,
1343 RequestPriority priority
,
1344 ClientSocketHandle
* handle
,
1345 const CompletionCallback
& callback
,
1346 const BoundNetLog
& net_log
) override
;
1348 void CancelRequest(const std::string
& group_name
,
1349 ClientSocketHandle
* handle
) override
;
1350 void ReleaseSocket(const std::string
& group_name
,
1351 scoped_ptr
<StreamSocket
> socket
,
1355 TransportClientSocketPool
* const transport_pool_
;
1357 DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool
);
1360 // Convenience class to temporarily set the WebSocketEndpointLockManager unlock
1361 // delay to zero for testing purposes. Automatically restores the original value
1363 class ScopedWebSocketEndpointZeroUnlockDelay
{
1365 ScopedWebSocketEndpointZeroUnlockDelay();
1366 ~ScopedWebSocketEndpointZeroUnlockDelay();
1369 base::TimeDelta old_delay_
;
1372 // Constants for a successful SOCKS v5 handshake.
1373 extern const char kSOCKS5GreetRequest
[];
1374 extern const int kSOCKS5GreetRequestLength
;
1376 extern const char kSOCKS5GreetResponse
[];
1377 extern const int kSOCKS5GreetResponseLength
;
1379 extern const char kSOCKS5OkRequest
[];
1380 extern const int kSOCKS5OkRequestLength
;
1382 extern const char kSOCKS5OkResponse
[];
1383 extern const int kSOCKS5OkResponseLength
;
1387 #endif // NET_SOCKET_SOCKET_TEST_UTIL_H_