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_CONST_METHOD1(GetConnectionAttempts
, void(net::ConnectionAttempts
*));
57 MOCK_METHOD0(ClearConnectionAttempts
, void());
58 MOCK_METHOD1(AddConnectionAttempts
, void(const net::ConnectionAttempts
&));
59 MOCK_METHOD5(ExportKeyingMaterial
,
60 int(const StringPiece
&,
65 MOCK_METHOD1(GetTLSUniqueChannelBinding
, int(std::string
*));
66 MOCK_METHOD1(GetSSLCertRequestInfo
, void(net::SSLCertRequestInfo
*));
67 MOCK_CONST_METHOD1(GetNextProto
,
68 net::SSLClientSocket::NextProtoStatus(std::string
*));
69 MOCK_CONST_METHOD0(GetUnverifiedServerCertificateChain
,
70 scoped_refptr
<net::X509Certificate
>());
71 MOCK_CONST_METHOD0(GetChannelIDService
, net::ChannelIDService
*());
72 MOCK_CONST_METHOD0(GetSSLFailureState
, net::SSLFailureState());
73 bool IsConnected() const override
{ return true; }
76 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket
);
79 class MockTCPSocket
: public net::TCPClientSocket
{
81 explicit MockTCPSocket(const net::AddressList
& address_list
)
82 : net::TCPClientSocket(address_list
, NULL
, net::NetLog::Source()) {}
85 int(net::IOBuffer
* buf
,
87 const net::CompletionCallback
& callback
));
89 int(net::IOBuffer
* buf
,
91 const net::CompletionCallback
& callback
));
92 MOCK_METHOD2(SetKeepAlive
, bool(bool enable
, int delay
));
93 MOCK_METHOD1(SetNoDelay
, bool(bool no_delay
));
95 bool IsConnected() const override
{ return true; }
98 DISALLOW_COPY_AND_ASSIGN(MockTCPSocket
);
101 class CompleteHandler
{
104 MOCK_METHOD1(OnComplete
, void(int result_code
));
105 MOCK_METHOD2(OnReadComplete
,
106 void(int result_code
, scoped_refptr
<net::IOBuffer
> io_buffer
));
107 MOCK_METHOD2(OnAccept
, void(int, net::TCPClientSocket
*));
110 DISALLOW_COPY_AND_ASSIGN(CompleteHandler
);
113 class TLSSocketTest
: public ::testing::Test
{
117 void SetUp() override
{
118 net::AddressList address_list
;
119 // |ssl_socket_| is owned by |socket_|. TLSSocketTest keeps a pointer to
120 // it to expect invocations from TLSSocket to |ssl_socket_|.
121 scoped_ptr
<MockSSLClientSocket
> ssl_sock(new MockSSLClientSocket
);
122 ssl_socket_
= ssl_sock
.get();
123 socket_
.reset(new TLSSocket(ssl_sock
.Pass(), "test_extension_id"));
124 EXPECT_CALL(*ssl_socket_
, Disconnect()).Times(1);
127 void TearDown() override
{
133 MockSSLClientSocket
* ssl_socket_
;
134 scoped_ptr
<TLSSocket
> socket_
;
137 // Verify that a Read() on TLSSocket will pass through into a Read() on
138 // |ssl_socket_| and invoke its completion callback.
139 TEST_F(TLSSocketTest
, TestTLSSocketRead
) {
140 CompleteHandler handler
;
142 EXPECT_CALL(*ssl_socket_
, Read(_
, _
, _
)).Times(1);
143 EXPECT_CALL(handler
, OnReadComplete(_
, _
)).Times(1);
145 const int count
= 512;
148 base::Bind(&CompleteHandler::OnReadComplete
, base::Unretained(&handler
)));
151 // Verify that a Write() on a TLSSocket will pass through to Write()
152 // invocations on |ssl_socket_|, handling partial writes correctly, and calls
153 // the completion callback correctly.
154 TEST_F(TLSSocketTest
, TestTLSSocketWrite
) {
155 CompleteHandler handler
;
156 net::CompletionCallback callback
;
158 EXPECT_CALL(*ssl_socket_
, Write(_
, _
, _
)).Times(2).WillRepeatedly(
159 DoAll(SaveArg
<2>(&callback
), Return(128)));
160 EXPECT_CALL(handler
, OnComplete(_
)).Times(1);
162 scoped_refptr
<net::IOBufferWithSize
> io_buffer(
163 new net::IOBufferWithSize(256));
167 base::Bind(&CompleteHandler::OnComplete
, base::Unretained(&handler
)));
170 // Simulate a blocked Write, and verify that, when simulating the Write going
171 // through, the callback gets invoked.
172 TEST_F(TLSSocketTest
, TestTLSSocketBlockedWrite
) {
173 CompleteHandler handler
;
174 net::CompletionCallback callback
;
176 // Return ERR_IO_PENDING to say the Write()'s blocked. Save the |callback|
178 EXPECT_CALL(*ssl_socket_
, Write(_
, _
, _
)).Times(2).WillRepeatedly(
179 DoAll(SaveArg
<2>(&callback
), Return(net::ERR_IO_PENDING
)));
181 scoped_refptr
<net::IOBufferWithSize
> io_buffer(new net::IOBufferWithSize(42));
185 base::Bind(&CompleteHandler::OnComplete
, base::Unretained(&handler
)));
187 // After the simulated asynchronous writes come back (via calls to
188 // callback.Run()), hander's OnComplete() should get invoked with the total
190 EXPECT_CALL(handler
, OnComplete(42)).Times(1);
195 // Simulate multiple blocked Write()s.
196 TEST_F(TLSSocketTest
, TestTLSSocketBlockedWriteReentry
) {
197 const int kNumIOs
= 5;
198 CompleteHandler handlers
[kNumIOs
];
199 net::CompletionCallback callback
;
200 scoped_refptr
<net::IOBufferWithSize
> io_buffers
[kNumIOs
];
202 // The implementation of TLSSocket::Write() is inherited from
203 // Socket::Write(), which implements an internal write queue that wraps
204 // TLSSocket::WriteImpl(). Each call from TLSSocket::WriteImpl() will invoke
205 // |ssl_socket_|'s Write() (mocked here). Save the |callback| (assume they
206 // will all be equivalent), and return ERR_IO_PENDING, to indicate a blocked
207 // request. The mocked SSLClientSocket::Write() will get one request per
208 // TLSSocket::Write() request invoked on |socket_| below.
209 EXPECT_CALL(*ssl_socket_
, Write(_
, _
, _
)).Times(kNumIOs
).WillRepeatedly(
210 DoAll(SaveArg
<2>(&callback
), Return(net::ERR_IO_PENDING
)));
212 // Send out |kNuMIOs| requests, each with a different size.
213 for (int i
= 0; i
< kNumIOs
; i
++) {
214 io_buffers
[i
] = new net::IOBufferWithSize(128 + i
* 50);
215 socket_
->Write(io_buffers
[i
].get(),
216 io_buffers
[i
]->size(),
217 base::Bind(&CompleteHandler::OnComplete
,
218 base::Unretained(&handlers
[i
])));
220 // Set up expectations on all |kNumIOs| handlers.
221 EXPECT_CALL(handlers
[i
], OnComplete(io_buffers
[i
]->size())).Times(1);
224 // Finish each pending I/O. This should satisfy the expectations on the
226 for (int i
= 0; i
< kNumIOs
; i
++) {
227 callback
.Run(128 + i
* 50);
231 typedef std::pair
<net::CompletionCallback
, int> PendingCallback
;
233 class CallbackList
: public std::deque
<PendingCallback
> {
235 void append(const net::CompletionCallback
& cb
, int arg
) {
236 push_back(std::make_pair(cb
, arg
));
240 // Simulate Write()s above and below a SSLClientSocket size limit.
241 TEST_F(TLSSocketTest
, TestTLSSocketLargeWrites
) {
242 const int kSizeIncrement
= 4096;
243 const int kNumIncrements
= 10;
244 const int kFragmentIncrement
= 4;
245 const int kSizeLimit
= kSizeIncrement
* kFragmentIncrement
;
246 net::CompletionCallback callback
;
247 CompleteHandler handler
;
248 scoped_refptr
<net::IOBufferWithSize
> io_buffers
[kNumIncrements
];
249 CallbackList pending_callbacks
;
250 size_t total_bytes_requested
= 0;
251 size_t total_bytes_written
= 0;
253 // Some implementations of SSLClientSocket may have write-size limits (e.g,
254 // max 1 TLS record, which is 16k). This test mocks a size limit at
255 // |kSizeIncrement| and calls Write() above and below that limit. It
256 // simulates SSLClientSocket::Write() behavior in only writing up to the size
257 // limit, requiring additional calls for the remaining data to be sent.
258 // Socket::Write() (and supporting methods) execute the additional calls as
259 // needed. This test verifies that this inherited implementation does
260 // properly issue additional calls, and that the total amount returned from
261 // all mocked SSLClientSocket::Write() calls is the same as originally
264 // |ssl_socket_|'s Write() will write at most |kSizeLimit| bytes. The
265 // inherited Socket::Write() will repeatedly call |ssl_socket_|'s Write()
266 // until the entire original request is sent. Socket::Write() will queue any
267 // additional write requests until the current request is complete. A
268 // request is complete when the callback passed to Socket::WriteImpl() is
269 // invoked with an argument equal to the original number of bytes requested
270 // from Socket::Write(). If the callback is invoked with a smaller number,
271 // Socket::WriteImpl() will get repeatedly invoked until the sum of the
272 // callbacks' arguments is equal to the original requested amount.
273 EXPECT_CALL(*ssl_socket_
, Write(_
, _
, _
)).WillRepeatedly(
274 DoAll(WithArgs
<2, 1>(Invoke(&pending_callbacks
, &CallbackList::append
)),
275 Return(net::ERR_IO_PENDING
)));
277 // Observe what comes back from Socket::Write() here.
278 EXPECT_CALL(handler
, OnComplete(Gt(0))).Times(kNumIncrements
);
280 // Send out |kNumIncrements| requests, each with a different size. The
281 // last request is the same size as the first, and the ones in the middle
282 // are monotonically increasing from the first.
283 for (int i
= 0; i
< kNumIncrements
; i
++) {
284 const bool last
= i
== (kNumIncrements
- 1);
285 io_buffers
[i
] = new net::IOBufferWithSize(last
? kSizeIncrement
286 : kSizeIncrement
* (i
+ 1));
287 total_bytes_requested
+= io_buffers
[i
]->size();
289 // Invoke Socket::Write(). This will invoke |ssl_socket_|'s Write(), which
290 // this test mocks out. That mocked Write() is in an asynchronous waiting
291 // state until the passed callback (saved in the EXPECT_CALL for
292 // |ssl_socket_|'s Write()) is invoked.
295 io_buffers
[i
]->size(),
296 base::Bind(&CompleteHandler::OnComplete
, base::Unretained(&handler
)));
299 // Invoke callbacks for pending I/Os. These can synchronously invoke more of
300 // |ssl_socket_|'s Write() as needed. The callback checks how much is left
301 // in the request, and then starts issuing any queued Socket::Write()
303 while (!pending_callbacks
.empty()) {
304 PendingCallback cb
= pending_callbacks
.front();
305 pending_callbacks
.pop_front();
307 int amount_written_invocation
= std::min(kSizeLimit
, cb
.second
);
308 total_bytes_written
+= amount_written_invocation
;
309 cb
.first
.Run(amount_written_invocation
);
312 ASSERT_EQ(total_bytes_requested
, total_bytes_written
)
313 << "There should be exactly as many bytes written as originally "
314 << "requested to Write().";
317 } // namespace extensions