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 #include "net/socket/ssl_client_socket.h"
7 #include "base/callback_helpers.h"
8 #include "base/memory/ref_counted.h"
9 #include "base/run_loop.h"
10 #include "base/time/time.h"
11 #include "net/base/address_list.h"
12 #include "net/base/io_buffer.h"
13 #include "net/base/net_errors.h"
14 #include "net/base/net_log.h"
15 #include "net/base/net_log_unittest.h"
16 #include "net/base/test_completion_callback.h"
17 #include "net/base/test_data_directory.h"
18 #include "net/cert/mock_cert_verifier.h"
19 #include "net/cert/test_root_certs.h"
20 #include "net/dns/host_resolver.h"
21 #include "net/http/transport_security_state.h"
22 #include "net/socket/client_socket_factory.h"
23 #include "net/socket/client_socket_handle.h"
24 #include "net/socket/socket_test_util.h"
25 #include "net/socket/tcp_client_socket.h"
26 #include "net/ssl/channel_id_service.h"
27 #include "net/ssl/default_channel_id_store.h"
28 #include "net/ssl/ssl_cert_request_info.h"
29 #include "net/ssl/ssl_config_service.h"
30 #include "net/test/cert_test_util.h"
31 #include "net/test/spawned_test_server/spawned_test_server.h"
32 #include "testing/gtest/include/gtest/gtest.h"
33 #include "testing/platform_test.h"
35 //-----------------------------------------------------------------------------
41 const SSLConfig kDefaultSSLConfig
;
43 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
44 // forwarding the Socket and StreamSocket interfaces to the underlying
46 // This is to provide a common base class for subclasses to override specific
47 // StreamSocket methods for testing, while still communicating with a 'real'
49 class WrappedStreamSocket
: public StreamSocket
{
51 explicit WrappedStreamSocket(scoped_ptr
<StreamSocket
> transport
)
52 : transport_(transport
.Pass()) {}
53 virtual ~WrappedStreamSocket() {}
55 // StreamSocket implementation:
56 virtual int Connect(const CompletionCallback
& callback
) OVERRIDE
{
57 return transport_
->Connect(callback
);
59 virtual void Disconnect() OVERRIDE
{ transport_
->Disconnect(); }
60 virtual bool IsConnected() const OVERRIDE
{
61 return transport_
->IsConnected();
63 virtual bool IsConnectedAndIdle() const OVERRIDE
{
64 return transport_
->IsConnectedAndIdle();
66 virtual int GetPeerAddress(IPEndPoint
* address
) const OVERRIDE
{
67 return transport_
->GetPeerAddress(address
);
69 virtual int GetLocalAddress(IPEndPoint
* address
) const OVERRIDE
{
70 return transport_
->GetLocalAddress(address
);
72 virtual const BoundNetLog
& NetLog() const OVERRIDE
{
73 return transport_
->NetLog();
75 virtual void SetSubresourceSpeculation() OVERRIDE
{
76 transport_
->SetSubresourceSpeculation();
78 virtual void SetOmniboxSpeculation() OVERRIDE
{
79 transport_
->SetOmniboxSpeculation();
81 virtual bool WasEverUsed() const OVERRIDE
{
82 return transport_
->WasEverUsed();
84 virtual bool UsingTCPFastOpen() const OVERRIDE
{
85 return transport_
->UsingTCPFastOpen();
87 virtual bool WasNpnNegotiated() const OVERRIDE
{
88 return transport_
->WasNpnNegotiated();
90 virtual NextProto
GetNegotiatedProtocol() const OVERRIDE
{
91 return transport_
->GetNegotiatedProtocol();
93 virtual bool GetSSLInfo(SSLInfo
* ssl_info
) OVERRIDE
{
94 return transport_
->GetSSLInfo(ssl_info
);
97 // Socket implementation:
98 virtual int Read(IOBuffer
* buf
,
100 const CompletionCallback
& callback
) OVERRIDE
{
101 return transport_
->Read(buf
, buf_len
, callback
);
103 virtual int Write(IOBuffer
* buf
,
105 const CompletionCallback
& callback
) OVERRIDE
{
106 return transport_
->Write(buf
, buf_len
, callback
);
108 virtual int SetReceiveBufferSize(int32 size
) OVERRIDE
{
109 return transport_
->SetReceiveBufferSize(size
);
111 virtual int SetSendBufferSize(int32 size
) OVERRIDE
{
112 return transport_
->SetSendBufferSize(size
);
116 scoped_ptr
<StreamSocket
> transport_
;
119 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
120 // will ensure a certain amount of data is internally buffered before
121 // satisfying a Read() request. It exists to mimic OS-level internal
122 // buffering, but in a way to guarantee that X number of bytes will be
123 // returned to callers of Read(), regardless of how quickly the OS receives
124 // them from the TestServer.
125 class ReadBufferingStreamSocket
: public WrappedStreamSocket
{
127 explicit ReadBufferingStreamSocket(scoped_ptr
<StreamSocket
> transport
);
128 virtual ~ReadBufferingStreamSocket() {}
130 // Socket implementation:
131 virtual int Read(IOBuffer
* buf
,
133 const CompletionCallback
& callback
) OVERRIDE
;
135 // Sets the internal buffer to |size|. This must not be greater than
136 // the largest value supplied to Read() - that is, it does not handle
137 // having "leftovers" at the end of Read().
138 // Each call to Read() will be prevented from completion until at least
139 // |size| data has been read.
140 // Set to 0 to turn off buffering, causing Read() to transparently
141 // read via the underlying transport.
142 void SetBufferSize(int size
);
151 int DoLoop(int result
);
153 int DoReadComplete(int result
);
154 void OnReadCompleted(int result
);
157 scoped_refptr
<GrowableIOBuffer
> read_buffer_
;
160 scoped_refptr
<IOBuffer
> user_read_buf_
;
161 CompletionCallback user_read_callback_
;
164 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
165 scoped_ptr
<StreamSocket
> transport
)
166 : WrappedStreamSocket(transport
.Pass()),
167 read_buffer_(new GrowableIOBuffer()),
170 void ReadBufferingStreamSocket::SetBufferSize(int size
) {
171 DCHECK(!user_read_buf_
.get());
173 read_buffer_
->SetCapacity(size
);
176 int ReadBufferingStreamSocket::Read(IOBuffer
* buf
,
178 const CompletionCallback
& callback
) {
179 if (buffer_size_
== 0)
180 return transport_
->Read(buf
, buf_len
, callback
);
182 if (buf_len
< buffer_size_
)
183 return ERR_UNEXPECTED
;
186 user_read_buf_
= buf
;
187 int result
= DoLoop(OK
);
188 if (result
== ERR_IO_PENDING
)
189 user_read_callback_
= callback
;
191 user_read_buf_
= NULL
;
195 int ReadBufferingStreamSocket::DoLoop(int result
) {
198 State current_state
= state_
;
200 switch (current_state
) {
204 case STATE_READ_COMPLETE
:
205 rv
= DoReadComplete(rv
);
209 NOTREACHED() << "Unexpected state: " << current_state
;
213 } while (rv
!= ERR_IO_PENDING
&& state_
!= STATE_NONE
);
217 int ReadBufferingStreamSocket::DoRead() {
218 state_
= STATE_READ_COMPLETE
;
220 transport_
->Read(read_buffer_
.get(),
221 read_buffer_
->RemainingCapacity(),
222 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted
,
223 base::Unretained(this)));
227 int ReadBufferingStreamSocket::DoReadComplete(int result
) {
232 read_buffer_
->set_offset(read_buffer_
->offset() + result
);
233 if (read_buffer_
->RemainingCapacity() > 0) {
238 memcpy(user_read_buf_
->data(),
239 read_buffer_
->StartOfBuffer(),
240 read_buffer_
->capacity());
241 read_buffer_
->set_offset(0);
242 return read_buffer_
->capacity();
245 void ReadBufferingStreamSocket::OnReadCompleted(int result
) {
246 result
= DoLoop(result
);
247 if (result
== ERR_IO_PENDING
)
250 user_read_buf_
= NULL
;
251 base::ResetAndReturn(&user_read_callback_
).Run(result
);
254 // Simulates synchronously receiving an error during Read() or Write()
255 class SynchronousErrorStreamSocket
: public WrappedStreamSocket
{
257 explicit SynchronousErrorStreamSocket(scoped_ptr
<StreamSocket
> transport
);
258 virtual ~SynchronousErrorStreamSocket() {}
260 // Socket implementation:
261 virtual int Read(IOBuffer
* buf
,
263 const CompletionCallback
& callback
) OVERRIDE
;
264 virtual int Write(IOBuffer
* buf
,
266 const CompletionCallback
& callback
) OVERRIDE
;
268 // Sets the next Read() call and all future calls to return |error|.
269 // If there is already a pending asynchronous read, the configured error
270 // will not be returned until that asynchronous read has completed and Read()
272 void SetNextReadError(Error error
) {
274 have_read_error_
= true;
275 pending_read_error_
= error
;
278 // Sets the next Write() call and all future calls to return |error|.
279 // If there is already a pending asynchronous write, the configured error
280 // will not be returned until that asynchronous write has completed and
281 // Write() is called again.
282 void SetNextWriteError(Error error
) {
284 have_write_error_
= true;
285 pending_write_error_
= error
;
289 bool have_read_error_
;
290 int pending_read_error_
;
292 bool have_write_error_
;
293 int pending_write_error_
;
295 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket
);
298 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
299 scoped_ptr
<StreamSocket
> transport
)
300 : WrappedStreamSocket(transport
.Pass()),
301 have_read_error_(false),
302 pending_read_error_(OK
),
303 have_write_error_(false),
304 pending_write_error_(OK
) {}
306 int SynchronousErrorStreamSocket::Read(IOBuffer
* buf
,
308 const CompletionCallback
& callback
) {
309 if (have_read_error_
)
310 return pending_read_error_
;
311 return transport_
->Read(buf
, buf_len
, callback
);
314 int SynchronousErrorStreamSocket::Write(IOBuffer
* buf
,
316 const CompletionCallback
& callback
) {
317 if (have_write_error_
)
318 return pending_write_error_
;
319 return transport_
->Write(buf
, buf_len
, callback
);
322 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
323 // underlying transport needing to complete things asynchronously in a
324 // deterministic manner (e.g.: independent of the TestServer and the OS's
326 class FakeBlockingStreamSocket
: public WrappedStreamSocket
{
328 explicit FakeBlockingStreamSocket(scoped_ptr
<StreamSocket
> transport
);
329 virtual ~FakeBlockingStreamSocket() {}
331 // Socket implementation:
332 virtual int Read(IOBuffer
* buf
,
334 const CompletionCallback
& callback
) OVERRIDE
;
335 virtual int Write(IOBuffer
* buf
,
337 const CompletionCallback
& callback
) OVERRIDE
;
339 // Blocks read results on the socket. Reads will not complete until
340 // UnblockReadResult() has been called and a result is ready from the
341 // underlying transport. Note: if BlockReadResult() is called while there is a
342 // hanging asynchronous Read(), that Read is blocked.
343 void BlockReadResult();
344 void UnblockReadResult();
346 // Waits for the blocked Read() call to be complete at the underlying
348 void WaitForReadResult();
350 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
351 // underlying transport until UnblockWrite() has been called. Note: if there
352 // is a pending asynchronous write, it is NOT blocked. For purposes of
353 // blocking writes, data is considered to have reached the underlying
354 // transport as soon as Write() is called.
358 // Waits for the blocked Write() call to be scheduled.
362 // Handles completion from the underlying transport read.
363 void OnReadCompleted(int result
);
365 // True if read callbacks are blocked.
366 bool should_block_read_
;
368 // The user callback for the pending read call.
369 CompletionCallback pending_read_callback_
;
371 // The result for the blocked read callback, or ERR_IO_PENDING if not
373 int pending_read_result_
;
375 // WaitForReadResult() wait loop.
376 scoped_ptr
<base::RunLoop
> read_loop_
;
378 // True if write calls are blocked.
379 bool should_block_write_
;
381 // The buffer for the pending write, or NULL if not scheduled.
382 scoped_refptr
<IOBuffer
> pending_write_buf_
;
384 // The callback for the pending write call.
385 CompletionCallback pending_write_callback_
;
387 // The length for the pending write, or -1 if not scheduled.
388 int pending_write_len_
;
390 // WaitForWrite() wait loop.
391 scoped_ptr
<base::RunLoop
> write_loop_
;
394 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
395 scoped_ptr
<StreamSocket
> transport
)
396 : WrappedStreamSocket(transport
.Pass()),
397 should_block_read_(false),
398 pending_read_result_(ERR_IO_PENDING
),
399 should_block_write_(false),
400 pending_write_len_(-1) {}
402 int FakeBlockingStreamSocket::Read(IOBuffer
* buf
,
404 const CompletionCallback
& callback
) {
405 DCHECK(pending_read_callback_
.is_null());
406 DCHECK_EQ(ERR_IO_PENDING
, pending_read_result_
);
407 DCHECK(!callback
.is_null());
409 int rv
= transport_
->Read(buf
, len
, base::Bind(
410 &FakeBlockingStreamSocket::OnReadCompleted
, base::Unretained(this)));
411 if (rv
== ERR_IO_PENDING
) {
412 // Save the callback to be called later.
413 pending_read_callback_
= callback
;
414 } else if (should_block_read_
) {
415 // Save the callback and read result to be called later.
416 pending_read_callback_
= callback
;
423 int FakeBlockingStreamSocket::Write(IOBuffer
* buf
,
425 const CompletionCallback
& callback
) {
429 if (!should_block_write_
)
430 return transport_
->Write(buf
, len
, callback
);
432 // Schedule the write, but do nothing.
433 DCHECK(!pending_write_buf_
);
434 DCHECK_EQ(-1, pending_write_len_
);
435 DCHECK(pending_write_callback_
.is_null());
436 DCHECK(!callback
.is_null());
437 pending_write_buf_
= buf
;
438 pending_write_len_
= len
;
439 pending_write_callback_
= callback
;
441 // Stop the write loop, if any.
444 return ERR_IO_PENDING
;
447 void FakeBlockingStreamSocket::BlockReadResult() {
448 DCHECK(!should_block_read_
);
449 should_block_read_
= true;
452 void FakeBlockingStreamSocket::UnblockReadResult() {
453 DCHECK(should_block_read_
);
454 should_block_read_
= false;
456 // If the operation is still pending in the underlying transport, immediately
457 // return - OnReadCompleted() will handle invoking the callback once the
458 // transport has completed.
459 if (pending_read_result_
== ERR_IO_PENDING
)
461 int result
= pending_read_result_
;
462 pending_read_result_
= ERR_IO_PENDING
;
463 base::ResetAndReturn(&pending_read_callback_
).Run(result
);
466 void FakeBlockingStreamSocket::WaitForReadResult() {
467 DCHECK(should_block_read_
);
470 if (pending_read_result_
!= ERR_IO_PENDING
)
472 read_loop_
.reset(new base::RunLoop
);
475 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
478 void FakeBlockingStreamSocket::BlockWrite() {
479 DCHECK(!should_block_write_
);
480 should_block_write_
= true;
483 void FakeBlockingStreamSocket::UnblockWrite() {
484 DCHECK(should_block_write_
);
485 should_block_write_
= false;
487 // Do nothing if UnblockWrite() was called after BlockWrite(),
488 // without a Write() in between.
489 if (!pending_write_buf_
)
492 int rv
= transport_
->Write(pending_write_buf_
, pending_write_len_
,
493 pending_write_callback_
);
494 pending_write_buf_
= NULL
;
495 pending_write_len_
= -1;
496 if (rv
== ERR_IO_PENDING
) {
497 pending_write_callback_
.Reset();
499 base::ResetAndReturn(&pending_write_callback_
).Run(rv
);
503 void FakeBlockingStreamSocket::WaitForWrite() {
504 DCHECK(should_block_write_
);
505 DCHECK(!write_loop_
);
507 if (pending_write_buf_
)
509 write_loop_
.reset(new base::RunLoop
);
512 DCHECK(pending_write_buf_
);
515 void FakeBlockingStreamSocket::OnReadCompleted(int result
) {
516 DCHECK_EQ(ERR_IO_PENDING
, pending_read_result_
);
517 DCHECK(!pending_read_callback_
.is_null());
519 if (should_block_read_
) {
520 // Store the result so that the callback can be invoked once Unblock() is
522 pending_read_result_
= result
;
524 // Stop the WaitForReadResult() call if any.
528 // Either the Read() was never blocked or UnblockReadResult() was called
529 // before the Read() completed. Either way, run the callback.
530 base::ResetAndReturn(&pending_read_callback_
).Run(result
);
534 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
535 // reads and writes on the socket.
536 class CountingStreamSocket
: public WrappedStreamSocket
{
538 explicit CountingStreamSocket(scoped_ptr
<StreamSocket
> transport
)
539 : WrappedStreamSocket(transport
.Pass()),
542 virtual ~CountingStreamSocket() {}
544 // Socket implementation:
545 virtual int Read(IOBuffer
* buf
,
547 const CompletionCallback
& callback
) OVERRIDE
{
549 return transport_
->Read(buf
, buf_len
, callback
);
551 virtual int Write(IOBuffer
* buf
,
553 const CompletionCallback
& callback
) OVERRIDE
{
555 return transport_
->Write(buf
, buf_len
, callback
);
558 int read_count() const { return read_count_
; }
559 int write_count() const { return write_count_
; }
566 // CompletionCallback that will delete the associated StreamSocket when
567 // the callback is invoked.
568 class DeleteSocketCallback
: public TestCompletionCallbackBase
{
570 explicit DeleteSocketCallback(StreamSocket
* socket
)
572 callback_(base::Bind(&DeleteSocketCallback::OnComplete
,
573 base::Unretained(this))) {}
574 virtual ~DeleteSocketCallback() {}
576 const CompletionCallback
& callback() const { return callback_
; }
579 void OnComplete(int result
) {
584 ADD_FAILURE() << "Deleting socket twice";
589 StreamSocket
* socket_
;
590 CompletionCallback callback_
;
592 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback
);
595 // A ChannelIDStore that always returns an error when asked for a
597 class FailingChannelIDStore
: public ChannelIDStore
{
598 virtual int GetChannelID(const std::string
& server_identifier
,
599 base::Time
* expiration_time
,
600 std::string
* private_key_result
,
601 std::string
* cert_result
,
602 const GetChannelIDCallback
& callback
) OVERRIDE
{
603 return ERR_UNEXPECTED
;
605 virtual void SetChannelID(const std::string
& server_identifier
,
606 base::Time creation_time
,
607 base::Time expiration_time
,
608 const std::string
& private_key
,
609 const std::string
& cert
) OVERRIDE
{}
610 virtual void DeleteChannelID(const std::string
& server_identifier
,
611 const base::Closure
& completion_callback
)
613 virtual void DeleteAllCreatedBetween(base::Time delete_begin
,
614 base::Time delete_end
,
615 const base::Closure
& completion_callback
)
617 virtual void DeleteAll(const base::Closure
& completion_callback
) OVERRIDE
{}
618 virtual void GetAllChannelIDs(const GetChannelIDListCallback
& callback
)
620 virtual int GetChannelIDCount() OVERRIDE
{ return 0; }
621 virtual void SetForceKeepSessionState() OVERRIDE
{}
624 // A ChannelIDStore that asynchronously returns an error when asked for a
626 class AsyncFailingChannelIDStore
: public ChannelIDStore
{
627 virtual int GetChannelID(const std::string
& server_identifier
,
628 base::Time
* expiration_time
,
629 std::string
* private_key_result
,
630 std::string
* cert_result
,
631 const GetChannelIDCallback
& callback
) OVERRIDE
{
632 base::MessageLoop::current()->PostTask(
633 FROM_HERE
, base::Bind(callback
, ERR_UNEXPECTED
,
634 server_identifier
, base::Time(), "", ""));
635 return ERR_IO_PENDING
;
637 virtual void SetChannelID(const std::string
& server_identifier
,
638 base::Time creation_time
,
639 base::Time expiration_time
,
640 const std::string
& private_key
,
641 const std::string
& cert
) OVERRIDE
{}
642 virtual void DeleteChannelID(const std::string
& server_identifier
,
643 const base::Closure
& completion_callback
)
645 virtual void DeleteAllCreatedBetween(base::Time delete_begin
,
646 base::Time delete_end
,
647 const base::Closure
& completion_callback
)
649 virtual void DeleteAll(const base::Closure
& completion_callback
) OVERRIDE
{}
650 virtual void GetAllChannelIDs(const GetChannelIDListCallback
& callback
)
652 virtual int GetChannelIDCount() OVERRIDE
{ return 0; }
653 virtual void SetForceKeepSessionState() OVERRIDE
{}
656 class SSLClientSocketTest
: public PlatformTest
{
658 SSLClientSocketTest()
659 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
660 cert_verifier_(new MockCertVerifier
),
661 transport_security_state_(new TransportSecurityState
),
662 ran_handshake_completion_callback_(false) {
663 cert_verifier_
->set_default_result(OK
);
664 context_
.cert_verifier
= cert_verifier_
.get();
665 context_
.transport_security_state
= transport_security_state_
.get();
668 void RecordCompletedHandshake() { ran_handshake_completion_callback_
= true; }
671 // The address of the spawned test server, after calling StartTestServer().
672 const AddressList
& addr() const { return addr_
; }
674 // The SpawnedTestServer object, after calling StartTestServer().
675 const SpawnedTestServer
* test_server() const { return test_server_
.get(); }
677 // Starts the test server with SSL configuration |ssl_options|. Returns true
679 bool StartTestServer(const SpawnedTestServer::SSLOptions
& ssl_options
) {
680 test_server_
.reset(new SpawnedTestServer(
681 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath()));
682 if (!test_server_
->Start()) {
683 LOG(ERROR
) << "Could not start SpawnedTestServer";
687 if (!test_server_
->GetAddressList(&addr_
)) {
688 LOG(ERROR
) << "Could not get SpawnedTestServer address list";
694 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
695 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
696 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions
& ssl_options
) {
697 if (!StartTestServer(ssl_options
))
700 transport_
.reset(new TCPClientSocket(addr_
, &log_
, NetLog::Source()));
701 int rv
= callback_
.GetResult(transport_
->Connect(callback_
.callback()));
703 LOG(ERROR
) << "Could not connect to SpawnedTestServer";
709 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
710 scoped_ptr
<StreamSocket
> transport_socket
,
711 const HostPortPair
& host_and_port
,
712 const SSLConfig
& ssl_config
) {
713 scoped_ptr
<ClientSocketHandle
> connection(new ClientSocketHandle
);
714 connection
->SetSocket(transport_socket
.Pass());
715 return socket_factory_
->CreateSSLClientSocket(
716 connection
.Pass(), host_and_port
, ssl_config
, context_
);
719 // Create an SSLClientSocket object and use it to connect to a test
720 // server, then wait for connection results. This must be called after
721 // a successful ConnectToTestServer() call.
722 // |ssl_config| the SSL configuration to use.
723 // |result| will retrieve the ::Connect() result value.
724 // Returns true on success, false otherwise. Success means that the socket
725 // could be created and its Connect() was called, not that the connection
726 // itself was a success.
727 bool CreateAndConnectSSLClientSocket(SSLConfig
& ssl_config
, int* result
) {
728 sock_
= CreateSSLClientSocket(
729 transport_
.Pass(), test_server_
->host_port_pair(), ssl_config
);
731 if (sock_
->IsConnected()) {
732 LOG(ERROR
) << "SSL Socket prematurely connected";
736 *result
= callback_
.GetResult(sock_
->Connect(callback_
.callback()));
740 ClientSocketFactory
* socket_factory_
;
741 scoped_ptr
<MockCertVerifier
> cert_verifier_
;
742 scoped_ptr
<TransportSecurityState
> transport_security_state_
;
743 SSLClientSocketContext context_
;
744 scoped_ptr
<SSLClientSocket
> sock_
;
745 CapturingNetLog log_
;
746 bool ran_handshake_completion_callback_
;
749 scoped_ptr
<StreamSocket
> transport_
;
750 scoped_ptr
<SpawnedTestServer
> test_server_
;
751 TestCompletionCallback callback_
;
755 // Verifies the correctness of GetSSLCertRequestInfo.
756 class SSLClientSocketCertRequestInfoTest
: public SSLClientSocketTest
{
758 // Creates a test server with the given SSLOptions, connects to it and returns
759 // the SSLCertRequestInfo reported by the socket.
760 scoped_refptr
<SSLCertRequestInfo
> GetCertRequest(
761 SpawnedTestServer::SSLOptions ssl_options
) {
762 SpawnedTestServer
test_server(
763 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
764 if (!test_server
.Start())
768 if (!test_server
.GetAddressList(&addr
))
771 TestCompletionCallback callback
;
773 scoped_ptr
<StreamSocket
> transport(
774 new TCPClientSocket(addr
, &log
, NetLog::Source()));
775 int rv
= transport
->Connect(callback
.callback());
776 if (rv
== ERR_IO_PENDING
)
777 rv
= callback
.WaitForResult();
780 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
781 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
782 EXPECT_FALSE(sock
->IsConnected());
784 rv
= sock
->Connect(callback
.callback());
785 if (rv
== ERR_IO_PENDING
)
786 rv
= callback
.WaitForResult();
787 scoped_refptr
<SSLCertRequestInfo
> request_info
= new SSLCertRequestInfo();
788 sock
->GetSSLCertRequestInfo(request_info
.get());
790 EXPECT_FALSE(sock
->IsConnected());
792 test_server
.host_port_pair().Equals(request_info
->host_and_port
));
798 class SSLClientSocketFalseStartTest
: public SSLClientSocketTest
{
800 // Creates an SSLClientSocket with |client_config| attached to a
801 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
802 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
803 // so |*out_raw_transport| is a raw pointer.
805 // The client socket will begin a connect using |callback| but stop before the
806 // server's finished message is received. The finished message will be blocked
807 // in |*out_raw_transport|. To complete the handshake and successfully read
808 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
809 // the client successfully false started, |callback.WaitForResult()| will
810 // return OK without unblocking transport reads. But Read() will still block.)
812 // Must be called after StartTestServer is called.
813 void CreateAndConnectUntilServerFinishedReceived(
814 const SSLConfig
& client_config
,
815 TestCompletionCallback
* callback
,
816 FakeBlockingStreamSocket
** out_raw_transport
,
817 scoped_ptr
<SSLClientSocket
>* out_sock
) {
818 CHECK(test_server());
820 scoped_ptr
<StreamSocket
> real_transport(
821 new TCPClientSocket(addr(), NULL
, NetLog::Source()));
822 scoped_ptr
<FakeBlockingStreamSocket
> transport(
823 new FakeBlockingStreamSocket(real_transport
.Pass()));
824 int rv
= callback
->GetResult(transport
->Connect(callback
->callback()));
827 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
828 scoped_ptr
<SSLClientSocket
> sock
=
829 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
830 test_server()->host_port_pair(),
833 // Connect. Stop before the client processes the first server leg
834 // (ServerHello, etc.)
835 raw_transport
->BlockReadResult();
836 rv
= sock
->Connect(callback
->callback());
837 EXPECT_EQ(ERR_IO_PENDING
, rv
);
838 raw_transport
->WaitForReadResult();
840 // Release the ServerHello and wait for the client to write
841 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
842 // server's leg to complete, since it may span multiple reads.)
843 EXPECT_FALSE(callback
->have_result());
844 raw_transport
->BlockWrite();
845 raw_transport
->UnblockReadResult();
846 raw_transport
->WaitForWrite();
848 // And, finally, release that and block the next server leg
849 // (ChangeCipherSpec, Finished).
850 raw_transport
->BlockReadResult();
851 raw_transport
->UnblockWrite();
853 *out_raw_transport
= raw_transport
;
854 *out_sock
= sock
.Pass();
857 void TestFalseStart(const SpawnedTestServer::SSLOptions
& server_options
,
858 const SSLConfig
& client_config
,
859 bool expect_false_start
) {
860 ASSERT_TRUE(StartTestServer(server_options
));
862 TestCompletionCallback callback
;
863 FakeBlockingStreamSocket
* raw_transport
= NULL
;
864 scoped_ptr
<SSLClientSocket
> sock
;
865 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
866 client_config
, &callback
, &raw_transport
, &sock
));
868 if (expect_false_start
) {
869 // When False Starting, the handshake should complete before receiving the
870 // Change Cipher Spec and Finished messages.
872 // Note: callback.have_result() may not be true without waiting. The NSS
873 // state machine sometimes lives on a separate thread, so this thread may
874 // not yet have processed the signal that the handshake has completed.
875 int rv
= callback
.WaitForResult();
877 EXPECT_TRUE(sock
->IsConnected());
879 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
880 static const int kRequestTextSize
=
881 static_cast<int>(arraysize(request_text
) - 1);
882 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
883 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
885 // Write the request.
886 rv
= callback
.GetResult(sock
->Write(request_buffer
.get(),
888 callback
.callback()));
889 EXPECT_EQ(kRequestTextSize
, rv
);
891 // The read will hang; it's waiting for the peer to complete the
892 // handshake, and the handshake is still blocked.
893 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
894 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
896 // After releasing reads, the connection proceeds.
897 raw_transport
->UnblockReadResult();
898 rv
= callback
.GetResult(rv
);
901 // False Start is not enabled, so the handshake will not complete because
902 // the server second leg is blocked.
903 base::RunLoop().RunUntilIdle();
904 EXPECT_FALSE(callback
.have_result());
909 class SSLClientSocketChannelIDTest
: public SSLClientSocketTest
{
911 void EnableChannelID() {
912 channel_id_service_
.reset(
913 new ChannelIDService(new DefaultChannelIDStore(NULL
),
914 base::MessageLoopProxy::current()));
915 context_
.channel_id_service
= channel_id_service_
.get();
918 void EnableFailingChannelID() {
919 channel_id_service_
.reset(new ChannelIDService(
920 new FailingChannelIDStore(), base::MessageLoopProxy::current()));
921 context_
.channel_id_service
= channel_id_service_
.get();
924 void EnableAsyncFailingChannelID() {
925 channel_id_service_
.reset(new ChannelIDService(
926 new AsyncFailingChannelIDStore(),
927 base::MessageLoopProxy::current()));
928 context_
.channel_id_service
= channel_id_service_
.get();
932 scoped_ptr
<ChannelIDService
> channel_id_service_
;
935 //-----------------------------------------------------------------------------
937 // LogContainsSSLConnectEndEvent returns true if the given index in the given
938 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
939 // merge the first application data record with the Finished message when false
940 // starting. However, in order to avoid the server timing out the handshake,
941 // they'll give up waiting for application data and send the Finished after a
942 // timeout. This means that an SSL connect end event may appear as a socket
944 static bool LogContainsSSLConnectEndEvent(
945 const CapturingNetLog::CapturedEntryList
& log
,
947 return LogContainsEndEvent(log
, i
, NetLog::TYPE_SSL_CONNECT
) ||
949 log
, i
, NetLog::TYPE_SOCKET_BYTES_SENT
, NetLog::PHASE_NONE
);
954 TEST_F(SSLClientSocketTest
, Connect
) {
955 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
956 SpawnedTestServer::kLocalhost
,
958 ASSERT_TRUE(test_server
.Start());
961 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
963 TestCompletionCallback callback
;
965 scoped_ptr
<StreamSocket
> transport(
966 new TCPClientSocket(addr
, &log
, NetLog::Source()));
967 int rv
= transport
->Connect(callback
.callback());
968 if (rv
== ERR_IO_PENDING
)
969 rv
= callback
.WaitForResult();
972 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
973 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
975 EXPECT_FALSE(sock
->IsConnected());
977 rv
= sock
->Connect(callback
.callback());
979 CapturingNetLog::CapturedEntryList entries
;
980 log
.GetEntries(&entries
);
981 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
982 if (rv
== ERR_IO_PENDING
)
983 rv
= callback
.WaitForResult();
985 EXPECT_TRUE(sock
->IsConnected());
986 log
.GetEntries(&entries
);
987 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
990 EXPECT_FALSE(sock
->IsConnected());
993 TEST_F(SSLClientSocketTest
, ConnectExpired
) {
994 SpawnedTestServer::SSLOptions
ssl_options(
995 SpawnedTestServer::SSLOptions::CERT_EXPIRED
);
996 SpawnedTestServer
test_server(
997 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
998 ASSERT_TRUE(test_server
.Start());
1000 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
1003 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1005 TestCompletionCallback callback
;
1006 CapturingNetLog log
;
1007 scoped_ptr
<StreamSocket
> transport(
1008 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1009 int rv
= transport
->Connect(callback
.callback());
1010 if (rv
== ERR_IO_PENDING
)
1011 rv
= callback
.WaitForResult();
1014 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1015 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1017 EXPECT_FALSE(sock
->IsConnected());
1019 rv
= sock
->Connect(callback
.callback());
1021 CapturingNetLog::CapturedEntryList entries
;
1022 log
.GetEntries(&entries
);
1023 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1024 if (rv
== ERR_IO_PENDING
)
1025 rv
= callback
.WaitForResult();
1027 EXPECT_EQ(ERR_CERT_DATE_INVALID
, rv
);
1029 // Rather than testing whether or not the underlying socket is connected,
1030 // test that the handshake has finished. This is because it may be
1031 // desirable to disconnect the socket before showing a user prompt, since
1032 // the user may take indefinitely long to respond.
1033 log
.GetEntries(&entries
);
1034 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1037 TEST_F(SSLClientSocketTest
, ConnectMismatched
) {
1038 SpawnedTestServer::SSLOptions
ssl_options(
1039 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
1040 SpawnedTestServer
test_server(
1041 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1042 ASSERT_TRUE(test_server
.Start());
1044 cert_verifier_
->set_default_result(ERR_CERT_COMMON_NAME_INVALID
);
1047 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1049 TestCompletionCallback callback
;
1050 CapturingNetLog log
;
1051 scoped_ptr
<StreamSocket
> transport(
1052 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1053 int rv
= transport
->Connect(callback
.callback());
1054 if (rv
== ERR_IO_PENDING
)
1055 rv
= callback
.WaitForResult();
1058 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1059 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1061 EXPECT_FALSE(sock
->IsConnected());
1063 rv
= sock
->Connect(callback
.callback());
1065 CapturingNetLog::CapturedEntryList entries
;
1066 log
.GetEntries(&entries
);
1067 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1068 if (rv
== ERR_IO_PENDING
)
1069 rv
= callback
.WaitForResult();
1071 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID
, rv
);
1073 // Rather than testing whether or not the underlying socket is connected,
1074 // test that the handshake has finished. This is because it may be
1075 // desirable to disconnect the socket before showing a user prompt, since
1076 // the user may take indefinitely long to respond.
1077 log
.GetEntries(&entries
);
1078 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1081 // Attempt to connect to a page which requests a client certificate. It should
1082 // return an error code on connect.
1083 TEST_F(SSLClientSocketTest
, ConnectClientAuthCertRequested
) {
1084 SpawnedTestServer::SSLOptions ssl_options
;
1085 ssl_options
.request_client_certificate
= true;
1086 SpawnedTestServer
test_server(
1087 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1088 ASSERT_TRUE(test_server
.Start());
1091 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1093 TestCompletionCallback callback
;
1094 CapturingNetLog log
;
1095 scoped_ptr
<StreamSocket
> transport(
1096 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1097 int rv
= transport
->Connect(callback
.callback());
1098 if (rv
== ERR_IO_PENDING
)
1099 rv
= callback
.WaitForResult();
1102 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1103 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1105 EXPECT_FALSE(sock
->IsConnected());
1107 rv
= sock
->Connect(callback
.callback());
1109 CapturingNetLog::CapturedEntryList entries
;
1110 log
.GetEntries(&entries
);
1111 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1112 if (rv
== ERR_IO_PENDING
)
1113 rv
= callback
.WaitForResult();
1115 log
.GetEntries(&entries
);
1116 // Because we prematurely kill the handshake at CertificateRequest,
1117 // the server may still send data (notably the ServerHelloDone)
1118 // after the error is returned. As a result, the SSL_CONNECT may not
1119 // be the last entry. See http://crbug.com/54445. We use
1120 // ExpectLogContainsSomewhere instead of
1121 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
1122 // extra read instead of two. This occurs before the handshake ends,
1123 // so the corking logic of LogContainsSSLConnectEndEvent isn't
1126 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
1127 // fixed and we can respond to the first CertificateRequest
1128 // without closing the socket, add a unit test for sending the
1129 // certificate. This test may still be useful as we'll want to close
1130 // the socket on a timeout if the user takes a long time to pick a
1131 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
1132 ExpectLogContainsSomewhere(
1133 entries
, 0, NetLog::TYPE_SSL_CONNECT
, NetLog::PHASE_END
);
1134 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
, rv
);
1135 EXPECT_FALSE(sock
->IsConnected());
1138 // Connect to a server requesting optional client authentication. Send it a
1139 // null certificate. It should allow the connection.
1141 // TODO(davidben): Also test providing an actual certificate.
1142 TEST_F(SSLClientSocketTest
, ConnectClientAuthSendNullCert
) {
1143 SpawnedTestServer::SSLOptions ssl_options
;
1144 ssl_options
.request_client_certificate
= true;
1145 SpawnedTestServer
test_server(
1146 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1147 ASSERT_TRUE(test_server
.Start());
1150 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1152 TestCompletionCallback callback
;
1153 CapturingNetLog log
;
1154 scoped_ptr
<StreamSocket
> transport(
1155 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1156 int rv
= transport
->Connect(callback
.callback());
1157 if (rv
== ERR_IO_PENDING
)
1158 rv
= callback
.WaitForResult();
1161 SSLConfig ssl_config
= kDefaultSSLConfig
;
1162 ssl_config
.send_client_cert
= true;
1163 ssl_config
.client_cert
= NULL
;
1165 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1166 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1168 EXPECT_FALSE(sock
->IsConnected());
1170 // Our test server accepts certificate-less connections.
1171 // TODO(davidben): Add a test which requires them and verify the error.
1172 rv
= sock
->Connect(callback
.callback());
1174 CapturingNetLog::CapturedEntryList entries
;
1175 log
.GetEntries(&entries
);
1176 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1177 if (rv
== ERR_IO_PENDING
)
1178 rv
= callback
.WaitForResult();
1181 EXPECT_TRUE(sock
->IsConnected());
1182 log
.GetEntries(&entries
);
1183 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1185 // We responded to the server's certificate request with a Certificate
1186 // message with no client certificate in it. ssl_info.client_cert_sent
1187 // should be false in this case.
1189 sock
->GetSSLInfo(&ssl_info
);
1190 EXPECT_FALSE(ssl_info
.client_cert_sent
);
1193 EXPECT_FALSE(sock
->IsConnected());
1196 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1197 // - Server closes an SSL connection (with a close_notify alert message).
1198 // - Server closes the underlying TCP connection directly.
1199 // - Server sends data unexpectedly.
1201 TEST_F(SSLClientSocketTest
, Read
) {
1202 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1203 SpawnedTestServer::kLocalhost
,
1205 ASSERT_TRUE(test_server
.Start());
1208 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1210 TestCompletionCallback callback
;
1211 scoped_ptr
<StreamSocket
> transport(
1212 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1213 int rv
= transport
->Connect(callback
.callback());
1214 if (rv
== ERR_IO_PENDING
)
1215 rv
= callback
.WaitForResult();
1218 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1219 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1221 rv
= sock
->Connect(callback
.callback());
1222 if (rv
== ERR_IO_PENDING
)
1223 rv
= callback
.WaitForResult();
1225 EXPECT_TRUE(sock
->IsConnected());
1227 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1228 scoped_refptr
<IOBuffer
> request_buffer(
1229 new IOBuffer(arraysize(request_text
) - 1));
1230 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1233 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1234 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1236 if (rv
== ERR_IO_PENDING
)
1237 rv
= callback
.WaitForResult();
1238 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1240 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1242 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1243 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1245 if (rv
== ERR_IO_PENDING
)
1246 rv
= callback
.WaitForResult();
1254 // Tests that SSLClientSocket properly handles when the underlying transport
1255 // synchronously fails a transport read in during the handshake. The error code
1256 // should be preserved so SSLv3 fallback logic can condition on it.
1257 TEST_F(SSLClientSocketTest
, Connect_WithSynchronousError
) {
1258 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1259 SpawnedTestServer::kLocalhost
,
1261 ASSERT_TRUE(test_server
.Start());
1264 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1266 TestCompletionCallback callback
;
1267 scoped_ptr
<StreamSocket
> real_transport(
1268 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1269 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1270 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1271 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1274 // Disable TLS False Start to avoid handshake non-determinism.
1275 SSLConfig ssl_config
;
1276 ssl_config
.false_start_enabled
= false;
1278 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1279 scoped_ptr
<SSLClientSocket
> sock(
1280 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
1281 test_server
.host_port_pair(),
1284 raw_transport
->SetNextWriteError(ERR_CONNECTION_RESET
);
1286 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1287 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1288 EXPECT_FALSE(sock
->IsConnected());
1291 // Tests that the SSLClientSocket properly handles when the underlying transport
1292 // synchronously returns an error code - such as if an intermediary terminates
1293 // the socket connection uncleanly.
1294 // This is a regression test for http://crbug.com/238536
1295 TEST_F(SSLClientSocketTest
, Read_WithSynchronousError
) {
1296 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1297 SpawnedTestServer::kLocalhost
,
1299 ASSERT_TRUE(test_server
.Start());
1302 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1304 TestCompletionCallback callback
;
1305 scoped_ptr
<StreamSocket
> real_transport(
1306 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1307 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1308 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1309 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1312 // Disable TLS False Start to avoid handshake non-determinism.
1313 SSLConfig ssl_config
;
1314 ssl_config
.false_start_enabled
= false;
1316 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1317 scoped_ptr
<SSLClientSocket
> sock(
1318 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
1319 test_server
.host_port_pair(),
1322 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1324 EXPECT_TRUE(sock
->IsConnected());
1326 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1327 static const int kRequestTextSize
=
1328 static_cast<int>(arraysize(request_text
) - 1);
1329 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1330 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1332 rv
= callback
.GetResult(
1333 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1334 EXPECT_EQ(kRequestTextSize
, rv
);
1336 // Simulate an unclean/forcible shutdown.
1337 raw_transport
->SetNextReadError(ERR_CONNECTION_RESET
);
1339 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1341 // Note: This test will hang if this bug has regressed. Simply checking that
1342 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1343 // result when using a dedicated task runner for NSS.
1344 rv
= callback
.GetResult(sock
->Read(buf
.get(), 4096, callback
.callback()));
1345 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1348 // Tests that the SSLClientSocket properly handles when the underlying transport
1349 // asynchronously returns an error code while writing data - such as if an
1350 // intermediary terminates the socket connection uncleanly.
1351 // This is a regression test for http://crbug.com/249848
1352 TEST_F(SSLClientSocketTest
, Write_WithSynchronousError
) {
1353 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1354 SpawnedTestServer::kLocalhost
,
1356 ASSERT_TRUE(test_server
.Start());
1359 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1361 TestCompletionCallback callback
;
1362 scoped_ptr
<StreamSocket
> real_transport(
1363 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1364 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1365 // is retained in order to configure additional errors.
1366 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1367 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1368 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1369 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1370 new FakeBlockingStreamSocket(error_socket
.PassAs
<StreamSocket
>()));
1371 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1372 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1375 // Disable TLS False Start to avoid handshake non-determinism.
1376 SSLConfig ssl_config
;
1377 ssl_config
.false_start_enabled
= false;
1379 scoped_ptr
<SSLClientSocket
> sock(
1380 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
1381 test_server
.host_port_pair(),
1384 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1386 EXPECT_TRUE(sock
->IsConnected());
1388 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1389 static const int kRequestTextSize
=
1390 static_cast<int>(arraysize(request_text
) - 1);
1391 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1392 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1394 // Simulate an unclean/forcible shutdown on the underlying socket.
1395 // However, simulate this error asynchronously.
1396 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1397 raw_transport
->BlockWrite();
1399 // This write should complete synchronously, because the TLS ciphertext
1400 // can be created and placed into the outgoing buffers independent of the
1401 // underlying transport.
1402 rv
= callback
.GetResult(
1403 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1404 EXPECT_EQ(kRequestTextSize
, rv
);
1406 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1408 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1409 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1411 // Now unblock the outgoing request, having it fail with the connection
1413 raw_transport
->UnblockWrite();
1415 // Note: This will cause an inifite loop if this bug has regressed. Simply
1416 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1417 // is a legitimate result when using a dedicated task runner for NSS.
1418 rv
= callback
.GetResult(rv
);
1419 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1422 // If there is a Write failure at the transport with no follow-up Read, although
1423 // the write error will not be returned to the client until a future Read or
1424 // Write operation, SSLClientSocket should not spin attempting to re-write on
1425 // the socket. This is a regression test for part of https://crbug.com/381160.
1426 TEST_F(SSLClientSocketTest
, Write_WithSynchronousErrorNoRead
) {
1427 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1428 SpawnedTestServer::kLocalhost
,
1430 ASSERT_TRUE(test_server
.Start());
1433 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1435 TestCompletionCallback callback
;
1436 scoped_ptr
<StreamSocket
> real_transport(
1437 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1438 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1439 // is retained in order to query them.
1440 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1441 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1442 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1443 scoped_ptr
<CountingStreamSocket
> counting_socket(
1444 new CountingStreamSocket(error_socket
.PassAs
<StreamSocket
>()));
1445 CountingStreamSocket
* raw_counting_socket
= counting_socket
.get();
1446 int rv
= callback
.GetResult(counting_socket
->Connect(callback
.callback()));
1449 // Disable TLS False Start to avoid handshake non-determinism.
1450 SSLConfig ssl_config
;
1451 ssl_config
.false_start_enabled
= false;
1453 scoped_ptr
<SSLClientSocket
> sock(
1454 CreateSSLClientSocket(counting_socket
.PassAs
<StreamSocket
>(),
1455 test_server
.host_port_pair(),
1458 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1460 ASSERT_TRUE(sock
->IsConnected());
1462 // Simulate an unclean/forcible shutdown on the underlying socket.
1463 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1465 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1466 static const int kRequestTextSize
=
1467 static_cast<int>(arraysize(request_text
) - 1);
1468 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1469 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1471 // This write should complete synchronously, because the TLS ciphertext
1472 // can be created and placed into the outgoing buffers independent of the
1473 // underlying transport.
1474 rv
= callback
.GetResult(
1475 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1476 ASSERT_EQ(kRequestTextSize
, rv
);
1478 // Let the event loop spin for a little bit of time. Even on platforms where
1479 // pumping the state machine involve thread hops, there should be no further
1480 // writes on the transport socket.
1482 // TODO(davidben): Avoid the arbitrary timeout?
1483 int old_write_count
= raw_counting_socket
->write_count();
1485 base::MessageLoop::current()->PostDelayedTask(
1486 FROM_HERE
, loop
.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1488 EXPECT_EQ(old_write_count
, raw_counting_socket
->write_count());
1491 // Test the full duplex mode, with Read and Write pending at the same time.
1492 // This test also serves as a regression test for http://crbug.com/29815.
1493 TEST_F(SSLClientSocketTest
, Read_FullDuplex
) {
1494 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1495 SpawnedTestServer::kLocalhost
,
1497 ASSERT_TRUE(test_server
.Start());
1500 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1502 TestCompletionCallback callback
; // Used for everything except Write.
1504 scoped_ptr
<StreamSocket
> transport(
1505 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1506 int rv
= transport
->Connect(callback
.callback());
1507 if (rv
== ERR_IO_PENDING
)
1508 rv
= callback
.WaitForResult();
1511 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1512 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1514 rv
= sock
->Connect(callback
.callback());
1515 if (rv
== ERR_IO_PENDING
)
1516 rv
= callback
.WaitForResult();
1518 EXPECT_TRUE(sock
->IsConnected());
1520 // Issue a "hanging" Read first.
1521 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1522 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1523 // We haven't written the request, so there should be no response yet.
1524 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1526 // Write the request.
1527 // The request is padded with a User-Agent header to a size that causes the
1528 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1529 // This tests the fix for http://crbug.com/29815.
1530 std::string request_text
= "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1531 for (int i
= 0; i
< 3770; ++i
)
1532 request_text
.push_back('*');
1533 request_text
.append("\r\n\r\n");
1534 scoped_refptr
<IOBuffer
> request_buffer(new StringIOBuffer(request_text
));
1536 TestCompletionCallback callback2
; // Used for Write only.
1538 request_buffer
.get(), request_text
.size(), callback2
.callback());
1539 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1541 if (rv
== ERR_IO_PENDING
)
1542 rv
= callback2
.WaitForResult();
1543 EXPECT_EQ(static_cast<int>(request_text
.size()), rv
);
1545 // Now get the Read result.
1546 rv
= callback
.WaitForResult();
1550 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1551 // mode when the underlying transport is blocked on sending data. When the
1552 // underlying transport completes due to an error, it should invoke both the
1553 // Read() and Write() callbacks. If the socket is deleted by the Read()
1554 // callback, the Write() callback should not be invoked.
1555 // Regression test for http://crbug.com/232633
1556 TEST_F(SSLClientSocketTest
, Read_DeleteWhilePendingFullDuplex
) {
1557 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1558 SpawnedTestServer::kLocalhost
,
1560 ASSERT_TRUE(test_server
.Start());
1563 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1565 TestCompletionCallback callback
;
1566 scoped_ptr
<StreamSocket
> real_transport(
1567 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1568 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1569 // is retained in order to configure additional errors.
1570 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1571 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1572 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1573 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1574 new FakeBlockingStreamSocket(error_socket
.PassAs
<StreamSocket
>()));
1575 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1577 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1580 // Disable TLS False Start to avoid handshake non-determinism.
1581 SSLConfig ssl_config
;
1582 ssl_config
.false_start_enabled
= false;
1584 scoped_ptr
<SSLClientSocket
> sock
=
1585 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
1586 test_server
.host_port_pair(),
1589 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1591 EXPECT_TRUE(sock
->IsConnected());
1593 std::string request_text
= "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1594 request_text
.append(20 * 1024, '*');
1595 request_text
.append("\r\n\r\n");
1596 scoped_refptr
<DrainableIOBuffer
> request_buffer(new DrainableIOBuffer(
1597 new StringIOBuffer(request_text
), request_text
.size()));
1599 // Simulate errors being returned from the underlying Read() and Write() ...
1600 raw_error_socket
->SetNextReadError(ERR_CONNECTION_RESET
);
1601 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1602 // ... but have those errors returned asynchronously. Because the Write() will
1603 // return first, this will trigger the error.
1604 raw_transport
->BlockReadResult();
1605 raw_transport
->BlockWrite();
1607 // Enqueue a Read() before calling Write(), which should "hang" due to
1608 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1609 SSLClientSocket
* raw_sock
= sock
.get();
1610 DeleteSocketCallback
read_callback(sock
.release());
1611 scoped_refptr
<IOBuffer
> read_buf(new IOBuffer(4096));
1612 rv
= raw_sock
->Read(read_buf
.get(), 4096, read_callback
.callback());
1614 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1615 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1616 ASSERT_FALSE(read_callback
.have_result());
1618 #if !defined(USE_OPENSSL)
1619 // NSS follows a pattern where a call to PR_Write will only consume as
1620 // much data as it can encode into application data records before the
1621 // internal memio buffer is full, which should only fill if writing a large
1622 // amount of data and the underlying transport is blocked. Once this happens,
1623 // NSS will return (total size of all application data records it wrote) - 1,
1624 // with the caller expected to resume with the remaining unsent data.
1626 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1627 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1628 // get the socket in the state needed for the test below.
1630 // This is not needed for OpenSSL, because for OpenSSL,
1631 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1632 // SSLClientSocketOpenSSL::Write() will not return until all of
1633 // |request_buffer| has been written to the underlying BIO (although not
1634 // necessarily the underlying transport).
1635 rv
= callback
.GetResult(raw_sock
->Write(request_buffer
.get(),
1636 request_buffer
->BytesRemaining(),
1637 callback
.callback()));
1639 request_buffer
->DidConsume(rv
);
1641 // Guard to ensure that |request_buffer| was larger than all of the internal
1642 // buffers (transport, memio, NSS) along the way - otherwise the next call
1643 // to Write() will crash with an invalid buffer.
1644 ASSERT_LT(0, request_buffer
->BytesRemaining());
1647 // Attempt to write the remaining data. NSS will not be able to consume the
1648 // application data because the internal buffers are full, while OpenSSL will
1649 // return that its blocked because the underlying transport is blocked.
1650 rv
= raw_sock
->Write(request_buffer
.get(),
1651 request_buffer
->BytesRemaining(),
1652 callback
.callback());
1653 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1654 ASSERT_FALSE(callback
.have_result());
1656 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1657 // call the Read() callback, deleting the socket and thus aborting calling
1658 // the Write() callback.
1659 raw_transport
->UnblockWrite();
1661 rv
= read_callback
.WaitForResult();
1662 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1664 // The Write callback should not have been called.
1665 EXPECT_FALSE(callback
.have_result());
1668 // Tests that the SSLClientSocket does not crash if data is received on the
1669 // transport socket after a failing write. This can occur if we have a Write
1670 // error in a SPDY socket.
1671 // Regression test for http://crbug.com/335557
1672 TEST_F(SSLClientSocketTest
, Read_WithWriteError
) {
1673 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1674 SpawnedTestServer::kLocalhost
,
1676 ASSERT_TRUE(test_server
.Start());
1679 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1681 TestCompletionCallback callback
;
1682 scoped_ptr
<StreamSocket
> real_transport(
1683 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1684 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1685 // is retained in order to configure additional errors.
1686 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1687 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1688 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1689 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1690 new FakeBlockingStreamSocket(error_socket
.PassAs
<StreamSocket
>()));
1691 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1693 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1696 // Disable TLS False Start to avoid handshake non-determinism.
1697 SSLConfig ssl_config
;
1698 ssl_config
.false_start_enabled
= false;
1700 scoped_ptr
<SSLClientSocket
> sock(
1701 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
1702 test_server
.host_port_pair(),
1705 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1707 EXPECT_TRUE(sock
->IsConnected());
1709 // Send a request so there is something to read from the socket.
1710 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1711 static const int kRequestTextSize
=
1712 static_cast<int>(arraysize(request_text
) - 1);
1713 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1714 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1716 rv
= callback
.GetResult(
1717 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1718 EXPECT_EQ(kRequestTextSize
, rv
);
1720 // Start a hanging read.
1721 TestCompletionCallback read_callback
;
1722 raw_transport
->BlockReadResult();
1723 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1724 rv
= sock
->Read(buf
.get(), 4096, read_callback
.callback());
1725 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1727 // Perform another write, but have it fail. Write a request larger than the
1728 // internal socket buffers so that the request hits the underlying transport
1729 // socket and detects the error.
1730 std::string long_request_text
=
1731 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1732 long_request_text
.append(20 * 1024, '*');
1733 long_request_text
.append("\r\n\r\n");
1734 scoped_refptr
<DrainableIOBuffer
> long_request_buffer(new DrainableIOBuffer(
1735 new StringIOBuffer(long_request_text
), long_request_text
.size()));
1737 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1739 // Write as much data as possible until hitting an error. This is necessary
1740 // for NSS. PR_Write will only consume as much data as it can encode into
1741 // application data records before the internal memio buffer is full, which
1742 // should only fill if writing a large amount of data and the underlying
1743 // transport is blocked. Once this happens, NSS will return (total size of all
1744 // application data records it wrote) - 1, with the caller expected to resume
1745 // with the remaining unsent data.
1747 rv
= callback
.GetResult(sock
->Write(long_request_buffer
.get(),
1748 long_request_buffer
->BytesRemaining(),
1749 callback
.callback()));
1751 long_request_buffer
->DidConsume(rv
);
1752 // Abort if the entire buffer is ever consumed.
1753 ASSERT_LT(0, long_request_buffer
->BytesRemaining());
1757 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1759 // Release the read.
1760 raw_transport
->UnblockReadResult();
1761 rv
= read_callback
.WaitForResult();
1763 #if defined(USE_OPENSSL)
1764 // Should still read bytes despite the write error.
1767 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1768 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1769 // the write error stops future reads.
1770 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1774 TEST_F(SSLClientSocketTest
, Read_SmallChunks
) {
1775 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1776 SpawnedTestServer::kLocalhost
,
1778 ASSERT_TRUE(test_server
.Start());
1781 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1783 TestCompletionCallback callback
;
1784 scoped_ptr
<StreamSocket
> transport(
1785 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1786 int rv
= transport
->Connect(callback
.callback());
1787 if (rv
== ERR_IO_PENDING
)
1788 rv
= callback
.WaitForResult();
1791 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1792 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1794 rv
= sock
->Connect(callback
.callback());
1795 if (rv
== ERR_IO_PENDING
)
1796 rv
= callback
.WaitForResult();
1799 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1800 scoped_refptr
<IOBuffer
> request_buffer(
1801 new IOBuffer(arraysize(request_text
) - 1));
1802 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1805 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1806 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1808 if (rv
== ERR_IO_PENDING
)
1809 rv
= callback
.WaitForResult();
1810 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1812 scoped_refptr
<IOBuffer
> buf(new IOBuffer(1));
1814 rv
= sock
->Read(buf
.get(), 1, callback
.callback());
1815 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1817 if (rv
== ERR_IO_PENDING
)
1818 rv
= callback
.WaitForResult();
1826 TEST_F(SSLClientSocketTest
, Read_ManySmallRecords
) {
1827 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1828 SpawnedTestServer::kLocalhost
,
1830 ASSERT_TRUE(test_server
.Start());
1833 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1835 TestCompletionCallback callback
;
1837 scoped_ptr
<StreamSocket
> real_transport(
1838 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1839 scoped_ptr
<ReadBufferingStreamSocket
> transport(
1840 new ReadBufferingStreamSocket(real_transport
.Pass()));
1841 ReadBufferingStreamSocket
* raw_transport
= transport
.get();
1842 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1845 scoped_ptr
<SSLClientSocket
> sock(
1846 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
1847 test_server
.host_port_pair(),
1848 kDefaultSSLConfig
));
1850 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1852 ASSERT_TRUE(sock
->IsConnected());
1854 const char request_text
[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
1855 scoped_refptr
<IOBuffer
> request_buffer(
1856 new IOBuffer(arraysize(request_text
) - 1));
1857 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1859 rv
= callback
.GetResult(sock
->Write(
1860 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback()));
1862 ASSERT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1864 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
1865 // data (the max SSL record size) at a time. Ensure that at least 15K worth
1866 // of SSL data is buffered first. The 15K of buffered data is made up of
1867 // many smaller SSL records (the TestServer writes along 1350 byte
1868 // plaintext boundaries), although there may also be a few records that are
1869 // smaller or larger, due to timing and SSL False Start.
1870 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
1871 // the SSLClientSocket implementation, and larger than the minimum amount
1872 // of ciphertext necessary to contain the 8K of plaintext requested below.
1873 raw_transport
->SetBufferSize(15000);
1875 scoped_refptr
<IOBuffer
> buffer(new IOBuffer(8192));
1876 rv
= callback
.GetResult(sock
->Read(buffer
.get(), 8192, callback
.callback()));
1877 ASSERT_EQ(rv
, 8192);
1880 TEST_F(SSLClientSocketTest
, Read_Interrupted
) {
1881 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1882 SpawnedTestServer::kLocalhost
,
1884 ASSERT_TRUE(test_server
.Start());
1887 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1889 TestCompletionCallback callback
;
1890 scoped_ptr
<StreamSocket
> transport(
1891 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1892 int rv
= transport
->Connect(callback
.callback());
1893 if (rv
== ERR_IO_PENDING
)
1894 rv
= callback
.WaitForResult();
1897 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1898 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1900 rv
= sock
->Connect(callback
.callback());
1901 if (rv
== ERR_IO_PENDING
)
1902 rv
= callback
.WaitForResult();
1905 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1906 scoped_refptr
<IOBuffer
> request_buffer(
1907 new IOBuffer(arraysize(request_text
) - 1));
1908 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1911 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1912 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1914 if (rv
== ERR_IO_PENDING
)
1915 rv
= callback
.WaitForResult();
1916 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1918 // Do a partial read and then exit. This test should not crash!
1919 scoped_refptr
<IOBuffer
> buf(new IOBuffer(512));
1920 rv
= sock
->Read(buf
.get(), 512, callback
.callback());
1921 EXPECT_TRUE(rv
> 0 || rv
== ERR_IO_PENDING
);
1923 if (rv
== ERR_IO_PENDING
)
1924 rv
= callback
.WaitForResult();
1929 TEST_F(SSLClientSocketTest
, Read_FullLogging
) {
1930 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1931 SpawnedTestServer::kLocalhost
,
1933 ASSERT_TRUE(test_server
.Start());
1936 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1938 TestCompletionCallback callback
;
1939 CapturingNetLog log
;
1940 log
.SetLogLevel(NetLog::LOG_ALL
);
1941 scoped_ptr
<StreamSocket
> transport(
1942 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1943 int rv
= transport
->Connect(callback
.callback());
1944 if (rv
== ERR_IO_PENDING
)
1945 rv
= callback
.WaitForResult();
1948 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1949 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1951 rv
= sock
->Connect(callback
.callback());
1952 if (rv
== ERR_IO_PENDING
)
1953 rv
= callback
.WaitForResult();
1955 EXPECT_TRUE(sock
->IsConnected());
1957 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1958 scoped_refptr
<IOBuffer
> request_buffer(
1959 new IOBuffer(arraysize(request_text
) - 1));
1960 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1963 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1964 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1966 if (rv
== ERR_IO_PENDING
)
1967 rv
= callback
.WaitForResult();
1968 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1970 CapturingNetLog::CapturedEntryList entries
;
1971 log
.GetEntries(&entries
);
1972 size_t last_index
= ExpectLogContainsSomewhereAfter(
1973 entries
, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, NetLog::PHASE_NONE
);
1975 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1977 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1978 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1980 if (rv
== ERR_IO_PENDING
)
1981 rv
= callback
.WaitForResult();
1987 log
.GetEntries(&entries
);
1989 ExpectLogContainsSomewhereAfter(entries
,
1991 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1992 NetLog::PHASE_NONE
);
1996 // Regression test for http://crbug.com/42538
1997 TEST_F(SSLClientSocketTest
, PrematureApplicationData
) {
1998 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1999 SpawnedTestServer::kLocalhost
,
2001 ASSERT_TRUE(test_server
.Start());
2004 TestCompletionCallback callback
;
2006 static const unsigned char application_data
[] = {
2007 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2008 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2009 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2010 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2011 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2012 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2013 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2014 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2015 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2018 // All reads and writes complete synchronously (async=false).
2019 MockRead data_reads
[] = {
2020 MockRead(SYNCHRONOUS
,
2021 reinterpret_cast<const char*>(application_data
),
2022 arraysize(application_data
)),
2023 MockRead(SYNCHRONOUS
, OK
), };
2025 StaticSocketDataProvider
data(data_reads
, arraysize(data_reads
), NULL
, 0);
2027 scoped_ptr
<StreamSocket
> transport(
2028 new MockTCPClientSocket(addr
, NULL
, &data
));
2029 int rv
= transport
->Connect(callback
.callback());
2030 if (rv
== ERR_IO_PENDING
)
2031 rv
= callback
.WaitForResult();
2034 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2035 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2037 rv
= sock
->Connect(callback
.callback());
2038 if (rv
== ERR_IO_PENDING
)
2039 rv
= callback
.WaitForResult();
2040 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, rv
);
2043 TEST_F(SSLClientSocketTest
, CipherSuiteDisables
) {
2044 // Rather than exhaustively disabling every RC4 ciphersuite defined at
2045 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
2046 // only disabling those cipher suites that the test server actually
2048 const uint16 kCiphersToDisable
[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA
2051 SpawnedTestServer::SSLOptions ssl_options
;
2052 // Enable only RC4 on the test server.
2053 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4
;
2054 SpawnedTestServer
test_server(
2055 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2056 ASSERT_TRUE(test_server
.Start());
2059 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2061 TestCompletionCallback callback
;
2062 CapturingNetLog log
;
2063 scoped_ptr
<StreamSocket
> transport(
2064 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2065 int rv
= transport
->Connect(callback
.callback());
2066 if (rv
== ERR_IO_PENDING
)
2067 rv
= callback
.WaitForResult();
2070 SSLConfig ssl_config
;
2071 for (size_t i
= 0; i
< arraysize(kCiphersToDisable
); ++i
)
2072 ssl_config
.disabled_cipher_suites
.push_back(kCiphersToDisable
[i
]);
2074 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2075 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2077 EXPECT_FALSE(sock
->IsConnected());
2079 rv
= sock
->Connect(callback
.callback());
2080 CapturingNetLog::CapturedEntryList entries
;
2081 log
.GetEntries(&entries
);
2082 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2084 // NSS has special handling that maps a handshake_failure alert received
2085 // immediately after a client_hello to be a mismatched cipher suite error,
2086 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
2087 // Secure Transport (OS X), the handshake_failure is bubbled up without any
2088 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
2089 // indicates that no cipher suite was negotiated with the test server.
2090 if (rv
== ERR_IO_PENDING
)
2091 rv
= callback
.WaitForResult();
2092 EXPECT_TRUE(rv
== ERR_SSL_VERSION_OR_CIPHER_MISMATCH
||
2093 rv
== ERR_SSL_PROTOCOL_ERROR
);
2094 // The exact ordering differs between SSLClientSocketNSS (which issues an
2095 // extra read) and SSLClientSocketMac (which does not). Just make sure the
2096 // error appears somewhere in the log.
2097 log
.GetEntries(&entries
);
2098 ExpectLogContainsSomewhere(
2099 entries
, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR
, NetLog::PHASE_NONE
);
2101 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2102 // the socket when it encounters an error, whereas other implementations
2103 // leave it connected.
2104 // Because this an error that the test server is mutually aware of, as opposed
2105 // to being an error such as a certificate name mismatch, which is
2106 // client-only, the exact index of the SSL connect end depends on how
2107 // quickly the test server closes the underlying socket. If the test server
2108 // closes before the IO message loop pumps messages, there may be a 0-byte
2109 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2110 // result, the SSL connect end event will be the second-to-last entry,
2111 // rather than the last entry.
2112 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1) ||
2113 LogContainsSSLConnectEndEvent(entries
, -2));
2116 // When creating an SSLClientSocket, it is allowed to pass in a
2117 // ClientSocketHandle that is not obtained from a client socket pool.
2118 // Here we verify that such a simple ClientSocketHandle, not associated with any
2119 // client socket pool, can be destroyed safely.
2120 TEST_F(SSLClientSocketTest
, ClientSocketHandleNotFromPool
) {
2121 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2122 SpawnedTestServer::kLocalhost
,
2124 ASSERT_TRUE(test_server
.Start());
2127 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2129 TestCompletionCallback callback
;
2130 scoped_ptr
<StreamSocket
> transport(
2131 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2132 int rv
= transport
->Connect(callback
.callback());
2133 if (rv
== ERR_IO_PENDING
)
2134 rv
= callback
.WaitForResult();
2137 scoped_ptr
<ClientSocketHandle
> socket_handle(new ClientSocketHandle());
2138 socket_handle
->SetSocket(transport
.Pass());
2140 scoped_ptr
<SSLClientSocket
> sock(
2141 socket_factory_
->CreateSSLClientSocket(socket_handle
.Pass(),
2142 test_server
.host_port_pair(),
2146 EXPECT_FALSE(sock
->IsConnected());
2147 rv
= sock
->Connect(callback
.callback());
2148 if (rv
== ERR_IO_PENDING
)
2149 rv
= callback
.WaitForResult();
2153 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2154 // code and different keying label results in different keying material.
2155 TEST_F(SSLClientSocketTest
, ExportKeyingMaterial
) {
2156 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2157 SpawnedTestServer::kLocalhost
,
2159 ASSERT_TRUE(test_server
.Start());
2162 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2164 TestCompletionCallback callback
;
2166 scoped_ptr
<StreamSocket
> transport(
2167 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2168 int rv
= transport
->Connect(callback
.callback());
2169 if (rv
== ERR_IO_PENDING
)
2170 rv
= callback
.WaitForResult();
2173 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2174 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2176 rv
= sock
->Connect(callback
.callback());
2177 if (rv
== ERR_IO_PENDING
)
2178 rv
= callback
.WaitForResult();
2180 EXPECT_TRUE(sock
->IsConnected());
2182 const int kKeyingMaterialSize
= 32;
2183 const char* kKeyingLabel1
= "client-socket-test-1";
2184 const char* kKeyingContext
= "";
2185 unsigned char client_out1
[kKeyingMaterialSize
];
2186 memset(client_out1
, 0, sizeof(client_out1
));
2187 rv
= sock
->ExportKeyingMaterial(
2188 kKeyingLabel1
, false, kKeyingContext
, client_out1
, sizeof(client_out1
));
2191 const char* kKeyingLabel2
= "client-socket-test-2";
2192 unsigned char client_out2
[kKeyingMaterialSize
];
2193 memset(client_out2
, 0, sizeof(client_out2
));
2194 rv
= sock
->ExportKeyingMaterial(
2195 kKeyingLabel2
, false, kKeyingContext
, client_out2
, sizeof(client_out2
));
2197 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2200 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2201 // explicit NSS initialization.
2202 TEST(SSLClientSocket
, ClearSessionCache
) {
2203 SSLClientSocket::ClearSessionCache();
2206 // Test that the server certificates are properly retrieved from the underlying
2208 TEST_F(SSLClientSocketTest
, VerifyServerChainProperlyOrdered
) {
2209 // The connection does not have to be successful.
2210 cert_verifier_
->set_default_result(ERR_CERT_INVALID
);
2212 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2213 // This makes the server present redundant-server-chain.pem, which contains
2214 // intermediate certificates.
2215 SpawnedTestServer::SSLOptions
ssl_options(
2216 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2217 SpawnedTestServer
test_server(
2218 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2219 ASSERT_TRUE(test_server
.Start());
2222 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2224 TestCompletionCallback callback
;
2225 scoped_ptr
<StreamSocket
> transport(
2226 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2227 int rv
= transport
->Connect(callback
.callback());
2228 rv
= callback
.GetResult(rv
);
2231 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2232 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2233 EXPECT_FALSE(sock
->IsConnected());
2234 rv
= sock
->Connect(callback
.callback());
2235 rv
= callback
.GetResult(rv
);
2237 EXPECT_EQ(ERR_CERT_INVALID
, rv
);
2238 EXPECT_TRUE(sock
->IsConnected());
2240 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2241 // certs from redundant-server-chain.pem.
2242 CertificateList server_certs
=
2243 CreateCertificateListFromFile(GetTestCertsDirectory(),
2244 "redundant-server-chain.pem",
2245 X509Certificate::FORMAT_AUTO
);
2247 // Get the server certificate as received client side.
2248 scoped_refptr
<X509Certificate
> server_certificate
=
2249 sock
->GetUnverifiedServerCertificateChain();
2251 // Get the intermediates as received client side.
2252 const X509Certificate::OSCertHandles
& server_intermediates
=
2253 server_certificate
->GetIntermediateCertificates();
2255 // Check that the unverified server certificate chain is properly retrieved
2256 // from the underlying ssl stack.
2257 ASSERT_EQ(4U, server_certs
.size());
2259 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2260 server_certificate
->os_cert_handle(), server_certs
[0]->os_cert_handle()));
2262 ASSERT_EQ(3U, server_intermediates
.size());
2264 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[0],
2265 server_certs
[1]->os_cert_handle()));
2266 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[1],
2267 server_certs
[2]->os_cert_handle()));
2268 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[2],
2269 server_certs
[3]->os_cert_handle()));
2272 EXPECT_FALSE(sock
->IsConnected());
2275 // This tests that SSLInfo contains a properly re-constructed certificate
2276 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2277 // verified, not the chain as served by the server. (They may be different.)
2279 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2280 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2281 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2282 // a self-signed root. Such a situation can occur when a new root (C2) is
2283 // cross-certified by an old root (D) and has two different versions of its
2284 // floating around. Servers may supply C2 as an intermediate, but the
2285 // SSLClientSocket should return the chain that was verified, from
2286 // verify_result, instead.
2287 TEST_F(SSLClientSocketTest
, VerifyReturnChainProperlyOrdered
) {
2288 // By default, cause the CertVerifier to treat all certificates as
2290 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
2292 // We will expect SSLInfo to ultimately contain this chain.
2293 CertificateList certs
=
2294 CreateCertificateListFromFile(GetTestCertsDirectory(),
2295 "redundant-validated-chain.pem",
2296 X509Certificate::FORMAT_AUTO
);
2297 ASSERT_EQ(3U, certs
.size());
2299 X509Certificate::OSCertHandles temp_intermediates
;
2300 temp_intermediates
.push_back(certs
[1]->os_cert_handle());
2301 temp_intermediates
.push_back(certs
[2]->os_cert_handle());
2303 CertVerifyResult verify_result
;
2304 verify_result
.verified_cert
= X509Certificate::CreateFromHandle(
2305 certs
[0]->os_cert_handle(), temp_intermediates
);
2307 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2308 // rather than A->B->C.
2309 cert_verifier_
->AddResultForCert(certs
[0].get(), verify_result
, OK
);
2311 // Load and install the root for the validated chain.
2312 scoped_refptr
<X509Certificate
> root_cert
= ImportCertFromFile(
2313 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2314 ASSERT_NE(static_cast<X509Certificate
*>(NULL
), root_cert
);
2315 ScopedTestRoot
scoped_root(root_cert
.get());
2317 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2318 SpawnedTestServer::SSLOptions
ssl_options(
2319 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2320 SpawnedTestServer
test_server(
2321 SpawnedTestServer::TYPE_HTTPS
,
2323 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2324 ASSERT_TRUE(test_server
.Start());
2327 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2329 TestCompletionCallback callback
;
2330 CapturingNetLog log
;
2331 scoped_ptr
<StreamSocket
> transport(
2332 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2333 int rv
= transport
->Connect(callback
.callback());
2334 if (rv
== ERR_IO_PENDING
)
2335 rv
= callback
.WaitForResult();
2338 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2339 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2340 EXPECT_FALSE(sock
->IsConnected());
2341 rv
= sock
->Connect(callback
.callback());
2343 CapturingNetLog::CapturedEntryList entries
;
2344 log
.GetEntries(&entries
);
2345 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2346 if (rv
== ERR_IO_PENDING
)
2347 rv
= callback
.WaitForResult();
2350 EXPECT_TRUE(sock
->IsConnected());
2351 log
.GetEntries(&entries
);
2352 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
2355 sock
->GetSSLInfo(&ssl_info
);
2357 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2359 const X509Certificate::OSCertHandles
& intermediates
=
2360 ssl_info
.cert
->GetIntermediateCertificates();
2361 ASSERT_EQ(2U, intermediates
.size());
2362 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info
.cert
->os_cert_handle(),
2363 certs
[0]->os_cert_handle()));
2364 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[0],
2365 certs
[1]->os_cert_handle()));
2366 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[1],
2367 certs
[2]->os_cert_handle()));
2370 EXPECT_FALSE(sock
->IsConnected());
2373 TEST_F(SSLClientSocketCertRequestInfoTest
, NoAuthorities
) {
2374 SpawnedTestServer::SSLOptions ssl_options
;
2375 ssl_options
.request_client_certificate
= true;
2376 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2377 ASSERT_TRUE(request_info
.get());
2378 EXPECT_EQ(0u, request_info
->cert_authorities
.size());
2381 TEST_F(SSLClientSocketCertRequestInfoTest
, TwoAuthorities
) {
2382 const base::FilePath::CharType kThawteFile
[] =
2383 FILE_PATH_LITERAL("thawte.single.pem");
2384 const unsigned char kThawteDN
[] = {
2385 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2386 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2387 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2388 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2389 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2390 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2391 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2392 const size_t kThawteLen
= sizeof(kThawteDN
);
2394 const base::FilePath::CharType kDiginotarFile
[] =
2395 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2396 const unsigned char kDiginotarDN
[] = {
2397 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2398 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2399 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2400 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2401 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2402 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2403 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2404 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2406 const size_t kDiginotarLen
= sizeof(kDiginotarDN
);
2408 SpawnedTestServer::SSLOptions ssl_options
;
2409 ssl_options
.request_client_certificate
= true;
2410 ssl_options
.client_authorities
.push_back(
2411 GetTestClientCertsDirectory().Append(kThawteFile
));
2412 ssl_options
.client_authorities
.push_back(
2413 GetTestClientCertsDirectory().Append(kDiginotarFile
));
2414 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2415 ASSERT_TRUE(request_info
.get());
2416 ASSERT_EQ(2u, request_info
->cert_authorities
.size());
2417 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN
), kThawteLen
),
2418 request_info
->cert_authorities
[0]);
2420 std::string(reinterpret_cast<const char*>(kDiginotarDN
), kDiginotarLen
),
2421 request_info
->cert_authorities
[1]);
2424 // cert_key_types is currently only populated on OpenSSL.
2425 #if defined(USE_OPENSSL)
2426 TEST_F(SSLClientSocketCertRequestInfoTest
, CertKeyTypes
) {
2427 SpawnedTestServer::SSLOptions ssl_options
;
2428 ssl_options
.request_client_certificate
= true;
2429 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_RSA_SIGN
);
2430 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_ECDSA_SIGN
);
2431 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2432 ASSERT_TRUE(request_info
.get());
2433 ASSERT_EQ(2u, request_info
->cert_key_types
.size());
2434 EXPECT_EQ(CLIENT_CERT_RSA_SIGN
, request_info
->cert_key_types
[0]);
2435 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN
, request_info
->cert_key_types
[1]);
2437 #endif // defined(USE_OPENSSL)
2439 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledTLSExtension
) {
2440 SpawnedTestServer::SSLOptions ssl_options
;
2441 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2443 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2446 ASSERT_TRUE(test_server
.Start());
2449 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2451 TestCompletionCallback callback
;
2452 CapturingNetLog log
;
2453 scoped_ptr
<StreamSocket
> transport(
2454 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2455 int rv
= transport
->Connect(callback
.callback());
2456 if (rv
== ERR_IO_PENDING
)
2457 rv
= callback
.WaitForResult();
2460 SSLConfig ssl_config
;
2461 ssl_config
.signed_cert_timestamps_enabled
= true;
2463 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2464 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2466 EXPECT_FALSE(sock
->IsConnected());
2468 rv
= sock
->Connect(callback
.callback());
2470 CapturingNetLog::CapturedEntryList entries
;
2471 log
.GetEntries(&entries
);
2472 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2473 if (rv
== ERR_IO_PENDING
)
2474 rv
= callback
.WaitForResult();
2476 EXPECT_TRUE(sock
->IsConnected());
2477 log
.GetEntries(&entries
);
2478 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
2480 #if !defined(USE_OPENSSL)
2481 EXPECT_TRUE(sock
->signed_cert_timestamps_received_
);
2483 // Enabling CT for OpenSSL is currently a noop.
2484 EXPECT_FALSE(sock
->signed_cert_timestamps_received_
);
2488 EXPECT_FALSE(sock
->IsConnected());
2491 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2492 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledOCSP
) {
2493 SpawnedTestServer::SSLOptions ssl_options
;
2494 ssl_options
.staple_ocsp_response
= true;
2495 // The test server currently only knows how to generate OCSP responses
2496 // for a freshly minted certificate.
2497 ssl_options
.server_certificate
= SpawnedTestServer::SSLOptions::CERT_AUTO
;
2499 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2502 ASSERT_TRUE(test_server
.Start());
2505 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2507 TestCompletionCallback callback
;
2508 CapturingNetLog log
;
2509 scoped_ptr
<StreamSocket
> transport(
2510 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2511 int rv
= transport
->Connect(callback
.callback());
2512 if (rv
== ERR_IO_PENDING
)
2513 rv
= callback
.WaitForResult();
2516 SSLConfig ssl_config
;
2517 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2518 // Certificate Transparency verification regardless of whether the platform
2519 // is able to process the OCSP status itself.
2520 ssl_config
.signed_cert_timestamps_enabled
= true;
2522 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2523 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2525 EXPECT_FALSE(sock
->IsConnected());
2527 rv
= sock
->Connect(callback
.callback());
2529 CapturingNetLog::CapturedEntryList entries
;
2530 log
.GetEntries(&entries
);
2531 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2532 if (rv
== ERR_IO_PENDING
)
2533 rv
= callback
.WaitForResult();
2535 EXPECT_TRUE(sock
->IsConnected());
2536 log
.GetEntries(&entries
);
2537 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
2539 #if !defined(USE_OPENSSL)
2540 EXPECT_TRUE(sock
->stapled_ocsp_response_received_
);
2542 // OCSP stapling isn't currently supported in the OpenSSL socket.
2543 EXPECT_FALSE(sock
->stapled_ocsp_response_received_
);
2547 EXPECT_FALSE(sock
->IsConnected());
2550 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsDisabled
) {
2551 SpawnedTestServer::SSLOptions ssl_options
;
2552 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2554 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2557 ASSERT_TRUE(test_server
.Start());
2560 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2562 TestCompletionCallback callback
;
2563 CapturingNetLog log
;
2564 scoped_ptr
<StreamSocket
> transport(
2565 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2566 int rv
= transport
->Connect(callback
.callback());
2567 if (rv
== ERR_IO_PENDING
)
2568 rv
= callback
.WaitForResult();
2571 SSLConfig ssl_config
;
2572 ssl_config
.signed_cert_timestamps_enabled
= false;
2574 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2575 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2577 EXPECT_FALSE(sock
->IsConnected());
2579 rv
= sock
->Connect(callback
.callback());
2581 CapturingNetLog::CapturedEntryList entries
;
2582 log
.GetEntries(&entries
);
2583 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2584 if (rv
== ERR_IO_PENDING
)
2585 rv
= callback
.WaitForResult();
2587 EXPECT_TRUE(sock
->IsConnected());
2588 log
.GetEntries(&entries
);
2589 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
2591 EXPECT_FALSE(sock
->signed_cert_timestamps_received_
);
2594 EXPECT_FALSE(sock
->IsConnected());
2597 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2598 TEST_F(SSLClientSocketTest
, ReuseStates
) {
2599 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2600 SpawnedTestServer::kLocalhost
,
2602 ASSERT_TRUE(test_server
.Start());
2605 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2607 TestCompletionCallback callback
;
2608 scoped_ptr
<StreamSocket
> transport(
2609 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2610 int rv
= transport
->Connect(callback
.callback());
2611 if (rv
== ERR_IO_PENDING
)
2612 rv
= callback
.WaitForResult();
2615 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2616 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2618 rv
= sock
->Connect(callback
.callback());
2619 if (rv
== ERR_IO_PENDING
)
2620 rv
= callback
.WaitForResult();
2623 // The socket was just connected. It should be idle because it is speaking
2624 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2626 EXPECT_TRUE(sock
->IsConnected());
2627 EXPECT_TRUE(sock
->IsConnectedAndIdle());
2628 EXPECT_FALSE(sock
->WasEverUsed());
2630 const char kRequestText
[] = "GET / HTTP/1.0\r\n\r\n";
2631 const size_t kRequestLen
= arraysize(kRequestText
) - 1;
2632 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestLen
));
2633 memcpy(request_buffer
->data(), kRequestText
, kRequestLen
);
2635 rv
= sock
->Write(request_buffer
.get(), kRequestLen
, callback
.callback());
2636 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2638 if (rv
== ERR_IO_PENDING
)
2639 rv
= callback
.WaitForResult();
2640 EXPECT_EQ(static_cast<int>(kRequestLen
), rv
);
2642 // The socket has now been used.
2643 EXPECT_TRUE(sock
->WasEverUsed());
2645 // TODO(davidben): Read one byte to ensure the test server has responded and
2646 // then assert IsConnectedAndIdle is false. This currently doesn't work
2647 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2648 // SSL implementation's internal buffers. Either call PR_Available and
2649 // SSL_pending, although the former isn't actually implemented or perhaps
2650 // attempt to read one byte extra.
2653 #if defined(USE_OPENSSL)
2655 TEST_F(SSLClientSocketTest
, HandshakeCallbackIsRun_WithFailure
) {
2656 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2657 SpawnedTestServer::kLocalhost
,
2659 ASSERT_TRUE(test_server
.Start());
2662 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2664 TestCompletionCallback callback
;
2665 scoped_ptr
<StreamSocket
> real_transport(
2666 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2667 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
2668 new SynchronousErrorStreamSocket(real_transport
.Pass()));
2669 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2672 // Disable TLS False Start to avoid handshake non-determinism.
2673 SSLConfig ssl_config
;
2674 ssl_config
.false_start_enabled
= false;
2676 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
2677 scoped_ptr
<SSLClientSocket
> sock(
2678 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
2679 test_server
.host_port_pair(),
2682 sock
->SetHandshakeCompletionCallback(base::Bind(
2683 &SSLClientSocketTest::RecordCompletedHandshake
, base::Unretained(this)));
2685 raw_transport
->SetNextWriteError(ERR_CONNECTION_RESET
);
2687 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2688 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
2689 EXPECT_FALSE(sock
->IsConnected());
2691 EXPECT_TRUE(ran_handshake_completion_callback_
);
2694 // Tests that the completion callback is run when an SSL connection
2695 // completes successfully.
2696 TEST_F(SSLClientSocketTest
, HandshakeCallbackIsRun_WithSuccess
) {
2697 SpawnedTestServer::SSLOptions ssl_options
;
2698 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2699 SpawnedTestServer::kLocalhost
,
2701 ASSERT_TRUE(test_server
.Start());
2704 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2706 scoped_ptr
<StreamSocket
> transport(
2707 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2709 TestCompletionCallback callback
;
2710 int rv
= transport
->Connect(callback
.callback());
2711 if (rv
== ERR_IO_PENDING
)
2712 rv
= callback
.WaitForResult();
2715 SSLConfig ssl_config
= kDefaultSSLConfig
;
2716 ssl_config
.false_start_enabled
= false;
2718 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2719 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2721 sock
->SetHandshakeCompletionCallback(base::Bind(
2722 &SSLClientSocketTest::RecordCompletedHandshake
, base::Unretained(this)));
2724 if (sock
->IsConnected())
2725 LOG(ERROR
) << "SSL Socket prematurely connected";
2727 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2730 EXPECT_TRUE(sock
->IsConnected());
2731 EXPECT_TRUE(ran_handshake_completion_callback_
);
2734 #endif // defined(USE_OPENSSL)
2736 TEST_F(SSLClientSocketFalseStartTest
, FalseStartEnabled
) {
2737 // False Start requires NPN and a forward-secret cipher suite.
2738 SpawnedTestServer::SSLOptions server_options
;
2739 server_options
.key_exchanges
=
2740 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2741 server_options
.enable_npn
= true;
2742 SSLConfig client_config
;
2743 client_config
.next_protos
.push_back("http/1.1");
2744 ASSERT_NO_FATAL_FAILURE(
2745 TestFalseStart(server_options
, client_config
, true));
2748 // Test that False Start is disabled without NPN.
2749 TEST_F(SSLClientSocketFalseStartTest
, NoNPN
) {
2750 SpawnedTestServer::SSLOptions server_options
;
2751 server_options
.key_exchanges
=
2752 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2753 SSLConfig client_config
;
2754 client_config
.next_protos
.clear();
2755 ASSERT_NO_FATAL_FAILURE(
2756 TestFalseStart(server_options
, client_config
, false));
2759 // Test that False Start is disabled without a forward-secret cipher suite.
2760 TEST_F(SSLClientSocketFalseStartTest
, NoForwardSecrecy
) {
2761 SpawnedTestServer::SSLOptions server_options
;
2762 server_options
.key_exchanges
=
2763 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA
;
2764 server_options
.enable_npn
= true;
2765 SSLConfig client_config
;
2766 client_config
.next_protos
.push_back("http/1.1");
2767 ASSERT_NO_FATAL_FAILURE(
2768 TestFalseStart(server_options
, client_config
, false));
2771 // Test that sessions are resumable after receiving the server Finished message.
2772 TEST_F(SSLClientSocketFalseStartTest
, SessionResumption
) {
2774 SpawnedTestServer::SSLOptions server_options
;
2775 server_options
.key_exchanges
=
2776 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2777 server_options
.enable_npn
= true;
2778 SSLConfig client_config
;
2779 client_config
.next_protos
.push_back("http/1.1");
2781 // Let a full handshake complete with False Start.
2782 ASSERT_NO_FATAL_FAILURE(
2783 TestFalseStart(server_options
, client_config
, true));
2785 // Make a second connection.
2786 TestCompletionCallback callback
;
2787 scoped_ptr
<StreamSocket
> transport2(
2788 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2789 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
2790 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
2791 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
2792 ASSERT_TRUE(sock2
.get());
2793 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
2795 // It should resume the session.
2797 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
2798 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2801 // Test that sessions are not resumable before receiving the server Finished
2803 TEST_F(SSLClientSocketFalseStartTest
, NoSessionResumptionBeforeFinish
) {
2805 SpawnedTestServer::SSLOptions server_options
;
2806 server_options
.key_exchanges
=
2807 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2808 server_options
.enable_npn
= true;
2809 ASSERT_TRUE(StartTestServer(server_options
));
2811 SSLConfig client_config
;
2812 client_config
.next_protos
.push_back("http/1.1");
2814 // Start a handshake up to the server Finished message.
2815 TestCompletionCallback callback
;
2816 FakeBlockingStreamSocket
* raw_transport1
;
2817 scoped_ptr
<SSLClientSocket
> sock1
;
2818 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
2819 client_config
, &callback
, &raw_transport1
, &sock1
));
2820 // Although raw_transport1 has the server Finished blocked, the handshake
2822 EXPECT_EQ(OK
, callback
.WaitForResult());
2824 // Drop the old socket. This is needed because the Python test server can't
2825 // service two sockets in parallel.
2828 // Start a second connection.
2829 scoped_ptr
<StreamSocket
> transport2(
2830 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2831 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
2832 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
2833 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
2834 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
2836 // No session resumption because the first connection never received a server
2837 // Finished message.
2839 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
2840 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2843 // Connect to a server using channel id. It should allow the connection.
2844 TEST_F(SSLClientSocketChannelIDTest
, SendChannelID
) {
2845 SpawnedTestServer::SSLOptions ssl_options
;
2847 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
2850 SSLConfig ssl_config
= kDefaultSSLConfig
;
2851 ssl_config
.channel_id_enabled
= true;
2854 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
2857 EXPECT_TRUE(sock_
->IsConnected());
2858 EXPECT_TRUE(sock_
->WasChannelIDSent());
2860 sock_
->Disconnect();
2861 EXPECT_FALSE(sock_
->IsConnected());
2864 // Connect to a server using Channel ID but failing to look up the Channel
2865 // ID. It should fail.
2866 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelID
) {
2867 SpawnedTestServer::SSLOptions ssl_options
;
2869 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
2871 EnableFailingChannelID();
2872 SSLConfig ssl_config
= kDefaultSSLConfig
;
2873 ssl_config
.channel_id_enabled
= true;
2876 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
2878 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
2879 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
2880 // error codes for now.
2881 // http://crbug.com/373670
2883 EXPECT_FALSE(sock_
->IsConnected());
2886 // Connect to a server using Channel ID but asynchronously failing to look up
2887 // the Channel ID. It should fail.
2888 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelIDAsync
) {
2889 SpawnedTestServer::SSLOptions ssl_options
;
2891 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
2893 EnableAsyncFailingChannelID();
2894 SSLConfig ssl_config
= kDefaultSSLConfig
;
2895 ssl_config
.channel_id_enabled
= true;
2898 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
2900 EXPECT_EQ(ERR_UNEXPECTED
, rv
);
2901 EXPECT_FALSE(sock_
->IsConnected());