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