Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / net / socket / ssl_client_socket_unittest.cc
blobf695e27c240f9edff7d8f4397f9f32f854190f2d
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 //-----------------------------------------------------------------------------
37 namespace net {
39 namespace {
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
45 // transport.
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'
48 // StreamSocket.
49 class WrappedStreamSocket : public StreamSocket {
50 public:
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,
99 int buf_len,
100 const CompletionCallback& callback) OVERRIDE {
101 return transport_->Read(buf, buf_len, callback);
103 virtual int Write(IOBuffer* buf,
104 int buf_len,
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);
115 protected:
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 {
126 public:
127 explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
128 virtual ~ReadBufferingStreamSocket() {}
130 // Socket implementation:
131 virtual int Read(IOBuffer* buf,
132 int buf_len,
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);
144 private:
145 enum State {
146 STATE_NONE,
147 STATE_READ,
148 STATE_READ_COMPLETE,
151 int DoLoop(int result);
152 int DoRead();
153 int DoReadComplete(int result);
154 void OnReadCompleted(int result);
156 State state_;
157 scoped_refptr<GrowableIOBuffer> read_buffer_;
158 int buffer_size_;
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()),
168 buffer_size_(0) {}
170 void ReadBufferingStreamSocket::SetBufferSize(int size) {
171 DCHECK(!user_read_buf_.get());
172 buffer_size_ = size;
173 read_buffer_->SetCapacity(size);
176 int ReadBufferingStreamSocket::Read(IOBuffer* buf,
177 int buf_len,
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;
185 state_ = STATE_READ;
186 user_read_buf_ = buf;
187 int result = DoLoop(OK);
188 if (result == ERR_IO_PENDING)
189 user_read_callback_ = callback;
190 else
191 user_read_buf_ = NULL;
192 return result;
195 int ReadBufferingStreamSocket::DoLoop(int result) {
196 int rv = result;
197 do {
198 State current_state = state_;
199 state_ = STATE_NONE;
200 switch (current_state) {
201 case STATE_READ:
202 rv = DoRead();
203 break;
204 case STATE_READ_COMPLETE:
205 rv = DoReadComplete(rv);
206 break;
207 case STATE_NONE:
208 default:
209 NOTREACHED() << "Unexpected state: " << current_state;
210 rv = ERR_UNEXPECTED;
211 break;
213 } while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
214 return rv;
217 int ReadBufferingStreamSocket::DoRead() {
218 state_ = STATE_READ_COMPLETE;
219 int rv =
220 transport_->Read(read_buffer_.get(),
221 read_buffer_->RemainingCapacity(),
222 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
223 base::Unretained(this)));
224 return rv;
227 int ReadBufferingStreamSocket::DoReadComplete(int result) {
228 state_ = STATE_NONE;
229 if (result <= 0)
230 return result;
232 read_buffer_->set_offset(read_buffer_->offset() + result);
233 if (read_buffer_->RemainingCapacity() > 0) {
234 state_ = STATE_READ;
235 return OK;
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)
248 return;
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 {
256 public:
257 explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
258 virtual ~SynchronousErrorStreamSocket() {}
260 // Socket implementation:
261 virtual int Read(IOBuffer* buf,
262 int buf_len,
263 const CompletionCallback& callback) OVERRIDE;
264 virtual int Write(IOBuffer* buf,
265 int buf_len,
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()
271 // is called again.
272 void SetNextReadError(Error error) {
273 DCHECK_GE(0, 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) {
283 DCHECK_GE(0, error);
284 have_write_error_ = true;
285 pending_write_error_ = error;
288 private:
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,
307 int buf_len,
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,
315 int buf_len,
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
325 // semantics).
326 class FakeBlockingStreamSocket : public WrappedStreamSocket {
327 public:
328 explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
329 virtual ~FakeBlockingStreamSocket() {}
331 // Socket implementation:
332 virtual int Read(IOBuffer* buf,
333 int buf_len,
334 const CompletionCallback& callback) OVERRIDE;
335 virtual int Write(IOBuffer* buf,
336 int buf_len,
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
347 // transport.
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.
355 void BlockWrite();
356 void UnblockWrite();
358 // Waits for the blocked Write() call to be scheduled.
359 void WaitForWrite();
361 // Returns the wrapped stream socket.
362 StreamSocket* transport() { return transport_.get(); }
364 private:
365 // Handles completion from the underlying transport read.
366 void OnReadCompleted(int result);
368 // True if read callbacks are blocked.
369 bool should_block_read_;
371 // The user callback for the pending read call.
372 CompletionCallback pending_read_callback_;
374 // The result for the blocked read callback, or ERR_IO_PENDING if not
375 // completed.
376 int pending_read_result_;
378 // WaitForReadResult() wait loop.
379 scoped_ptr<base::RunLoop> read_loop_;
381 // True if write calls are blocked.
382 bool should_block_write_;
384 // The buffer for the pending write, or NULL if not scheduled.
385 scoped_refptr<IOBuffer> pending_write_buf_;
387 // The callback for the pending write call.
388 CompletionCallback pending_write_callback_;
390 // The length for the pending write, or -1 if not scheduled.
391 int pending_write_len_;
393 // WaitForWrite() wait loop.
394 scoped_ptr<base::RunLoop> write_loop_;
397 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
398 scoped_ptr<StreamSocket> transport)
399 : WrappedStreamSocket(transport.Pass()),
400 should_block_read_(false),
401 pending_read_result_(ERR_IO_PENDING),
402 should_block_write_(false),
403 pending_write_len_(-1) {}
405 int FakeBlockingStreamSocket::Read(IOBuffer* buf,
406 int len,
407 const CompletionCallback& callback) {
408 DCHECK(pending_read_callback_.is_null());
409 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
410 DCHECK(!callback.is_null());
412 int rv = transport_->Read(buf, len, base::Bind(
413 &FakeBlockingStreamSocket::OnReadCompleted, base::Unretained(this)));
414 if (rv == ERR_IO_PENDING) {
415 // Save the callback to be called later.
416 pending_read_callback_ = callback;
417 } else if (should_block_read_) {
418 // Save the callback and read result to be called later.
419 pending_read_callback_ = callback;
420 OnReadCompleted(rv);
421 rv = ERR_IO_PENDING;
423 return rv;
426 int FakeBlockingStreamSocket::Write(IOBuffer* buf,
427 int len,
428 const CompletionCallback& callback) {
429 DCHECK(buf);
430 DCHECK_LE(0, len);
432 if (!should_block_write_)
433 return transport_->Write(buf, len, callback);
435 // Schedule the write, but do nothing.
436 DCHECK(!pending_write_buf_.get());
437 DCHECK_EQ(-1, pending_write_len_);
438 DCHECK(pending_write_callback_.is_null());
439 DCHECK(!callback.is_null());
440 pending_write_buf_ = buf;
441 pending_write_len_ = len;
442 pending_write_callback_ = callback;
444 // Stop the write loop, if any.
445 if (write_loop_)
446 write_loop_->Quit();
447 return ERR_IO_PENDING;
450 void FakeBlockingStreamSocket::BlockReadResult() {
451 DCHECK(!should_block_read_);
452 should_block_read_ = true;
455 void FakeBlockingStreamSocket::UnblockReadResult() {
456 DCHECK(should_block_read_);
457 should_block_read_ = false;
459 // If the operation is still pending in the underlying transport, immediately
460 // return - OnReadCompleted() will handle invoking the callback once the
461 // transport has completed.
462 if (pending_read_result_ == ERR_IO_PENDING)
463 return;
464 int result = pending_read_result_;
465 pending_read_result_ = ERR_IO_PENDING;
466 base::ResetAndReturn(&pending_read_callback_).Run(result);
469 void FakeBlockingStreamSocket::WaitForReadResult() {
470 DCHECK(should_block_read_);
471 DCHECK(!read_loop_);
473 if (pending_read_result_ != ERR_IO_PENDING)
474 return;
475 read_loop_.reset(new base::RunLoop);
476 read_loop_->Run();
477 read_loop_.reset();
478 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
481 void FakeBlockingStreamSocket::BlockWrite() {
482 DCHECK(!should_block_write_);
483 should_block_write_ = true;
486 void FakeBlockingStreamSocket::UnblockWrite() {
487 DCHECK(should_block_write_);
488 should_block_write_ = false;
490 // Do nothing if UnblockWrite() was called after BlockWrite(),
491 // without a Write() in between.
492 if (!pending_write_buf_.get())
493 return;
495 int rv = transport_->Write(
496 pending_write_buf_.get(), pending_write_len_, pending_write_callback_);
497 pending_write_buf_ = NULL;
498 pending_write_len_ = -1;
499 if (rv == ERR_IO_PENDING) {
500 pending_write_callback_.Reset();
501 } else {
502 base::ResetAndReturn(&pending_write_callback_).Run(rv);
506 void FakeBlockingStreamSocket::WaitForWrite() {
507 DCHECK(should_block_write_);
508 DCHECK(!write_loop_);
510 if (pending_write_buf_.get())
511 return;
512 write_loop_.reset(new base::RunLoop);
513 write_loop_->Run();
514 write_loop_.reset();
515 DCHECK(pending_write_buf_.get());
518 void FakeBlockingStreamSocket::OnReadCompleted(int result) {
519 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
520 DCHECK(!pending_read_callback_.is_null());
522 if (should_block_read_) {
523 // Store the result so that the callback can be invoked once Unblock() is
524 // called.
525 pending_read_result_ = result;
527 // Stop the WaitForReadResult() call if any.
528 if (read_loop_)
529 read_loop_->Quit();
530 } else {
531 // Either the Read() was never blocked or UnblockReadResult() was called
532 // before the Read() completed. Either way, run the callback.
533 base::ResetAndReturn(&pending_read_callback_).Run(result);
537 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
538 // reads and writes on the socket.
539 class CountingStreamSocket : public WrappedStreamSocket {
540 public:
541 explicit CountingStreamSocket(scoped_ptr<StreamSocket> transport)
542 : WrappedStreamSocket(transport.Pass()),
543 read_count_(0),
544 write_count_(0) {}
545 virtual ~CountingStreamSocket() {}
547 // Socket implementation:
548 virtual int Read(IOBuffer* buf,
549 int buf_len,
550 const CompletionCallback& callback) OVERRIDE {
551 read_count_++;
552 return transport_->Read(buf, buf_len, callback);
554 virtual int Write(IOBuffer* buf,
555 int buf_len,
556 const CompletionCallback& callback) OVERRIDE {
557 write_count_++;
558 return transport_->Write(buf, buf_len, callback);
561 int read_count() const { return read_count_; }
562 int write_count() const { return write_count_; }
564 private:
565 int read_count_;
566 int write_count_;
569 // CompletionCallback that will delete the associated StreamSocket when
570 // the callback is invoked.
571 class DeleteSocketCallback : public TestCompletionCallbackBase {
572 public:
573 explicit DeleteSocketCallback(StreamSocket* socket)
574 : socket_(socket),
575 callback_(base::Bind(&DeleteSocketCallback::OnComplete,
576 base::Unretained(this))) {}
577 virtual ~DeleteSocketCallback() {}
579 const CompletionCallback& callback() const { return callback_; }
581 private:
582 void OnComplete(int result) {
583 if (socket_) {
584 delete socket_;
585 socket_ = NULL;
586 } else {
587 ADD_FAILURE() << "Deleting socket twice";
589 SetResult(result);
592 StreamSocket* socket_;
593 CompletionCallback callback_;
595 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
598 // A ChannelIDStore that always returns an error when asked for a
599 // channel id.
600 class FailingChannelIDStore : public ChannelIDStore {
601 virtual int GetChannelID(const std::string& server_identifier,
602 base::Time* expiration_time,
603 std::string* private_key_result,
604 std::string* cert_result,
605 const GetChannelIDCallback& callback) OVERRIDE {
606 return ERR_UNEXPECTED;
608 virtual void SetChannelID(const std::string& server_identifier,
609 base::Time creation_time,
610 base::Time expiration_time,
611 const std::string& private_key,
612 const std::string& cert) OVERRIDE {}
613 virtual void DeleteChannelID(const std::string& server_identifier,
614 const base::Closure& completion_callback)
615 OVERRIDE {}
616 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
617 base::Time delete_end,
618 const base::Closure& completion_callback)
619 OVERRIDE {}
620 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
621 virtual void GetAllChannelIDs(const GetChannelIDListCallback& callback)
622 OVERRIDE {}
623 virtual int GetChannelIDCount() OVERRIDE { return 0; }
624 virtual void SetForceKeepSessionState() OVERRIDE {}
627 // A ChannelIDStore that asynchronously returns an error when asked for a
628 // channel id.
629 class AsyncFailingChannelIDStore : public ChannelIDStore {
630 virtual int GetChannelID(const std::string& server_identifier,
631 base::Time* expiration_time,
632 std::string* private_key_result,
633 std::string* cert_result,
634 const GetChannelIDCallback& callback) OVERRIDE {
635 base::MessageLoop::current()->PostTask(
636 FROM_HERE, base::Bind(callback, ERR_UNEXPECTED,
637 server_identifier, base::Time(), "", ""));
638 return ERR_IO_PENDING;
640 virtual void SetChannelID(const std::string& server_identifier,
641 base::Time creation_time,
642 base::Time expiration_time,
643 const std::string& private_key,
644 const std::string& cert) OVERRIDE {}
645 virtual void DeleteChannelID(const std::string& server_identifier,
646 const base::Closure& completion_callback)
647 OVERRIDE {}
648 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
649 base::Time delete_end,
650 const base::Closure& completion_callback)
651 OVERRIDE {}
652 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
653 virtual void GetAllChannelIDs(const GetChannelIDListCallback& callback)
654 OVERRIDE {}
655 virtual int GetChannelIDCount() OVERRIDE { return 0; }
656 virtual void SetForceKeepSessionState() OVERRIDE {}
659 class SSLClientSocketTest : public PlatformTest {
660 public:
661 SSLClientSocketTest()
662 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
663 cert_verifier_(new MockCertVerifier),
664 transport_security_state_(new TransportSecurityState),
665 ran_handshake_completion_callback_(false) {
666 cert_verifier_->set_default_result(OK);
667 context_.cert_verifier = cert_verifier_.get();
668 context_.transport_security_state = transport_security_state_.get();
671 void RecordCompletedHandshake() { ran_handshake_completion_callback_ = true; }
673 protected:
674 // The address of the spawned test server, after calling StartTestServer().
675 const AddressList& addr() const { return addr_; }
677 // The SpawnedTestServer object, after calling StartTestServer().
678 const SpawnedTestServer* test_server() const { return test_server_.get(); }
680 // Starts the test server with SSL configuration |ssl_options|. Returns true
681 // on success.
682 bool StartTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
683 test_server_.reset(new SpawnedTestServer(
684 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()));
685 if (!test_server_->Start()) {
686 LOG(ERROR) << "Could not start SpawnedTestServer";
687 return false;
690 if (!test_server_->GetAddressList(&addr_)) {
691 LOG(ERROR) << "Could not get SpawnedTestServer address list";
692 return false;
694 return true;
697 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
698 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
699 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
700 if (!StartTestServer(ssl_options))
701 return false;
703 transport_.reset(new TCPClientSocket(addr_, &log_, NetLog::Source()));
704 int rv = callback_.GetResult(transport_->Connect(callback_.callback()));
705 if (rv != OK) {
706 LOG(ERROR) << "Could not connect to SpawnedTestServer";
707 return false;
709 return true;
712 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
713 scoped_ptr<StreamSocket> transport_socket,
714 const HostPortPair& host_and_port,
715 const SSLConfig& ssl_config) {
716 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
717 connection->SetSocket(transport_socket.Pass());
718 return socket_factory_->CreateSSLClientSocket(
719 connection.Pass(), host_and_port, ssl_config, context_);
722 // Create an SSLClientSocket object and use it to connect to a test
723 // server, then wait for connection results. This must be called after
724 // a successful ConnectToTestServer() call.
725 // |ssl_config| the SSL configuration to use.
726 // |result| will retrieve the ::Connect() result value.
727 // Returns true on success, false otherwise. Success means that the socket
728 // could be created and its Connect() was called, not that the connection
729 // itself was a success.
730 bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config, int* result) {
731 sock_ = CreateSSLClientSocket(
732 transport_.Pass(), test_server_->host_port_pair(), ssl_config);
734 if (sock_->IsConnected()) {
735 LOG(ERROR) << "SSL Socket prematurely connected";
736 return false;
739 *result = callback_.GetResult(sock_->Connect(callback_.callback()));
740 return true;
743 ClientSocketFactory* socket_factory_;
744 scoped_ptr<MockCertVerifier> cert_verifier_;
745 scoped_ptr<TransportSecurityState> transport_security_state_;
746 SSLClientSocketContext context_;
747 scoped_ptr<SSLClientSocket> sock_;
748 CapturingNetLog log_;
749 bool ran_handshake_completion_callback_;
751 private:
752 scoped_ptr<StreamSocket> transport_;
753 scoped_ptr<SpawnedTestServer> test_server_;
754 TestCompletionCallback callback_;
755 AddressList addr_;
758 // Verifies the correctness of GetSSLCertRequestInfo.
759 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
760 protected:
761 // Creates a test server with the given SSLOptions, connects to it and returns
762 // the SSLCertRequestInfo reported by the socket.
763 scoped_refptr<SSLCertRequestInfo> GetCertRequest(
764 SpawnedTestServer::SSLOptions ssl_options) {
765 SpawnedTestServer test_server(
766 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
767 if (!test_server.Start())
768 return NULL;
770 AddressList addr;
771 if (!test_server.GetAddressList(&addr))
772 return NULL;
774 TestCompletionCallback callback;
775 CapturingNetLog log;
776 scoped_ptr<StreamSocket> transport(
777 new TCPClientSocket(addr, &log, NetLog::Source()));
778 int rv = transport->Connect(callback.callback());
779 if (rv == ERR_IO_PENDING)
780 rv = callback.WaitForResult();
781 EXPECT_EQ(OK, rv);
783 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
784 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
785 EXPECT_FALSE(sock->IsConnected());
787 rv = sock->Connect(callback.callback());
788 if (rv == ERR_IO_PENDING)
789 rv = callback.WaitForResult();
790 scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo();
791 sock->GetSSLCertRequestInfo(request_info.get());
792 sock->Disconnect();
793 EXPECT_FALSE(sock->IsConnected());
794 EXPECT_TRUE(
795 test_server.host_port_pair().Equals(request_info->host_and_port));
797 return request_info;
801 class SSLClientSocketFalseStartTest : public SSLClientSocketTest {
802 public:
803 SSLClientSocketFalseStartTest()
804 : monitor_handshake_callback_(false),
805 fail_handshake_after_false_start_(false) {}
807 protected:
808 // Creates an SSLClientSocket with |client_config| attached to a
809 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
810 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
811 // so |*out_raw_transport| is a raw pointer.
813 // The client socket will begin a connect using |callback| but stop before the
814 // server's finished message is received. The finished message will be blocked
815 // in |*out_raw_transport|. To complete the handshake and successfully read
816 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
817 // the client successfully false started, |callback.WaitForResult()| will
818 // return OK without unblocking transport reads. But Read() will still block.)
820 // Must be called after StartTestServer is called.
821 void CreateAndConnectUntilServerFinishedReceived(
822 const SSLConfig& client_config,
823 TestCompletionCallback* callback,
824 FakeBlockingStreamSocket** out_raw_transport,
825 scoped_ptr<SSLClientSocket>* out_sock) {
826 CHECK(test_server());
828 scoped_ptr<StreamSocket> real_transport(scoped_ptr<StreamSocket>(
829 new TCPClientSocket(addr(), NULL, NetLog::Source())));
830 real_transport.reset(
831 new SynchronousErrorStreamSocket(real_transport.Pass()));
833 scoped_ptr<FakeBlockingStreamSocket> transport(
834 new FakeBlockingStreamSocket(real_transport.Pass()));
835 int rv = callback->GetResult(transport->Connect(callback->callback()));
836 EXPECT_EQ(OK, rv);
838 FakeBlockingStreamSocket* raw_transport = transport.get();
839 scoped_ptr<SSLClientSocket> sock =
840 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
841 test_server()->host_port_pair(),
842 client_config);
844 if (monitor_handshake_callback_) {
845 sock->SetHandshakeCompletionCallback(
846 base::Bind(&SSLClientSocketTest::RecordCompletedHandshake,
847 base::Unretained(this)));
850 // Connect. Stop before the client processes the first server leg
851 // (ServerHello, etc.)
852 raw_transport->BlockReadResult();
853 rv = sock->Connect(callback->callback());
854 EXPECT_EQ(ERR_IO_PENDING, rv);
855 raw_transport->WaitForReadResult();
857 // Release the ServerHello and wait for the client to write
858 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
859 // server's leg to complete, since it may span multiple reads.)
860 EXPECT_FALSE(callback->have_result());
861 raw_transport->BlockWrite();
862 raw_transport->UnblockReadResult();
863 raw_transport->WaitForWrite();
865 if (fail_handshake_after_false_start_) {
866 SynchronousErrorStreamSocket* error_socket =
867 static_cast<SynchronousErrorStreamSocket*>(
868 raw_transport->transport());
869 error_socket->SetNextReadError(ERR_CONNECTION_RESET);
871 // And, finally, release that and block the next server leg
872 // (ChangeCipherSpec, Finished).
873 raw_transport->BlockReadResult();
874 raw_transport->UnblockWrite();
876 *out_raw_transport = raw_transport;
877 *out_sock = sock.Pass();
880 void TestFalseStart(const SpawnedTestServer::SSLOptions& server_options,
881 const SSLConfig& client_config,
882 bool expect_false_start) {
883 ASSERT_TRUE(StartTestServer(server_options));
885 TestCompletionCallback callback;
886 FakeBlockingStreamSocket* raw_transport = NULL;
887 scoped_ptr<SSLClientSocket> sock;
889 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
890 client_config, &callback, &raw_transport, &sock));
892 if (expect_false_start) {
893 // When False Starting, the handshake should complete before receiving the
894 // Change Cipher Spec and Finished messages.
896 // Note: callback.have_result() may not be true without waiting. The NSS
897 // state machine sometimes lives on a separate thread, so this thread may
898 // not yet have processed the signal that the handshake has completed.
899 int rv = callback.WaitForResult();
900 EXPECT_EQ(OK, rv);
901 EXPECT_TRUE(sock->IsConnected());
903 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
904 static const int kRequestTextSize =
905 static_cast<int>(arraysize(request_text) - 1);
906 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
907 memcpy(request_buffer->data(), request_text, kRequestTextSize);
909 // Write the request.
910 rv = callback.GetResult(sock->Write(request_buffer.get(),
911 kRequestTextSize,
912 callback.callback()));
913 EXPECT_EQ(kRequestTextSize, rv);
915 // The read will hang; it's waiting for the peer to complete the
916 // handshake, and the handshake is still blocked.
917 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
918 rv = sock->Read(buf.get(), 4096, callback.callback());
920 // After releasing reads, the connection proceeds.
921 raw_transport->UnblockReadResult();
922 rv = callback.GetResult(rv);
923 if (fail_handshake_after_false_start_)
924 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
925 else
926 EXPECT_LT(0, rv);
927 } else {
928 // False Start is not enabled, so the handshake will not complete because
929 // the server second leg is blocked.
930 base::RunLoop().RunUntilIdle();
931 EXPECT_FALSE(callback.have_result());
935 // Indicates that the socket's handshake completion callback should
936 // be monitored.
937 bool monitor_handshake_callback_;
938 // Indicates that this test's handshake should fail after the client
939 // "finished" message is sent.
940 bool fail_handshake_after_false_start_;
943 class SSLClientSocketChannelIDTest : public SSLClientSocketTest {
944 protected:
945 void EnableChannelID() {
946 channel_id_service_.reset(
947 new ChannelIDService(new DefaultChannelIDStore(NULL),
948 base::MessageLoopProxy::current()));
949 context_.channel_id_service = channel_id_service_.get();
952 void EnableFailingChannelID() {
953 channel_id_service_.reset(new ChannelIDService(
954 new FailingChannelIDStore(), base::MessageLoopProxy::current()));
955 context_.channel_id_service = channel_id_service_.get();
958 void EnableAsyncFailingChannelID() {
959 channel_id_service_.reset(new ChannelIDService(
960 new AsyncFailingChannelIDStore(),
961 base::MessageLoopProxy::current()));
962 context_.channel_id_service = channel_id_service_.get();
965 private:
966 scoped_ptr<ChannelIDService> channel_id_service_;
969 //-----------------------------------------------------------------------------
971 // LogContainsSSLConnectEndEvent returns true if the given index in the given
972 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
973 // merge the first application data record with the Finished message when false
974 // starting. However, in order to avoid the server timing out the handshake,
975 // they'll give up waiting for application data and send the Finished after a
976 // timeout. This means that an SSL connect end event may appear as a socket
977 // write.
978 static bool LogContainsSSLConnectEndEvent(
979 const CapturingNetLog::CapturedEntryList& log,
980 int i) {
981 return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) ||
982 LogContainsEvent(
983 log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
986 } // namespace
988 TEST_F(SSLClientSocketTest, Connect) {
989 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
990 SpawnedTestServer::kLocalhost,
991 base::FilePath());
992 ASSERT_TRUE(test_server.Start());
994 AddressList addr;
995 ASSERT_TRUE(test_server.GetAddressList(&addr));
997 TestCompletionCallback callback;
998 CapturingNetLog log;
999 scoped_ptr<StreamSocket> transport(
1000 new TCPClientSocket(addr, &log, NetLog::Source()));
1001 int rv = transport->Connect(callback.callback());
1002 if (rv == ERR_IO_PENDING)
1003 rv = callback.WaitForResult();
1004 EXPECT_EQ(OK, rv);
1006 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1007 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1009 EXPECT_FALSE(sock->IsConnected());
1011 rv = sock->Connect(callback.callback());
1013 CapturingNetLog::CapturedEntryList entries;
1014 log.GetEntries(&entries);
1015 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1016 if (rv == ERR_IO_PENDING)
1017 rv = callback.WaitForResult();
1018 EXPECT_EQ(OK, rv);
1019 EXPECT_TRUE(sock->IsConnected());
1020 log.GetEntries(&entries);
1021 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1023 sock->Disconnect();
1024 EXPECT_FALSE(sock->IsConnected());
1027 TEST_F(SSLClientSocketTest, ConnectExpired) {
1028 SpawnedTestServer::SSLOptions ssl_options(
1029 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
1030 SpawnedTestServer test_server(
1031 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1032 ASSERT_TRUE(test_server.Start());
1034 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
1036 AddressList addr;
1037 ASSERT_TRUE(test_server.GetAddressList(&addr));
1039 TestCompletionCallback callback;
1040 CapturingNetLog log;
1041 scoped_ptr<StreamSocket> transport(
1042 new TCPClientSocket(addr, &log, NetLog::Source()));
1043 int rv = transport->Connect(callback.callback());
1044 if (rv == ERR_IO_PENDING)
1045 rv = callback.WaitForResult();
1046 EXPECT_EQ(OK, rv);
1048 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1049 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1051 EXPECT_FALSE(sock->IsConnected());
1053 rv = sock->Connect(callback.callback());
1055 CapturingNetLog::CapturedEntryList entries;
1056 log.GetEntries(&entries);
1057 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1058 if (rv == ERR_IO_PENDING)
1059 rv = callback.WaitForResult();
1061 EXPECT_EQ(ERR_CERT_DATE_INVALID, rv);
1063 // Rather than testing whether or not the underlying socket is connected,
1064 // test that the handshake has finished. This is because it may be
1065 // desirable to disconnect the socket before showing a user prompt, since
1066 // the user may take indefinitely long to respond.
1067 log.GetEntries(&entries);
1068 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1071 TEST_F(SSLClientSocketTest, ConnectMismatched) {
1072 SpawnedTestServer::SSLOptions ssl_options(
1073 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
1074 SpawnedTestServer test_server(
1075 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1076 ASSERT_TRUE(test_server.Start());
1078 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
1080 AddressList addr;
1081 ASSERT_TRUE(test_server.GetAddressList(&addr));
1083 TestCompletionCallback callback;
1084 CapturingNetLog log;
1085 scoped_ptr<StreamSocket> transport(
1086 new TCPClientSocket(addr, &log, NetLog::Source()));
1087 int rv = transport->Connect(callback.callback());
1088 if (rv == ERR_IO_PENDING)
1089 rv = callback.WaitForResult();
1090 EXPECT_EQ(OK, rv);
1092 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1093 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1095 EXPECT_FALSE(sock->IsConnected());
1097 rv = sock->Connect(callback.callback());
1099 CapturingNetLog::CapturedEntryList entries;
1100 log.GetEntries(&entries);
1101 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1102 if (rv == ERR_IO_PENDING)
1103 rv = callback.WaitForResult();
1105 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv);
1107 // Rather than testing whether or not the underlying socket is connected,
1108 // test that the handshake has finished. This is because it may be
1109 // desirable to disconnect the socket before showing a user prompt, since
1110 // the user may take indefinitely long to respond.
1111 log.GetEntries(&entries);
1112 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1115 // Attempt to connect to a page which requests a client certificate. It should
1116 // return an error code on connect.
1117 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
1118 SpawnedTestServer::SSLOptions ssl_options;
1119 ssl_options.request_client_certificate = true;
1120 SpawnedTestServer test_server(
1121 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1122 ASSERT_TRUE(test_server.Start());
1124 AddressList addr;
1125 ASSERT_TRUE(test_server.GetAddressList(&addr));
1127 TestCompletionCallback callback;
1128 CapturingNetLog log;
1129 scoped_ptr<StreamSocket> transport(
1130 new TCPClientSocket(addr, &log, NetLog::Source()));
1131 int rv = transport->Connect(callback.callback());
1132 if (rv == ERR_IO_PENDING)
1133 rv = callback.WaitForResult();
1134 EXPECT_EQ(OK, rv);
1136 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1137 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1139 EXPECT_FALSE(sock->IsConnected());
1141 rv = sock->Connect(callback.callback());
1143 CapturingNetLog::CapturedEntryList entries;
1144 log.GetEntries(&entries);
1145 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1146 if (rv == ERR_IO_PENDING)
1147 rv = callback.WaitForResult();
1149 log.GetEntries(&entries);
1150 // Because we prematurely kill the handshake at CertificateRequest,
1151 // the server may still send data (notably the ServerHelloDone)
1152 // after the error is returned. As a result, the SSL_CONNECT may not
1153 // be the last entry. See http://crbug.com/54445. We use
1154 // ExpectLogContainsSomewhere instead of
1155 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
1156 // extra read instead of two. This occurs before the handshake ends,
1157 // so the corking logic of LogContainsSSLConnectEndEvent isn't
1158 // necessary.
1160 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
1161 // fixed and we can respond to the first CertificateRequest
1162 // without closing the socket, add a unit test for sending the
1163 // certificate. This test may still be useful as we'll want to close
1164 // the socket on a timeout if the user takes a long time to pick a
1165 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
1166 ExpectLogContainsSomewhere(
1167 entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END);
1168 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
1169 EXPECT_FALSE(sock->IsConnected());
1172 // Connect to a server requesting optional client authentication. Send it a
1173 // null certificate. It should allow the connection.
1175 // TODO(davidben): Also test providing an actual certificate.
1176 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
1177 SpawnedTestServer::SSLOptions ssl_options;
1178 ssl_options.request_client_certificate = true;
1179 SpawnedTestServer test_server(
1180 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1181 ASSERT_TRUE(test_server.Start());
1183 AddressList addr;
1184 ASSERT_TRUE(test_server.GetAddressList(&addr));
1186 TestCompletionCallback callback;
1187 CapturingNetLog log;
1188 scoped_ptr<StreamSocket> transport(
1189 new TCPClientSocket(addr, &log, NetLog::Source()));
1190 int rv = transport->Connect(callback.callback());
1191 if (rv == ERR_IO_PENDING)
1192 rv = callback.WaitForResult();
1193 EXPECT_EQ(OK, rv);
1195 SSLConfig ssl_config = kDefaultSSLConfig;
1196 ssl_config.send_client_cert = true;
1197 ssl_config.client_cert = NULL;
1199 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1200 transport.Pass(), test_server.host_port_pair(), ssl_config));
1202 EXPECT_FALSE(sock->IsConnected());
1204 // Our test server accepts certificate-less connections.
1205 // TODO(davidben): Add a test which requires them and verify the error.
1206 rv = sock->Connect(callback.callback());
1208 CapturingNetLog::CapturedEntryList entries;
1209 log.GetEntries(&entries);
1210 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1211 if (rv == ERR_IO_PENDING)
1212 rv = callback.WaitForResult();
1214 EXPECT_EQ(OK, rv);
1215 EXPECT_TRUE(sock->IsConnected());
1216 log.GetEntries(&entries);
1217 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1219 // We responded to the server's certificate request with a Certificate
1220 // message with no client certificate in it. ssl_info.client_cert_sent
1221 // should be false in this case.
1222 SSLInfo ssl_info;
1223 sock->GetSSLInfo(&ssl_info);
1224 EXPECT_FALSE(ssl_info.client_cert_sent);
1226 sock->Disconnect();
1227 EXPECT_FALSE(sock->IsConnected());
1230 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1231 // - Server closes an SSL connection (with a close_notify alert message).
1232 // - Server closes the underlying TCP connection directly.
1233 // - Server sends data unexpectedly.
1235 TEST_F(SSLClientSocketTest, Read) {
1236 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1237 SpawnedTestServer::kLocalhost,
1238 base::FilePath());
1239 ASSERT_TRUE(test_server.Start());
1241 AddressList addr;
1242 ASSERT_TRUE(test_server.GetAddressList(&addr));
1244 TestCompletionCallback callback;
1245 scoped_ptr<StreamSocket> transport(
1246 new TCPClientSocket(addr, NULL, NetLog::Source()));
1247 int rv = transport->Connect(callback.callback());
1248 if (rv == ERR_IO_PENDING)
1249 rv = callback.WaitForResult();
1250 EXPECT_EQ(OK, rv);
1252 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1253 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1255 rv = sock->Connect(callback.callback());
1256 if (rv == ERR_IO_PENDING)
1257 rv = callback.WaitForResult();
1258 EXPECT_EQ(OK, rv);
1259 EXPECT_TRUE(sock->IsConnected());
1261 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1262 scoped_refptr<IOBuffer> request_buffer(
1263 new IOBuffer(arraysize(request_text) - 1));
1264 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1266 rv = sock->Write(
1267 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1268 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1270 if (rv == ERR_IO_PENDING)
1271 rv = callback.WaitForResult();
1272 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1274 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1275 for (;;) {
1276 rv = sock->Read(buf.get(), 4096, callback.callback());
1277 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1279 if (rv == ERR_IO_PENDING)
1280 rv = callback.WaitForResult();
1282 EXPECT_GE(rv, 0);
1283 if (rv <= 0)
1284 break;
1288 // Tests that SSLClientSocket properly handles when the underlying transport
1289 // synchronously fails a transport read in during the handshake. The error code
1290 // should be preserved so SSLv3 fallback logic can condition on it.
1291 TEST_F(SSLClientSocketTest, Connect_WithSynchronousError) {
1292 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1293 SpawnedTestServer::kLocalhost,
1294 base::FilePath());
1295 ASSERT_TRUE(test_server.Start());
1297 AddressList addr;
1298 ASSERT_TRUE(test_server.GetAddressList(&addr));
1300 TestCompletionCallback callback;
1301 scoped_ptr<StreamSocket> real_transport(
1302 new TCPClientSocket(addr, NULL, NetLog::Source()));
1303 scoped_ptr<SynchronousErrorStreamSocket> transport(
1304 new SynchronousErrorStreamSocket(real_transport.Pass()));
1305 int rv = callback.GetResult(transport->Connect(callback.callback()));
1306 EXPECT_EQ(OK, rv);
1308 // Disable TLS False Start to avoid handshake non-determinism.
1309 SSLConfig ssl_config;
1310 ssl_config.false_start_enabled = false;
1312 SynchronousErrorStreamSocket* raw_transport = transport.get();
1313 scoped_ptr<SSLClientSocket> sock(
1314 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1315 test_server.host_port_pair(),
1316 ssl_config));
1318 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
1320 rv = callback.GetResult(sock->Connect(callback.callback()));
1321 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1322 EXPECT_FALSE(sock->IsConnected());
1325 // Tests that the SSLClientSocket properly handles when the underlying transport
1326 // synchronously returns an error code - such as if an intermediary terminates
1327 // the socket connection uncleanly.
1328 // This is a regression test for http://crbug.com/238536
1329 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
1330 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1331 SpawnedTestServer::kLocalhost,
1332 base::FilePath());
1333 ASSERT_TRUE(test_server.Start());
1335 AddressList addr;
1336 ASSERT_TRUE(test_server.GetAddressList(&addr));
1338 TestCompletionCallback callback;
1339 scoped_ptr<StreamSocket> real_transport(
1340 new TCPClientSocket(addr, NULL, NetLog::Source()));
1341 scoped_ptr<SynchronousErrorStreamSocket> transport(
1342 new SynchronousErrorStreamSocket(real_transport.Pass()));
1343 int rv = callback.GetResult(transport->Connect(callback.callback()));
1344 EXPECT_EQ(OK, rv);
1346 // Disable TLS False Start to avoid handshake non-determinism.
1347 SSLConfig ssl_config;
1348 ssl_config.false_start_enabled = false;
1350 SynchronousErrorStreamSocket* raw_transport = transport.get();
1351 scoped_ptr<SSLClientSocket> sock(
1352 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1353 test_server.host_port_pair(),
1354 ssl_config));
1356 rv = callback.GetResult(sock->Connect(callback.callback()));
1357 EXPECT_EQ(OK, rv);
1358 EXPECT_TRUE(sock->IsConnected());
1360 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1361 static const int kRequestTextSize =
1362 static_cast<int>(arraysize(request_text) - 1);
1363 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1364 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1366 rv = callback.GetResult(
1367 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1368 EXPECT_EQ(kRequestTextSize, rv);
1370 // Simulate an unclean/forcible shutdown.
1371 raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
1373 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1375 // Note: This test will hang if this bug has regressed. Simply checking that
1376 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1377 // result when using a dedicated task runner for NSS.
1378 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1379 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1382 // Tests that the SSLClientSocket properly handles when the underlying transport
1383 // asynchronously returns an error code while writing data - such as if an
1384 // intermediary terminates the socket connection uncleanly.
1385 // This is a regression test for http://crbug.com/249848
1386 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
1387 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1388 SpawnedTestServer::kLocalhost,
1389 base::FilePath());
1390 ASSERT_TRUE(test_server.Start());
1392 AddressList addr;
1393 ASSERT_TRUE(test_server.GetAddressList(&addr));
1395 TestCompletionCallback callback;
1396 scoped_ptr<StreamSocket> real_transport(
1397 new TCPClientSocket(addr, NULL, NetLog::Source()));
1398 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1399 // is retained in order to configure additional errors.
1400 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1401 new SynchronousErrorStreamSocket(real_transport.Pass()));
1402 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1403 scoped_ptr<FakeBlockingStreamSocket> transport(
1404 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1405 FakeBlockingStreamSocket* raw_transport = transport.get();
1406 int rv = callback.GetResult(transport->Connect(callback.callback()));
1407 EXPECT_EQ(OK, rv);
1409 // Disable TLS False Start to avoid handshake non-determinism.
1410 SSLConfig ssl_config;
1411 ssl_config.false_start_enabled = false;
1413 scoped_ptr<SSLClientSocket> sock(
1414 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1415 test_server.host_port_pair(),
1416 ssl_config));
1418 rv = callback.GetResult(sock->Connect(callback.callback()));
1419 EXPECT_EQ(OK, rv);
1420 EXPECT_TRUE(sock->IsConnected());
1422 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1423 static const int kRequestTextSize =
1424 static_cast<int>(arraysize(request_text) - 1);
1425 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1426 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1428 // Simulate an unclean/forcible shutdown on the underlying socket.
1429 // However, simulate this error asynchronously.
1430 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1431 raw_transport->BlockWrite();
1433 // This write should complete synchronously, because the TLS ciphertext
1434 // can be created and placed into the outgoing buffers independent of the
1435 // underlying transport.
1436 rv = callback.GetResult(
1437 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1438 EXPECT_EQ(kRequestTextSize, rv);
1440 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1442 rv = sock->Read(buf.get(), 4096, callback.callback());
1443 EXPECT_EQ(ERR_IO_PENDING, rv);
1445 // Now unblock the outgoing request, having it fail with the connection
1446 // being reset.
1447 raw_transport->UnblockWrite();
1449 // Note: This will cause an inifite loop if this bug has regressed. Simply
1450 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1451 // is a legitimate result when using a dedicated task runner for NSS.
1452 rv = callback.GetResult(rv);
1453 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1456 // If there is a Write failure at the transport with no follow-up Read, although
1457 // the write error will not be returned to the client until a future Read or
1458 // Write operation, SSLClientSocket should not spin attempting to re-write on
1459 // the socket. This is a regression test for part of https://crbug.com/381160.
1460 TEST_F(SSLClientSocketTest, Write_WithSynchronousErrorNoRead) {
1461 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1462 SpawnedTestServer::kLocalhost,
1463 base::FilePath());
1464 ASSERT_TRUE(test_server.Start());
1466 AddressList addr;
1467 ASSERT_TRUE(test_server.GetAddressList(&addr));
1469 TestCompletionCallback callback;
1470 scoped_ptr<StreamSocket> real_transport(
1471 new TCPClientSocket(addr, NULL, NetLog::Source()));
1472 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1473 // is retained in order to query them.
1474 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1475 new SynchronousErrorStreamSocket(real_transport.Pass()));
1476 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1477 scoped_ptr<CountingStreamSocket> counting_socket(
1478 new CountingStreamSocket(error_socket.PassAs<StreamSocket>()));
1479 CountingStreamSocket* raw_counting_socket = counting_socket.get();
1480 int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
1481 ASSERT_EQ(OK, rv);
1483 // Disable TLS False Start to avoid handshake non-determinism.
1484 SSLConfig ssl_config;
1485 ssl_config.false_start_enabled = false;
1487 scoped_ptr<SSLClientSocket> sock(
1488 CreateSSLClientSocket(counting_socket.PassAs<StreamSocket>(),
1489 test_server.host_port_pair(),
1490 ssl_config));
1492 rv = callback.GetResult(sock->Connect(callback.callback()));
1493 ASSERT_EQ(OK, rv);
1494 ASSERT_TRUE(sock->IsConnected());
1496 // Simulate an unclean/forcible shutdown on the underlying socket.
1497 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1499 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1500 static const int kRequestTextSize =
1501 static_cast<int>(arraysize(request_text) - 1);
1502 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1503 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1505 // This write should complete synchronously, because the TLS ciphertext
1506 // can be created and placed into the outgoing buffers independent of the
1507 // underlying transport.
1508 rv = callback.GetResult(
1509 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1510 ASSERT_EQ(kRequestTextSize, rv);
1512 // Let the event loop spin for a little bit of time. Even on platforms where
1513 // pumping the state machine involve thread hops, there should be no further
1514 // writes on the transport socket.
1516 // TODO(davidben): Avoid the arbitrary timeout?
1517 int old_write_count = raw_counting_socket->write_count();
1518 base::RunLoop loop;
1519 base::MessageLoop::current()->PostDelayedTask(
1520 FROM_HERE, loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1521 loop.Run();
1522 EXPECT_EQ(old_write_count, raw_counting_socket->write_count());
1525 // Test the full duplex mode, with Read and Write pending at the same time.
1526 // This test also serves as a regression test for http://crbug.com/29815.
1527 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1528 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1529 SpawnedTestServer::kLocalhost,
1530 base::FilePath());
1531 ASSERT_TRUE(test_server.Start());
1533 AddressList addr;
1534 ASSERT_TRUE(test_server.GetAddressList(&addr));
1536 TestCompletionCallback callback; // Used for everything except Write.
1538 scoped_ptr<StreamSocket> transport(
1539 new TCPClientSocket(addr, NULL, NetLog::Source()));
1540 int rv = transport->Connect(callback.callback());
1541 if (rv == ERR_IO_PENDING)
1542 rv = callback.WaitForResult();
1543 EXPECT_EQ(OK, rv);
1545 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1546 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1548 rv = sock->Connect(callback.callback());
1549 if (rv == ERR_IO_PENDING)
1550 rv = callback.WaitForResult();
1551 EXPECT_EQ(OK, rv);
1552 EXPECT_TRUE(sock->IsConnected());
1554 // Issue a "hanging" Read first.
1555 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1556 rv = sock->Read(buf.get(), 4096, callback.callback());
1557 // We haven't written the request, so there should be no response yet.
1558 ASSERT_EQ(ERR_IO_PENDING, rv);
1560 // Write the request.
1561 // The request is padded with a User-Agent header to a size that causes the
1562 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1563 // This tests the fix for http://crbug.com/29815.
1564 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1565 for (int i = 0; i < 3770; ++i)
1566 request_text.push_back('*');
1567 request_text.append("\r\n\r\n");
1568 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1570 TestCompletionCallback callback2; // Used for Write only.
1571 rv = sock->Write(
1572 request_buffer.get(), request_text.size(), callback2.callback());
1573 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1575 if (rv == ERR_IO_PENDING)
1576 rv = callback2.WaitForResult();
1577 EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1579 // Now get the Read result.
1580 rv = callback.WaitForResult();
1581 EXPECT_GT(rv, 0);
1584 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1585 // mode when the underlying transport is blocked on sending data. When the
1586 // underlying transport completes due to an error, it should invoke both the
1587 // Read() and Write() callbacks. If the socket is deleted by the Read()
1588 // callback, the Write() callback should not be invoked.
1589 // Regression test for http://crbug.com/232633
1590 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1591 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1592 SpawnedTestServer::kLocalhost,
1593 base::FilePath());
1594 ASSERT_TRUE(test_server.Start());
1596 AddressList addr;
1597 ASSERT_TRUE(test_server.GetAddressList(&addr));
1599 TestCompletionCallback callback;
1600 scoped_ptr<StreamSocket> real_transport(
1601 new TCPClientSocket(addr, NULL, NetLog::Source()));
1602 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1603 // is retained in order to configure additional errors.
1604 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1605 new SynchronousErrorStreamSocket(real_transport.Pass()));
1606 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1607 scoped_ptr<FakeBlockingStreamSocket> transport(
1608 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1609 FakeBlockingStreamSocket* raw_transport = transport.get();
1611 int rv = callback.GetResult(transport->Connect(callback.callback()));
1612 EXPECT_EQ(OK, rv);
1614 // Disable TLS False Start to avoid handshake non-determinism.
1615 SSLConfig ssl_config;
1616 ssl_config.false_start_enabled = false;
1618 scoped_ptr<SSLClientSocket> sock =
1619 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1620 test_server.host_port_pair(),
1621 ssl_config);
1623 rv = callback.GetResult(sock->Connect(callback.callback()));
1624 EXPECT_EQ(OK, rv);
1625 EXPECT_TRUE(sock->IsConnected());
1627 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1628 request_text.append(20 * 1024, '*');
1629 request_text.append("\r\n\r\n");
1630 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1631 new StringIOBuffer(request_text), request_text.size()));
1633 // Simulate errors being returned from the underlying Read() and Write() ...
1634 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1635 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1636 // ... but have those errors returned asynchronously. Because the Write() will
1637 // return first, this will trigger the error.
1638 raw_transport->BlockReadResult();
1639 raw_transport->BlockWrite();
1641 // Enqueue a Read() before calling Write(), which should "hang" due to
1642 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1643 SSLClientSocket* raw_sock = sock.get();
1644 DeleteSocketCallback read_callback(sock.release());
1645 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1646 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1648 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1649 ASSERT_EQ(ERR_IO_PENDING, rv);
1650 ASSERT_FALSE(read_callback.have_result());
1652 #if !defined(USE_OPENSSL)
1653 // NSS follows a pattern where a call to PR_Write will only consume as
1654 // much data as it can encode into application data records before the
1655 // internal memio buffer is full, which should only fill if writing a large
1656 // amount of data and the underlying transport is blocked. Once this happens,
1657 // NSS will return (total size of all application data records it wrote) - 1,
1658 // with the caller expected to resume with the remaining unsent data.
1660 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1661 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1662 // get the socket in the state needed for the test below.
1664 // This is not needed for OpenSSL, because for OpenSSL,
1665 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1666 // SSLClientSocketOpenSSL::Write() will not return until all of
1667 // |request_buffer| has been written to the underlying BIO (although not
1668 // necessarily the underlying transport).
1669 rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1670 request_buffer->BytesRemaining(),
1671 callback.callback()));
1672 ASSERT_LT(0, rv);
1673 request_buffer->DidConsume(rv);
1675 // Guard to ensure that |request_buffer| was larger than all of the internal
1676 // buffers (transport, memio, NSS) along the way - otherwise the next call
1677 // to Write() will crash with an invalid buffer.
1678 ASSERT_LT(0, request_buffer->BytesRemaining());
1679 #endif
1681 // Attempt to write the remaining data. NSS will not be able to consume the
1682 // application data because the internal buffers are full, while OpenSSL will
1683 // return that its blocked because the underlying transport is blocked.
1684 rv = raw_sock->Write(request_buffer.get(),
1685 request_buffer->BytesRemaining(),
1686 callback.callback());
1687 ASSERT_EQ(ERR_IO_PENDING, rv);
1688 ASSERT_FALSE(callback.have_result());
1690 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1691 // call the Read() callback, deleting the socket and thus aborting calling
1692 // the Write() callback.
1693 raw_transport->UnblockWrite();
1695 rv = read_callback.WaitForResult();
1696 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1698 // The Write callback should not have been called.
1699 EXPECT_FALSE(callback.have_result());
1702 // Tests that the SSLClientSocket does not crash if data is received on the
1703 // transport socket after a failing write. This can occur if we have a Write
1704 // error in a SPDY socket.
1705 // Regression test for http://crbug.com/335557
1706 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1707 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1708 SpawnedTestServer::kLocalhost,
1709 base::FilePath());
1710 ASSERT_TRUE(test_server.Start());
1712 AddressList addr;
1713 ASSERT_TRUE(test_server.GetAddressList(&addr));
1715 TestCompletionCallback callback;
1716 scoped_ptr<StreamSocket> real_transport(
1717 new TCPClientSocket(addr, NULL, NetLog::Source()));
1718 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1719 // is retained in order to configure additional errors.
1720 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1721 new SynchronousErrorStreamSocket(real_transport.Pass()));
1722 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1723 scoped_ptr<FakeBlockingStreamSocket> transport(
1724 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1725 FakeBlockingStreamSocket* raw_transport = transport.get();
1727 int rv = callback.GetResult(transport->Connect(callback.callback()));
1728 EXPECT_EQ(OK, rv);
1730 // Disable TLS False Start to avoid handshake non-determinism.
1731 SSLConfig ssl_config;
1732 ssl_config.false_start_enabled = false;
1734 scoped_ptr<SSLClientSocket> sock(
1735 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1736 test_server.host_port_pair(),
1737 ssl_config));
1739 rv = callback.GetResult(sock->Connect(callback.callback()));
1740 EXPECT_EQ(OK, rv);
1741 EXPECT_TRUE(sock->IsConnected());
1743 // Send a request so there is something to read from the socket.
1744 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1745 static const int kRequestTextSize =
1746 static_cast<int>(arraysize(request_text) - 1);
1747 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1748 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1750 rv = callback.GetResult(
1751 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1752 EXPECT_EQ(kRequestTextSize, rv);
1754 // Start a hanging read.
1755 TestCompletionCallback read_callback;
1756 raw_transport->BlockReadResult();
1757 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1758 rv = sock->Read(buf.get(), 4096, read_callback.callback());
1759 EXPECT_EQ(ERR_IO_PENDING, rv);
1761 // Perform another write, but have it fail. Write a request larger than the
1762 // internal socket buffers so that the request hits the underlying transport
1763 // socket and detects the error.
1764 std::string long_request_text =
1765 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1766 long_request_text.append(20 * 1024, '*');
1767 long_request_text.append("\r\n\r\n");
1768 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1769 new StringIOBuffer(long_request_text), long_request_text.size()));
1771 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1773 // Write as much data as possible until hitting an error. This is necessary
1774 // for NSS. PR_Write will only consume as much data as it can encode into
1775 // application data records before the internal memio buffer is full, which
1776 // should only fill if writing a large amount of data and the underlying
1777 // transport is blocked. Once this happens, NSS will return (total size of all
1778 // application data records it wrote) - 1, with the caller expected to resume
1779 // with the remaining unsent data.
1780 do {
1781 rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1782 long_request_buffer->BytesRemaining(),
1783 callback.callback()));
1784 if (rv > 0) {
1785 long_request_buffer->DidConsume(rv);
1786 // Abort if the entire buffer is ever consumed.
1787 ASSERT_LT(0, long_request_buffer->BytesRemaining());
1789 } while (rv > 0);
1791 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1793 // Release the read.
1794 raw_transport->UnblockReadResult();
1795 rv = read_callback.WaitForResult();
1797 #if defined(USE_OPENSSL)
1798 // Should still read bytes despite the write error.
1799 EXPECT_LT(0, rv);
1800 #else
1801 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1802 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1803 // the write error stops future reads.
1804 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1805 #endif
1808 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1809 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1810 SpawnedTestServer::kLocalhost,
1811 base::FilePath());
1812 ASSERT_TRUE(test_server.Start());
1814 AddressList addr;
1815 ASSERT_TRUE(test_server.GetAddressList(&addr));
1817 TestCompletionCallback callback;
1818 scoped_ptr<StreamSocket> transport(
1819 new TCPClientSocket(addr, NULL, NetLog::Source()));
1820 int rv = transport->Connect(callback.callback());
1821 if (rv == ERR_IO_PENDING)
1822 rv = callback.WaitForResult();
1823 EXPECT_EQ(OK, rv);
1825 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1826 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1828 rv = sock->Connect(callback.callback());
1829 if (rv == ERR_IO_PENDING)
1830 rv = callback.WaitForResult();
1831 EXPECT_EQ(OK, rv);
1833 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1834 scoped_refptr<IOBuffer> request_buffer(
1835 new IOBuffer(arraysize(request_text) - 1));
1836 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1838 rv = sock->Write(
1839 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1840 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1842 if (rv == ERR_IO_PENDING)
1843 rv = callback.WaitForResult();
1844 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1846 scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1847 for (;;) {
1848 rv = sock->Read(buf.get(), 1, callback.callback());
1849 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1851 if (rv == ERR_IO_PENDING)
1852 rv = callback.WaitForResult();
1854 EXPECT_GE(rv, 0);
1855 if (rv <= 0)
1856 break;
1860 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
1861 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1862 SpawnedTestServer::kLocalhost,
1863 base::FilePath());
1864 ASSERT_TRUE(test_server.Start());
1866 AddressList addr;
1867 ASSERT_TRUE(test_server.GetAddressList(&addr));
1869 TestCompletionCallback callback;
1871 scoped_ptr<StreamSocket> real_transport(
1872 new TCPClientSocket(addr, NULL, NetLog::Source()));
1873 scoped_ptr<ReadBufferingStreamSocket> transport(
1874 new ReadBufferingStreamSocket(real_transport.Pass()));
1875 ReadBufferingStreamSocket* raw_transport = transport.get();
1876 int rv = callback.GetResult(transport->Connect(callback.callback()));
1877 ASSERT_EQ(OK, rv);
1879 scoped_ptr<SSLClientSocket> sock(
1880 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1881 test_server.host_port_pair(),
1882 kDefaultSSLConfig));
1884 rv = callback.GetResult(sock->Connect(callback.callback()));
1885 ASSERT_EQ(OK, rv);
1886 ASSERT_TRUE(sock->IsConnected());
1888 const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
1889 scoped_refptr<IOBuffer> request_buffer(
1890 new IOBuffer(arraysize(request_text) - 1));
1891 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1893 rv = callback.GetResult(sock->Write(
1894 request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
1895 ASSERT_GT(rv, 0);
1896 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1898 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
1899 // data (the max SSL record size) at a time. Ensure that at least 15K worth
1900 // of SSL data is buffered first. The 15K of buffered data is made up of
1901 // many smaller SSL records (the TestServer writes along 1350 byte
1902 // plaintext boundaries), although there may also be a few records that are
1903 // smaller or larger, due to timing and SSL False Start.
1904 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
1905 // the SSLClientSocket implementation, and larger than the minimum amount
1906 // of ciphertext necessary to contain the 8K of plaintext requested below.
1907 raw_transport->SetBufferSize(15000);
1909 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
1910 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
1911 ASSERT_EQ(rv, 8192);
1914 TEST_F(SSLClientSocketTest, Read_Interrupted) {
1915 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1916 SpawnedTestServer::kLocalhost,
1917 base::FilePath());
1918 ASSERT_TRUE(test_server.Start());
1920 AddressList addr;
1921 ASSERT_TRUE(test_server.GetAddressList(&addr));
1923 TestCompletionCallback callback;
1924 scoped_ptr<StreamSocket> transport(
1925 new TCPClientSocket(addr, NULL, NetLog::Source()));
1926 int rv = transport->Connect(callback.callback());
1927 if (rv == ERR_IO_PENDING)
1928 rv = callback.WaitForResult();
1929 EXPECT_EQ(OK, rv);
1931 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1932 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1934 rv = sock->Connect(callback.callback());
1935 if (rv == ERR_IO_PENDING)
1936 rv = callback.WaitForResult();
1937 EXPECT_EQ(OK, rv);
1939 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1940 scoped_refptr<IOBuffer> request_buffer(
1941 new IOBuffer(arraysize(request_text) - 1));
1942 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1944 rv = sock->Write(
1945 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1946 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1948 if (rv == ERR_IO_PENDING)
1949 rv = callback.WaitForResult();
1950 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1952 // Do a partial read and then exit. This test should not crash!
1953 scoped_refptr<IOBuffer> buf(new IOBuffer(512));
1954 rv = sock->Read(buf.get(), 512, callback.callback());
1955 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
1957 if (rv == ERR_IO_PENDING)
1958 rv = callback.WaitForResult();
1960 EXPECT_GT(rv, 0);
1963 TEST_F(SSLClientSocketTest, Read_FullLogging) {
1964 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1965 SpawnedTestServer::kLocalhost,
1966 base::FilePath());
1967 ASSERT_TRUE(test_server.Start());
1969 AddressList addr;
1970 ASSERT_TRUE(test_server.GetAddressList(&addr));
1972 TestCompletionCallback callback;
1973 CapturingNetLog log;
1974 log.SetLogLevel(NetLog::LOG_ALL);
1975 scoped_ptr<StreamSocket> transport(
1976 new TCPClientSocket(addr, &log, NetLog::Source()));
1977 int rv = transport->Connect(callback.callback());
1978 if (rv == ERR_IO_PENDING)
1979 rv = callback.WaitForResult();
1980 EXPECT_EQ(OK, rv);
1982 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1983 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1985 rv = sock->Connect(callback.callback());
1986 if (rv == ERR_IO_PENDING)
1987 rv = callback.WaitForResult();
1988 EXPECT_EQ(OK, rv);
1989 EXPECT_TRUE(sock->IsConnected());
1991 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1992 scoped_refptr<IOBuffer> request_buffer(
1993 new IOBuffer(arraysize(request_text) - 1));
1994 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1996 rv = sock->Write(
1997 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1998 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2000 if (rv == ERR_IO_PENDING)
2001 rv = callback.WaitForResult();
2002 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2004 CapturingNetLog::CapturedEntryList entries;
2005 log.GetEntries(&entries);
2006 size_t last_index = ExpectLogContainsSomewhereAfter(
2007 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
2009 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
2010 for (;;) {
2011 rv = sock->Read(buf.get(), 4096, callback.callback());
2012 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2014 if (rv == ERR_IO_PENDING)
2015 rv = callback.WaitForResult();
2017 EXPECT_GE(rv, 0);
2018 if (rv <= 0)
2019 break;
2021 log.GetEntries(&entries);
2022 last_index =
2023 ExpectLogContainsSomewhereAfter(entries,
2024 last_index + 1,
2025 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
2026 NetLog::PHASE_NONE);
2030 // Regression test for http://crbug.com/42538
2031 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
2032 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2033 SpawnedTestServer::kLocalhost,
2034 base::FilePath());
2035 ASSERT_TRUE(test_server.Start());
2037 AddressList addr;
2038 TestCompletionCallback callback;
2040 static const unsigned char application_data[] = {
2041 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2042 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2043 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2044 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2045 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2046 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2047 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2048 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2049 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2050 0x0a};
2052 // All reads and writes complete synchronously (async=false).
2053 MockRead data_reads[] = {
2054 MockRead(SYNCHRONOUS,
2055 reinterpret_cast<const char*>(application_data),
2056 arraysize(application_data)),
2057 MockRead(SYNCHRONOUS, OK), };
2059 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
2061 scoped_ptr<StreamSocket> transport(
2062 new MockTCPClientSocket(addr, NULL, &data));
2063 int rv = transport->Connect(callback.callback());
2064 if (rv == ERR_IO_PENDING)
2065 rv = callback.WaitForResult();
2066 EXPECT_EQ(OK, rv);
2068 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2069 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2071 rv = sock->Connect(callback.callback());
2072 if (rv == ERR_IO_PENDING)
2073 rv = callback.WaitForResult();
2074 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
2077 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
2078 // Rather than exhaustively disabling every RC4 ciphersuite defined at
2079 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
2080 // only disabling those cipher suites that the test server actually
2081 // implements.
2082 const uint16 kCiphersToDisable[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA
2085 SpawnedTestServer::SSLOptions ssl_options;
2086 // Enable only RC4 on the test server.
2087 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
2088 SpawnedTestServer test_server(
2089 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2090 ASSERT_TRUE(test_server.Start());
2092 AddressList addr;
2093 ASSERT_TRUE(test_server.GetAddressList(&addr));
2095 TestCompletionCallback callback;
2096 CapturingNetLog log;
2097 scoped_ptr<StreamSocket> transport(
2098 new TCPClientSocket(addr, &log, NetLog::Source()));
2099 int rv = transport->Connect(callback.callback());
2100 if (rv == ERR_IO_PENDING)
2101 rv = callback.WaitForResult();
2102 EXPECT_EQ(OK, rv);
2104 SSLConfig ssl_config;
2105 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
2106 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
2108 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2109 transport.Pass(), test_server.host_port_pair(), ssl_config));
2111 EXPECT_FALSE(sock->IsConnected());
2113 rv = sock->Connect(callback.callback());
2114 CapturingNetLog::CapturedEntryList entries;
2115 log.GetEntries(&entries);
2116 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2118 // NSS has special handling that maps a handshake_failure alert received
2119 // immediately after a client_hello to be a mismatched cipher suite error,
2120 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
2121 // Secure Transport (OS X), the handshake_failure is bubbled up without any
2122 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
2123 // indicates that no cipher suite was negotiated with the test server.
2124 if (rv == ERR_IO_PENDING)
2125 rv = callback.WaitForResult();
2126 EXPECT_TRUE(rv == ERR_SSL_VERSION_OR_CIPHER_MISMATCH ||
2127 rv == ERR_SSL_PROTOCOL_ERROR);
2128 // The exact ordering differs between SSLClientSocketNSS (which issues an
2129 // extra read) and SSLClientSocketMac (which does not). Just make sure the
2130 // error appears somewhere in the log.
2131 log.GetEntries(&entries);
2132 ExpectLogContainsSomewhere(
2133 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
2135 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2136 // the socket when it encounters an error, whereas other implementations
2137 // leave it connected.
2138 // Because this an error that the test server is mutually aware of, as opposed
2139 // to being an error such as a certificate name mismatch, which is
2140 // client-only, the exact index of the SSL connect end depends on how
2141 // quickly the test server closes the underlying socket. If the test server
2142 // closes before the IO message loop pumps messages, there may be a 0-byte
2143 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2144 // result, the SSL connect end event will be the second-to-last entry,
2145 // rather than the last entry.
2146 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1) ||
2147 LogContainsSSLConnectEndEvent(entries, -2));
2150 // When creating an SSLClientSocket, it is allowed to pass in a
2151 // ClientSocketHandle that is not obtained from a client socket pool.
2152 // Here we verify that such a simple ClientSocketHandle, not associated with any
2153 // client socket pool, can be destroyed safely.
2154 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
2155 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2156 SpawnedTestServer::kLocalhost,
2157 base::FilePath());
2158 ASSERT_TRUE(test_server.Start());
2160 AddressList addr;
2161 ASSERT_TRUE(test_server.GetAddressList(&addr));
2163 TestCompletionCallback callback;
2164 scoped_ptr<StreamSocket> transport(
2165 new TCPClientSocket(addr, NULL, NetLog::Source()));
2166 int rv = transport->Connect(callback.callback());
2167 if (rv == ERR_IO_PENDING)
2168 rv = callback.WaitForResult();
2169 EXPECT_EQ(OK, rv);
2171 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
2172 socket_handle->SetSocket(transport.Pass());
2174 scoped_ptr<SSLClientSocket> sock(
2175 socket_factory_->CreateSSLClientSocket(socket_handle.Pass(),
2176 test_server.host_port_pair(),
2177 kDefaultSSLConfig,
2178 context_));
2180 EXPECT_FALSE(sock->IsConnected());
2181 rv = sock->Connect(callback.callback());
2182 if (rv == ERR_IO_PENDING)
2183 rv = callback.WaitForResult();
2184 EXPECT_EQ(OK, rv);
2187 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2188 // code and different keying label results in different keying material.
2189 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
2190 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2191 SpawnedTestServer::kLocalhost,
2192 base::FilePath());
2193 ASSERT_TRUE(test_server.Start());
2195 AddressList addr;
2196 ASSERT_TRUE(test_server.GetAddressList(&addr));
2198 TestCompletionCallback callback;
2200 scoped_ptr<StreamSocket> transport(
2201 new TCPClientSocket(addr, NULL, NetLog::Source()));
2202 int rv = transport->Connect(callback.callback());
2203 if (rv == ERR_IO_PENDING)
2204 rv = callback.WaitForResult();
2205 EXPECT_EQ(OK, rv);
2207 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2208 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2210 rv = sock->Connect(callback.callback());
2211 if (rv == ERR_IO_PENDING)
2212 rv = callback.WaitForResult();
2213 EXPECT_EQ(OK, rv);
2214 EXPECT_TRUE(sock->IsConnected());
2216 const int kKeyingMaterialSize = 32;
2217 const char* kKeyingLabel1 = "client-socket-test-1";
2218 const char* kKeyingContext = "";
2219 unsigned char client_out1[kKeyingMaterialSize];
2220 memset(client_out1, 0, sizeof(client_out1));
2221 rv = sock->ExportKeyingMaterial(
2222 kKeyingLabel1, false, kKeyingContext, client_out1, sizeof(client_out1));
2223 EXPECT_EQ(rv, OK);
2225 const char* kKeyingLabel2 = "client-socket-test-2";
2226 unsigned char client_out2[kKeyingMaterialSize];
2227 memset(client_out2, 0, sizeof(client_out2));
2228 rv = sock->ExportKeyingMaterial(
2229 kKeyingLabel2, false, kKeyingContext, client_out2, sizeof(client_out2));
2230 EXPECT_EQ(rv, OK);
2231 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2234 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2235 // explicit NSS initialization.
2236 TEST(SSLClientSocket, ClearSessionCache) {
2237 SSLClientSocket::ClearSessionCache();
2240 // Test that the server certificates are properly retrieved from the underlying
2241 // SSL stack.
2242 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
2243 // The connection does not have to be successful.
2244 cert_verifier_->set_default_result(ERR_CERT_INVALID);
2246 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2247 // This makes the server present redundant-server-chain.pem, which contains
2248 // intermediate certificates.
2249 SpawnedTestServer::SSLOptions ssl_options(
2250 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2251 SpawnedTestServer test_server(
2252 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2253 ASSERT_TRUE(test_server.Start());
2255 AddressList addr;
2256 ASSERT_TRUE(test_server.GetAddressList(&addr));
2258 TestCompletionCallback callback;
2259 scoped_ptr<StreamSocket> transport(
2260 new TCPClientSocket(addr, NULL, NetLog::Source()));
2261 int rv = transport->Connect(callback.callback());
2262 rv = callback.GetResult(rv);
2263 EXPECT_EQ(OK, rv);
2265 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2266 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2267 EXPECT_FALSE(sock->IsConnected());
2268 rv = sock->Connect(callback.callback());
2269 rv = callback.GetResult(rv);
2271 EXPECT_EQ(ERR_CERT_INVALID, rv);
2272 EXPECT_TRUE(sock->IsConnected());
2274 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2275 // certs from redundant-server-chain.pem.
2276 CertificateList server_certs =
2277 CreateCertificateListFromFile(GetTestCertsDirectory(),
2278 "redundant-server-chain.pem",
2279 X509Certificate::FORMAT_AUTO);
2281 // Get the server certificate as received client side.
2282 scoped_refptr<X509Certificate> server_certificate =
2283 sock->GetUnverifiedServerCertificateChain();
2285 // Get the intermediates as received client side.
2286 const X509Certificate::OSCertHandles& server_intermediates =
2287 server_certificate->GetIntermediateCertificates();
2289 // Check that the unverified server certificate chain is properly retrieved
2290 // from the underlying ssl stack.
2291 ASSERT_EQ(4U, server_certs.size());
2293 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2294 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
2296 ASSERT_EQ(3U, server_intermediates.size());
2298 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
2299 server_certs[1]->os_cert_handle()));
2300 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
2301 server_certs[2]->os_cert_handle()));
2302 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
2303 server_certs[3]->os_cert_handle()));
2305 sock->Disconnect();
2306 EXPECT_FALSE(sock->IsConnected());
2309 // This tests that SSLInfo contains a properly re-constructed certificate
2310 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2311 // verified, not the chain as served by the server. (They may be different.)
2313 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2314 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2315 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2316 // a self-signed root. Such a situation can occur when a new root (C2) is
2317 // cross-certified by an old root (D) and has two different versions of its
2318 // floating around. Servers may supply C2 as an intermediate, but the
2319 // SSLClientSocket should return the chain that was verified, from
2320 // verify_result, instead.
2321 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
2322 // By default, cause the CertVerifier to treat all certificates as
2323 // expired.
2324 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
2326 // We will expect SSLInfo to ultimately contain this chain.
2327 CertificateList certs =
2328 CreateCertificateListFromFile(GetTestCertsDirectory(),
2329 "redundant-validated-chain.pem",
2330 X509Certificate::FORMAT_AUTO);
2331 ASSERT_EQ(3U, certs.size());
2333 X509Certificate::OSCertHandles temp_intermediates;
2334 temp_intermediates.push_back(certs[1]->os_cert_handle());
2335 temp_intermediates.push_back(certs[2]->os_cert_handle());
2337 CertVerifyResult verify_result;
2338 verify_result.verified_cert = X509Certificate::CreateFromHandle(
2339 certs[0]->os_cert_handle(), temp_intermediates);
2341 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2342 // rather than A->B->C.
2343 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
2345 // Load and install the root for the validated chain.
2346 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
2347 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2348 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
2349 ScopedTestRoot scoped_root(root_cert.get());
2351 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2352 SpawnedTestServer::SSLOptions ssl_options(
2353 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2354 SpawnedTestServer test_server(
2355 SpawnedTestServer::TYPE_HTTPS,
2356 ssl_options,
2357 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2358 ASSERT_TRUE(test_server.Start());
2360 AddressList addr;
2361 ASSERT_TRUE(test_server.GetAddressList(&addr));
2363 TestCompletionCallback callback;
2364 CapturingNetLog log;
2365 scoped_ptr<StreamSocket> transport(
2366 new TCPClientSocket(addr, &log, NetLog::Source()));
2367 int rv = transport->Connect(callback.callback());
2368 if (rv == ERR_IO_PENDING)
2369 rv = callback.WaitForResult();
2370 EXPECT_EQ(OK, rv);
2372 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2373 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2374 EXPECT_FALSE(sock->IsConnected());
2375 rv = sock->Connect(callback.callback());
2377 CapturingNetLog::CapturedEntryList entries;
2378 log.GetEntries(&entries);
2379 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2380 if (rv == ERR_IO_PENDING)
2381 rv = callback.WaitForResult();
2383 EXPECT_EQ(OK, rv);
2384 EXPECT_TRUE(sock->IsConnected());
2385 log.GetEntries(&entries);
2386 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2388 SSLInfo ssl_info;
2389 sock->GetSSLInfo(&ssl_info);
2391 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2392 // -> C2.
2393 const X509Certificate::OSCertHandles& intermediates =
2394 ssl_info.cert->GetIntermediateCertificates();
2395 ASSERT_EQ(2U, intermediates.size());
2396 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
2397 certs[0]->os_cert_handle()));
2398 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
2399 certs[1]->os_cert_handle()));
2400 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
2401 certs[2]->os_cert_handle()));
2403 sock->Disconnect();
2404 EXPECT_FALSE(sock->IsConnected());
2407 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
2408 SpawnedTestServer::SSLOptions ssl_options;
2409 ssl_options.request_client_certificate = true;
2410 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2411 ASSERT_TRUE(request_info.get());
2412 EXPECT_EQ(0u, request_info->cert_authorities.size());
2415 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
2416 const base::FilePath::CharType kThawteFile[] =
2417 FILE_PATH_LITERAL("thawte.single.pem");
2418 const unsigned char kThawteDN[] = {
2419 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2420 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2421 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2422 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2423 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2424 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2425 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2426 const size_t kThawteLen = sizeof(kThawteDN);
2428 const base::FilePath::CharType kDiginotarFile[] =
2429 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2430 const unsigned char kDiginotarDN[] = {
2431 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2432 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2433 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2434 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2435 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2436 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2437 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2438 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2439 0x6c};
2440 const size_t kDiginotarLen = sizeof(kDiginotarDN);
2442 SpawnedTestServer::SSLOptions ssl_options;
2443 ssl_options.request_client_certificate = true;
2444 ssl_options.client_authorities.push_back(
2445 GetTestClientCertsDirectory().Append(kThawteFile));
2446 ssl_options.client_authorities.push_back(
2447 GetTestClientCertsDirectory().Append(kDiginotarFile));
2448 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2449 ASSERT_TRUE(request_info.get());
2450 ASSERT_EQ(2u, request_info->cert_authorities.size());
2451 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
2452 request_info->cert_authorities[0]);
2453 EXPECT_EQ(
2454 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
2455 request_info->cert_authorities[1]);
2458 // cert_key_types is currently only populated on OpenSSL.
2459 #if defined(USE_OPENSSL)
2460 TEST_F(SSLClientSocketCertRequestInfoTest, CertKeyTypes) {
2461 SpawnedTestServer::SSLOptions ssl_options;
2462 ssl_options.request_client_certificate = true;
2463 ssl_options.client_cert_types.push_back(CLIENT_CERT_RSA_SIGN);
2464 ssl_options.client_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2465 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2466 ASSERT_TRUE(request_info.get());
2467 ASSERT_EQ(2u, request_info->cert_key_types.size());
2468 EXPECT_EQ(CLIENT_CERT_RSA_SIGN, request_info->cert_key_types[0]);
2469 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, request_info->cert_key_types[1]);
2471 #endif // defined(USE_OPENSSL)
2473 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
2474 SpawnedTestServer::SSLOptions ssl_options;
2475 ssl_options.signed_cert_timestamps_tls_ext = "test";
2477 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2478 ssl_options,
2479 base::FilePath());
2480 ASSERT_TRUE(test_server.Start());
2482 AddressList addr;
2483 ASSERT_TRUE(test_server.GetAddressList(&addr));
2485 TestCompletionCallback callback;
2486 CapturingNetLog log;
2487 scoped_ptr<StreamSocket> transport(
2488 new TCPClientSocket(addr, &log, NetLog::Source()));
2489 int rv = transport->Connect(callback.callback());
2490 if (rv == ERR_IO_PENDING)
2491 rv = callback.WaitForResult();
2492 EXPECT_EQ(OK, rv);
2494 SSLConfig ssl_config;
2495 ssl_config.signed_cert_timestamps_enabled = true;
2497 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2498 transport.Pass(), test_server.host_port_pair(), ssl_config));
2500 EXPECT_FALSE(sock->IsConnected());
2502 rv = sock->Connect(callback.callback());
2504 CapturingNetLog::CapturedEntryList entries;
2505 log.GetEntries(&entries);
2506 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2507 if (rv == ERR_IO_PENDING)
2508 rv = callback.WaitForResult();
2509 EXPECT_EQ(OK, rv);
2510 EXPECT_TRUE(sock->IsConnected());
2511 log.GetEntries(&entries);
2512 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2514 #if !defined(USE_OPENSSL)
2515 EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2516 #else
2517 // Enabling CT for OpenSSL is currently a noop.
2518 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2519 #endif
2521 sock->Disconnect();
2522 EXPECT_FALSE(sock->IsConnected());
2525 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2526 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2527 SpawnedTestServer::SSLOptions ssl_options;
2528 ssl_options.staple_ocsp_response = true;
2529 // The test server currently only knows how to generate OCSP responses
2530 // for a freshly minted certificate.
2531 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2533 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2534 ssl_options,
2535 base::FilePath());
2536 ASSERT_TRUE(test_server.Start());
2538 AddressList addr;
2539 ASSERT_TRUE(test_server.GetAddressList(&addr));
2541 TestCompletionCallback callback;
2542 CapturingNetLog log;
2543 scoped_ptr<StreamSocket> transport(
2544 new TCPClientSocket(addr, &log, NetLog::Source()));
2545 int rv = transport->Connect(callback.callback());
2546 if (rv == ERR_IO_PENDING)
2547 rv = callback.WaitForResult();
2548 EXPECT_EQ(OK, rv);
2550 SSLConfig ssl_config;
2551 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2552 // Certificate Transparency verification regardless of whether the platform
2553 // is able to process the OCSP status itself.
2554 ssl_config.signed_cert_timestamps_enabled = true;
2556 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2557 transport.Pass(), test_server.host_port_pair(), ssl_config));
2559 EXPECT_FALSE(sock->IsConnected());
2561 rv = sock->Connect(callback.callback());
2563 CapturingNetLog::CapturedEntryList entries;
2564 log.GetEntries(&entries);
2565 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2566 if (rv == ERR_IO_PENDING)
2567 rv = callback.WaitForResult();
2568 EXPECT_EQ(OK, rv);
2569 EXPECT_TRUE(sock->IsConnected());
2570 log.GetEntries(&entries);
2571 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2573 #if !defined(USE_OPENSSL)
2574 EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2575 #else
2576 // OCSP stapling isn't currently supported in the OpenSSL socket.
2577 EXPECT_FALSE(sock->stapled_ocsp_response_received_);
2578 #endif
2580 sock->Disconnect();
2581 EXPECT_FALSE(sock->IsConnected());
2584 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2585 SpawnedTestServer::SSLOptions ssl_options;
2586 ssl_options.signed_cert_timestamps_tls_ext = "test";
2588 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2589 ssl_options,
2590 base::FilePath());
2591 ASSERT_TRUE(test_server.Start());
2593 AddressList addr;
2594 ASSERT_TRUE(test_server.GetAddressList(&addr));
2596 TestCompletionCallback callback;
2597 CapturingNetLog log;
2598 scoped_ptr<StreamSocket> transport(
2599 new TCPClientSocket(addr, &log, NetLog::Source()));
2600 int rv = transport->Connect(callback.callback());
2601 if (rv == ERR_IO_PENDING)
2602 rv = callback.WaitForResult();
2603 EXPECT_EQ(OK, rv);
2605 SSLConfig ssl_config;
2606 ssl_config.signed_cert_timestamps_enabled = false;
2608 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2609 transport.Pass(), test_server.host_port_pair(), ssl_config));
2611 EXPECT_FALSE(sock->IsConnected());
2613 rv = sock->Connect(callback.callback());
2615 CapturingNetLog::CapturedEntryList entries;
2616 log.GetEntries(&entries);
2617 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2618 if (rv == ERR_IO_PENDING)
2619 rv = callback.WaitForResult();
2620 EXPECT_EQ(OK, rv);
2621 EXPECT_TRUE(sock->IsConnected());
2622 log.GetEntries(&entries);
2623 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2625 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2627 sock->Disconnect();
2628 EXPECT_FALSE(sock->IsConnected());
2631 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2632 TEST_F(SSLClientSocketTest, ReuseStates) {
2633 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2634 SpawnedTestServer::kLocalhost,
2635 base::FilePath());
2636 ASSERT_TRUE(test_server.Start());
2638 AddressList addr;
2639 ASSERT_TRUE(test_server.GetAddressList(&addr));
2641 TestCompletionCallback callback;
2642 scoped_ptr<StreamSocket> transport(
2643 new TCPClientSocket(addr, NULL, NetLog::Source()));
2644 int rv = transport->Connect(callback.callback());
2645 if (rv == ERR_IO_PENDING)
2646 rv = callback.WaitForResult();
2647 EXPECT_EQ(OK, rv);
2649 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2650 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2652 rv = sock->Connect(callback.callback());
2653 if (rv == ERR_IO_PENDING)
2654 rv = callback.WaitForResult();
2655 EXPECT_EQ(OK, rv);
2657 // The socket was just connected. It should be idle because it is speaking
2658 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2659 // returns false.
2660 EXPECT_TRUE(sock->IsConnected());
2661 EXPECT_TRUE(sock->IsConnectedAndIdle());
2662 EXPECT_FALSE(sock->WasEverUsed());
2664 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2665 const size_t kRequestLen = arraysize(kRequestText) - 1;
2666 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2667 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2669 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2670 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2672 if (rv == ERR_IO_PENDING)
2673 rv = callback.WaitForResult();
2674 EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2676 // The socket has now been used.
2677 EXPECT_TRUE(sock->WasEverUsed());
2679 // TODO(davidben): Read one byte to ensure the test server has responded and
2680 // then assert IsConnectedAndIdle is false. This currently doesn't work
2681 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2682 // SSL implementation's internal buffers. Either call PR_Available and
2683 // SSL_pending, although the former isn't actually implemented or perhaps
2684 // attempt to read one byte extra.
2687 #if defined(USE_OPENSSL)
2689 TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithFailure) {
2690 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2691 SpawnedTestServer::kLocalhost,
2692 base::FilePath());
2693 ASSERT_TRUE(test_server.Start());
2695 AddressList addr;
2696 ASSERT_TRUE(test_server.GetAddressList(&addr));
2698 TestCompletionCallback callback;
2699 scoped_ptr<StreamSocket> real_transport(
2700 new TCPClientSocket(addr, NULL, NetLog::Source()));
2701 scoped_ptr<SynchronousErrorStreamSocket> transport(
2702 new SynchronousErrorStreamSocket(real_transport.Pass()));
2703 int rv = callback.GetResult(transport->Connect(callback.callback()));
2704 EXPECT_EQ(OK, rv);
2706 // Disable TLS False Start to avoid handshake non-determinism.
2707 SSLConfig ssl_config;
2708 ssl_config.false_start_enabled = false;
2710 SynchronousErrorStreamSocket* raw_transport = transport.get();
2711 scoped_ptr<SSLClientSocket> sock(
2712 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
2713 test_server.host_port_pair(),
2714 ssl_config));
2716 sock->SetHandshakeCompletionCallback(base::Bind(
2717 &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
2719 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
2721 rv = callback.GetResult(sock->Connect(callback.callback()));
2722 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
2723 EXPECT_FALSE(sock->IsConnected());
2725 EXPECT_TRUE(ran_handshake_completion_callback_);
2728 // Tests that the completion callback is run when an SSL connection
2729 // completes successfully.
2730 TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithSuccess) {
2731 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2732 SpawnedTestServer::kLocalhost,
2733 base::FilePath());
2734 ASSERT_TRUE(test_server.Start());
2736 AddressList addr;
2737 ASSERT_TRUE(test_server.GetAddressList(&addr));
2739 scoped_ptr<StreamSocket> transport(
2740 new TCPClientSocket(addr, NULL, NetLog::Source()));
2742 TestCompletionCallback callback;
2743 int rv = transport->Connect(callback.callback());
2744 if (rv == ERR_IO_PENDING)
2745 rv = callback.WaitForResult();
2746 EXPECT_EQ(OK, rv);
2748 SSLConfig ssl_config = kDefaultSSLConfig;
2749 ssl_config.false_start_enabled = false;
2751 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2752 transport.Pass(), test_server.host_port_pair(), ssl_config));
2754 sock->SetHandshakeCompletionCallback(base::Bind(
2755 &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
2757 rv = callback.GetResult(sock->Connect(callback.callback()));
2759 EXPECT_EQ(OK, rv);
2760 EXPECT_TRUE(sock->IsConnected());
2761 EXPECT_TRUE(ran_handshake_completion_callback_);
2764 // Tests that the completion callback is run with a server that doesn't cache
2765 // sessions.
2766 TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithDisabledSessionCache) {
2767 SpawnedTestServer::SSLOptions ssl_options;
2768 ssl_options.disable_session_cache = true;
2769 SpawnedTestServer test_server(
2770 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2771 ASSERT_TRUE(test_server.Start());
2773 AddressList addr;
2774 ASSERT_TRUE(test_server.GetAddressList(&addr));
2776 scoped_ptr<StreamSocket> transport(
2777 new TCPClientSocket(addr, NULL, NetLog::Source()));
2779 TestCompletionCallback callback;
2780 int rv = transport->Connect(callback.callback());
2781 if (rv == ERR_IO_PENDING)
2782 rv = callback.WaitForResult();
2783 EXPECT_EQ(OK, rv);
2785 SSLConfig ssl_config = kDefaultSSLConfig;
2786 ssl_config.false_start_enabled = false;
2788 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2789 transport.Pass(), test_server.host_port_pair(), ssl_config));
2791 sock->SetHandshakeCompletionCallback(base::Bind(
2792 &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
2794 rv = callback.GetResult(sock->Connect(callback.callback()));
2796 EXPECT_EQ(OK, rv);
2797 EXPECT_TRUE(sock->IsConnected());
2798 EXPECT_TRUE(ran_handshake_completion_callback_);
2801 TEST_F(SSLClientSocketFalseStartTest,
2802 HandshakeCallbackIsRun_WithFalseStartFailure) {
2803 // False Start requires NPN and a forward-secret cipher suite.
2804 SpawnedTestServer::SSLOptions server_options;
2805 server_options.key_exchanges =
2806 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2807 server_options.enable_npn = true;
2808 SSLConfig client_config;
2809 client_config.next_protos.push_back("http/1.1");
2810 monitor_handshake_callback_ = true;
2811 fail_handshake_after_false_start_ = true;
2812 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, true));
2813 ASSERT_TRUE(ran_handshake_completion_callback_);
2816 TEST_F(SSLClientSocketFalseStartTest,
2817 HandshakeCallbackIsRun_WithFalseStartSuccess) {
2818 // False Start requires NPN and a forward-secret cipher suite.
2819 SpawnedTestServer::SSLOptions server_options;
2820 server_options.key_exchanges =
2821 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2822 server_options.enable_npn = true;
2823 SSLConfig client_config;
2824 client_config.next_protos.push_back("http/1.1");
2825 monitor_handshake_callback_ = true;
2826 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, true));
2827 ASSERT_TRUE(ran_handshake_completion_callback_);
2829 #endif // defined(USE_OPENSSL)
2831 TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) {
2832 // False Start requires NPN and a forward-secret cipher suite.
2833 SpawnedTestServer::SSLOptions server_options;
2834 server_options.key_exchanges =
2835 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2836 server_options.enable_npn = true;
2837 SSLConfig client_config;
2838 client_config.next_protos.push_back("http/1.1");
2839 ASSERT_NO_FATAL_FAILURE(
2840 TestFalseStart(server_options, client_config, true));
2843 // Test that False Start is disabled without NPN.
2844 TEST_F(SSLClientSocketFalseStartTest, NoNPN) {
2845 SpawnedTestServer::SSLOptions server_options;
2846 server_options.key_exchanges =
2847 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2848 SSLConfig client_config;
2849 client_config.next_protos.clear();
2850 ASSERT_NO_FATAL_FAILURE(
2851 TestFalseStart(server_options, client_config, false));
2854 // Test that False Start is disabled without a forward-secret cipher suite.
2855 TEST_F(SSLClientSocketFalseStartTest, NoForwardSecrecy) {
2856 SpawnedTestServer::SSLOptions server_options;
2857 server_options.key_exchanges =
2858 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA;
2859 server_options.enable_npn = true;
2860 SSLConfig client_config;
2861 client_config.next_protos.push_back("http/1.1");
2862 ASSERT_NO_FATAL_FAILURE(
2863 TestFalseStart(server_options, client_config, false));
2866 // Test that sessions are resumable after receiving the server Finished message.
2867 TEST_F(SSLClientSocketFalseStartTest, SessionResumption) {
2868 // Start a server.
2869 SpawnedTestServer::SSLOptions server_options;
2870 server_options.key_exchanges =
2871 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2872 server_options.enable_npn = true;
2873 SSLConfig client_config;
2874 client_config.next_protos.push_back("http/1.1");
2876 // Let a full handshake complete with False Start.
2877 ASSERT_NO_FATAL_FAILURE(
2878 TestFalseStart(server_options, client_config, true));
2880 // Make a second connection.
2881 TestCompletionCallback callback;
2882 scoped_ptr<StreamSocket> transport2(
2883 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2884 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
2885 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
2886 transport2.Pass(), test_server()->host_port_pair(), client_config);
2887 ASSERT_TRUE(sock2.get());
2888 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
2890 // It should resume the session.
2891 SSLInfo ssl_info;
2892 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
2893 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
2896 // Test that sessions are not resumable before receiving the server Finished
2897 // message.
2898 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinish) {
2899 // Start a server.
2900 SpawnedTestServer::SSLOptions server_options;
2901 server_options.key_exchanges =
2902 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2903 server_options.enable_npn = true;
2904 ASSERT_TRUE(StartTestServer(server_options));
2906 SSLConfig client_config;
2907 client_config.next_protos.push_back("http/1.1");
2909 // Start a handshake up to the server Finished message.
2910 TestCompletionCallback callback;
2911 FakeBlockingStreamSocket* raw_transport1;
2912 scoped_ptr<SSLClientSocket> sock1;
2913 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
2914 client_config, &callback, &raw_transport1, &sock1));
2915 // Although raw_transport1 has the server Finished blocked, the handshake
2916 // still completes.
2917 EXPECT_EQ(OK, callback.WaitForResult());
2919 // Drop the old socket. This is needed because the Python test server can't
2920 // service two sockets in parallel.
2921 sock1.reset();
2923 // Start a second connection.
2924 scoped_ptr<StreamSocket> transport2(
2925 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2926 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
2927 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
2928 transport2.Pass(), test_server()->host_port_pair(), client_config);
2929 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
2931 // No session resumption because the first connection never received a server
2932 // Finished message.
2933 SSLInfo ssl_info;
2934 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
2935 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2938 // Connect to a server using channel id. It should allow the connection.
2939 TEST_F(SSLClientSocketChannelIDTest, SendChannelID) {
2940 SpawnedTestServer::SSLOptions ssl_options;
2942 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2944 EnableChannelID();
2945 SSLConfig ssl_config = kDefaultSSLConfig;
2946 ssl_config.channel_id_enabled = true;
2948 int rv;
2949 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2951 EXPECT_EQ(OK, rv);
2952 EXPECT_TRUE(sock_->IsConnected());
2953 EXPECT_TRUE(sock_->WasChannelIDSent());
2955 sock_->Disconnect();
2956 EXPECT_FALSE(sock_->IsConnected());
2959 // Connect to a server using Channel ID but failing to look up the Channel
2960 // ID. It should fail.
2961 TEST_F(SSLClientSocketChannelIDTest, FailingChannelID) {
2962 SpawnedTestServer::SSLOptions ssl_options;
2964 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2966 EnableFailingChannelID();
2967 SSLConfig ssl_config = kDefaultSSLConfig;
2968 ssl_config.channel_id_enabled = true;
2970 int rv;
2971 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2973 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
2974 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
2975 // error codes for now.
2976 // http://crbug.com/373670
2977 EXPECT_NE(OK, rv);
2978 EXPECT_FALSE(sock_->IsConnected());
2981 // Connect to a server using Channel ID but asynchronously failing to look up
2982 // the Channel ID. It should fail.
2983 TEST_F(SSLClientSocketChannelIDTest, FailingChannelIDAsync) {
2984 SpawnedTestServer::SSLOptions ssl_options;
2986 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2988 EnableAsyncFailingChannelID();
2989 SSLConfig ssl_config = kDefaultSSLConfig;
2990 ssl_config.channel_id_enabled = true;
2992 int rv;
2993 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2995 EXPECT_EQ(ERR_UNEXPECTED, rv);
2996 EXPECT_FALSE(sock_->IsConnected());
2999 } // namespace net