Lots of random cleanups, mostly for native_theme_win.cc:
[chromium-blink-merge.git] / net / socket / ssl_client_socket_unittest.cc
blob2eaa47e058f6e21a0072d75b8f2f620623a7c4b9
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/default_server_bound_cert_store.h"
27 #include "net/ssl/ssl_cert_request_info.h"
28 #include "net/ssl/ssl_config_service.h"
29 #include "net/test/cert_test_util.h"
30 #include "net/test/spawned_test_server/spawned_test_server.h"
31 #include "testing/gtest/include/gtest/gtest.h"
32 #include "testing/platform_test.h"
34 //-----------------------------------------------------------------------------
36 namespace net {
38 namespace {
40 const SSLConfig kDefaultSSLConfig;
42 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
43 // forwarding the Socket and StreamSocket interfaces to the underlying
44 // transport.
45 // This is to provide a common base class for subclasses to override specific
46 // StreamSocket methods for testing, while still communicating with a 'real'
47 // StreamSocket.
48 class WrappedStreamSocket : public StreamSocket {
49 public:
50 explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport)
51 : transport_(transport.Pass()) {}
52 virtual ~WrappedStreamSocket() {}
54 // StreamSocket implementation:
55 virtual int Connect(const CompletionCallback& callback) OVERRIDE {
56 return transport_->Connect(callback);
58 virtual void Disconnect() OVERRIDE { transport_->Disconnect(); }
59 virtual bool IsConnected() const OVERRIDE {
60 return transport_->IsConnected();
62 virtual bool IsConnectedAndIdle() const OVERRIDE {
63 return transport_->IsConnectedAndIdle();
65 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE {
66 return transport_->GetPeerAddress(address);
68 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE {
69 return transport_->GetLocalAddress(address);
71 virtual const BoundNetLog& NetLog() const OVERRIDE {
72 return transport_->NetLog();
74 virtual void SetSubresourceSpeculation() OVERRIDE {
75 transport_->SetSubresourceSpeculation();
77 virtual void SetOmniboxSpeculation() OVERRIDE {
78 transport_->SetOmniboxSpeculation();
80 virtual bool WasEverUsed() const OVERRIDE {
81 return transport_->WasEverUsed();
83 virtual bool UsingTCPFastOpen() const OVERRIDE {
84 return transport_->UsingTCPFastOpen();
86 virtual bool WasNpnNegotiated() const OVERRIDE {
87 return transport_->WasNpnNegotiated();
89 virtual NextProto GetNegotiatedProtocol() const OVERRIDE {
90 return transport_->GetNegotiatedProtocol();
92 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE {
93 return transport_->GetSSLInfo(ssl_info);
96 // Socket implementation:
97 virtual int Read(IOBuffer* buf,
98 int buf_len,
99 const CompletionCallback& callback) OVERRIDE {
100 return transport_->Read(buf, buf_len, callback);
102 virtual int Write(IOBuffer* buf,
103 int buf_len,
104 const CompletionCallback& callback) OVERRIDE {
105 return transport_->Write(buf, buf_len, callback);
107 virtual int SetReceiveBufferSize(int32 size) OVERRIDE {
108 return transport_->SetReceiveBufferSize(size);
110 virtual int SetSendBufferSize(int32 size) OVERRIDE {
111 return transport_->SetSendBufferSize(size);
114 protected:
115 scoped_ptr<StreamSocket> transport_;
118 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
119 // will ensure a certain amount of data is internally buffered before
120 // satisfying a Read() request. It exists to mimic OS-level internal
121 // buffering, but in a way to guarantee that X number of bytes will be
122 // returned to callers of Read(), regardless of how quickly the OS receives
123 // them from the TestServer.
124 class ReadBufferingStreamSocket : public WrappedStreamSocket {
125 public:
126 explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
127 virtual ~ReadBufferingStreamSocket() {}
129 // Socket implementation:
130 virtual int Read(IOBuffer* buf,
131 int buf_len,
132 const CompletionCallback& callback) OVERRIDE;
134 // Sets the internal buffer to |size|. This must not be greater than
135 // the largest value supplied to Read() - that is, it does not handle
136 // having "leftovers" at the end of Read().
137 // Each call to Read() will be prevented from completion until at least
138 // |size| data has been read.
139 // Set to 0 to turn off buffering, causing Read() to transparently
140 // read via the underlying transport.
141 void SetBufferSize(int size);
143 private:
144 enum State {
145 STATE_NONE,
146 STATE_READ,
147 STATE_READ_COMPLETE,
150 int DoLoop(int result);
151 int DoRead();
152 int DoReadComplete(int result);
153 void OnReadCompleted(int result);
155 State state_;
156 scoped_refptr<GrowableIOBuffer> read_buffer_;
157 int buffer_size_;
159 scoped_refptr<IOBuffer> user_read_buf_;
160 CompletionCallback user_read_callback_;
163 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
164 scoped_ptr<StreamSocket> transport)
165 : WrappedStreamSocket(transport.Pass()),
166 read_buffer_(new GrowableIOBuffer()),
167 buffer_size_(0) {}
169 void ReadBufferingStreamSocket::SetBufferSize(int size) {
170 DCHECK(!user_read_buf_.get());
171 buffer_size_ = size;
172 read_buffer_->SetCapacity(size);
175 int ReadBufferingStreamSocket::Read(IOBuffer* buf,
176 int buf_len,
177 const CompletionCallback& callback) {
178 if (buffer_size_ == 0)
179 return transport_->Read(buf, buf_len, callback);
181 if (buf_len < buffer_size_)
182 return ERR_UNEXPECTED;
184 state_ = STATE_READ;
185 user_read_buf_ = buf;
186 int result = DoLoop(OK);
187 if (result == ERR_IO_PENDING)
188 user_read_callback_ = callback;
189 else
190 user_read_buf_ = NULL;
191 return result;
194 int ReadBufferingStreamSocket::DoLoop(int result) {
195 int rv = result;
196 do {
197 State current_state = state_;
198 state_ = STATE_NONE;
199 switch (current_state) {
200 case STATE_READ:
201 rv = DoRead();
202 break;
203 case STATE_READ_COMPLETE:
204 rv = DoReadComplete(rv);
205 break;
206 case STATE_NONE:
207 default:
208 NOTREACHED() << "Unexpected state: " << current_state;
209 rv = ERR_UNEXPECTED;
210 break;
212 } while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
213 return rv;
216 int ReadBufferingStreamSocket::DoRead() {
217 state_ = STATE_READ_COMPLETE;
218 int rv =
219 transport_->Read(read_buffer_.get(),
220 read_buffer_->RemainingCapacity(),
221 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
222 base::Unretained(this)));
223 return rv;
226 int ReadBufferingStreamSocket::DoReadComplete(int result) {
227 state_ = STATE_NONE;
228 if (result <= 0)
229 return result;
231 read_buffer_->set_offset(read_buffer_->offset() + result);
232 if (read_buffer_->RemainingCapacity() > 0) {
233 state_ = STATE_READ;
234 return OK;
237 memcpy(user_read_buf_->data(),
238 read_buffer_->StartOfBuffer(),
239 read_buffer_->capacity());
240 read_buffer_->set_offset(0);
241 return read_buffer_->capacity();
244 void ReadBufferingStreamSocket::OnReadCompleted(int result) {
245 result = DoLoop(result);
246 if (result == ERR_IO_PENDING)
247 return;
249 user_read_buf_ = NULL;
250 base::ResetAndReturn(&user_read_callback_).Run(result);
253 // Simulates synchronously receiving an error during Read() or Write()
254 class SynchronousErrorStreamSocket : public WrappedStreamSocket {
255 public:
256 explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
257 virtual ~SynchronousErrorStreamSocket() {}
259 // Socket implementation:
260 virtual int Read(IOBuffer* buf,
261 int buf_len,
262 const CompletionCallback& callback) OVERRIDE;
263 virtual int Write(IOBuffer* buf,
264 int buf_len,
265 const CompletionCallback& callback) OVERRIDE;
267 // Sets the next Read() call and all future calls to return |error|.
268 // If there is already a pending asynchronous read, the configured error
269 // will not be returned until that asynchronous read has completed and Read()
270 // is called again.
271 void SetNextReadError(Error error) {
272 DCHECK_GE(0, error);
273 have_read_error_ = true;
274 pending_read_error_ = error;
277 // Sets the next Write() call and all future calls to return |error|.
278 // If there is already a pending asynchronous write, the configured error
279 // will not be returned until that asynchronous write has completed and
280 // Write() is called again.
281 void SetNextWriteError(Error error) {
282 DCHECK_GE(0, error);
283 have_write_error_ = true;
284 pending_write_error_ = error;
287 private:
288 bool have_read_error_;
289 int pending_read_error_;
291 bool have_write_error_;
292 int pending_write_error_;
294 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket);
297 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
298 scoped_ptr<StreamSocket> transport)
299 : WrappedStreamSocket(transport.Pass()),
300 have_read_error_(false),
301 pending_read_error_(OK),
302 have_write_error_(false),
303 pending_write_error_(OK) {}
305 int SynchronousErrorStreamSocket::Read(IOBuffer* buf,
306 int buf_len,
307 const CompletionCallback& callback) {
308 if (have_read_error_)
309 return pending_read_error_;
310 return transport_->Read(buf, buf_len, callback);
313 int SynchronousErrorStreamSocket::Write(IOBuffer* buf,
314 int buf_len,
315 const CompletionCallback& callback) {
316 if (have_write_error_)
317 return pending_write_error_;
318 return transport_->Write(buf, buf_len, callback);
321 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
322 // underlying transport needing to complete things asynchronously in a
323 // deterministic manner (e.g.: independent of the TestServer and the OS's
324 // semantics).
325 class FakeBlockingStreamSocket : public WrappedStreamSocket {
326 public:
327 explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
328 virtual ~FakeBlockingStreamSocket() {}
330 // Socket implementation:
331 virtual int Read(IOBuffer* buf,
332 int buf_len,
333 const CompletionCallback& callback) OVERRIDE;
334 virtual int Write(IOBuffer* buf,
335 int buf_len,
336 const CompletionCallback& callback) OVERRIDE;
338 // Blocks read results on the socket. Reads will not complete until
339 // UnblockReadResult() has been called and a result is ready from the
340 // underlying transport. Note: if BlockReadResult() is called while there is a
341 // hanging asynchronous Read(), that Read is blocked.
342 void BlockReadResult();
343 void UnblockReadResult();
345 // Waits for the blocked Read() call to be complete at the underlying
346 // transport.
347 void WaitForReadResult();
349 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
350 // underlying transport until UnblockWrite() has been called. Note: if there
351 // is a pending asynchronous write, it is NOT blocked. For purposes of
352 // blocking writes, data is considered to have reached the underlying
353 // transport as soon as Write() is called.
354 void BlockWrite();
355 void UnblockWrite();
357 // Waits for the blocked Write() call to be scheduled.
358 void WaitForWrite();
360 private:
361 // Handles completion from the underlying transport read.
362 void OnReadCompleted(int result);
364 // True if read callbacks are blocked.
365 bool should_block_read_;
367 // The user callback for the pending read call.
368 CompletionCallback pending_read_callback_;
370 // The result for the blocked read callback, or ERR_IO_PENDING if not
371 // completed.
372 int pending_read_result_;
374 // WaitForReadResult() wait loop.
375 scoped_ptr<base::RunLoop> read_loop_;
377 // True if write calls are blocked.
378 bool should_block_write_;
380 // The buffer for the pending write, or NULL if not scheduled.
381 scoped_refptr<IOBuffer> pending_write_buf_;
383 // The callback for the pending write call.
384 CompletionCallback pending_write_callback_;
386 // The length for the pending write, or -1 if not scheduled.
387 int pending_write_len_;
389 // WaitForWrite() wait loop.
390 scoped_ptr<base::RunLoop> write_loop_;
393 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
394 scoped_ptr<StreamSocket> transport)
395 : WrappedStreamSocket(transport.Pass()),
396 should_block_read_(false),
397 pending_read_result_(ERR_IO_PENDING),
398 should_block_write_(false),
399 pending_write_len_(-1) {}
401 int FakeBlockingStreamSocket::Read(IOBuffer* buf,
402 int len,
403 const CompletionCallback& callback) {
404 DCHECK(pending_read_callback_.is_null());
405 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
406 DCHECK(!callback.is_null());
408 int rv = transport_->Read(buf, len, base::Bind(
409 &FakeBlockingStreamSocket::OnReadCompleted, base::Unretained(this)));
410 if (rv == ERR_IO_PENDING) {
411 // Save the callback to be called later.
412 pending_read_callback_ = callback;
413 } else if (should_block_read_) {
414 // Save the callback and read result to be called later.
415 pending_read_callback_ = callback;
416 OnReadCompleted(rv);
417 rv = ERR_IO_PENDING;
419 return rv;
422 int FakeBlockingStreamSocket::Write(IOBuffer* buf,
423 int len,
424 const CompletionCallback& callback) {
425 DCHECK(buf);
426 DCHECK_LE(0, len);
428 if (!should_block_write_)
429 return transport_->Write(buf, len, callback);
431 // Schedule the write, but do nothing.
432 DCHECK(!pending_write_buf_);
433 DCHECK_EQ(-1, pending_write_len_);
434 DCHECK(pending_write_callback_.is_null());
435 DCHECK(!callback.is_null());
436 pending_write_buf_ = buf;
437 pending_write_len_ = len;
438 pending_write_callback_ = callback;
440 // Stop the write loop, if any.
441 if (write_loop_)
442 write_loop_->Quit();
443 return ERR_IO_PENDING;
446 void FakeBlockingStreamSocket::BlockReadResult() {
447 DCHECK(!should_block_read_);
448 should_block_read_ = true;
451 void FakeBlockingStreamSocket::UnblockReadResult() {
452 DCHECK(should_block_read_);
453 should_block_read_ = false;
455 // If the operation is still pending in the underlying transport, immediately
456 // return - OnReadCompleted() will handle invoking the callback once the
457 // transport has completed.
458 if (pending_read_result_ == ERR_IO_PENDING)
459 return;
460 int result = pending_read_result_;
461 pending_read_result_ = ERR_IO_PENDING;
462 base::ResetAndReturn(&pending_read_callback_).Run(result);
465 void FakeBlockingStreamSocket::WaitForReadResult() {
466 DCHECK(should_block_read_);
467 DCHECK(!read_loop_);
469 if (pending_read_result_ != ERR_IO_PENDING)
470 return;
471 read_loop_.reset(new base::RunLoop);
472 read_loop_->Run();
473 read_loop_.reset();
474 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
477 void FakeBlockingStreamSocket::BlockWrite() {
478 DCHECK(!should_block_write_);
479 should_block_write_ = true;
482 void FakeBlockingStreamSocket::UnblockWrite() {
483 DCHECK(should_block_write_);
484 should_block_write_ = false;
486 // Do nothing if UnblockWrite() was called after BlockWrite(),
487 // without a Write() in between.
488 if (!pending_write_buf_)
489 return;
491 int rv = transport_->Write(pending_write_buf_, pending_write_len_,
492 pending_write_callback_);
493 pending_write_buf_ = NULL;
494 pending_write_len_ = -1;
495 if (rv == ERR_IO_PENDING) {
496 pending_write_callback_.Reset();
497 } else {
498 base::ResetAndReturn(&pending_write_callback_).Run(rv);
502 void FakeBlockingStreamSocket::WaitForWrite() {
503 DCHECK(should_block_write_);
504 DCHECK(!write_loop_);
506 if (pending_write_buf_)
507 return;
508 write_loop_.reset(new base::RunLoop);
509 write_loop_->Run();
510 write_loop_.reset();
511 DCHECK(pending_write_buf_);
514 void FakeBlockingStreamSocket::OnReadCompleted(int result) {
515 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
516 DCHECK(!pending_read_callback_.is_null());
518 if (should_block_read_) {
519 // Store the result so that the callback can be invoked once Unblock() is
520 // called.
521 pending_read_result_ = result;
523 // Stop the WaitForReadResult() call if any.
524 if (read_loop_)
525 read_loop_->Quit();
526 } else {
527 // Either the Read() was never blocked or UnblockReadResult() was called
528 // before the Read() completed. Either way, run the callback.
529 base::ResetAndReturn(&pending_read_callback_).Run(result);
533 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
534 // reads and writes on the socket.
535 class CountingStreamSocket : public WrappedStreamSocket {
536 public:
537 explicit CountingStreamSocket(scoped_ptr<StreamSocket> transport)
538 : WrappedStreamSocket(transport.Pass()),
539 read_count_(0),
540 write_count_(0) {}
541 virtual ~CountingStreamSocket() {}
543 // Socket implementation:
544 virtual int Read(IOBuffer* buf,
545 int buf_len,
546 const CompletionCallback& callback) OVERRIDE {
547 read_count_++;
548 return transport_->Read(buf, buf_len, callback);
550 virtual int Write(IOBuffer* buf,
551 int buf_len,
552 const CompletionCallback& callback) OVERRIDE {
553 write_count_++;
554 return transport_->Write(buf, buf_len, callback);
557 int read_count() const { return read_count_; }
558 int write_count() const { return write_count_; }
560 private:
561 int read_count_;
562 int write_count_;
565 // CompletionCallback that will delete the associated StreamSocket when
566 // the callback is invoked.
567 class DeleteSocketCallback : public TestCompletionCallbackBase {
568 public:
569 explicit DeleteSocketCallback(StreamSocket* socket)
570 : socket_(socket),
571 callback_(base::Bind(&DeleteSocketCallback::OnComplete,
572 base::Unretained(this))) {}
573 virtual ~DeleteSocketCallback() {}
575 const CompletionCallback& callback() const { return callback_; }
577 private:
578 void OnComplete(int result) {
579 if (socket_) {
580 delete socket_;
581 socket_ = NULL;
582 } else {
583 ADD_FAILURE() << "Deleting socket twice";
585 SetResult(result);
588 StreamSocket* socket_;
589 CompletionCallback callback_;
591 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
594 // A ServerBoundCertStore that always returns an error when asked for a
595 // certificate.
596 class FailingServerBoundCertStore : public ServerBoundCertStore {
597 virtual int GetServerBoundCert(const std::string& server_identifier,
598 base::Time* expiration_time,
599 std::string* private_key_result,
600 std::string* cert_result,
601 const GetCertCallback& callback) OVERRIDE {
602 return ERR_UNEXPECTED;
604 virtual void SetServerBoundCert(const std::string& server_identifier,
605 base::Time creation_time,
606 base::Time expiration_time,
607 const std::string& private_key,
608 const std::string& cert) OVERRIDE {}
609 virtual void DeleteServerBoundCert(const std::string& server_identifier,
610 const base::Closure& completion_callback)
611 OVERRIDE {}
612 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
613 base::Time delete_end,
614 const base::Closure& completion_callback)
615 OVERRIDE {}
616 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
617 virtual void GetAllServerBoundCerts(const GetCertListCallback& callback)
618 OVERRIDE {}
619 virtual int GetCertCount() OVERRIDE { return 0; }
620 virtual void SetForceKeepSessionState() OVERRIDE {}
623 // A ServerBoundCertStore that asynchronously returns an error when asked for a
624 // certificate.
625 class AsyncFailingServerBoundCertStore : public ServerBoundCertStore {
626 virtual int GetServerBoundCert(const std::string& server_identifier,
627 base::Time* expiration_time,
628 std::string* private_key_result,
629 std::string* cert_result,
630 const GetCertCallback& callback) OVERRIDE {
631 base::MessageLoop::current()->PostTask(
632 FROM_HERE, base::Bind(callback, ERR_UNEXPECTED,
633 server_identifier, base::Time(), "", ""));
634 return ERR_IO_PENDING;
636 virtual void SetServerBoundCert(const std::string& server_identifier,
637 base::Time creation_time,
638 base::Time expiration_time,
639 const std::string& private_key,
640 const std::string& cert) OVERRIDE {}
641 virtual void DeleteServerBoundCert(const std::string& server_identifier,
642 const base::Closure& completion_callback)
643 OVERRIDE {}
644 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
645 base::Time delete_end,
646 const base::Closure& completion_callback)
647 OVERRIDE {}
648 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
649 virtual void GetAllServerBoundCerts(const GetCertListCallback& callback)
650 OVERRIDE {}
651 virtual int GetCertCount() OVERRIDE { return 0; }
652 virtual void SetForceKeepSessionState() OVERRIDE {}
655 class SSLClientSocketTest : public PlatformTest {
656 public:
657 SSLClientSocketTest()
658 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
659 cert_verifier_(new MockCertVerifier),
660 transport_security_state_(new TransportSecurityState) {
661 cert_verifier_->set_default_result(OK);
662 context_.cert_verifier = cert_verifier_.get();
663 context_.transport_security_state = transport_security_state_.get();
666 protected:
667 // The address of the spawned test server, after calling StartTestServer().
668 const AddressList& addr() const { return addr_; }
670 // The SpawnedTestServer object, after calling StartTestServer().
671 const SpawnedTestServer* test_server() const { return test_server_.get(); }
673 // Starts the test server with SSL configuration |ssl_options|. Returns true
674 // on success.
675 bool StartTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
676 test_server_.reset(new SpawnedTestServer(
677 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()));
678 if (!test_server_->Start()) {
679 LOG(ERROR) << "Could not start SpawnedTestServer";
680 return false;
683 if (!test_server_->GetAddressList(&addr_)) {
684 LOG(ERROR) << "Could not get SpawnedTestServer address list";
685 return false;
687 return true;
690 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
691 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
692 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
693 if (!StartTestServer(ssl_options))
694 return false;
696 transport_.reset(new TCPClientSocket(addr_, &log_, NetLog::Source()));
697 int rv = callback_.GetResult(transport_->Connect(callback_.callback()));
698 if (rv != OK) {
699 LOG(ERROR) << "Could not connect to SpawnedTestServer";
700 return false;
702 return true;
705 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
706 scoped_ptr<StreamSocket> transport_socket,
707 const HostPortPair& host_and_port,
708 const SSLConfig& ssl_config) {
709 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
710 connection->SetSocket(transport_socket.Pass());
711 return socket_factory_->CreateSSLClientSocket(
712 connection.Pass(), host_and_port, ssl_config, context_);
715 // Create an SSLClientSocket object and use it to connect to a test
716 // server, then wait for connection results. This must be called after
717 // a successful ConnectToTestServer() call.
718 // |ssl_config| the SSL configuration to use.
719 // |result| will retrieve the ::Connect() result value.
720 // Returns true on success, false otherwise. Success means that the socket
721 // could be created and its Connect() was called, not that the connection
722 // itself was a success.
723 bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config, int* result) {
724 sock_ = CreateSSLClientSocket(
725 transport_.Pass(), test_server_->host_port_pair(), ssl_config);
727 if (sock_->IsConnected()) {
728 LOG(ERROR) << "SSL Socket prematurely connected";
729 return false;
732 *result = callback_.GetResult(sock_->Connect(callback_.callback()));
733 return true;
736 ClientSocketFactory* socket_factory_;
737 scoped_ptr<MockCertVerifier> cert_verifier_;
738 scoped_ptr<TransportSecurityState> transport_security_state_;
739 SSLClientSocketContext context_;
740 scoped_ptr<SSLClientSocket> sock_;
741 CapturingNetLog log_;
743 private:
744 scoped_ptr<StreamSocket> transport_;
745 scoped_ptr<SpawnedTestServer> test_server_;
746 TestCompletionCallback callback_;
747 AddressList addr_;
750 // Verifies the correctness of GetSSLCertRequestInfo.
751 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
752 protected:
753 // Creates a test server with the given SSLOptions, connects to it and returns
754 // the SSLCertRequestInfo reported by the socket.
755 scoped_refptr<SSLCertRequestInfo> GetCertRequest(
756 SpawnedTestServer::SSLOptions ssl_options) {
757 SpawnedTestServer test_server(
758 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
759 if (!test_server.Start())
760 return NULL;
762 AddressList addr;
763 if (!test_server.GetAddressList(&addr))
764 return NULL;
766 TestCompletionCallback callback;
767 CapturingNetLog log;
768 scoped_ptr<StreamSocket> transport(
769 new TCPClientSocket(addr, &log, NetLog::Source()));
770 int rv = transport->Connect(callback.callback());
771 if (rv == ERR_IO_PENDING)
772 rv = callback.WaitForResult();
773 EXPECT_EQ(OK, rv);
775 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
776 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
777 EXPECT_FALSE(sock->IsConnected());
779 rv = sock->Connect(callback.callback());
780 if (rv == ERR_IO_PENDING)
781 rv = callback.WaitForResult();
782 scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo();
783 sock->GetSSLCertRequestInfo(request_info.get());
784 sock->Disconnect();
785 EXPECT_FALSE(sock->IsConnected());
786 EXPECT_TRUE(
787 test_server.host_port_pair().Equals(request_info->host_and_port));
789 return request_info;
793 class SSLClientSocketFalseStartTest : public SSLClientSocketTest {
794 protected:
795 // Creates an SSLClientSocket with |client_config| attached to a
796 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
797 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
798 // so |*out_raw_transport| is a raw pointer.
800 // The client socket will begin a connect using |callback| but stop before the
801 // server's finished message is received. The finished message will be blocked
802 // in |*out_raw_transport|. To complete the handshake and successfully read
803 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
804 // the client successfully false started, |callback.WaitForResult()| will
805 // return OK without unblocking transport reads. But Read() will still block.)
807 // Must be called after StartTestServer is called.
808 void CreateAndConnectUntilServerFinishedReceived(
809 const SSLConfig& client_config,
810 TestCompletionCallback* callback,
811 FakeBlockingStreamSocket** out_raw_transport,
812 scoped_ptr<SSLClientSocket>* out_sock) {
813 CHECK(test_server());
815 scoped_ptr<StreamSocket> real_transport(
816 new TCPClientSocket(addr(), NULL, NetLog::Source()));
817 scoped_ptr<FakeBlockingStreamSocket> transport(
818 new FakeBlockingStreamSocket(real_transport.Pass()));
819 int rv = callback->GetResult(transport->Connect(callback->callback()));
820 EXPECT_EQ(OK, rv);
822 FakeBlockingStreamSocket* raw_transport = transport.get();
823 scoped_ptr<SSLClientSocket> sock =
824 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
825 test_server()->host_port_pair(),
826 client_config);
828 // Connect. Stop before the client processes the first server leg
829 // (ServerHello, etc.)
830 raw_transport->BlockReadResult();
831 rv = sock->Connect(callback->callback());
832 EXPECT_EQ(ERR_IO_PENDING, rv);
833 raw_transport->WaitForReadResult();
835 // Release the ServerHello and wait for the client to write
836 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
837 // server's leg to complete, since it may span multiple reads.)
838 EXPECT_FALSE(callback->have_result());
839 raw_transport->BlockWrite();
840 raw_transport->UnblockReadResult();
841 raw_transport->WaitForWrite();
843 // And, finally, release that and block the next server leg
844 // (ChangeCipherSpec, Finished).
845 raw_transport->BlockReadResult();
846 raw_transport->UnblockWrite();
848 *out_raw_transport = raw_transport;
849 *out_sock = sock.Pass();
852 void TestFalseStart(const SpawnedTestServer::SSLOptions& server_options,
853 const SSLConfig& client_config,
854 bool expect_false_start) {
855 ASSERT_TRUE(StartTestServer(server_options));
857 TestCompletionCallback callback;
858 FakeBlockingStreamSocket* raw_transport = NULL;
859 scoped_ptr<SSLClientSocket> sock;
860 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
861 client_config, &callback, &raw_transport, &sock));
863 if (expect_false_start) {
864 // When False Starting, the handshake should complete before receiving the
865 // Change Cipher Spec and Finished messages.
867 // Note: callback.have_result() may not be true without waiting. The NSS
868 // state machine sometimes lives on a separate thread, so this thread may
869 // not yet have processed the signal that the handshake has completed.
870 int rv = callback.WaitForResult();
871 EXPECT_EQ(OK, rv);
872 EXPECT_TRUE(sock->IsConnected());
874 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
875 static const int kRequestTextSize =
876 static_cast<int>(arraysize(request_text) - 1);
877 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
878 memcpy(request_buffer->data(), request_text, kRequestTextSize);
880 // Write the request.
881 rv = callback.GetResult(sock->Write(request_buffer.get(),
882 kRequestTextSize,
883 callback.callback()));
884 EXPECT_EQ(kRequestTextSize, rv);
886 // The read will hang; it's waiting for the peer to complete the
887 // handshake, and the handshake is still blocked.
888 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
889 rv = sock->Read(buf.get(), 4096, callback.callback());
891 // After releasing reads, the connection proceeds.
892 raw_transport->UnblockReadResult();
893 rv = callback.GetResult(rv);
894 EXPECT_LT(0, rv);
895 } else {
896 // False Start is not enabled, so the handshake will not complete because
897 // the server second leg is blocked.
898 base::RunLoop().RunUntilIdle();
899 EXPECT_FALSE(callback.have_result());
904 class SSLClientSocketChannelIDTest : public SSLClientSocketTest {
905 protected:
906 void EnableChannelID() {
907 cert_service_.reset(
908 new ServerBoundCertService(new DefaultServerBoundCertStore(NULL),
909 base::MessageLoopProxy::current()));
910 context_.server_bound_cert_service = cert_service_.get();
913 void EnableFailingChannelID() {
914 cert_service_.reset(new ServerBoundCertService(
915 new FailingServerBoundCertStore(), base::MessageLoopProxy::current()));
916 context_.server_bound_cert_service = cert_service_.get();
919 void EnableAsyncFailingChannelID() {
920 cert_service_.reset(new ServerBoundCertService(
921 new AsyncFailingServerBoundCertStore(),
922 base::MessageLoopProxy::current()));
923 context_.server_bound_cert_service = cert_service_.get();
926 private:
927 scoped_ptr<ServerBoundCertService> cert_service_;
930 //-----------------------------------------------------------------------------
932 // LogContainsSSLConnectEndEvent returns true if the given index in the given
933 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
934 // merge the first application data record with the Finished message when false
935 // starting. However, in order to avoid the server timing out the handshake,
936 // they'll give up waiting for application data and send the Finished after a
937 // timeout. This means that an SSL connect end event may appear as a socket
938 // write.
939 static bool LogContainsSSLConnectEndEvent(
940 const CapturingNetLog::CapturedEntryList& log,
941 int i) {
942 return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) ||
943 LogContainsEvent(
944 log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
947 } // namespace
949 TEST_F(SSLClientSocketTest, Connect) {
950 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
951 SpawnedTestServer::kLocalhost,
952 base::FilePath());
953 ASSERT_TRUE(test_server.Start());
955 AddressList addr;
956 ASSERT_TRUE(test_server.GetAddressList(&addr));
958 TestCompletionCallback callback;
959 CapturingNetLog log;
960 scoped_ptr<StreamSocket> transport(
961 new TCPClientSocket(addr, &log, NetLog::Source()));
962 int rv = transport->Connect(callback.callback());
963 if (rv == ERR_IO_PENDING)
964 rv = callback.WaitForResult();
965 EXPECT_EQ(OK, rv);
967 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
968 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
970 EXPECT_FALSE(sock->IsConnected());
972 rv = sock->Connect(callback.callback());
974 CapturingNetLog::CapturedEntryList entries;
975 log.GetEntries(&entries);
976 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
977 if (rv == ERR_IO_PENDING)
978 rv = callback.WaitForResult();
979 EXPECT_EQ(OK, rv);
980 EXPECT_TRUE(sock->IsConnected());
981 log.GetEntries(&entries);
982 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
984 sock->Disconnect();
985 EXPECT_FALSE(sock->IsConnected());
988 TEST_F(SSLClientSocketTest, ConnectExpired) {
989 SpawnedTestServer::SSLOptions ssl_options(
990 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
991 SpawnedTestServer test_server(
992 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
993 ASSERT_TRUE(test_server.Start());
995 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
997 AddressList addr;
998 ASSERT_TRUE(test_server.GetAddressList(&addr));
1000 TestCompletionCallback callback;
1001 CapturingNetLog log;
1002 scoped_ptr<StreamSocket> transport(
1003 new TCPClientSocket(addr, &log, NetLog::Source()));
1004 int rv = transport->Connect(callback.callback());
1005 if (rv == ERR_IO_PENDING)
1006 rv = callback.WaitForResult();
1007 EXPECT_EQ(OK, rv);
1009 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1010 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1012 EXPECT_FALSE(sock->IsConnected());
1014 rv = sock->Connect(callback.callback());
1016 CapturingNetLog::CapturedEntryList entries;
1017 log.GetEntries(&entries);
1018 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1019 if (rv == ERR_IO_PENDING)
1020 rv = callback.WaitForResult();
1022 EXPECT_EQ(ERR_CERT_DATE_INVALID, rv);
1024 // Rather than testing whether or not the underlying socket is connected,
1025 // test that the handshake has finished. This is because it may be
1026 // desirable to disconnect the socket before showing a user prompt, since
1027 // the user may take indefinitely long to respond.
1028 log.GetEntries(&entries);
1029 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1032 TEST_F(SSLClientSocketTest, ConnectMismatched) {
1033 SpawnedTestServer::SSLOptions ssl_options(
1034 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
1035 SpawnedTestServer test_server(
1036 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1037 ASSERT_TRUE(test_server.Start());
1039 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
1041 AddressList addr;
1042 ASSERT_TRUE(test_server.GetAddressList(&addr));
1044 TestCompletionCallback callback;
1045 CapturingNetLog log;
1046 scoped_ptr<StreamSocket> transport(
1047 new TCPClientSocket(addr, &log, NetLog::Source()));
1048 int rv = transport->Connect(callback.callback());
1049 if (rv == ERR_IO_PENDING)
1050 rv = callback.WaitForResult();
1051 EXPECT_EQ(OK, rv);
1053 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1054 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1056 EXPECT_FALSE(sock->IsConnected());
1058 rv = sock->Connect(callback.callback());
1060 CapturingNetLog::CapturedEntryList entries;
1061 log.GetEntries(&entries);
1062 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1063 if (rv == ERR_IO_PENDING)
1064 rv = callback.WaitForResult();
1066 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv);
1068 // Rather than testing whether or not the underlying socket is connected,
1069 // test that the handshake has finished. This is because it may be
1070 // desirable to disconnect the socket before showing a user prompt, since
1071 // the user may take indefinitely long to respond.
1072 log.GetEntries(&entries);
1073 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1076 // Attempt to connect to a page which requests a client certificate. It should
1077 // return an error code on connect.
1078 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
1079 SpawnedTestServer::SSLOptions ssl_options;
1080 ssl_options.request_client_certificate = true;
1081 SpawnedTestServer test_server(
1082 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1083 ASSERT_TRUE(test_server.Start());
1085 AddressList addr;
1086 ASSERT_TRUE(test_server.GetAddressList(&addr));
1088 TestCompletionCallback callback;
1089 CapturingNetLog log;
1090 scoped_ptr<StreamSocket> transport(
1091 new TCPClientSocket(addr, &log, NetLog::Source()));
1092 int rv = transport->Connect(callback.callback());
1093 if (rv == ERR_IO_PENDING)
1094 rv = callback.WaitForResult();
1095 EXPECT_EQ(OK, rv);
1097 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1098 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1100 EXPECT_FALSE(sock->IsConnected());
1102 rv = sock->Connect(callback.callback());
1104 CapturingNetLog::CapturedEntryList entries;
1105 log.GetEntries(&entries);
1106 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1107 if (rv == ERR_IO_PENDING)
1108 rv = callback.WaitForResult();
1110 log.GetEntries(&entries);
1111 // Because we prematurely kill the handshake at CertificateRequest,
1112 // the server may still send data (notably the ServerHelloDone)
1113 // after the error is returned. As a result, the SSL_CONNECT may not
1114 // be the last entry. See http://crbug.com/54445. We use
1115 // ExpectLogContainsSomewhere instead of
1116 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
1117 // extra read instead of two. This occurs before the handshake ends,
1118 // so the corking logic of LogContainsSSLConnectEndEvent isn't
1119 // necessary.
1121 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
1122 // fixed and we can respond to the first CertificateRequest
1123 // without closing the socket, add a unit test for sending the
1124 // certificate. This test may still be useful as we'll want to close
1125 // the socket on a timeout if the user takes a long time to pick a
1126 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
1127 ExpectLogContainsSomewhere(
1128 entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END);
1129 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
1130 EXPECT_FALSE(sock->IsConnected());
1133 // Connect to a server requesting optional client authentication. Send it a
1134 // null certificate. It should allow the connection.
1136 // TODO(davidben): Also test providing an actual certificate.
1137 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
1138 SpawnedTestServer::SSLOptions ssl_options;
1139 ssl_options.request_client_certificate = true;
1140 SpawnedTestServer test_server(
1141 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1142 ASSERT_TRUE(test_server.Start());
1144 AddressList addr;
1145 ASSERT_TRUE(test_server.GetAddressList(&addr));
1147 TestCompletionCallback callback;
1148 CapturingNetLog log;
1149 scoped_ptr<StreamSocket> transport(
1150 new TCPClientSocket(addr, &log, NetLog::Source()));
1151 int rv = transport->Connect(callback.callback());
1152 if (rv == ERR_IO_PENDING)
1153 rv = callback.WaitForResult();
1154 EXPECT_EQ(OK, rv);
1156 SSLConfig ssl_config = kDefaultSSLConfig;
1157 ssl_config.send_client_cert = true;
1158 ssl_config.client_cert = NULL;
1160 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1161 transport.Pass(), test_server.host_port_pair(), ssl_config));
1163 EXPECT_FALSE(sock->IsConnected());
1165 // Our test server accepts certificate-less connections.
1166 // TODO(davidben): Add a test which requires them and verify the error.
1167 rv = sock->Connect(callback.callback());
1169 CapturingNetLog::CapturedEntryList entries;
1170 log.GetEntries(&entries);
1171 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1172 if (rv == ERR_IO_PENDING)
1173 rv = callback.WaitForResult();
1175 EXPECT_EQ(OK, rv);
1176 EXPECT_TRUE(sock->IsConnected());
1177 log.GetEntries(&entries);
1178 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1180 // We responded to the server's certificate request with a Certificate
1181 // message with no client certificate in it. ssl_info.client_cert_sent
1182 // should be false in this case.
1183 SSLInfo ssl_info;
1184 sock->GetSSLInfo(&ssl_info);
1185 EXPECT_FALSE(ssl_info.client_cert_sent);
1187 sock->Disconnect();
1188 EXPECT_FALSE(sock->IsConnected());
1191 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1192 // - Server closes an SSL connection (with a close_notify alert message).
1193 // - Server closes the underlying TCP connection directly.
1194 // - Server sends data unexpectedly.
1196 TEST_F(SSLClientSocketTest, Read) {
1197 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1198 SpawnedTestServer::kLocalhost,
1199 base::FilePath());
1200 ASSERT_TRUE(test_server.Start());
1202 AddressList addr;
1203 ASSERT_TRUE(test_server.GetAddressList(&addr));
1205 TestCompletionCallback callback;
1206 scoped_ptr<StreamSocket> transport(
1207 new TCPClientSocket(addr, NULL, NetLog::Source()));
1208 int rv = transport->Connect(callback.callback());
1209 if (rv == ERR_IO_PENDING)
1210 rv = callback.WaitForResult();
1211 EXPECT_EQ(OK, rv);
1213 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1214 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1216 rv = sock->Connect(callback.callback());
1217 if (rv == ERR_IO_PENDING)
1218 rv = callback.WaitForResult();
1219 EXPECT_EQ(OK, rv);
1220 EXPECT_TRUE(sock->IsConnected());
1222 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1223 scoped_refptr<IOBuffer> request_buffer(
1224 new IOBuffer(arraysize(request_text) - 1));
1225 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1227 rv = sock->Write(
1228 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1229 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1231 if (rv == ERR_IO_PENDING)
1232 rv = callback.WaitForResult();
1233 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1235 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1236 for (;;) {
1237 rv = sock->Read(buf.get(), 4096, callback.callback());
1238 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1240 if (rv == ERR_IO_PENDING)
1241 rv = callback.WaitForResult();
1243 EXPECT_GE(rv, 0);
1244 if (rv <= 0)
1245 break;
1249 // Tests that the SSLClientSocket properly handles when the underlying transport
1250 // synchronously returns an error code - such as if an intermediary terminates
1251 // the socket connection uncleanly.
1252 // This is a regression test for http://crbug.com/238536
1253 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
1254 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1255 SpawnedTestServer::kLocalhost,
1256 base::FilePath());
1257 ASSERT_TRUE(test_server.Start());
1259 AddressList addr;
1260 ASSERT_TRUE(test_server.GetAddressList(&addr));
1262 TestCompletionCallback callback;
1263 scoped_ptr<StreamSocket> real_transport(
1264 new TCPClientSocket(addr, NULL, NetLog::Source()));
1265 scoped_ptr<SynchronousErrorStreamSocket> transport(
1266 new SynchronousErrorStreamSocket(real_transport.Pass()));
1267 int rv = callback.GetResult(transport->Connect(callback.callback()));
1268 EXPECT_EQ(OK, rv);
1270 // Disable TLS False Start to avoid handshake non-determinism.
1271 SSLConfig ssl_config;
1272 ssl_config.false_start_enabled = false;
1274 SynchronousErrorStreamSocket* raw_transport = transport.get();
1275 scoped_ptr<SSLClientSocket> sock(
1276 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1277 test_server.host_port_pair(),
1278 ssl_config));
1280 rv = callback.GetResult(sock->Connect(callback.callback()));
1281 EXPECT_EQ(OK, rv);
1282 EXPECT_TRUE(sock->IsConnected());
1284 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1285 static const int kRequestTextSize =
1286 static_cast<int>(arraysize(request_text) - 1);
1287 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1288 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1290 rv = callback.GetResult(
1291 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1292 EXPECT_EQ(kRequestTextSize, rv);
1294 // Simulate an unclean/forcible shutdown.
1295 raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
1297 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1299 // Note: This test will hang if this bug has regressed. Simply checking that
1300 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1301 // result when using a dedicated task runner for NSS.
1302 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1304 #if !defined(USE_OPENSSL)
1305 // SSLClientSocketNSS records the error exactly
1306 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1307 #else
1308 // SSLClientSocketOpenSSL treats any errors as a simple EOF.
1309 EXPECT_EQ(0, rv);
1310 #endif
1313 // Tests that the SSLClientSocket properly handles when the underlying transport
1314 // asynchronously returns an error code while writing data - such as if an
1315 // intermediary terminates the socket connection uncleanly.
1316 // This is a regression test for http://crbug.com/249848
1317 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
1318 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1319 SpawnedTestServer::kLocalhost,
1320 base::FilePath());
1321 ASSERT_TRUE(test_server.Start());
1323 AddressList addr;
1324 ASSERT_TRUE(test_server.GetAddressList(&addr));
1326 TestCompletionCallback callback;
1327 scoped_ptr<StreamSocket> real_transport(
1328 new TCPClientSocket(addr, NULL, NetLog::Source()));
1329 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1330 // is retained in order to configure additional errors.
1331 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1332 new SynchronousErrorStreamSocket(real_transport.Pass()));
1333 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1334 scoped_ptr<FakeBlockingStreamSocket> transport(
1335 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1336 FakeBlockingStreamSocket* raw_transport = transport.get();
1337 int rv = callback.GetResult(transport->Connect(callback.callback()));
1338 EXPECT_EQ(OK, rv);
1340 // Disable TLS False Start to avoid handshake non-determinism.
1341 SSLConfig ssl_config;
1342 ssl_config.false_start_enabled = false;
1344 scoped_ptr<SSLClientSocket> sock(
1345 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1346 test_server.host_port_pair(),
1347 ssl_config));
1349 rv = callback.GetResult(sock->Connect(callback.callback()));
1350 EXPECT_EQ(OK, rv);
1351 EXPECT_TRUE(sock->IsConnected());
1353 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1354 static const int kRequestTextSize =
1355 static_cast<int>(arraysize(request_text) - 1);
1356 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1357 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1359 // Simulate an unclean/forcible shutdown on the underlying socket.
1360 // However, simulate this error asynchronously.
1361 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1362 raw_transport->BlockWrite();
1364 // This write should complete synchronously, because the TLS ciphertext
1365 // can be created and placed into the outgoing buffers independent of the
1366 // underlying transport.
1367 rv = callback.GetResult(
1368 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1369 EXPECT_EQ(kRequestTextSize, rv);
1371 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1373 rv = sock->Read(buf.get(), 4096, callback.callback());
1374 EXPECT_EQ(ERR_IO_PENDING, rv);
1376 // Now unblock the outgoing request, having it fail with the connection
1377 // being reset.
1378 raw_transport->UnblockWrite();
1380 // Note: This will cause an inifite loop if this bug has regressed. Simply
1381 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1382 // is a legitimate result when using a dedicated task runner for NSS.
1383 rv = callback.GetResult(rv);
1385 #if !defined(USE_OPENSSL)
1386 // SSLClientSocketNSS records the error exactly
1387 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1388 #else
1389 // SSLClientSocketOpenSSL treats any errors as a simple EOF.
1390 EXPECT_EQ(0, rv);
1391 #endif
1394 // If there is a Write failure at the transport with no follow-up Read, although
1395 // the write error will not be returned to the client until a future Read or
1396 // Write operation, SSLClientSocket should not spin attempting to re-write on
1397 // the socket. This is a regression test for part of https://crbug.com/381160.
1398 TEST_F(SSLClientSocketTest, Write_WithSynchronousErrorNoRead) {
1399 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1400 SpawnedTestServer::kLocalhost,
1401 base::FilePath());
1402 ASSERT_TRUE(test_server.Start());
1404 AddressList addr;
1405 ASSERT_TRUE(test_server.GetAddressList(&addr));
1407 TestCompletionCallback callback;
1408 scoped_ptr<StreamSocket> real_transport(
1409 new TCPClientSocket(addr, NULL, NetLog::Source()));
1410 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1411 // is retained in order to query them.
1412 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1413 new SynchronousErrorStreamSocket(real_transport.Pass()));
1414 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1415 scoped_ptr<CountingStreamSocket> counting_socket(
1416 new CountingStreamSocket(error_socket.PassAs<StreamSocket>()));
1417 CountingStreamSocket* raw_counting_socket = counting_socket.get();
1418 int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
1419 ASSERT_EQ(OK, rv);
1421 // Disable TLS False Start to avoid handshake non-determinism.
1422 SSLConfig ssl_config;
1423 ssl_config.false_start_enabled = false;
1425 scoped_ptr<SSLClientSocket> sock(
1426 CreateSSLClientSocket(counting_socket.PassAs<StreamSocket>(),
1427 test_server.host_port_pair(),
1428 ssl_config));
1430 rv = callback.GetResult(sock->Connect(callback.callback()));
1431 ASSERT_EQ(OK, rv);
1432 ASSERT_TRUE(sock->IsConnected());
1434 // Simulate an unclean/forcible shutdown on the underlying socket.
1435 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1437 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1438 static const int kRequestTextSize =
1439 static_cast<int>(arraysize(request_text) - 1);
1440 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1441 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1443 // This write should complete synchronously, because the TLS ciphertext
1444 // can be created and placed into the outgoing buffers independent of the
1445 // underlying transport.
1446 rv = callback.GetResult(
1447 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1448 ASSERT_EQ(kRequestTextSize, rv);
1450 // Let the event loop spin for a little bit of time. Even on platforms where
1451 // pumping the state machine involve thread hops, there should be no further
1452 // writes on the transport socket.
1454 // TODO(davidben): Avoid the arbitrary timeout?
1455 int old_write_count = raw_counting_socket->write_count();
1456 base::RunLoop loop;
1457 base::MessageLoop::current()->PostDelayedTask(
1458 FROM_HERE, loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1459 loop.Run();
1460 EXPECT_EQ(old_write_count, raw_counting_socket->write_count());
1463 // Test the full duplex mode, with Read and Write pending at the same time.
1464 // This test also serves as a regression test for http://crbug.com/29815.
1465 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1466 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1467 SpawnedTestServer::kLocalhost,
1468 base::FilePath());
1469 ASSERT_TRUE(test_server.Start());
1471 AddressList addr;
1472 ASSERT_TRUE(test_server.GetAddressList(&addr));
1474 TestCompletionCallback callback; // Used for everything except Write.
1476 scoped_ptr<StreamSocket> transport(
1477 new TCPClientSocket(addr, NULL, NetLog::Source()));
1478 int rv = transport->Connect(callback.callback());
1479 if (rv == ERR_IO_PENDING)
1480 rv = callback.WaitForResult();
1481 EXPECT_EQ(OK, rv);
1483 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1484 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1486 rv = sock->Connect(callback.callback());
1487 if (rv == ERR_IO_PENDING)
1488 rv = callback.WaitForResult();
1489 EXPECT_EQ(OK, rv);
1490 EXPECT_TRUE(sock->IsConnected());
1492 // Issue a "hanging" Read first.
1493 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1494 rv = sock->Read(buf.get(), 4096, callback.callback());
1495 // We haven't written the request, so there should be no response yet.
1496 ASSERT_EQ(ERR_IO_PENDING, rv);
1498 // Write the request.
1499 // The request is padded with a User-Agent header to a size that causes the
1500 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1501 // This tests the fix for http://crbug.com/29815.
1502 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1503 for (int i = 0; i < 3770; ++i)
1504 request_text.push_back('*');
1505 request_text.append("\r\n\r\n");
1506 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1508 TestCompletionCallback callback2; // Used for Write only.
1509 rv = sock->Write(
1510 request_buffer.get(), request_text.size(), callback2.callback());
1511 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1513 if (rv == ERR_IO_PENDING)
1514 rv = callback2.WaitForResult();
1515 EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1517 // Now get the Read result.
1518 rv = callback.WaitForResult();
1519 EXPECT_GT(rv, 0);
1522 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1523 // mode when the underlying transport is blocked on sending data. When the
1524 // underlying transport completes due to an error, it should invoke both the
1525 // Read() and Write() callbacks. If the socket is deleted by the Read()
1526 // callback, the Write() callback should not be invoked.
1527 // Regression test for http://crbug.com/232633
1528 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1529 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1530 SpawnedTestServer::kLocalhost,
1531 base::FilePath());
1532 ASSERT_TRUE(test_server.Start());
1534 AddressList addr;
1535 ASSERT_TRUE(test_server.GetAddressList(&addr));
1537 TestCompletionCallback callback;
1538 scoped_ptr<StreamSocket> real_transport(
1539 new TCPClientSocket(addr, NULL, NetLog::Source()));
1540 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1541 // is retained in order to configure additional errors.
1542 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1543 new SynchronousErrorStreamSocket(real_transport.Pass()));
1544 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1545 scoped_ptr<FakeBlockingStreamSocket> transport(
1546 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1547 FakeBlockingStreamSocket* raw_transport = transport.get();
1549 int rv = callback.GetResult(transport->Connect(callback.callback()));
1550 EXPECT_EQ(OK, rv);
1552 // Disable TLS False Start to avoid handshake non-determinism.
1553 SSLConfig ssl_config;
1554 ssl_config.false_start_enabled = false;
1556 scoped_ptr<SSLClientSocket> sock =
1557 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1558 test_server.host_port_pair(),
1559 ssl_config);
1561 rv = callback.GetResult(sock->Connect(callback.callback()));
1562 EXPECT_EQ(OK, rv);
1563 EXPECT_TRUE(sock->IsConnected());
1565 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1566 request_text.append(20 * 1024, '*');
1567 request_text.append("\r\n\r\n");
1568 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1569 new StringIOBuffer(request_text), request_text.size()));
1571 // Simulate errors being returned from the underlying Read() and Write() ...
1572 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1573 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1574 // ... but have those errors returned asynchronously. Because the Write() will
1575 // return first, this will trigger the error.
1576 raw_transport->BlockReadResult();
1577 raw_transport->BlockWrite();
1579 // Enqueue a Read() before calling Write(), which should "hang" due to
1580 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1581 SSLClientSocket* raw_sock = sock.get();
1582 DeleteSocketCallback read_callback(sock.release());
1583 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1584 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1586 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1587 ASSERT_EQ(ERR_IO_PENDING, rv);
1588 ASSERT_FALSE(read_callback.have_result());
1590 #if !defined(USE_OPENSSL)
1591 // NSS follows a pattern where a call to PR_Write will only consume as
1592 // much data as it can encode into application data records before the
1593 // internal memio buffer is full, which should only fill if writing a large
1594 // amount of data and the underlying transport is blocked. Once this happens,
1595 // NSS will return (total size of all application data records it wrote) - 1,
1596 // with the caller expected to resume with the remaining unsent data.
1598 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1599 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1600 // get the socket in the state needed for the test below.
1602 // This is not needed for OpenSSL, because for OpenSSL,
1603 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1604 // SSLClientSocketOpenSSL::Write() will not return until all of
1605 // |request_buffer| has been written to the underlying BIO (although not
1606 // necessarily the underlying transport).
1607 rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1608 request_buffer->BytesRemaining(),
1609 callback.callback()));
1610 ASSERT_LT(0, rv);
1611 request_buffer->DidConsume(rv);
1613 // Guard to ensure that |request_buffer| was larger than all of the internal
1614 // buffers (transport, memio, NSS) along the way - otherwise the next call
1615 // to Write() will crash with an invalid buffer.
1616 ASSERT_LT(0, request_buffer->BytesRemaining());
1617 #endif
1619 // Attempt to write the remaining data. NSS will not be able to consume the
1620 // application data because the internal buffers are full, while OpenSSL will
1621 // return that its blocked because the underlying transport is blocked.
1622 rv = raw_sock->Write(request_buffer.get(),
1623 request_buffer->BytesRemaining(),
1624 callback.callback());
1625 ASSERT_EQ(ERR_IO_PENDING, rv);
1626 ASSERT_FALSE(callback.have_result());
1628 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1629 // call the Read() callback, deleting the socket and thus aborting calling
1630 // the Write() callback.
1631 raw_transport->UnblockWrite();
1633 rv = read_callback.WaitForResult();
1635 #if !defined(USE_OPENSSL)
1636 // NSS records the error exactly.
1637 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1638 #else
1639 // OpenSSL treats any errors as a simple EOF.
1640 EXPECT_EQ(0, rv);
1641 #endif
1643 // The Write callback should not have been called.
1644 EXPECT_FALSE(callback.have_result());
1647 // Tests that the SSLClientSocket does not crash if data is received on the
1648 // transport socket after a failing write. This can occur if we have a Write
1649 // error in a SPDY socket.
1650 // Regression test for http://crbug.com/335557
1651 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1652 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1653 SpawnedTestServer::kLocalhost,
1654 base::FilePath());
1655 ASSERT_TRUE(test_server.Start());
1657 AddressList addr;
1658 ASSERT_TRUE(test_server.GetAddressList(&addr));
1660 TestCompletionCallback callback;
1661 scoped_ptr<StreamSocket> real_transport(
1662 new TCPClientSocket(addr, NULL, NetLog::Source()));
1663 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1664 // is retained in order to configure additional errors.
1665 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1666 new SynchronousErrorStreamSocket(real_transport.Pass()));
1667 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1668 scoped_ptr<FakeBlockingStreamSocket> transport(
1669 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1670 FakeBlockingStreamSocket* raw_transport = transport.get();
1672 int rv = callback.GetResult(transport->Connect(callback.callback()));
1673 EXPECT_EQ(OK, rv);
1675 // Disable TLS False Start to avoid handshake non-determinism.
1676 SSLConfig ssl_config;
1677 ssl_config.false_start_enabled = false;
1679 scoped_ptr<SSLClientSocket> sock(
1680 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1681 test_server.host_port_pair(),
1682 ssl_config));
1684 rv = callback.GetResult(sock->Connect(callback.callback()));
1685 EXPECT_EQ(OK, rv);
1686 EXPECT_TRUE(sock->IsConnected());
1688 // Send a request so there is something to read from the socket.
1689 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1690 static const int kRequestTextSize =
1691 static_cast<int>(arraysize(request_text) - 1);
1692 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1693 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1695 rv = callback.GetResult(
1696 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1697 EXPECT_EQ(kRequestTextSize, rv);
1699 // Start a hanging read.
1700 TestCompletionCallback read_callback;
1701 raw_transport->BlockReadResult();
1702 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1703 rv = sock->Read(buf.get(), 4096, read_callback.callback());
1704 EXPECT_EQ(ERR_IO_PENDING, rv);
1706 // Perform another write, but have it fail. Write a request larger than the
1707 // internal socket buffers so that the request hits the underlying transport
1708 // socket and detects the error.
1709 std::string long_request_text =
1710 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1711 long_request_text.append(20 * 1024, '*');
1712 long_request_text.append("\r\n\r\n");
1713 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1714 new StringIOBuffer(long_request_text), long_request_text.size()));
1716 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1718 // Write as much data as possible until hitting an error. This is necessary
1719 // for NSS. PR_Write will only consume as much data as it can encode into
1720 // application data records before the internal memio buffer is full, which
1721 // should only fill if writing a large amount of data and the underlying
1722 // transport is blocked. Once this happens, NSS will return (total size of all
1723 // application data records it wrote) - 1, with the caller expected to resume
1724 // with the remaining unsent data.
1725 do {
1726 rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1727 long_request_buffer->BytesRemaining(),
1728 callback.callback()));
1729 if (rv > 0) {
1730 long_request_buffer->DidConsume(rv);
1731 // Abort if the entire buffer is ever consumed.
1732 ASSERT_LT(0, long_request_buffer->BytesRemaining());
1734 } while (rv > 0);
1736 #if !defined(USE_OPENSSL)
1737 // NSS records the error exactly.
1738 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1739 #else
1740 // OpenSSL treats the reset as a generic protocol error.
1741 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
1742 #endif
1744 // Release the read. Some bytes should go through.
1745 raw_transport->UnblockReadResult();
1746 rv = read_callback.WaitForResult();
1748 // Per the fix for http://crbug.com/249848, write failures currently break
1749 // reads. Change this assertion if they're changed to not collide.
1750 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1753 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1754 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1755 SpawnedTestServer::kLocalhost,
1756 base::FilePath());
1757 ASSERT_TRUE(test_server.Start());
1759 AddressList addr;
1760 ASSERT_TRUE(test_server.GetAddressList(&addr));
1762 TestCompletionCallback callback;
1763 scoped_ptr<StreamSocket> transport(
1764 new TCPClientSocket(addr, NULL, NetLog::Source()));
1765 int rv = transport->Connect(callback.callback());
1766 if (rv == ERR_IO_PENDING)
1767 rv = callback.WaitForResult();
1768 EXPECT_EQ(OK, rv);
1770 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1771 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1773 rv = sock->Connect(callback.callback());
1774 if (rv == ERR_IO_PENDING)
1775 rv = callback.WaitForResult();
1776 EXPECT_EQ(OK, rv);
1778 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1779 scoped_refptr<IOBuffer> request_buffer(
1780 new IOBuffer(arraysize(request_text) - 1));
1781 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1783 rv = sock->Write(
1784 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1785 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1787 if (rv == ERR_IO_PENDING)
1788 rv = callback.WaitForResult();
1789 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1791 scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1792 for (;;) {
1793 rv = sock->Read(buf.get(), 1, callback.callback());
1794 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1796 if (rv == ERR_IO_PENDING)
1797 rv = callback.WaitForResult();
1799 EXPECT_GE(rv, 0);
1800 if (rv <= 0)
1801 break;
1805 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
1806 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1807 SpawnedTestServer::kLocalhost,
1808 base::FilePath());
1809 ASSERT_TRUE(test_server.Start());
1811 AddressList addr;
1812 ASSERT_TRUE(test_server.GetAddressList(&addr));
1814 TestCompletionCallback callback;
1816 scoped_ptr<StreamSocket> real_transport(
1817 new TCPClientSocket(addr, NULL, NetLog::Source()));
1818 scoped_ptr<ReadBufferingStreamSocket> transport(
1819 new ReadBufferingStreamSocket(real_transport.Pass()));
1820 ReadBufferingStreamSocket* raw_transport = transport.get();
1821 int rv = callback.GetResult(transport->Connect(callback.callback()));
1822 ASSERT_EQ(OK, rv);
1824 scoped_ptr<SSLClientSocket> sock(
1825 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1826 test_server.host_port_pair(),
1827 kDefaultSSLConfig));
1829 rv = callback.GetResult(sock->Connect(callback.callback()));
1830 ASSERT_EQ(OK, rv);
1831 ASSERT_TRUE(sock->IsConnected());
1833 const char request_text[] = "GET /ssl-many-small-records 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 = callback.GetResult(sock->Write(
1839 request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
1840 ASSERT_GT(rv, 0);
1841 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1843 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
1844 // data (the max SSL record size) at a time. Ensure that at least 15K worth
1845 // of SSL data is buffered first. The 15K of buffered data is made up of
1846 // many smaller SSL records (the TestServer writes along 1350 byte
1847 // plaintext boundaries), although there may also be a few records that are
1848 // smaller or larger, due to timing and SSL False Start.
1849 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
1850 // the SSLClientSocket implementation, and larger than the minimum amount
1851 // of ciphertext necessary to contain the 8K of plaintext requested below.
1852 raw_transport->SetBufferSize(15000);
1854 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
1855 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
1856 ASSERT_EQ(rv, 8192);
1859 TEST_F(SSLClientSocketTest, Read_Interrupted) {
1860 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1861 SpawnedTestServer::kLocalhost,
1862 base::FilePath());
1863 ASSERT_TRUE(test_server.Start());
1865 AddressList addr;
1866 ASSERT_TRUE(test_server.GetAddressList(&addr));
1868 TestCompletionCallback callback;
1869 scoped_ptr<StreamSocket> transport(
1870 new TCPClientSocket(addr, NULL, NetLog::Source()));
1871 int rv = transport->Connect(callback.callback());
1872 if (rv == ERR_IO_PENDING)
1873 rv = callback.WaitForResult();
1874 EXPECT_EQ(OK, rv);
1876 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1877 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1879 rv = sock->Connect(callback.callback());
1880 if (rv == ERR_IO_PENDING)
1881 rv = callback.WaitForResult();
1882 EXPECT_EQ(OK, rv);
1884 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1885 scoped_refptr<IOBuffer> request_buffer(
1886 new IOBuffer(arraysize(request_text) - 1));
1887 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1889 rv = sock->Write(
1890 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1891 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1893 if (rv == ERR_IO_PENDING)
1894 rv = callback.WaitForResult();
1895 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1897 // Do a partial read and then exit. This test should not crash!
1898 scoped_refptr<IOBuffer> buf(new IOBuffer(512));
1899 rv = sock->Read(buf.get(), 512, callback.callback());
1900 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
1902 if (rv == ERR_IO_PENDING)
1903 rv = callback.WaitForResult();
1905 EXPECT_GT(rv, 0);
1908 TEST_F(SSLClientSocketTest, Read_FullLogging) {
1909 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1910 SpawnedTestServer::kLocalhost,
1911 base::FilePath());
1912 ASSERT_TRUE(test_server.Start());
1914 AddressList addr;
1915 ASSERT_TRUE(test_server.GetAddressList(&addr));
1917 TestCompletionCallback callback;
1918 CapturingNetLog log;
1919 log.SetLogLevel(NetLog::LOG_ALL);
1920 scoped_ptr<StreamSocket> transport(
1921 new TCPClientSocket(addr, &log, NetLog::Source()));
1922 int rv = transport->Connect(callback.callback());
1923 if (rv == ERR_IO_PENDING)
1924 rv = callback.WaitForResult();
1925 EXPECT_EQ(OK, rv);
1927 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1928 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1930 rv = sock->Connect(callback.callback());
1931 if (rv == ERR_IO_PENDING)
1932 rv = callback.WaitForResult();
1933 EXPECT_EQ(OK, rv);
1934 EXPECT_TRUE(sock->IsConnected());
1936 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1937 scoped_refptr<IOBuffer> request_buffer(
1938 new IOBuffer(arraysize(request_text) - 1));
1939 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1941 rv = sock->Write(
1942 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1943 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1945 if (rv == ERR_IO_PENDING)
1946 rv = callback.WaitForResult();
1947 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1949 CapturingNetLog::CapturedEntryList entries;
1950 log.GetEntries(&entries);
1951 size_t last_index = ExpectLogContainsSomewhereAfter(
1952 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
1954 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1955 for (;;) {
1956 rv = sock->Read(buf.get(), 4096, callback.callback());
1957 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1959 if (rv == ERR_IO_PENDING)
1960 rv = callback.WaitForResult();
1962 EXPECT_GE(rv, 0);
1963 if (rv <= 0)
1964 break;
1966 log.GetEntries(&entries);
1967 last_index =
1968 ExpectLogContainsSomewhereAfter(entries,
1969 last_index + 1,
1970 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1971 NetLog::PHASE_NONE);
1975 // Regression test for http://crbug.com/42538
1976 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
1977 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1978 SpawnedTestServer::kLocalhost,
1979 base::FilePath());
1980 ASSERT_TRUE(test_server.Start());
1982 AddressList addr;
1983 TestCompletionCallback callback;
1985 static const unsigned char application_data[] = {
1986 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
1987 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
1988 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
1989 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
1990 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
1991 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
1992 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
1993 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
1994 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
1995 0x0a};
1997 // All reads and writes complete synchronously (async=false).
1998 MockRead data_reads[] = {
1999 MockRead(SYNCHRONOUS,
2000 reinterpret_cast<const char*>(application_data),
2001 arraysize(application_data)),
2002 MockRead(SYNCHRONOUS, OK), };
2004 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
2006 scoped_ptr<StreamSocket> transport(
2007 new MockTCPClientSocket(addr, NULL, &data));
2008 int rv = transport->Connect(callback.callback());
2009 if (rv == ERR_IO_PENDING)
2010 rv = callback.WaitForResult();
2011 EXPECT_EQ(OK, rv);
2013 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2014 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2016 rv = sock->Connect(callback.callback());
2017 if (rv == ERR_IO_PENDING)
2018 rv = callback.WaitForResult();
2019 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
2022 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
2023 // Rather than exhaustively disabling every RC4 ciphersuite defined at
2024 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
2025 // only disabling those cipher suites that the test server actually
2026 // implements.
2027 const uint16 kCiphersToDisable[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA
2030 SpawnedTestServer::SSLOptions ssl_options;
2031 // Enable only RC4 on the test server.
2032 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
2033 SpawnedTestServer test_server(
2034 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2035 ASSERT_TRUE(test_server.Start());
2037 AddressList addr;
2038 ASSERT_TRUE(test_server.GetAddressList(&addr));
2040 TestCompletionCallback callback;
2041 CapturingNetLog log;
2042 scoped_ptr<StreamSocket> transport(
2043 new TCPClientSocket(addr, &log, NetLog::Source()));
2044 int rv = transport->Connect(callback.callback());
2045 if (rv == ERR_IO_PENDING)
2046 rv = callback.WaitForResult();
2047 EXPECT_EQ(OK, rv);
2049 SSLConfig ssl_config;
2050 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
2051 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
2053 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2054 transport.Pass(), test_server.host_port_pair(), ssl_config));
2056 EXPECT_FALSE(sock->IsConnected());
2058 rv = sock->Connect(callback.callback());
2059 CapturingNetLog::CapturedEntryList entries;
2060 log.GetEntries(&entries);
2061 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2063 // NSS has special handling that maps a handshake_failure alert received
2064 // immediately after a client_hello to be a mismatched cipher suite error,
2065 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
2066 // Secure Transport (OS X), the handshake_failure is bubbled up without any
2067 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
2068 // indicates that no cipher suite was negotiated with the test server.
2069 if (rv == ERR_IO_PENDING)
2070 rv = callback.WaitForResult();
2071 EXPECT_TRUE(rv == ERR_SSL_VERSION_OR_CIPHER_MISMATCH ||
2072 rv == ERR_SSL_PROTOCOL_ERROR);
2073 // The exact ordering differs between SSLClientSocketNSS (which issues an
2074 // extra read) and SSLClientSocketMac (which does not). Just make sure the
2075 // error appears somewhere in the log.
2076 log.GetEntries(&entries);
2077 ExpectLogContainsSomewhere(
2078 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
2080 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2081 // the socket when it encounters an error, whereas other implementations
2082 // leave it connected.
2083 // Because this an error that the test server is mutually aware of, as opposed
2084 // to being an error such as a certificate name mismatch, which is
2085 // client-only, the exact index of the SSL connect end depends on how
2086 // quickly the test server closes the underlying socket. If the test server
2087 // closes before the IO message loop pumps messages, there may be a 0-byte
2088 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2089 // result, the SSL connect end event will be the second-to-last entry,
2090 // rather than the last entry.
2091 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1) ||
2092 LogContainsSSLConnectEndEvent(entries, -2));
2095 // When creating an SSLClientSocket, it is allowed to pass in a
2096 // ClientSocketHandle that is not obtained from a client socket pool.
2097 // Here we verify that such a simple ClientSocketHandle, not associated with any
2098 // client socket pool, can be destroyed safely.
2099 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
2100 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2101 SpawnedTestServer::kLocalhost,
2102 base::FilePath());
2103 ASSERT_TRUE(test_server.Start());
2105 AddressList addr;
2106 ASSERT_TRUE(test_server.GetAddressList(&addr));
2108 TestCompletionCallback callback;
2109 scoped_ptr<StreamSocket> transport(
2110 new TCPClientSocket(addr, NULL, NetLog::Source()));
2111 int rv = transport->Connect(callback.callback());
2112 if (rv == ERR_IO_PENDING)
2113 rv = callback.WaitForResult();
2114 EXPECT_EQ(OK, rv);
2116 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
2117 socket_handle->SetSocket(transport.Pass());
2119 scoped_ptr<SSLClientSocket> sock(
2120 socket_factory_->CreateSSLClientSocket(socket_handle.Pass(),
2121 test_server.host_port_pair(),
2122 kDefaultSSLConfig,
2123 context_));
2125 EXPECT_FALSE(sock->IsConnected());
2126 rv = sock->Connect(callback.callback());
2127 if (rv == ERR_IO_PENDING)
2128 rv = callback.WaitForResult();
2129 EXPECT_EQ(OK, rv);
2132 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2133 // code and different keying label results in different keying material.
2134 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
2135 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2136 SpawnedTestServer::kLocalhost,
2137 base::FilePath());
2138 ASSERT_TRUE(test_server.Start());
2140 AddressList addr;
2141 ASSERT_TRUE(test_server.GetAddressList(&addr));
2143 TestCompletionCallback callback;
2145 scoped_ptr<StreamSocket> transport(
2146 new TCPClientSocket(addr, NULL, NetLog::Source()));
2147 int rv = transport->Connect(callback.callback());
2148 if (rv == ERR_IO_PENDING)
2149 rv = callback.WaitForResult();
2150 EXPECT_EQ(OK, rv);
2152 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2153 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2155 rv = sock->Connect(callback.callback());
2156 if (rv == ERR_IO_PENDING)
2157 rv = callback.WaitForResult();
2158 EXPECT_EQ(OK, rv);
2159 EXPECT_TRUE(sock->IsConnected());
2161 const int kKeyingMaterialSize = 32;
2162 const char* kKeyingLabel1 = "client-socket-test-1";
2163 const char* kKeyingContext = "";
2164 unsigned char client_out1[kKeyingMaterialSize];
2165 memset(client_out1, 0, sizeof(client_out1));
2166 rv = sock->ExportKeyingMaterial(
2167 kKeyingLabel1, false, kKeyingContext, client_out1, sizeof(client_out1));
2168 EXPECT_EQ(rv, OK);
2170 const char* kKeyingLabel2 = "client-socket-test-2";
2171 unsigned char client_out2[kKeyingMaterialSize];
2172 memset(client_out2, 0, sizeof(client_out2));
2173 rv = sock->ExportKeyingMaterial(
2174 kKeyingLabel2, false, kKeyingContext, client_out2, sizeof(client_out2));
2175 EXPECT_EQ(rv, OK);
2176 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2179 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2180 // explicit NSS initialization.
2181 TEST(SSLClientSocket, ClearSessionCache) {
2182 SSLClientSocket::ClearSessionCache();
2185 // Test that the server certificates are properly retrieved from the underlying
2186 // SSL stack.
2187 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
2188 // The connection does not have to be successful.
2189 cert_verifier_->set_default_result(ERR_CERT_INVALID);
2191 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2192 // This makes the server present redundant-server-chain.pem, which contains
2193 // intermediate certificates.
2194 SpawnedTestServer::SSLOptions ssl_options(
2195 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2196 SpawnedTestServer test_server(
2197 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2198 ASSERT_TRUE(test_server.Start());
2200 AddressList addr;
2201 ASSERT_TRUE(test_server.GetAddressList(&addr));
2203 TestCompletionCallback callback;
2204 scoped_ptr<StreamSocket> transport(
2205 new TCPClientSocket(addr, NULL, NetLog::Source()));
2206 int rv = transport->Connect(callback.callback());
2207 rv = callback.GetResult(rv);
2208 EXPECT_EQ(OK, rv);
2210 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2211 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2212 EXPECT_FALSE(sock->IsConnected());
2213 rv = sock->Connect(callback.callback());
2214 rv = callback.GetResult(rv);
2216 EXPECT_EQ(ERR_CERT_INVALID, rv);
2217 EXPECT_TRUE(sock->IsConnected());
2219 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2220 // certs from redundant-server-chain.pem.
2221 CertificateList server_certs =
2222 CreateCertificateListFromFile(GetTestCertsDirectory(),
2223 "redundant-server-chain.pem",
2224 X509Certificate::FORMAT_AUTO);
2226 // Get the server certificate as received client side.
2227 scoped_refptr<X509Certificate> server_certificate =
2228 sock->GetUnverifiedServerCertificateChain();
2230 // Get the intermediates as received client side.
2231 const X509Certificate::OSCertHandles& server_intermediates =
2232 server_certificate->GetIntermediateCertificates();
2234 // Check that the unverified server certificate chain is properly retrieved
2235 // from the underlying ssl stack.
2236 ASSERT_EQ(4U, server_certs.size());
2238 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2239 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
2241 ASSERT_EQ(3U, server_intermediates.size());
2243 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
2244 server_certs[1]->os_cert_handle()));
2245 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
2246 server_certs[2]->os_cert_handle()));
2247 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
2248 server_certs[3]->os_cert_handle()));
2250 sock->Disconnect();
2251 EXPECT_FALSE(sock->IsConnected());
2254 // This tests that SSLInfo contains a properly re-constructed certificate
2255 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2256 // verified, not the chain as served by the server. (They may be different.)
2258 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2259 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2260 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2261 // a self-signed root. Such a situation can occur when a new root (C2) is
2262 // cross-certified by an old root (D) and has two different versions of its
2263 // floating around. Servers may supply C2 as an intermediate, but the
2264 // SSLClientSocket should return the chain that was verified, from
2265 // verify_result, instead.
2266 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
2267 // By default, cause the CertVerifier to treat all certificates as
2268 // expired.
2269 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
2271 // We will expect SSLInfo to ultimately contain this chain.
2272 CertificateList certs =
2273 CreateCertificateListFromFile(GetTestCertsDirectory(),
2274 "redundant-validated-chain.pem",
2275 X509Certificate::FORMAT_AUTO);
2276 ASSERT_EQ(3U, certs.size());
2278 X509Certificate::OSCertHandles temp_intermediates;
2279 temp_intermediates.push_back(certs[1]->os_cert_handle());
2280 temp_intermediates.push_back(certs[2]->os_cert_handle());
2282 CertVerifyResult verify_result;
2283 verify_result.verified_cert = X509Certificate::CreateFromHandle(
2284 certs[0]->os_cert_handle(), temp_intermediates);
2286 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2287 // rather than A->B->C.
2288 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
2290 // Load and install the root for the validated chain.
2291 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
2292 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2293 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert);
2294 ScopedTestRoot scoped_root(root_cert.get());
2296 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2297 SpawnedTestServer::SSLOptions ssl_options(
2298 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2299 SpawnedTestServer test_server(
2300 SpawnedTestServer::TYPE_HTTPS,
2301 ssl_options,
2302 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2303 ASSERT_TRUE(test_server.Start());
2305 AddressList addr;
2306 ASSERT_TRUE(test_server.GetAddressList(&addr));
2308 TestCompletionCallback callback;
2309 CapturingNetLog log;
2310 scoped_ptr<StreamSocket> transport(
2311 new TCPClientSocket(addr, &log, NetLog::Source()));
2312 int rv = transport->Connect(callback.callback());
2313 if (rv == ERR_IO_PENDING)
2314 rv = callback.WaitForResult();
2315 EXPECT_EQ(OK, rv);
2317 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2318 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2319 EXPECT_FALSE(sock->IsConnected());
2320 rv = sock->Connect(callback.callback());
2322 CapturingNetLog::CapturedEntryList entries;
2323 log.GetEntries(&entries);
2324 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2325 if (rv == ERR_IO_PENDING)
2326 rv = callback.WaitForResult();
2328 EXPECT_EQ(OK, rv);
2329 EXPECT_TRUE(sock->IsConnected());
2330 log.GetEntries(&entries);
2331 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2333 SSLInfo ssl_info;
2334 sock->GetSSLInfo(&ssl_info);
2336 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2337 // -> C2.
2338 const X509Certificate::OSCertHandles& intermediates =
2339 ssl_info.cert->GetIntermediateCertificates();
2340 ASSERT_EQ(2U, intermediates.size());
2341 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
2342 certs[0]->os_cert_handle()));
2343 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
2344 certs[1]->os_cert_handle()));
2345 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
2346 certs[2]->os_cert_handle()));
2348 sock->Disconnect();
2349 EXPECT_FALSE(sock->IsConnected());
2352 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
2353 SpawnedTestServer::SSLOptions ssl_options;
2354 ssl_options.request_client_certificate = true;
2355 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2356 ASSERT_TRUE(request_info.get());
2357 EXPECT_EQ(0u, request_info->cert_authorities.size());
2360 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
2361 const base::FilePath::CharType kThawteFile[] =
2362 FILE_PATH_LITERAL("thawte.single.pem");
2363 const unsigned char kThawteDN[] = {
2364 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2365 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2366 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2367 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2368 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2369 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2370 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2371 const size_t kThawteLen = sizeof(kThawteDN);
2373 const base::FilePath::CharType kDiginotarFile[] =
2374 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2375 const unsigned char kDiginotarDN[] = {
2376 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2377 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2378 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2379 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2380 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2381 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2382 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2383 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2384 0x6c};
2385 const size_t kDiginotarLen = sizeof(kDiginotarDN);
2387 SpawnedTestServer::SSLOptions ssl_options;
2388 ssl_options.request_client_certificate = true;
2389 ssl_options.client_authorities.push_back(
2390 GetTestClientCertsDirectory().Append(kThawteFile));
2391 ssl_options.client_authorities.push_back(
2392 GetTestClientCertsDirectory().Append(kDiginotarFile));
2393 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2394 ASSERT_TRUE(request_info.get());
2395 ASSERT_EQ(2u, request_info->cert_authorities.size());
2396 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
2397 request_info->cert_authorities[0]);
2398 EXPECT_EQ(
2399 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
2400 request_info->cert_authorities[1]);
2403 // cert_key_types is currently only populated on OpenSSL.
2404 #if defined(USE_OPENSSL)
2405 TEST_F(SSLClientSocketCertRequestInfoTest, CertKeyTypes) {
2406 SpawnedTestServer::SSLOptions ssl_options;
2407 ssl_options.request_client_certificate = true;
2408 ssl_options.client_cert_types.push_back(CLIENT_CERT_RSA_SIGN);
2409 ssl_options.client_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2410 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2411 ASSERT_TRUE(request_info.get());
2412 ASSERT_EQ(2u, request_info->cert_key_types.size());
2413 EXPECT_EQ(CLIENT_CERT_RSA_SIGN, request_info->cert_key_types[0]);
2414 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, request_info->cert_key_types[1]);
2416 #endif // defined(USE_OPENSSL)
2418 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
2419 SpawnedTestServer::SSLOptions ssl_options;
2420 ssl_options.signed_cert_timestamps_tls_ext = "test";
2422 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2423 ssl_options,
2424 base::FilePath());
2425 ASSERT_TRUE(test_server.Start());
2427 AddressList addr;
2428 ASSERT_TRUE(test_server.GetAddressList(&addr));
2430 TestCompletionCallback callback;
2431 CapturingNetLog log;
2432 scoped_ptr<StreamSocket> transport(
2433 new TCPClientSocket(addr, &log, NetLog::Source()));
2434 int rv = transport->Connect(callback.callback());
2435 if (rv == ERR_IO_PENDING)
2436 rv = callback.WaitForResult();
2437 EXPECT_EQ(OK, rv);
2439 SSLConfig ssl_config;
2440 ssl_config.signed_cert_timestamps_enabled = true;
2442 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2443 transport.Pass(), test_server.host_port_pair(), ssl_config));
2445 EXPECT_FALSE(sock->IsConnected());
2447 rv = sock->Connect(callback.callback());
2449 CapturingNetLog::CapturedEntryList entries;
2450 log.GetEntries(&entries);
2451 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2452 if (rv == ERR_IO_PENDING)
2453 rv = callback.WaitForResult();
2454 EXPECT_EQ(OK, rv);
2455 EXPECT_TRUE(sock->IsConnected());
2456 log.GetEntries(&entries);
2457 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2459 #if !defined(USE_OPENSSL)
2460 EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2461 #else
2462 // Enabling CT for OpenSSL is currently a noop.
2463 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2464 #endif
2466 sock->Disconnect();
2467 EXPECT_FALSE(sock->IsConnected());
2470 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2471 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2472 SpawnedTestServer::SSLOptions ssl_options;
2473 ssl_options.staple_ocsp_response = true;
2474 // The test server currently only knows how to generate OCSP responses
2475 // for a freshly minted certificate.
2476 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2478 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2479 ssl_options,
2480 base::FilePath());
2481 ASSERT_TRUE(test_server.Start());
2483 AddressList addr;
2484 ASSERT_TRUE(test_server.GetAddressList(&addr));
2486 TestCompletionCallback callback;
2487 CapturingNetLog log;
2488 scoped_ptr<StreamSocket> transport(
2489 new TCPClientSocket(addr, &log, NetLog::Source()));
2490 int rv = transport->Connect(callback.callback());
2491 if (rv == ERR_IO_PENDING)
2492 rv = callback.WaitForResult();
2493 EXPECT_EQ(OK, rv);
2495 SSLConfig ssl_config;
2496 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2497 // Certificate Transparency verification regardless of whether the platform
2498 // is able to process the OCSP status itself.
2499 ssl_config.signed_cert_timestamps_enabled = true;
2501 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2502 transport.Pass(), test_server.host_port_pair(), ssl_config));
2504 EXPECT_FALSE(sock->IsConnected());
2506 rv = sock->Connect(callback.callback());
2508 CapturingNetLog::CapturedEntryList entries;
2509 log.GetEntries(&entries);
2510 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2511 if (rv == ERR_IO_PENDING)
2512 rv = callback.WaitForResult();
2513 EXPECT_EQ(OK, rv);
2514 EXPECT_TRUE(sock->IsConnected());
2515 log.GetEntries(&entries);
2516 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2518 #if !defined(USE_OPENSSL)
2519 EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2520 #else
2521 // OCSP stapling isn't currently supported in the OpenSSL socket.
2522 EXPECT_FALSE(sock->stapled_ocsp_response_received_);
2523 #endif
2525 sock->Disconnect();
2526 EXPECT_FALSE(sock->IsConnected());
2529 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2530 SpawnedTestServer::SSLOptions ssl_options;
2531 ssl_options.signed_cert_timestamps_tls_ext = "test";
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 ssl_config.signed_cert_timestamps_enabled = false;
2553 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2554 transport.Pass(), test_server.host_port_pair(), ssl_config));
2556 EXPECT_FALSE(sock->IsConnected());
2558 rv = sock->Connect(callback.callback());
2560 CapturingNetLog::CapturedEntryList entries;
2561 log.GetEntries(&entries);
2562 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2563 if (rv == ERR_IO_PENDING)
2564 rv = callback.WaitForResult();
2565 EXPECT_EQ(OK, rv);
2566 EXPECT_TRUE(sock->IsConnected());
2567 log.GetEntries(&entries);
2568 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2570 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2572 sock->Disconnect();
2573 EXPECT_FALSE(sock->IsConnected());
2576 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2577 TEST_F(SSLClientSocketTest, ReuseStates) {
2578 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2579 SpawnedTestServer::kLocalhost,
2580 base::FilePath());
2581 ASSERT_TRUE(test_server.Start());
2583 AddressList addr;
2584 ASSERT_TRUE(test_server.GetAddressList(&addr));
2586 TestCompletionCallback callback;
2587 scoped_ptr<StreamSocket> transport(
2588 new TCPClientSocket(addr, NULL, NetLog::Source()));
2589 int rv = transport->Connect(callback.callback());
2590 if (rv == ERR_IO_PENDING)
2591 rv = callback.WaitForResult();
2592 EXPECT_EQ(OK, rv);
2594 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2595 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2597 rv = sock->Connect(callback.callback());
2598 if (rv == ERR_IO_PENDING)
2599 rv = callback.WaitForResult();
2600 EXPECT_EQ(OK, rv);
2602 // The socket was just connected. It should be idle because it is speaking
2603 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2604 // returns false.
2605 EXPECT_TRUE(sock->IsConnected());
2606 EXPECT_TRUE(sock->IsConnectedAndIdle());
2607 EXPECT_FALSE(sock->WasEverUsed());
2609 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2610 const size_t kRequestLen = arraysize(kRequestText) - 1;
2611 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2612 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2614 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2615 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2617 if (rv == ERR_IO_PENDING)
2618 rv = callback.WaitForResult();
2619 EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2621 // The socket has now been used.
2622 EXPECT_TRUE(sock->WasEverUsed());
2624 // TODO(davidben): Read one byte to ensure the test server has responded and
2625 // then assert IsConnectedAndIdle is false. This currently doesn't work
2626 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2627 // SSL implementation's internal buffers. Either call PR_Available and
2628 // SSL_pending, although the former isn't actually implemented or perhaps
2629 // attempt to read one byte extra.
2632 TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) {
2633 // False Start requires NPN and a forward-secret cipher suite.
2634 SpawnedTestServer::SSLOptions server_options;
2635 server_options.key_exchanges =
2636 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2637 server_options.enable_npn = true;
2638 SSLConfig client_config;
2639 client_config.next_protos.push_back("http/1.1");
2640 ASSERT_NO_FATAL_FAILURE(
2641 TestFalseStart(server_options, client_config, true));
2644 // Test that False Start is disabled without NPN.
2645 TEST_F(SSLClientSocketFalseStartTest, NoNPN) {
2646 SpawnedTestServer::SSLOptions server_options;
2647 server_options.key_exchanges =
2648 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2649 SSLConfig client_config;
2650 client_config.next_protos.clear();
2651 ASSERT_NO_FATAL_FAILURE(
2652 TestFalseStart(server_options, client_config, false));
2655 // Test that False Start is disabled without a forward-secret cipher suite.
2656 TEST_F(SSLClientSocketFalseStartTest, NoForwardSecrecy) {
2657 SpawnedTestServer::SSLOptions server_options;
2658 server_options.key_exchanges =
2659 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA;
2660 server_options.enable_npn = true;
2661 SSLConfig client_config;
2662 client_config.next_protos.push_back("http/1.1");
2663 ASSERT_NO_FATAL_FAILURE(
2664 TestFalseStart(server_options, client_config, false));
2667 // Test that sessions are resumable after receiving the server Finished message.
2668 TEST_F(SSLClientSocketFalseStartTest, SessionResumption) {
2669 // Start a server.
2670 SpawnedTestServer::SSLOptions server_options;
2671 server_options.key_exchanges =
2672 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2673 server_options.enable_npn = true;
2674 SSLConfig client_config;
2675 client_config.next_protos.push_back("http/1.1");
2677 // Let a full handshake complete with False Start.
2678 ASSERT_NO_FATAL_FAILURE(
2679 TestFalseStart(server_options, client_config, true));
2681 // Make a second connection.
2682 TestCompletionCallback callback;
2683 scoped_ptr<StreamSocket> transport2(
2684 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2685 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
2686 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
2687 transport2.Pass(), test_server()->host_port_pair(), client_config);
2688 ASSERT_TRUE(sock2.get());
2689 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
2691 // It should resume the session.
2692 SSLInfo ssl_info;
2693 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
2694 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
2697 // Test that sessions are not resumable before receiving the server Finished
2698 // message.
2699 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinish) {
2700 // Start a server.
2701 SpawnedTestServer::SSLOptions server_options;
2702 server_options.key_exchanges =
2703 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2704 server_options.enable_npn = true;
2705 ASSERT_TRUE(StartTestServer(server_options));
2707 SSLConfig client_config;
2708 client_config.next_protos.push_back("http/1.1");
2710 // Start a handshake up to the server Finished message.
2711 TestCompletionCallback callback;
2712 FakeBlockingStreamSocket* raw_transport1;
2713 scoped_ptr<SSLClientSocket> sock1;
2714 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
2715 client_config, &callback, &raw_transport1, &sock1));
2716 // Although raw_transport1 has the server Finished blocked, the handshake
2717 // still completes.
2718 EXPECT_EQ(OK, callback.WaitForResult());
2720 // Drop the old socket. This is needed because the Python test server can't
2721 // service two sockets in parallel.
2722 sock1.reset();
2724 // Start a second connection.
2725 scoped_ptr<StreamSocket> transport2(
2726 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2727 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
2728 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
2729 transport2.Pass(), test_server()->host_port_pair(), client_config);
2730 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
2732 // No session resumption because the first connection never received a server
2733 // Finished message.
2734 SSLInfo ssl_info;
2735 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
2736 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2739 // Connect to a server using channel id. It should allow the connection.
2740 TEST_F(SSLClientSocketChannelIDTest, SendChannelID) {
2741 SpawnedTestServer::SSLOptions ssl_options;
2743 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2745 EnableChannelID();
2746 SSLConfig ssl_config = kDefaultSSLConfig;
2747 ssl_config.channel_id_enabled = true;
2749 int rv;
2750 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2752 EXPECT_EQ(OK, rv);
2753 EXPECT_TRUE(sock_->IsConnected());
2754 EXPECT_TRUE(sock_->WasChannelIDSent());
2756 sock_->Disconnect();
2757 EXPECT_FALSE(sock_->IsConnected());
2760 // Connect to a server using Channel ID but failing to look up the Channel
2761 // ID. It should fail.
2762 TEST_F(SSLClientSocketChannelIDTest, FailingChannelID) {
2763 SpawnedTestServer::SSLOptions ssl_options;
2765 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2767 EnableFailingChannelID();
2768 SSLConfig ssl_config = kDefaultSSLConfig;
2769 ssl_config.channel_id_enabled = true;
2771 int rv;
2772 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2774 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
2775 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
2776 // error codes for now.
2777 // http://crbug.com/373670
2778 EXPECT_NE(OK, rv);
2779 EXPECT_FALSE(sock_->IsConnected());
2782 // Connect to a server using Channel ID but asynchronously failing to look up
2783 // the Channel ID. It should fail.
2784 TEST_F(SSLClientSocketChannelIDTest, FailingChannelIDAsync) {
2785 SpawnedTestServer::SSLOptions ssl_options;
2787 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2789 EnableAsyncFailingChannelID();
2790 SSLConfig ssl_config = kDefaultSSLConfig;
2791 ssl_config.channel_id_enabled = true;
2793 int rv;
2794 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2796 EXPECT_EQ(ERR_UNEXPECTED, rv);
2797 EXPECT_FALSE(sock_->IsConnected());
2800 } // namespace net