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"
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"
23 using testing::Invoke;
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 {
34 MockSSLClientSocket() {}
35 MOCK_METHOD0(Disconnect, void());
37 int(net::IOBuffer* buf,
39 const net::CompletionCallback& callback));
41 int(net::IOBuffer* buf,
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&,
62 MOCK_METHOD1(GetTLSUniqueChannelBinding, int(std::string*));
63 MOCK_CONST_METHOD0(InSessionCache, bool());
64 MOCK_METHOD1(SetHandshakeCompletionCallback, void(const base::Closure&));
65 MOCK_METHOD1(GetSSLCertRequestInfo, void(net::SSLCertRequestInfo*));
66 MOCK_METHOD1(GetNextProto,
67 net::SSLClientSocket::NextProtoStatus(std::string*));
68 MOCK_CONST_METHOD0(GetUnverifiedServerCertificateChain,
69 scoped_refptr<net::X509Certificate>());
70 MOCK_CONST_METHOD0(GetChannelIDService, net::ChannelIDService*());
71 virtual bool IsConnected() const OVERRIDE { return true; }
74 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket);
77 class MockTCPSocket : public net::TCPClientSocket {
79 explicit MockTCPSocket(const net::AddressList& address_list)
80 : net::TCPClientSocket(address_list, NULL, net::NetLog::Source()) {}
83 int(net::IOBuffer* buf,
85 const net::CompletionCallback& callback));
87 int(net::IOBuffer* buf,
89 const net::CompletionCallback& callback));
90 MOCK_METHOD2(SetKeepAlive, bool(bool enable, int delay));
91 MOCK_METHOD1(SetNoDelay, bool(bool no_delay));
93 virtual bool IsConnected() const OVERRIDE { return true; }
96 DISALLOW_COPY_AND_ASSIGN(MockTCPSocket);
99 class CompleteHandler {
102 MOCK_METHOD1(OnComplete, void(int result_code));
103 MOCK_METHOD2(OnReadComplete,
104 void(int result_code, scoped_refptr<net::IOBuffer> io_buffer));
105 MOCK_METHOD2(OnAccept, void(int, net::TCPClientSocket*));
108 DISALLOW_COPY_AND_ASSIGN(CompleteHandler);
111 class TLSSocketTest : public ::testing::Test {
115 virtual void SetUp() {
116 net::AddressList address_list;
117 // |ssl_socket_| is owned by |socket_|. TLSSocketTest keeps a pointer to
118 // it to expect invocations from TLSSocket to |ssl_socket_|.
119 scoped_ptr<MockSSLClientSocket> ssl_sock(new MockSSLClientSocket);
120 ssl_socket_ = ssl_sock.get();
121 socket_.reset(new TLSSocket(ssl_sock.PassAs<net::StreamSocket>(),
122 "test_extension_id"));
123 EXPECT_CALL(*ssl_socket_, Disconnect()).Times(1);
126 virtual void TearDown() {
132 MockSSLClientSocket* ssl_socket_;
133 scoped_ptr<TLSSocket> socket_;
136 // Verify that a Read() on TLSSocket will pass through into a Read() on
137 // |ssl_socket_| and invoke its completion callback.
138 TEST_F(TLSSocketTest, TestTLSSocketRead) {
139 CompleteHandler handler;
141 EXPECT_CALL(*ssl_socket_, Read(_, _, _)).Times(1);
142 EXPECT_CALL(handler, OnReadComplete(_, _)).Times(1);
144 const int count = 512;
147 base::Bind(&CompleteHandler::OnReadComplete, base::Unretained(&handler)));
150 // Verify that a Write() on a TLSSocket will pass through to Write()
151 // invocations on |ssl_socket_|, handling partial writes correctly, and calls
152 // the completion callback correctly.
153 TEST_F(TLSSocketTest, TestTLSSocketWrite) {
154 CompleteHandler handler;
155 net::CompletionCallback callback;
157 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(2).WillRepeatedly(
158 DoAll(SaveArg<2>(&callback), Return(128)));
159 EXPECT_CALL(handler, OnComplete(_)).Times(1);
161 scoped_refptr<net::IOBufferWithSize> io_buffer(
162 new net::IOBufferWithSize(256));
166 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
169 // Simulate a blocked Write, and verify that, when simulating the Write going
170 // through, the callback gets invoked.
171 TEST_F(TLSSocketTest, TestTLSSocketBlockedWrite) {
172 CompleteHandler handler;
173 net::CompletionCallback callback;
175 // Return ERR_IO_PENDING to say the Write()'s blocked. Save the |callback|
177 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(2).WillRepeatedly(
178 DoAll(SaveArg<2>(&callback), Return(net::ERR_IO_PENDING)));
180 scoped_refptr<net::IOBufferWithSize> io_buffer(new net::IOBufferWithSize(42));
184 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
186 // After the simulated asynchronous writes come back (via calls to
187 // callback.Run()), hander's OnComplete() should get invoked with the total
189 EXPECT_CALL(handler, OnComplete(42)).Times(1);
194 // Simulate multiple blocked Write()s.
195 TEST_F(TLSSocketTest, TestTLSSocketBlockedWriteReentry) {
196 const int kNumIOs = 5;
197 CompleteHandler handlers[kNumIOs];
198 net::CompletionCallback callback;
199 scoped_refptr<net::IOBufferWithSize> io_buffers[kNumIOs];
201 // The implementation of TLSSocket::Write() is inherited from
202 // Socket::Write(), which implements an internal write queue that wraps
203 // TLSSocket::WriteImpl(). Each call from TLSSocket::WriteImpl() will invoke
204 // |ssl_socket_|'s Write() (mocked here). Save the |callback| (assume they
205 // will all be equivalent), and return ERR_IO_PENDING, to indicate a blocked
206 // request. The mocked SSLClientSocket::Write() will get one request per
207 // TLSSocket::Write() request invoked on |socket_| below.
208 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(kNumIOs).WillRepeatedly(
209 DoAll(SaveArg<2>(&callback), Return(net::ERR_IO_PENDING)));
211 // Send out |kNuMIOs| requests, each with a different size.
212 for (int i = 0; i < kNumIOs; i++) {
213 io_buffers[i] = new net::IOBufferWithSize(128 + i * 50);
214 socket_->Write(io_buffers[i].get(),
215 io_buffers[i]->size(),
216 base::Bind(&CompleteHandler::OnComplete,
217 base::Unretained(&handlers[i])));
219 // Set up expectations on all |kNumIOs| handlers.
220 EXPECT_CALL(handlers[i], OnComplete(io_buffers[i]->size())).Times(1);
223 // Finish each pending I/O. This should satisfy the expectations on the
225 for (int i = 0; i < kNumIOs; i++) {
226 callback.Run(128 + i * 50);
230 typedef std::pair<net::CompletionCallback, int> PendingCallback;
232 class CallbackList : public std::deque<PendingCallback> {
234 void append(const net::CompletionCallback& cb, int arg) {
235 push_back(std::make_pair(cb, arg));
239 // Simulate Write()s above and below a SSLClientSocket size limit.
240 TEST_F(TLSSocketTest, TestTLSSocketLargeWrites) {
241 const int kSizeIncrement = 4096;
242 const int kNumIncrements = 10;
243 const int kFragmentIncrement = 4;
244 const int kSizeLimit = kSizeIncrement * kFragmentIncrement;
245 net::CompletionCallback callback;
246 CompleteHandler handler;
247 scoped_refptr<net::IOBufferWithSize> io_buffers[kNumIncrements];
248 CallbackList pending_callbacks;
249 size_t total_bytes_requested = 0;
250 size_t total_bytes_written = 0;
252 // Some implementations of SSLClientSocket may have write-size limits (e.g,
253 // max 1 TLS record, which is 16k). This test mocks a size limit at
254 // |kSizeIncrement| and calls Write() above and below that limit. It
255 // simulates SSLClientSocket::Write() behavior in only writing up to the size
256 // limit, requiring additional calls for the remaining data to be sent.
257 // Socket::Write() (and supporting methods) execute the additional calls as
258 // needed. This test verifies that this inherited implementation does
259 // properly issue additional calls, and that the total amount returned from
260 // all mocked SSLClientSocket::Write() calls is the same as originally
263 // |ssl_socket_|'s Write() will write at most |kSizeLimit| bytes. The
264 // inherited Socket::Write() will repeatedly call |ssl_socket_|'s Write()
265 // until the entire original request is sent. Socket::Write() will queue any
266 // additional write requests until the current request is complete. A
267 // request is complete when the callback passed to Socket::WriteImpl() is
268 // invoked with an argument equal to the original number of bytes requested
269 // from Socket::Write(). If the callback is invoked with a smaller number,
270 // Socket::WriteImpl() will get repeatedly invoked until the sum of the
271 // callbacks' arguments is equal to the original requested amount.
272 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).WillRepeatedly(
273 DoAll(WithArgs<2, 1>(Invoke(&pending_callbacks, &CallbackList::append)),
274 Return(net::ERR_IO_PENDING)));
276 // Observe what comes back from Socket::Write() here.
277 EXPECT_CALL(handler, OnComplete(Gt(0))).Times(kNumIncrements);
279 // Send out |kNumIncrements| requests, each with a different size. The
280 // last request is the same size as the first, and the ones in the middle
281 // are monotonically increasing from the first.
282 for (int i = 0; i < kNumIncrements; i++) {
283 const bool last = i == (kNumIncrements - 1);
284 io_buffers[i] = new net::IOBufferWithSize(last ? kSizeIncrement
285 : kSizeIncrement * (i + 1));
286 total_bytes_requested += io_buffers[i]->size();
288 // Invoke Socket::Write(). This will invoke |ssl_socket_|'s Write(), which
289 // this test mocks out. That mocked Write() is in an asynchronous waiting
290 // state until the passed callback (saved in the EXPECT_CALL for
291 // |ssl_socket_|'s Write()) is invoked.
294 io_buffers[i]->size(),
295 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
298 // Invoke callbacks for pending I/Os. These can synchronously invoke more of
299 // |ssl_socket_|'s Write() as needed. The callback checks how much is left
300 // in the request, and then starts issuing any queued Socket::Write()
302 while (!pending_callbacks.empty()) {
303 PendingCallback cb = pending_callbacks.front();
304 pending_callbacks.pop_front();
306 int amount_written_invocation = std::min(kSizeLimit, cb.second);
307 total_bytes_written += amount_written_invocation;
308 cb.first.Run(amount_written_invocation);
311 ASSERT_EQ(total_bytes_requested, total_bytes_written)
312 << "There should be exactly as many bytes written as originally "
313 << "requested to Write().";
316 } // namespace extensions