Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / chrome / browser / extensions / api / socket / tls_socket_unittest.cc
bloba0c9cdeef5c801a7f78b261c1222b5b08e3eeab2
1 // Copyright 2014 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 #include "extensions/browser/api/socket/tls_socket.h"
7 #include <deque>
8 #include <utility>
10 #include "base/memory/scoped_ptr.h"
11 #include "base/strings/string_piece.h"
12 #include "net/base/address_list.h"
13 #include "net/base/completion_callback.h"
14 #include "net/base/io_buffer.h"
15 #include "net/base/net_errors.h"
16 #include "net/base/rand_callback.h"
17 #include "net/socket/ssl_client_socket.h"
18 #include "net/socket/tcp_client_socket.h"
19 #include "testing/gmock/include/gmock/gmock.h"
21 using testing::_;
22 using testing::DoAll;
23 using testing::Invoke;
24 using testing::Gt;
25 using testing::Return;
26 using testing::SaveArg;
27 using testing::WithArgs;
28 using base::StringPiece;
30 namespace extensions {
32 class MockSSLClientSocket : public net::SSLClientSocket {
33 public:
34 MockSSLClientSocket() {}
35 MOCK_METHOD0(Disconnect, void());
36 MOCK_METHOD3(Read,
37 int(net::IOBuffer* buf,
38 int buf_len,
39 const net::CompletionCallback& callback));
40 MOCK_METHOD3(Write,
41 int(net::IOBuffer* buf,
42 int buf_len,
43 const net::CompletionCallback& callback));
44 MOCK_METHOD1(SetReceiveBufferSize, int(int32));
45 MOCK_METHOD1(SetSendBufferSize, int(int32));
46 MOCK_METHOD1(Connect, int(const CompletionCallback&));
47 MOCK_CONST_METHOD0(IsConnectedAndIdle, bool());
48 MOCK_CONST_METHOD1(GetPeerAddress, int(net::IPEndPoint*));
49 MOCK_CONST_METHOD1(GetLocalAddress, int(net::IPEndPoint*));
50 MOCK_CONST_METHOD0(NetLog, const net::BoundNetLog&());
51 MOCK_METHOD0(SetSubresourceSpeculation, void());
52 MOCK_METHOD0(SetOmniboxSpeculation, void());
53 MOCK_CONST_METHOD0(WasEverUsed, bool());
54 MOCK_CONST_METHOD0(UsingTCPFastOpen, bool());
55 MOCK_METHOD1(GetSSLInfo, bool(net::SSLInfo*));
56 MOCK_METHOD5(ExportKeyingMaterial,
57 int(const StringPiece&,
58 bool,
59 const StringPiece&,
60 unsigned char*,
61 unsigned int));
62 MOCK_METHOD1(GetTLSUniqueChannelBinding, int(std::string*));
63 MOCK_METHOD1(GetSSLCertRequestInfo, void(net::SSLCertRequestInfo*));
64 MOCK_METHOD1(GetNextProto,
65 net::SSLClientSocket::NextProtoStatus(std::string*));
66 MOCK_CONST_METHOD0(GetUnverifiedServerCertificateChain,
67 scoped_refptr<net::X509Certificate>());
68 MOCK_CONST_METHOD0(GetChannelIDService, net::ChannelIDService*());
69 virtual bool IsConnected() const override { return true; }
71 private:
72 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket);
75 class MockTCPSocket : public net::TCPClientSocket {
76 public:
77 explicit MockTCPSocket(const net::AddressList& address_list)
78 : net::TCPClientSocket(address_list, NULL, net::NetLog::Source()) {}
80 MOCK_METHOD3(Read,
81 int(net::IOBuffer* buf,
82 int buf_len,
83 const net::CompletionCallback& callback));
84 MOCK_METHOD3(Write,
85 int(net::IOBuffer* buf,
86 int buf_len,
87 const net::CompletionCallback& callback));
88 MOCK_METHOD2(SetKeepAlive, bool(bool enable, int delay));
89 MOCK_METHOD1(SetNoDelay, bool(bool no_delay));
91 virtual bool IsConnected() const override { return true; }
93 private:
94 DISALLOW_COPY_AND_ASSIGN(MockTCPSocket);
97 class CompleteHandler {
98 public:
99 CompleteHandler() {}
100 MOCK_METHOD1(OnComplete, void(int result_code));
101 MOCK_METHOD2(OnReadComplete,
102 void(int result_code, scoped_refptr<net::IOBuffer> io_buffer));
103 MOCK_METHOD2(OnAccept, void(int, net::TCPClientSocket*));
105 private:
106 DISALLOW_COPY_AND_ASSIGN(CompleteHandler);
109 class TLSSocketTest : public ::testing::Test {
110 public:
111 TLSSocketTest() {}
113 void SetUp() override {
114 net::AddressList address_list;
115 // |ssl_socket_| is owned by |socket_|. TLSSocketTest keeps a pointer to
116 // it to expect invocations from TLSSocket to |ssl_socket_|.
117 scoped_ptr<MockSSLClientSocket> ssl_sock(new MockSSLClientSocket);
118 ssl_socket_ = ssl_sock.get();
119 socket_.reset(new TLSSocket(ssl_sock.Pass(), "test_extension_id"));
120 EXPECT_CALL(*ssl_socket_, Disconnect()).Times(1);
123 void TearDown() override {
124 ssl_socket_ = NULL;
125 socket_.reset();
128 protected:
129 MockSSLClientSocket* ssl_socket_;
130 scoped_ptr<TLSSocket> socket_;
133 // Verify that a Read() on TLSSocket will pass through into a Read() on
134 // |ssl_socket_| and invoke its completion callback.
135 TEST_F(TLSSocketTest, TestTLSSocketRead) {
136 CompleteHandler handler;
138 EXPECT_CALL(*ssl_socket_, Read(_, _, _)).Times(1);
139 EXPECT_CALL(handler, OnReadComplete(_, _)).Times(1);
141 const int count = 512;
142 socket_->Read(
143 count,
144 base::Bind(&CompleteHandler::OnReadComplete, base::Unretained(&handler)));
147 // Verify that a Write() on a TLSSocket will pass through to Write()
148 // invocations on |ssl_socket_|, handling partial writes correctly, and calls
149 // the completion callback correctly.
150 TEST_F(TLSSocketTest, TestTLSSocketWrite) {
151 CompleteHandler handler;
152 net::CompletionCallback callback;
154 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(2).WillRepeatedly(
155 DoAll(SaveArg<2>(&callback), Return(128)));
156 EXPECT_CALL(handler, OnComplete(_)).Times(1);
158 scoped_refptr<net::IOBufferWithSize> io_buffer(
159 new net::IOBufferWithSize(256));
160 socket_->Write(
161 io_buffer.get(),
162 io_buffer->size(),
163 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
166 // Simulate a blocked Write, and verify that, when simulating the Write going
167 // through, the callback gets invoked.
168 TEST_F(TLSSocketTest, TestTLSSocketBlockedWrite) {
169 CompleteHandler handler;
170 net::CompletionCallback callback;
172 // Return ERR_IO_PENDING to say the Write()'s blocked. Save the |callback|
173 // Write()'s passed.
174 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(2).WillRepeatedly(
175 DoAll(SaveArg<2>(&callback), Return(net::ERR_IO_PENDING)));
177 scoped_refptr<net::IOBufferWithSize> io_buffer(new net::IOBufferWithSize(42));
178 socket_->Write(
179 io_buffer.get(),
180 io_buffer->size(),
181 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
183 // After the simulated asynchronous writes come back (via calls to
184 // callback.Run()), hander's OnComplete() should get invoked with the total
185 // amount written.
186 EXPECT_CALL(handler, OnComplete(42)).Times(1);
187 callback.Run(40);
188 callback.Run(2);
191 // Simulate multiple blocked Write()s.
192 TEST_F(TLSSocketTest, TestTLSSocketBlockedWriteReentry) {
193 const int kNumIOs = 5;
194 CompleteHandler handlers[kNumIOs];
195 net::CompletionCallback callback;
196 scoped_refptr<net::IOBufferWithSize> io_buffers[kNumIOs];
198 // The implementation of TLSSocket::Write() is inherited from
199 // Socket::Write(), which implements an internal write queue that wraps
200 // TLSSocket::WriteImpl(). Each call from TLSSocket::WriteImpl() will invoke
201 // |ssl_socket_|'s Write() (mocked here). Save the |callback| (assume they
202 // will all be equivalent), and return ERR_IO_PENDING, to indicate a blocked
203 // request. The mocked SSLClientSocket::Write() will get one request per
204 // TLSSocket::Write() request invoked on |socket_| below.
205 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(kNumIOs).WillRepeatedly(
206 DoAll(SaveArg<2>(&callback), Return(net::ERR_IO_PENDING)));
208 // Send out |kNuMIOs| requests, each with a different size.
209 for (int i = 0; i < kNumIOs; i++) {
210 io_buffers[i] = new net::IOBufferWithSize(128 + i * 50);
211 socket_->Write(io_buffers[i].get(),
212 io_buffers[i]->size(),
213 base::Bind(&CompleteHandler::OnComplete,
214 base::Unretained(&handlers[i])));
216 // Set up expectations on all |kNumIOs| handlers.
217 EXPECT_CALL(handlers[i], OnComplete(io_buffers[i]->size())).Times(1);
220 // Finish each pending I/O. This should satisfy the expectations on the
221 // handlers.
222 for (int i = 0; i < kNumIOs; i++) {
223 callback.Run(128 + i * 50);
227 typedef std::pair<net::CompletionCallback, int> PendingCallback;
229 class CallbackList : public std::deque<PendingCallback> {
230 public:
231 void append(const net::CompletionCallback& cb, int arg) {
232 push_back(std::make_pair(cb, arg));
236 // Simulate Write()s above and below a SSLClientSocket size limit.
237 TEST_F(TLSSocketTest, TestTLSSocketLargeWrites) {
238 const int kSizeIncrement = 4096;
239 const int kNumIncrements = 10;
240 const int kFragmentIncrement = 4;
241 const int kSizeLimit = kSizeIncrement * kFragmentIncrement;
242 net::CompletionCallback callback;
243 CompleteHandler handler;
244 scoped_refptr<net::IOBufferWithSize> io_buffers[kNumIncrements];
245 CallbackList pending_callbacks;
246 size_t total_bytes_requested = 0;
247 size_t total_bytes_written = 0;
249 // Some implementations of SSLClientSocket may have write-size limits (e.g,
250 // max 1 TLS record, which is 16k). This test mocks a size limit at
251 // |kSizeIncrement| and calls Write() above and below that limit. It
252 // simulates SSLClientSocket::Write() behavior in only writing up to the size
253 // limit, requiring additional calls for the remaining data to be sent.
254 // Socket::Write() (and supporting methods) execute the additional calls as
255 // needed. This test verifies that this inherited implementation does
256 // properly issue additional calls, and that the total amount returned from
257 // all mocked SSLClientSocket::Write() calls is the same as originally
258 // requested.
260 // |ssl_socket_|'s Write() will write at most |kSizeLimit| bytes. The
261 // inherited Socket::Write() will repeatedly call |ssl_socket_|'s Write()
262 // until the entire original request is sent. Socket::Write() will queue any
263 // additional write requests until the current request is complete. A
264 // request is complete when the callback passed to Socket::WriteImpl() is
265 // invoked with an argument equal to the original number of bytes requested
266 // from Socket::Write(). If the callback is invoked with a smaller number,
267 // Socket::WriteImpl() will get repeatedly invoked until the sum of the
268 // callbacks' arguments is equal to the original requested amount.
269 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).WillRepeatedly(
270 DoAll(WithArgs<2, 1>(Invoke(&pending_callbacks, &CallbackList::append)),
271 Return(net::ERR_IO_PENDING)));
273 // Observe what comes back from Socket::Write() here.
274 EXPECT_CALL(handler, OnComplete(Gt(0))).Times(kNumIncrements);
276 // Send out |kNumIncrements| requests, each with a different size. The
277 // last request is the same size as the first, and the ones in the middle
278 // are monotonically increasing from the first.
279 for (int i = 0; i < kNumIncrements; i++) {
280 const bool last = i == (kNumIncrements - 1);
281 io_buffers[i] = new net::IOBufferWithSize(last ? kSizeIncrement
282 : kSizeIncrement * (i + 1));
283 total_bytes_requested += io_buffers[i]->size();
285 // Invoke Socket::Write(). This will invoke |ssl_socket_|'s Write(), which
286 // this test mocks out. That mocked Write() is in an asynchronous waiting
287 // state until the passed callback (saved in the EXPECT_CALL for
288 // |ssl_socket_|'s Write()) is invoked.
289 socket_->Write(
290 io_buffers[i].get(),
291 io_buffers[i]->size(),
292 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
295 // Invoke callbacks for pending I/Os. These can synchronously invoke more of
296 // |ssl_socket_|'s Write() as needed. The callback checks how much is left
297 // in the request, and then starts issuing any queued Socket::Write()
298 // invocations.
299 while (!pending_callbacks.empty()) {
300 PendingCallback cb = pending_callbacks.front();
301 pending_callbacks.pop_front();
303 int amount_written_invocation = std::min(kSizeLimit, cb.second);
304 total_bytes_written += amount_written_invocation;
305 cb.first.Run(amount_written_invocation);
308 ASSERT_EQ(total_bytes_requested, total_bytes_written)
309 << "There should be exactly as many bytes written as originally "
310 << "requested to Write().";
313 } // namespace extensions