Roll src/third_party/WebKit a3b4a2e:7441784 (svn 202551:202552)
[chromium-blink-merge.git] / net / socket / socket_test_util.h
blob523e9acd7cc0f31fd933d5e8f2a7970ecbf0076d
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_
8 #include <stdint.h>
10 #include <cstring>
11 #include <deque>
12 #include <string>
13 #include <vector>
15 #include "base/basictypes.h"
16 #include "base/callback.h"
17 #include "base/logging.h"
18 #include "base/memory/ref_counted.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/memory/scoped_vector.h"
21 #include "base/memory/weak_ptr.h"
22 #include "base/strings/string16.h"
23 #include "base/time/time.h"
24 #include "net/base/address_list.h"
25 #include "net/base/io_buffer.h"
26 #include "net/base/net_errors.h"
27 #include "net/base/test_completion_callback.h"
28 #include "net/http/http_auth_controller.h"
29 #include "net/http/http_proxy_client_socket_pool.h"
30 #include "net/log/net_log.h"
31 #include "net/socket/client_socket_factory.h"
32 #include "net/socket/client_socket_handle.h"
33 #include "net/socket/socks_client_socket_pool.h"
34 #include "net/socket/ssl_client_socket.h"
35 #include "net/socket/ssl_client_socket_pool.h"
36 #include "net/socket/transport_client_socket_pool.h"
37 #include "net/ssl/ssl_config_service.h"
38 #include "net/udp/datagram_client_socket.h"
39 #include "testing/gtest/include/gtest/gtest.h"
41 namespace net {
43 enum {
44 // A private network error code used by the socket test utility classes.
45 // If the |result| member of a MockRead is
46 // ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ, that MockRead is just a
47 // marker that indicates the peer will close the connection after the next
48 // MockRead. The other members of that MockRead are ignored.
49 ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ = -10000,
52 class AsyncSocket;
53 class ChannelIDService;
54 class MockClientSocket;
55 class SSLClientSocket;
56 class StreamSocket;
58 enum IoMode {
59 ASYNC,
60 SYNCHRONOUS
63 struct MockConnect {
64 // Asynchronous connection success.
65 // Creates a MockConnect with |mode| ASYC, |result| OK, and
66 // |peer_addr| 192.0.2.33.
67 MockConnect();
68 // Creates a MockConnect with the specified mode and result, with
69 // |peer_addr| 192.0.2.33.
70 MockConnect(IoMode io_mode, int r);
71 MockConnect(IoMode io_mode, int r, IPEndPoint addr);
72 ~MockConnect();
74 IoMode mode;
75 int result;
76 IPEndPoint peer_addr;
79 // MockRead and MockWrite shares the same interface and members, but we'd like
80 // to have distinct types because we don't want to have them used
81 // interchangably. To do this, a struct template is defined, and MockRead and
82 // MockWrite are instantiated by using this template. Template parameter |type|
83 // is not used in the struct definition (it purely exists for creating a new
84 // type).
86 // |data| in MockRead and MockWrite has different meanings: |data| in MockRead
87 // is the data returned from the socket when MockTCPClientSocket::Read() is
88 // attempted, while |data| in MockWrite is the expected data that should be
89 // given in MockTCPClientSocket::Write().
90 enum MockReadWriteType {
91 MOCK_READ,
92 MOCK_WRITE
95 template <MockReadWriteType type>
96 struct MockReadWrite {
97 // Flag to indicate that the message loop should be terminated.
98 enum {
99 STOPLOOP = 1 << 31
102 // Default
103 MockReadWrite()
104 : mode(SYNCHRONOUS),
105 result(0),
106 data(NULL),
107 data_len(0),
108 sequence_number(0) {}
110 // Read/write failure (no data).
111 MockReadWrite(IoMode io_mode, int result)
112 : mode(io_mode),
113 result(result),
114 data(NULL),
115 data_len(0),
116 sequence_number(0) {}
118 // Read/write failure (no data), with sequence information.
119 MockReadWrite(IoMode io_mode, int result, int seq)
120 : mode(io_mode),
121 result(result),
122 data(NULL),
123 data_len(0),
124 sequence_number(seq) {}
126 // Asynchronous read/write success (inferred data length).
127 explicit MockReadWrite(const char* data)
128 : mode(ASYNC),
129 result(0),
130 data(data),
131 data_len(strlen(data)),
132 sequence_number(0) {}
134 // Read/write success (inferred data length).
135 MockReadWrite(IoMode io_mode, const char* data)
136 : mode(io_mode),
137 result(0),
138 data(data),
139 data_len(strlen(data)),
140 sequence_number(0) {}
142 // Read/write success.
143 MockReadWrite(IoMode io_mode, const char* data, int data_len)
144 : mode(io_mode),
145 result(0),
146 data(data),
147 data_len(data_len),
148 sequence_number(0) {}
150 // Read/write success (inferred data length) with sequence information.
151 MockReadWrite(IoMode io_mode, int seq, const char* data)
152 : mode(io_mode),
153 result(0),
154 data(data),
155 data_len(strlen(data)),
156 sequence_number(seq) {}
158 // Read/write success with sequence information.
159 MockReadWrite(IoMode io_mode, const char* data, int data_len, int seq)
160 : mode(io_mode),
161 result(0),
162 data(data),
163 data_len(data_len),
164 sequence_number(seq) {}
166 IoMode mode;
167 int result;
168 const char* data;
169 int data_len;
171 // For data providers that only allows reads to occur in a particular
172 // sequence. If a read occurs before the given |sequence_number| is reached,
173 // an ERR_IO_PENDING is returned.
174 int sequence_number; // The sequence number at which a read is allowed
175 // to occur.
178 typedef MockReadWrite<MOCK_READ> MockRead;
179 typedef MockReadWrite<MOCK_WRITE> MockWrite;
181 struct MockWriteResult {
182 MockWriteResult(IoMode io_mode, int result) : mode(io_mode), result(result) {}
184 IoMode mode;
185 int result;
188 // The SocketDataProvider is an interface used by the MockClientSocket
189 // for getting data about individual reads and writes on the socket.
190 class SocketDataProvider {
191 public:
192 SocketDataProvider() : socket_(NULL) {}
194 virtual ~SocketDataProvider() {}
196 // Returns the buffer and result code for the next simulated read.
197 // If the |MockRead.result| is ERR_IO_PENDING, it informs the caller
198 // that it will be called via the AsyncSocket::OnReadComplete()
199 // function at a later time.
200 virtual MockRead OnRead() = 0;
201 virtual MockWriteResult OnWrite(const std::string& data) = 0;
202 virtual void Reset() = 0;
203 virtual bool AllReadDataConsumed() const = 0;
204 virtual bool AllWriteDataConsumed() const = 0;
206 // Accessor for the socket which is using the SocketDataProvider.
207 AsyncSocket* socket() { return socket_; }
208 void set_socket(AsyncSocket* socket) { socket_ = socket; }
210 MockConnect connect_data() const { return connect_; }
211 void set_connect_data(const MockConnect& connect) { connect_ = connect; }
213 private:
214 MockConnect connect_;
215 AsyncSocket* socket_;
217 DISALLOW_COPY_AND_ASSIGN(SocketDataProvider);
220 // The AsyncSocket is an interface used by the SocketDataProvider to
221 // complete the asynchronous read operation.
222 class AsyncSocket {
223 public:
224 // If an async IO is pending because the SocketDataProvider returned
225 // ERR_IO_PENDING, then the AsyncSocket waits until this OnReadComplete
226 // is called to complete the asynchronous read operation.
227 // data.async is ignored, and this read is completed synchronously as
228 // part of this call.
229 // TODO(rch): this should take a StringPiece since most of the fields
230 // are ignored.
231 virtual void OnReadComplete(const MockRead& data) = 0;
232 // If an async IO is pending because the SocketDataProvider returned
233 // ERR_IO_PENDING, then the AsyncSocket waits until this OnReadComplete
234 // is called to complete the asynchronous read operation.
235 virtual void OnWriteComplete(int rv) = 0;
236 virtual void OnConnectComplete(const MockConnect& data) = 0;
239 // StaticSocketDataHelper manages a list of reads and writes.
240 class StaticSocketDataHelper {
241 public:
242 StaticSocketDataHelper(MockRead* reads,
243 size_t reads_count,
244 MockWrite* writes,
245 size_t writes_count);
246 ~StaticSocketDataHelper();
248 // These functions get access to the next available read and write data,
249 // or null if there is no more data available.
250 const MockRead& PeekRead() const;
251 const MockWrite& PeekWrite() const;
253 // Returns the current read or write , and then advances to the next one.
254 const MockRead& AdvanceRead();
255 const MockWrite& AdvanceWrite();
257 // Resets the read and write indexes to 0.
258 void Reset();
260 // Returns true if |data| is valid data for the next write. In order
261 // to support short writes, the next write may be longer than |data|
262 // in which case this method will still return true.
263 bool VerifyWriteData(const std::string& data);
265 size_t read_index() const { return read_index_; }
266 size_t write_index() const { return write_index_; }
267 size_t read_count() const { return read_count_; }
268 size_t write_count() const { return write_count_; }
270 bool AllReadDataConsumed() const { return read_index_ >= read_count_; }
271 bool AllWriteDataConsumed() const { return write_index_ >= write_count_; }
273 private:
274 MockRead* reads_;
275 size_t read_index_;
276 size_t read_count_;
277 MockWrite* writes_;
278 size_t write_index_;
279 size_t write_count_;
281 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataHelper);
284 // SocketDataProvider which responds based on static tables of mock reads and
285 // writes.
286 class StaticSocketDataProvider : public SocketDataProvider {
287 public:
288 StaticSocketDataProvider();
289 StaticSocketDataProvider(MockRead* reads,
290 size_t reads_count,
291 MockWrite* writes,
292 size_t writes_count);
293 ~StaticSocketDataProvider() override;
295 virtual void CompleteRead() {}
297 // SocketDataProvider implementation.
298 MockRead OnRead() override;
299 MockWriteResult OnWrite(const std::string& data) override;
300 void Reset() override;
301 bool AllReadDataConsumed() const override;
302 bool AllWriteDataConsumed() const override;
304 size_t read_index() const { return helper_.read_index(); }
305 size_t write_index() const { return helper_.write_index(); }
306 size_t read_count() const { return helper_.read_count(); }
307 size_t write_count() const { return helper_.write_count(); }
309 protected:
310 StaticSocketDataHelper* helper() { return &helper_; }
312 private:
313 StaticSocketDataHelper helper_;
315 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataProvider);
318 // SSLSocketDataProviders only need to keep track of the return code from calls
319 // to Connect().
320 struct SSLSocketDataProvider {
321 SSLSocketDataProvider(IoMode mode, int result);
322 ~SSLSocketDataProvider();
324 void SetNextProto(NextProto proto);
326 MockConnect connect;
327 SSLClientSocket::NextProtoStatus next_proto_status;
328 std::string next_proto;
329 NextProtoVector next_protos_expected_in_ssl_config;
330 bool client_cert_sent;
331 SSLCertRequestInfo* cert_request_info;
332 scoped_refptr<X509Certificate> cert;
333 bool channel_id_sent;
334 ChannelIDService* channel_id_service;
335 int connection_status;
338 // Uses the sequence_number field in the mock reads and writes to
339 // complete the operations in a specified order.
340 class SequencedSocketData : public SocketDataProvider {
341 public:
342 // |reads| is the list of MockRead completions.
343 // |writes| is the list of MockWrite completions.
344 SequencedSocketData(MockRead* reads,
345 size_t reads_count,
346 MockWrite* writes,
347 size_t writes_count);
349 // |connect| is the result for the connect phase.
350 // |reads| is the list of MockRead completions.
351 // |writes| is the list of MockWrite completions.
352 SequencedSocketData(const MockConnect& connect,
353 MockRead* reads,
354 size_t reads_count,
355 MockWrite* writes,
356 size_t writes_count);
358 ~SequencedSocketData() override;
360 // SocketDataProviderBase implementation.
361 MockRead OnRead() override;
362 MockWriteResult OnWrite(const std::string& data) override;
363 void Reset() override;
364 bool AllReadDataConsumed() const override;
365 bool AllWriteDataConsumed() const override;
367 bool IsReadPaused();
368 void CompleteRead();
370 private:
371 // Defines the state for the read or write path.
372 enum IoState {
373 IDLE, // No async operation is in progress.
374 PENDING, // An async operation in waiting for another opteration to
375 // complete.
376 COMPLETING, // A task has been posted to complet an async operation.
377 PAUSED, // IO is paused until CompleteRead() is called.
380 void OnReadComplete();
381 void OnWriteComplete();
383 void MaybePostReadCompleteTask();
384 void MaybePostWriteCompleteTask();
386 StaticSocketDataHelper helper_;
387 int sequence_number_;
388 IoState read_state_;
389 IoState write_state_;
391 base::WeakPtrFactory<SequencedSocketData> weak_factory_;
393 DISALLOW_COPY_AND_ASSIGN(SequencedSocketData);
396 class DeterministicMockTCPClientSocket;
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.
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:
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.
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.
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.
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 // };
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.
453 // For examples of how to use this class, see:
454 // deterministic_socket_data_unittests.cc
455 class DeterministicSocketData {
456 public:
457 // The Delegate is an abstract interface which handles the communication from
458 // the DeterministicSocketData to the Deterministic MockSocket. The
459 // MockSockets directly store a pointer to the DeterministicSocketData,
460 // whereas the DeterministicSocketData only stores a pointer to the
461 // abstract Delegate interface.
462 class Delegate {
463 public:
464 // Returns true if there is currently a write pending. That is to say, if
465 // an asynchronous write has been started but the callback has not been
466 // invoked.
467 virtual bool WritePending() const = 0;
468 // Returns true if there is currently a read pending. That is to say, if
469 // an asynchronous read has been started but the callback has not been
470 // invoked.
471 virtual bool ReadPending() const = 0;
472 // Called to complete an asynchronous write to execute the write callback.
473 virtual void CompleteWrite() = 0;
474 // Called to complete an asynchronous read to execute the read callback.
475 virtual int CompleteRead() = 0;
477 protected:
478 virtual ~Delegate() {}
481 // |reads| the list of MockRead completions.
482 // |writes| the list of MockWrite completions.
483 DeterministicSocketData(MockRead* reads,
484 size_t reads_count,
485 MockWrite* writes,
486 size_t writes_count);
487 ~DeterministicSocketData();
489 // Consume all the data up to the give stop point (via SetStop()).
490 void Run();
492 // Set the stop point to be |steps| from now, and then invoke Run().
493 void RunFor(int steps);
495 // Stop at step |seq|, which must be in the future.
496 void SetStop(int seq);
498 // Stop |seq| steps after the current step.
499 void StopAfter(int seq);
501 bool stopped() const { return stopped_; }
502 void SetStopped(bool val) { stopped_ = val; }
503 MockRead& current_read() { return current_read_; }
504 MockWrite& current_write() { return current_write_; }
505 int sequence_number() const { return sequence_number_; }
506 void set_delegate(base::WeakPtr<Delegate> delegate) { delegate_ = delegate; }
507 MockConnect connect_data() const { return connect_; }
508 void set_connect_data(const MockConnect& connect) { connect_ = connect; }
510 // When the socket calls Read(), that calls OnRead(), and expects either
511 // ERR_IO_PENDING or data.
512 MockRead OnRead();
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 MockWriteResult OnWrite(const std::string& data);
519 bool AllReadDataConsumed() const;
520 bool AllWriteDataConsumed() const;
522 private:
523 // Invoke the read and write callbacks, if the timing is appropriate.
524 void InvokeCallbacks();
526 void NextStep();
528 void VerifyCorrectSequenceNumbers(MockRead* reads,
529 size_t reads_count,
530 MockWrite* writes,
531 size_t writes_count);
532 StaticSocketDataHelper helper_;
533 MockConnect connect_;
534 int sequence_number_;
535 MockRead current_read_;
536 MockWrite current_write_;
537 int stopping_sequence_number_;
538 bool stopped_;
539 base::WeakPtr<Delegate> delegate_;
540 bool print_debug_;
541 bool is_running_;
544 // Holds an array of SocketDataProvider elements. As Mock{TCP,SSL}StreamSocket
545 // objects get instantiated, they take their data from the i'th element of this
546 // array.
547 template <typename T>
548 class SocketDataProviderArray {
549 public:
550 SocketDataProviderArray() : next_index_(0) {}
552 T* GetNext() {
553 DCHECK_LT(next_index_, data_providers_.size());
554 return data_providers_[next_index_++];
557 void Add(T* data_provider) {
558 DCHECK(data_provider);
559 data_providers_.push_back(data_provider);
562 size_t next_index() { return next_index_; }
564 void ResetNextIndex() { next_index_ = 0; }
566 private:
567 // Index of the next |data_providers_| element to use. Not an iterator
568 // because those are invalidated on vector reallocation.
569 size_t next_index_;
571 // SocketDataProviders to be returned.
572 std::vector<T*> data_providers_;
575 class MockUDPClientSocket;
576 class MockTCPClientSocket;
577 class MockSSLClientSocket;
579 // ClientSocketFactory which contains arrays of sockets of each type.
580 // You should first fill the arrays using AddMock{SSL,}Socket. When the factory
581 // is asked to create a socket, it takes next entry from appropriate array.
582 // You can use ResetNextMockIndexes to reset that next entry index for all mock
583 // socket types.
584 class MockClientSocketFactory : public ClientSocketFactory {
585 public:
586 MockClientSocketFactory();
587 ~MockClientSocketFactory() override;
589 void AddSocketDataProvider(SocketDataProvider* socket);
590 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
591 void ResetNextMockIndexes();
593 SocketDataProviderArray<SocketDataProvider>& mock_data() {
594 return mock_data_;
597 // ClientSocketFactory
598 scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
599 DatagramSocket::BindType bind_type,
600 const RandIntCallback& rand_int_cb,
601 NetLog* net_log,
602 const NetLog::Source& source) override;
603 scoped_ptr<StreamSocket> CreateTransportClientSocket(
604 const AddressList& addresses,
605 NetLog* net_log,
606 const NetLog::Source& source) override;
607 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
608 scoped_ptr<ClientSocketHandle> transport_socket,
609 const HostPortPair& host_and_port,
610 const SSLConfig& ssl_config,
611 const SSLClientSocketContext& context) override;
612 void ClearSSLSessionCache() override;
614 private:
615 SocketDataProviderArray<SocketDataProvider> mock_data_;
616 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
619 class MockClientSocket : public SSLClientSocket {
620 public:
621 // Value returned by GetTLSUniqueChannelBinding().
622 static const char kTlsUnique[];
624 // The BoundNetLog is needed to test LoadTimingInfo, which uses NetLog IDs as
625 // unique socket IDs.
626 explicit MockClientSocket(const BoundNetLog& net_log);
628 // Socket implementation.
629 int Read(IOBuffer* buf,
630 int buf_len,
631 const CompletionCallback& callback) override = 0;
632 int Write(IOBuffer* buf,
633 int buf_len,
634 const CompletionCallback& callback) override = 0;
635 int SetReceiveBufferSize(int32 size) override;
636 int SetSendBufferSize(int32 size) override;
638 // StreamSocket implementation.
639 int Connect(const CompletionCallback& callback) override = 0;
640 void Disconnect() override;
641 bool IsConnected() const override;
642 bool IsConnectedAndIdle() const override;
643 int GetPeerAddress(IPEndPoint* address) const override;
644 int GetLocalAddress(IPEndPoint* address) const override;
645 const BoundNetLog& NetLog() const override;
646 void SetSubresourceSpeculation() override {}
647 void SetOmniboxSpeculation() override {}
648 void GetConnectionAttempts(ConnectionAttempts* out) const override;
649 void ClearConnectionAttempts() override {}
650 void AddConnectionAttempts(const ConnectionAttempts& attempts) override {}
652 // SSLClientSocket implementation.
653 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override;
654 int ExportKeyingMaterial(const base::StringPiece& label,
655 bool has_context,
656 const base::StringPiece& context,
657 unsigned char* out,
658 unsigned int outlen) override;
659 int GetTLSUniqueChannelBinding(std::string* out) override;
660 NextProtoStatus GetNextProto(std::string* proto) const override;
661 ChannelIDService* GetChannelIDService() const override;
662 SSLFailureState GetSSLFailureState() const override;
664 protected:
665 ~MockClientSocket() override;
666 void RunCallbackAsync(const CompletionCallback& callback, int result);
667 void RunCallback(const CompletionCallback& callback, int result);
669 // True if Connect completed successfully and Disconnect hasn't been called.
670 bool connected_;
672 // Address of the "remote" peer we're connected to.
673 IPEndPoint peer_addr_;
675 BoundNetLog net_log_;
677 private:
678 base::WeakPtrFactory<MockClientSocket> weak_factory_;
680 DISALLOW_COPY_AND_ASSIGN(MockClientSocket);
683 class MockTCPClientSocket : public MockClientSocket, public AsyncSocket {
684 public:
685 MockTCPClientSocket(const AddressList& addresses,
686 net::NetLog* net_log,
687 SocketDataProvider* socket);
688 ~MockTCPClientSocket() override;
690 const AddressList& addresses() const { return addresses_; }
692 // Socket implementation.
693 int Read(IOBuffer* buf,
694 int buf_len,
695 const CompletionCallback& callback) override;
696 int Write(IOBuffer* buf,
697 int buf_len,
698 const CompletionCallback& callback) override;
700 // StreamSocket implementation.
701 int Connect(const CompletionCallback& callback) override;
702 void Disconnect() override;
703 bool IsConnected() const override;
704 bool IsConnectedAndIdle() const override;
705 int GetPeerAddress(IPEndPoint* address) const override;
706 bool WasEverUsed() const override;
707 bool UsingTCPFastOpen() const override;
708 bool WasNpnNegotiated() const override;
709 bool GetSSLInfo(SSLInfo* ssl_info) override;
710 void GetConnectionAttempts(ConnectionAttempts* out) const override;
711 void ClearConnectionAttempts() override;
712 void AddConnectionAttempts(const ConnectionAttempts& attempts) override;
714 // AsyncSocket:
715 void OnReadComplete(const MockRead& data) override;
716 void OnWriteComplete(int rv) override;
717 void OnConnectComplete(const MockConnect& data) override;
719 private:
720 int CompleteRead();
722 AddressList addresses_;
724 SocketDataProvider* data_;
725 int read_offset_;
726 MockRead read_data_;
727 bool need_read_data_;
729 // True if the peer has closed the connection. This allows us to simulate
730 // the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real
731 // TCPClientSocket.
732 bool peer_closed_connection_;
734 // While an asynchronous read is pending, we save our user-buffer state.
735 scoped_refptr<IOBuffer> pending_read_buf_;
736 int pending_read_buf_len_;
737 CompletionCallback pending_read_callback_;
738 CompletionCallback pending_write_callback_;
739 bool was_used_to_convey_data_;
741 DISALLOW_COPY_AND_ASSIGN(MockTCPClientSocket);
744 // DeterministicSocketHelper is a helper class that can be used
745 // to simulate Socket::Read() and Socket::Write()
746 // using deterministic |data|.
747 // Note: This is provided as a common helper class because
748 // of the inheritance hierarchy of DeterministicMock[UDP,TCP]ClientSocket and a
749 // desire not to introduce an additional common base class.
750 class DeterministicSocketHelper {
751 public:
752 DeterministicSocketHelper(NetLog* net_log, DeterministicSocketData* data);
753 virtual ~DeterministicSocketHelper();
755 bool write_pending() const { return write_pending_; }
756 bool read_pending() const { return read_pending_; }
758 void CompleteWrite();
759 int CompleteRead();
761 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
762 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
764 const BoundNetLog& net_log() const { return net_log_; }
766 bool was_used_to_convey_data() const { return was_used_to_convey_data_; }
768 bool peer_closed_connection() const { return peer_closed_connection_; }
770 DeterministicSocketData* data() const { return data_; }
772 private:
773 bool write_pending_;
774 CompletionCallback write_callback_;
775 int write_result_;
777 MockRead read_data_;
779 IOBuffer* read_buf_;
780 int read_buf_len_;
781 bool read_pending_;
782 CompletionCallback read_callback_;
783 DeterministicSocketData* data_;
784 bool was_used_to_convey_data_;
785 bool peer_closed_connection_;
786 BoundNetLog net_log_;
789 // Mock UDP socket to be used in conjunction with DeterministicSocketData.
790 class DeterministicMockUDPClientSocket
791 : public DatagramClientSocket,
792 public DeterministicSocketData::Delegate,
793 public base::SupportsWeakPtr<DeterministicMockUDPClientSocket> {
794 public:
795 DeterministicMockUDPClientSocket(net::NetLog* net_log,
796 DeterministicSocketData* data);
797 ~DeterministicMockUDPClientSocket() override;
799 // DeterministicSocketData::Delegate:
800 bool WritePending() const override;
801 bool ReadPending() const override;
802 void CompleteWrite() override;
803 int CompleteRead() override;
805 // Socket implementation.
806 int Read(IOBuffer* buf,
807 int buf_len,
808 const CompletionCallback& callback) override;
809 int Write(IOBuffer* buf,
810 int buf_len,
811 const CompletionCallback& callback) override;
812 int SetReceiveBufferSize(int32 size) override;
813 int SetSendBufferSize(int32 size) override;
815 // DatagramSocket implementation.
816 void Close() override;
817 int GetPeerAddress(IPEndPoint* address) const override;
818 int GetLocalAddress(IPEndPoint* address) const override;
819 const BoundNetLog& NetLog() const override;
821 // DatagramClientSocket implementation.
822 int Connect(const IPEndPoint& address) override;
824 void set_source_port(uint16 port) { source_port_ = port; }
826 private:
827 bool connected_;
828 IPEndPoint peer_address_;
829 DeterministicSocketHelper helper_;
830 uint16 source_port_; // Ephemeral source port.
832 DISALLOW_COPY_AND_ASSIGN(DeterministicMockUDPClientSocket);
835 // Mock TCP socket to be used in conjunction with DeterministicSocketData.
836 class DeterministicMockTCPClientSocket
837 : public MockClientSocket,
838 public DeterministicSocketData::Delegate,
839 public base::SupportsWeakPtr<DeterministicMockTCPClientSocket> {
840 public:
841 DeterministicMockTCPClientSocket(net::NetLog* net_log,
842 DeterministicSocketData* data);
843 ~DeterministicMockTCPClientSocket() override;
845 // DeterministicSocketData::Delegate:
846 bool WritePending() const override;
847 bool ReadPending() const override;
848 void CompleteWrite() override;
849 int CompleteRead() override;
851 // Socket:
852 int Write(IOBuffer* buf,
853 int buf_len,
854 const CompletionCallback& callback) override;
855 int Read(IOBuffer* buf,
856 int buf_len,
857 const CompletionCallback& callback) override;
859 // StreamSocket:
860 int Connect(const CompletionCallback& callback) override;
861 void Disconnect() override;
862 bool IsConnected() const override;
863 bool IsConnectedAndIdle() const override;
864 bool WasEverUsed() const override;
865 bool UsingTCPFastOpen() const override;
866 bool WasNpnNegotiated() const override;
867 bool GetSSLInfo(SSLInfo* ssl_info) override;
869 private:
870 DeterministicSocketHelper helper_;
872 DISALLOW_COPY_AND_ASSIGN(DeterministicMockTCPClientSocket);
875 class MockSSLClientSocket : public MockClientSocket, public AsyncSocket {
876 public:
877 MockSSLClientSocket(scoped_ptr<ClientSocketHandle> transport_socket,
878 const HostPortPair& host_and_port,
879 const SSLConfig& ssl_config,
880 SSLSocketDataProvider* socket);
881 ~MockSSLClientSocket() override;
883 // Socket implementation.
884 int Read(IOBuffer* buf,
885 int buf_len,
886 const CompletionCallback& callback) override;
887 int Write(IOBuffer* buf,
888 int buf_len,
889 const CompletionCallback& callback) override;
891 // StreamSocket implementation.
892 int Connect(const CompletionCallback& callback) override;
893 void Disconnect() override;
894 bool IsConnected() const override;
895 bool WasEverUsed() const override;
896 bool UsingTCPFastOpen() const override;
897 int GetPeerAddress(IPEndPoint* address) const override;
898 bool GetSSLInfo(SSLInfo* ssl_info) override;
900 // SSLClientSocket implementation.
901 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override;
902 NextProtoStatus GetNextProto(std::string* proto) const override;
904 // This MockSocket does not implement the manual async IO feature.
905 void OnReadComplete(const MockRead& data) override;
906 void OnWriteComplete(int rv) override;
907 void OnConnectComplete(const MockConnect& data) override;
909 ChannelIDService* GetChannelIDService() const override;
911 private:
912 static void ConnectCallback(MockSSLClientSocket* ssl_client_socket,
913 const CompletionCallback& callback,
914 int rv);
916 scoped_ptr<ClientSocketHandle> transport_;
917 SSLSocketDataProvider* data_;
919 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket);
922 class MockUDPClientSocket : public DatagramClientSocket, public AsyncSocket {
923 public:
924 MockUDPClientSocket(SocketDataProvider* data, net::NetLog* net_log);
925 ~MockUDPClientSocket() override;
927 // Socket implementation.
928 int Read(IOBuffer* buf,
929 int buf_len,
930 const CompletionCallback& callback) override;
931 int Write(IOBuffer* buf,
932 int buf_len,
933 const CompletionCallback& callback) override;
934 int SetReceiveBufferSize(int32 size) override;
935 int SetSendBufferSize(int32 size) override;
937 // DatagramSocket implementation.
938 void Close() override;
939 int GetPeerAddress(IPEndPoint* address) const override;
940 int GetLocalAddress(IPEndPoint* address) const override;
941 const BoundNetLog& NetLog() const override;
943 // DatagramClientSocket implementation.
944 int Connect(const IPEndPoint& address) override;
946 // AsyncSocket implementation.
947 void OnReadComplete(const MockRead& data) override;
948 void OnWriteComplete(int rv) override;
949 void OnConnectComplete(const MockConnect& data) override;
951 void set_source_port(uint16 port) { source_port_ = port;}
953 private:
954 int CompleteRead();
956 void RunCallbackAsync(const CompletionCallback& callback, int result);
957 void RunCallback(const CompletionCallback& callback, int result);
959 bool connected_;
960 SocketDataProvider* data_;
961 int read_offset_;
962 MockRead read_data_;
963 bool need_read_data_;
964 uint16 source_port_; // Ephemeral source port.
966 // Address of the "remote" peer we're connected to.
967 IPEndPoint peer_addr_;
969 // While an asynchronous IO is pending, we save our user-buffer state.
970 scoped_refptr<IOBuffer> pending_read_buf_;
971 int pending_read_buf_len_;
972 CompletionCallback pending_read_callback_;
973 CompletionCallback pending_write_callback_;
975 BoundNetLog net_log_;
977 base::WeakPtrFactory<MockUDPClientSocket> weak_factory_;
979 DISALLOW_COPY_AND_ASSIGN(MockUDPClientSocket);
982 class TestSocketRequest : public TestCompletionCallbackBase {
983 public:
984 TestSocketRequest(std::vector<TestSocketRequest*>* request_order,
985 size_t* completion_count);
986 ~TestSocketRequest() override;
988 ClientSocketHandle* handle() { return &handle_; }
990 const CompletionCallback& callback() const { return callback_; }
992 private:
993 void OnComplete(int result);
995 ClientSocketHandle handle_;
996 std::vector<TestSocketRequest*>* request_order_;
997 size_t* completion_count_;
998 CompletionCallback callback_;
1000 DISALLOW_COPY_AND_ASSIGN(TestSocketRequest);
1003 class ClientSocketPoolTest {
1004 public:
1005 enum KeepAlive {
1006 KEEP_ALIVE,
1008 // A socket will be disconnected in addition to handle being reset.
1009 NO_KEEP_ALIVE,
1012 static const int kIndexOutOfBounds;
1013 static const int kRequestNotFound;
1015 ClientSocketPoolTest();
1016 ~ClientSocketPoolTest();
1018 template <typename PoolType>
1019 int StartRequestUsingPool(
1020 PoolType* socket_pool,
1021 const std::string& group_name,
1022 RequestPriority priority,
1023 const scoped_refptr<typename PoolType::SocketParams>& socket_params) {
1024 DCHECK(socket_pool);
1025 TestSocketRequest* request =
1026 new TestSocketRequest(&request_order_, &completion_count_);
1027 requests_.push_back(request);
1028 int rv = request->handle()->Init(group_name,
1029 socket_params,
1030 priority,
1031 request->callback(),
1032 socket_pool,
1033 BoundNetLog());
1034 if (rv != ERR_IO_PENDING)
1035 request_order_.push_back(request);
1036 return rv;
1039 // Provided there were n requests started, takes |index| in range 1..n
1040 // and returns order in which that request completed, in range 1..n,
1041 // or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound
1042 // if that request did not complete (for example was canceled).
1043 int GetOrderOfRequest(size_t index) const;
1045 // Resets first initialized socket handle from |requests_|. If found such
1046 // a handle, returns true.
1047 bool ReleaseOneConnection(KeepAlive keep_alive);
1049 // Releases connections until there is nothing to release.
1050 void ReleaseAllConnections(KeepAlive keep_alive);
1052 // Note that this uses 0-based indices, while GetOrderOfRequest takes and
1053 // returns 0-based indices.
1054 TestSocketRequest* request(int i) { return requests_[i]; }
1056 size_t requests_size() const { return requests_.size(); }
1057 ScopedVector<TestSocketRequest>* requests() { return &requests_; }
1058 size_t completion_count() const { return completion_count_; }
1060 private:
1061 ScopedVector<TestSocketRequest> requests_;
1062 std::vector<TestSocketRequest*> request_order_;
1063 size_t completion_count_;
1065 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolTest);
1068 class MockTransportSocketParams
1069 : public base::RefCounted<MockTransportSocketParams> {
1070 private:
1071 friend class base::RefCounted<MockTransportSocketParams>;
1072 ~MockTransportSocketParams() {}
1074 DISALLOW_COPY_AND_ASSIGN(MockTransportSocketParams);
1077 class MockTransportClientSocketPool : public TransportClientSocketPool {
1078 public:
1079 typedef MockTransportSocketParams SocketParams;
1081 class MockConnectJob {
1082 public:
1083 MockConnectJob(scoped_ptr<StreamSocket> socket,
1084 ClientSocketHandle* handle,
1085 const CompletionCallback& callback);
1086 ~MockConnectJob();
1088 int Connect();
1089 bool CancelHandle(const ClientSocketHandle* handle);
1091 private:
1092 void OnConnect(int rv);
1094 scoped_ptr<StreamSocket> socket_;
1095 ClientSocketHandle* handle_;
1096 CompletionCallback user_callback_;
1098 DISALLOW_COPY_AND_ASSIGN(MockConnectJob);
1101 MockTransportClientSocketPool(int max_sockets,
1102 int max_sockets_per_group,
1103 ClientSocketFactory* socket_factory);
1105 ~MockTransportClientSocketPool() override;
1107 RequestPriority last_request_priority() const {
1108 return last_request_priority_;
1110 int release_count() const { return release_count_; }
1111 int cancel_count() const { return cancel_count_; }
1113 // TransportClientSocketPool implementation.
1114 int RequestSocket(const std::string& group_name,
1115 const void* socket_params,
1116 RequestPriority priority,
1117 ClientSocketHandle* handle,
1118 const CompletionCallback& callback,
1119 const BoundNetLog& net_log) override;
1121 void CancelRequest(const std::string& group_name,
1122 ClientSocketHandle* handle) override;
1123 void ReleaseSocket(const std::string& group_name,
1124 scoped_ptr<StreamSocket> socket,
1125 int id) override;
1127 private:
1128 ClientSocketFactory* client_socket_factory_;
1129 ScopedVector<MockConnectJob> job_list_;
1130 RequestPriority last_request_priority_;
1131 int release_count_;
1132 int cancel_count_;
1134 DISALLOW_COPY_AND_ASSIGN(MockTransportClientSocketPool);
1137 class DeterministicMockClientSocketFactory : public ClientSocketFactory {
1138 public:
1139 DeterministicMockClientSocketFactory();
1140 ~DeterministicMockClientSocketFactory() override;
1142 void AddSocketDataProvider(DeterministicSocketData* socket);
1143 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
1144 void ResetNextMockIndexes();
1146 // Return |index|-th MockSSLClientSocket (starting from 0) that the factory
1147 // created.
1148 MockSSLClientSocket* GetMockSSLClientSocket(size_t index) const;
1150 SocketDataProviderArray<DeterministicSocketData>& mock_data() {
1151 return mock_data_;
1153 std::vector<DeterministicMockTCPClientSocket*>& tcp_client_sockets() {
1154 return tcp_client_sockets_;
1156 std::vector<DeterministicMockUDPClientSocket*>& udp_client_sockets() {
1157 return udp_client_sockets_;
1160 // ClientSocketFactory
1161 scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
1162 DatagramSocket::BindType bind_type,
1163 const RandIntCallback& rand_int_cb,
1164 NetLog* net_log,
1165 const NetLog::Source& source) override;
1166 scoped_ptr<StreamSocket> CreateTransportClientSocket(
1167 const AddressList& addresses,
1168 NetLog* net_log,
1169 const NetLog::Source& source) override;
1170 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
1171 scoped_ptr<ClientSocketHandle> transport_socket,
1172 const HostPortPair& host_and_port,
1173 const SSLConfig& ssl_config,
1174 const SSLClientSocketContext& context) override;
1175 void ClearSSLSessionCache() override;
1177 private:
1178 SocketDataProviderArray<DeterministicSocketData> mock_data_;
1179 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
1181 // Store pointers to handed out sockets in case the test wants to get them.
1182 std::vector<DeterministicMockTCPClientSocket*> tcp_client_sockets_;
1183 std::vector<DeterministicMockUDPClientSocket*> udp_client_sockets_;
1184 std::vector<MockSSLClientSocket*> ssl_client_sockets_;
1186 DISALLOW_COPY_AND_ASSIGN(DeterministicMockClientSocketFactory);
1189 class MockSOCKSClientSocketPool : public SOCKSClientSocketPool {
1190 public:
1191 MockSOCKSClientSocketPool(int max_sockets,
1192 int max_sockets_per_group,
1193 TransportClientSocketPool* transport_pool);
1195 ~MockSOCKSClientSocketPool() override;
1197 // SOCKSClientSocketPool implementation.
1198 int RequestSocket(const std::string& group_name,
1199 const void* socket_params,
1200 RequestPriority priority,
1201 ClientSocketHandle* handle,
1202 const CompletionCallback& callback,
1203 const BoundNetLog& net_log) override;
1205 void CancelRequest(const std::string& group_name,
1206 ClientSocketHandle* handle) override;
1207 void ReleaseSocket(const std::string& group_name,
1208 scoped_ptr<StreamSocket> socket,
1209 int id) override;
1211 private:
1212 TransportClientSocketPool* const transport_pool_;
1214 DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool);
1217 // Convenience class to temporarily set the WebSocketEndpointLockManager unlock
1218 // delay to zero for testing purposes. Automatically restores the original value
1219 // when destroyed.
1220 class ScopedWebSocketEndpointZeroUnlockDelay {
1221 public:
1222 ScopedWebSocketEndpointZeroUnlockDelay();
1223 ~ScopedWebSocketEndpointZeroUnlockDelay();
1225 private:
1226 base::TimeDelta old_delay_;
1229 // Constants for a successful SOCKS v5 handshake.
1230 extern const char kSOCKS5GreetRequest[];
1231 extern const int kSOCKS5GreetRequestLength;
1233 extern const char kSOCKS5GreetResponse[];
1234 extern const int kSOCKS5GreetResponseLength;
1236 extern const char kSOCKS5OkRequest[];
1237 extern const int kSOCKS5OkRequestLength;
1239 extern const char kSOCKS5OkResponse[];
1240 extern const int kSOCKS5OkResponseLength;
1242 // Helper function to get the total data size of the MockReads in |reads|.
1243 int64_t CountReadBytes(const MockRead reads[], size_t reads_size);
1245 // Helper function to get the total data size of the MockWrites in |writes|.
1246 int64_t CountWriteBytes(const MockWrite writes[], size_t writes_size);
1248 } // namespace net
1250 #endif // NET_SOCKET_SOCKET_TEST_UTIL_H_