Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / net / socket / ssl_client_socket_unittest.cc
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.
4
5 #include "net/socket/ssl_client_socket.h"
6
7 #include "base/callback_helpers.h"
8 #include "base/memory/ref_counted.h"
9 #include "net/base/address_list.h"
10 #include "net/base/io_buffer.h"
11 #include "net/base/net_errors.h"
12 #include "net/base/net_log.h"
13 #include "net/base/net_log_unittest.h"
14 #include "net/base/test_completion_callback.h"
15 #include "net/base/test_data_directory.h"
16 #include "net/cert/mock_cert_verifier.h"
17 #include "net/cert/test_root_certs.h"
18 #include "net/dns/host_resolver.h"
19 #include "net/http/transport_security_state.h"
20 #include "net/socket/client_socket_factory.h"
21 #include "net/socket/client_socket_handle.h"
22 #include "net/socket/socket_test_util.h"
23 #include "net/socket/tcp_client_socket.h"
24 #include "net/ssl/ssl_cert_request_info.h"
25 #include "net/ssl/ssl_config_service.h"
26 #include "net/test/cert_test_util.h"
27 #include "net/test/spawned_test_server/spawned_test_server.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29 #include "testing/platform_test.h"
30
31 //-----------------------------------------------------------------------------
32
33 namespace net {
34
35 namespace {
36
37 const SSLConfig kDefaultSSLConfig;
38
39 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
40 // forwarding the Socket and StreamSocket interfaces to the underlying
41 // transport.
42 // This is to provide a common base class for subclasses to override specific
43 // StreamSocket methods for testing, while still communicating with a 'real'
44 // StreamSocket.
45 class WrappedStreamSocket : public StreamSocket {
46  public:
47   explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport)
48       : transport_(transport.Pass()) {}
49   virtual ~WrappedStreamSocket() {}
50
51   // StreamSocket implementation:
52   virtual int Connect(const CompletionCallback& callback) OVERRIDE {
53     return transport_->Connect(callback);
54   }
55   virtual void Disconnect() OVERRIDE { transport_->Disconnect(); }
56   virtual bool IsConnected() const OVERRIDE {
57     return transport_->IsConnected();
58   }
59   virtual bool IsConnectedAndIdle() const OVERRIDE {
60     return transport_->IsConnectedAndIdle();
61   }
62   virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE {
63     return transport_->GetPeerAddress(address);
64   }
65   virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE {
66     return transport_->GetLocalAddress(address);
67   }
68   virtual const BoundNetLog& NetLog() const OVERRIDE {
69     return transport_->NetLog();
70   }
71   virtual void SetSubresourceSpeculation() OVERRIDE {
72     transport_->SetSubresourceSpeculation();
73   }
74   virtual void SetOmniboxSpeculation() OVERRIDE {
75     transport_->SetOmniboxSpeculation();
76   }
77   virtual bool WasEverUsed() const OVERRIDE {
78     return transport_->WasEverUsed();
79   }
80   virtual bool UsingTCPFastOpen() const OVERRIDE {
81     return transport_->UsingTCPFastOpen();
82   }
83   virtual bool WasNpnNegotiated() const OVERRIDE {
84     return transport_->WasNpnNegotiated();
85   }
86   virtual NextProto GetNegotiatedProtocol() const OVERRIDE {
87     return transport_->GetNegotiatedProtocol();
88   }
89   virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE {
90     return transport_->GetSSLInfo(ssl_info);
91   }
92
93   // Socket implementation:
94   virtual int Read(IOBuffer* buf,
95                    int buf_len,
96                    const CompletionCallback& callback) OVERRIDE {
97     return transport_->Read(buf, buf_len, callback);
98   }
99   virtual int Write(IOBuffer* buf,
100                     int buf_len,
101                     const CompletionCallback& callback) OVERRIDE {
102     return transport_->Write(buf, buf_len, callback);
103   }
104   virtual bool SetReceiveBufferSize(int32 size) OVERRIDE {
105     return transport_->SetReceiveBufferSize(size);
106   }
107   virtual bool SetSendBufferSize(int32 size) OVERRIDE {
108     return transport_->SetSendBufferSize(size);
109   }
110
111  protected:
112   scoped_ptr<StreamSocket> transport_;
113 };
114
115 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
116 // will ensure a certain amount of data is internally buffered before
117 // satisfying a Read() request. It exists to mimic OS-level internal
118 // buffering, but in a way to guarantee that X number of bytes will be
119 // returned to callers of Read(), regardless of how quickly the OS receives
120 // them from the TestServer.
121 class ReadBufferingStreamSocket : public WrappedStreamSocket {
122  public:
123   explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
124   virtual ~ReadBufferingStreamSocket() {}
125
126   // Socket implementation:
127   virtual int Read(IOBuffer* buf,
128                    int buf_len,
129                    const CompletionCallback& callback) OVERRIDE;
130
131   // Sets the internal buffer to |size|. This must not be greater than
132   // the largest value supplied to Read() - that is, it does not handle
133   // having "leftovers" at the end of Read().
134   // Each call to Read() will be prevented from completion until at least
135   // |size| data has been read.
136   // Set to 0 to turn off buffering, causing Read() to transparently
137   // read via the underlying transport.
138   void SetBufferSize(int size);
139
140  private:
141   enum State {
142     STATE_NONE,
143     STATE_READ,
144     STATE_READ_COMPLETE,
145   };
146
147   int DoLoop(int result);
148   int DoRead();
149   int DoReadComplete(int result);
150   void OnReadCompleted(int result);
151
152   State state_;
153   scoped_refptr<GrowableIOBuffer> read_buffer_;
154   int buffer_size_;
155
156   scoped_refptr<IOBuffer> user_read_buf_;
157   CompletionCallback user_read_callback_;
158 };
159
160 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
161     scoped_ptr<StreamSocket> transport)
162     : WrappedStreamSocket(transport.Pass()),
163       read_buffer_(new GrowableIOBuffer()),
164       buffer_size_(0) {}
165
166 void ReadBufferingStreamSocket::SetBufferSize(int size) {
167   DCHECK(!user_read_buf_.get());
168   buffer_size_ = size;
169   read_buffer_->SetCapacity(size);
170 }
171
172 int ReadBufferingStreamSocket::Read(IOBuffer* buf,
173                                     int buf_len,
174                                     const CompletionCallback& callback) {
175   if (buffer_size_ == 0)
176     return transport_->Read(buf, buf_len, callback);
177
178   if (buf_len < buffer_size_)
179     return ERR_UNEXPECTED;
180
181   state_ = STATE_READ;
182   user_read_buf_ = buf;
183   int result = DoLoop(OK);
184   if (result == ERR_IO_PENDING)
185     user_read_callback_ = callback;
186   else
187     user_read_buf_ = NULL;
188   return result;
189 }
190
191 int ReadBufferingStreamSocket::DoLoop(int result) {
192   int rv = result;
193   do {
194     State current_state = state_;
195     state_ = STATE_NONE;
196     switch (current_state) {
197       case STATE_READ:
198         rv = DoRead();
199         break;
200       case STATE_READ_COMPLETE:
201         rv = DoReadComplete(rv);
202         break;
203       case STATE_NONE:
204       default:
205         NOTREACHED() << "Unexpected state: " << current_state;
206         rv = ERR_UNEXPECTED;
207         break;
208     }
209   } while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
210   return rv;
211 }
212
213 int ReadBufferingStreamSocket::DoRead() {
214   state_ = STATE_READ_COMPLETE;
215   int rv =
216       transport_->Read(read_buffer_.get(),
217                        read_buffer_->RemainingCapacity(),
218                        base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
219                                   base::Unretained(this)));
220   return rv;
221 }
222
223 int ReadBufferingStreamSocket::DoReadComplete(int result) {
224   state_ = STATE_NONE;
225   if (result <= 0)
226     return result;
227
228   read_buffer_->set_offset(read_buffer_->offset() + result);
229   if (read_buffer_->RemainingCapacity() > 0) {
230     state_ = STATE_READ;
231     return OK;
232   }
233
234   memcpy(user_read_buf_->data(),
235          read_buffer_->StartOfBuffer(),
236          read_buffer_->capacity());
237   read_buffer_->set_offset(0);
238   return read_buffer_->capacity();
239 }
240
241 void ReadBufferingStreamSocket::OnReadCompleted(int result) {
242   result = DoLoop(result);
243   if (result == ERR_IO_PENDING)
244     return;
245
246   user_read_buf_ = NULL;
247   base::ResetAndReturn(&user_read_callback_).Run(result);
248 }
249
250 // Simulates synchronously receiving an error during Read() or Write()
251 class SynchronousErrorStreamSocket : public WrappedStreamSocket {
252  public:
253   explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
254   virtual ~SynchronousErrorStreamSocket() {}
255
256   // Socket implementation:
257   virtual int Read(IOBuffer* buf,
258                    int buf_len,
259                    const CompletionCallback& callback) OVERRIDE;
260   virtual int Write(IOBuffer* buf,
261                     int buf_len,
262                     const CompletionCallback& callback) OVERRIDE;
263
264   // Sets the next Read() call and all future calls to return |error|.
265   // If there is already a pending asynchronous read, the configured error
266   // will not be returned until that asynchronous read has completed and Read()
267   // is called again.
268   void SetNextReadError(Error error) {
269     DCHECK_GE(0, error);
270     have_read_error_ = true;
271     pending_read_error_ = error;
272   }
273
274   // Sets the next Write() call and all future calls to return |error|.
275   // If there is already a pending asynchronous write, the configured error
276   // will not be returned until that asynchronous write has completed and
277   // Write() is called again.
278   void SetNextWriteError(Error error) {
279     DCHECK_GE(0, error);
280     have_write_error_ = true;
281     pending_write_error_ = error;
282   }
283
284  private:
285   bool have_read_error_;
286   int pending_read_error_;
287
288   bool have_write_error_;
289   int pending_write_error_;
290
291   DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket);
292 };
293
294 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
295     scoped_ptr<StreamSocket> transport)
296     : WrappedStreamSocket(transport.Pass()),
297       have_read_error_(false),
298       pending_read_error_(OK),
299       have_write_error_(false),
300       pending_write_error_(OK) {}
301
302 int SynchronousErrorStreamSocket::Read(IOBuffer* buf,
303                                        int buf_len,
304                                        const CompletionCallback& callback) {
305   if (have_read_error_)
306     return pending_read_error_;
307   return transport_->Read(buf, buf_len, callback);
308 }
309
310 int SynchronousErrorStreamSocket::Write(IOBuffer* buf,
311                                         int buf_len,
312                                         const CompletionCallback& callback) {
313   if (have_write_error_)
314     return pending_write_error_;
315   return transport_->Write(buf, buf_len, callback);
316 }
317
318 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
319 // underlying transport needing to complete things asynchronously in a
320 // deterministic manner (e.g.: independent of the TestServer and the OS's
321 // semantics).
322 class FakeBlockingStreamSocket : public WrappedStreamSocket {
323  public:
324   explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
325   virtual ~FakeBlockingStreamSocket() {}
326
327   // Socket implementation:
328   virtual int Read(IOBuffer* buf,
329                    int buf_len,
330                    const CompletionCallback& callback) OVERRIDE {
331     return read_state_.RunWrappedFunction(buf, buf_len, callback);
332   }
333   virtual int Write(IOBuffer* buf,
334                     int buf_len,
335                     const CompletionCallback& callback) OVERRIDE {
336     return write_state_.RunWrappedFunction(buf, buf_len, callback);
337   }
338
339   // Causes the next call to Read() to return ERR_IO_PENDING, not completing
340   // (invoking the callback) until UnblockRead() has been called and the
341   // underlying transport has completed.
342   void SetNextReadShouldBlock() { read_state_.SetShouldBlock(); }
343   void UnblockRead() { read_state_.Unblock(); }
344
345   // Causes the next call to Write() to return ERR_IO_PENDING, not completing
346   // (invoking the callback) until UnblockWrite() has been called and the
347   // underlying transport has completed.
348   void SetNextWriteShouldBlock() { write_state_.SetShouldBlock(); }
349   void UnblockWrite() { write_state_.Unblock(); }
350
351  private:
352   // Tracks the state for simulating a blocking Read/Write operation.
353   class BlockingState {
354    public:
355     // Wrapper for the underlying Socket function to call (ie: Read/Write).
356     typedef base::Callback<int(IOBuffer*, int, const CompletionCallback&)>
357         WrappedSocketFunction;
358
359     explicit BlockingState(const WrappedSocketFunction& function);
360     ~BlockingState() {}
361
362     // Sets the next call to RunWrappedFunction() to block, returning
363     // ERR_IO_PENDING and not invoking the user callback until Unblock() is
364     // called.
365     void SetShouldBlock();
366
367     // Unblocks the currently blocked pending function, invoking the user
368     // callback if the results are immediately available.
369     // Note: It's not valid to call this unless SetShouldBlock() has been
370     // called beforehand.
371     void Unblock();
372
373     // Performs the wrapped socket function on the underlying transport. If
374     // configured to block via SetShouldBlock(), then |user_callback| will not
375     // be invoked until Unblock() has been called.
376     int RunWrappedFunction(IOBuffer* buf,
377                            int len,
378                            const CompletionCallback& user_callback);
379
380    private:
381     // Handles completion from the underlying wrapped socket function.
382     void OnCompleted(int result);
383
384     WrappedSocketFunction wrapped_function_;
385     bool should_block_;
386     bool have_result_;
387     int pending_result_;
388     CompletionCallback user_callback_;
389   };
390
391   BlockingState read_state_;
392   BlockingState write_state_;
393
394   DISALLOW_COPY_AND_ASSIGN(FakeBlockingStreamSocket);
395 };
396
397 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
398     scoped_ptr<StreamSocket> transport)
399     : WrappedStreamSocket(transport.Pass()),
400       read_state_(base::Bind(&Socket::Read,
401                              base::Unretained(transport_.get()))),
402       write_state_(base::Bind(&Socket::Write,
403                               base::Unretained(transport_.get()))) {}
404
405 FakeBlockingStreamSocket::BlockingState::BlockingState(
406     const WrappedSocketFunction& function)
407     : wrapped_function_(function),
408       should_block_(false),
409       have_result_(false),
410       pending_result_(OK) {}
411
412 void FakeBlockingStreamSocket::BlockingState::SetShouldBlock() {
413   DCHECK(!should_block_);
414   should_block_ = true;
415 }
416
417 void FakeBlockingStreamSocket::BlockingState::Unblock() {
418   DCHECK(should_block_);
419   should_block_ = false;
420
421   // If the operation is still pending in the underlying transport, immediately
422   // return - OnCompleted() will handle invoking the callback once the transport
423   // has completed.
424   if (!have_result_)
425     return;
426
427   have_result_ = false;
428
429   base::ResetAndReturn(&user_callback_).Run(pending_result_);
430 }
431
432 int FakeBlockingStreamSocket::BlockingState::RunWrappedFunction(
433     IOBuffer* buf,
434     int len,
435     const CompletionCallback& callback) {
436
437   // The callback to be called by the underlying transport. Either forward
438   // directly to the user's callback if not set to block, or intercept it with
439   // OnCompleted so that the user's callback is not invoked until Unblock() is
440   // called.
441   CompletionCallback transport_callback =
442       !should_block_ ? callback : base::Bind(&BlockingState::OnCompleted,
443                                              base::Unretained(this));
444   int rv = wrapped_function_.Run(buf, len, transport_callback);
445   if (should_block_) {
446     user_callback_ = callback;
447     // May have completed synchronously.
448     have_result_ = (rv != ERR_IO_PENDING);
449     pending_result_ = rv;
450     return ERR_IO_PENDING;
451   }
452
453   return rv;
454 }
455
456 void FakeBlockingStreamSocket::BlockingState::OnCompleted(int result) {
457   if (should_block_) {
458     // Store the result so that the callback can be invoked once Unblock() is
459     // called.
460     have_result_ = true;
461     pending_result_ = result;
462     return;
463   }
464
465   // Otherwise, the Unblock() function was called before the underlying
466   // transport completed, so run the user's callback immediately.
467   base::ResetAndReturn(&user_callback_).Run(result);
468 }
469
470 // CompletionCallback that will delete the associated StreamSocket when
471 // the callback is invoked.
472 class DeleteSocketCallback : public TestCompletionCallbackBase {
473  public:
474   explicit DeleteSocketCallback(StreamSocket* socket)
475       : socket_(socket),
476         callback_(base::Bind(&DeleteSocketCallback::OnComplete,
477                              base::Unretained(this))) {}
478   virtual ~DeleteSocketCallback() {}
479
480   const CompletionCallback& callback() const { return callback_; }
481
482  private:
483   void OnComplete(int result) {
484     if (socket_) {
485       delete socket_;
486       socket_ = NULL;
487     } else {
488       ADD_FAILURE() << "Deleting socket twice";
489     }
490     SetResult(result);
491   }
492
493   StreamSocket* socket_;
494   CompletionCallback callback_;
495
496   DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
497 };
498
499 class SSLClientSocketTest : public PlatformTest {
500  public:
501   SSLClientSocketTest()
502       : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
503         cert_verifier_(new MockCertVerifier),
504         transport_security_state_(new TransportSecurityState) {
505     cert_verifier_->set_default_result(OK);
506     context_.cert_verifier = cert_verifier_.get();
507     context_.transport_security_state = transport_security_state_.get();
508   }
509
510  protected:
511   scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
512       scoped_ptr<StreamSocket> transport_socket,
513       const HostPortPair& host_and_port,
514       const SSLConfig& ssl_config) {
515     scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
516     connection->SetSocket(transport_socket.Pass());
517     return socket_factory_->CreateSSLClientSocket(
518         connection.Pass(), host_and_port, ssl_config, context_);
519   }
520
521   ClientSocketFactory* socket_factory_;
522   scoped_ptr<MockCertVerifier> cert_verifier_;
523   scoped_ptr<TransportSecurityState> transport_security_state_;
524   SSLClientSocketContext context_;
525 };
526
527 // Verifies the correctness of GetSSLCertRequestInfo.
528 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
529  protected:
530   // Creates a test server with the given SSLOptions, connects to it and returns
531   // the SSLCertRequestInfo reported by the socket.
532   scoped_refptr<SSLCertRequestInfo> GetCertRequest(
533       SpawnedTestServer::SSLOptions ssl_options) {
534     SpawnedTestServer test_server(
535         SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
536     if (!test_server.Start())
537       return NULL;
538
539     AddressList addr;
540     if (!test_server.GetAddressList(&addr))
541       return NULL;
542
543     TestCompletionCallback callback;
544     CapturingNetLog log;
545     scoped_ptr<StreamSocket> transport(
546         new TCPClientSocket(addr, &log, NetLog::Source()));
547     int rv = transport->Connect(callback.callback());
548     if (rv == ERR_IO_PENDING)
549       rv = callback.WaitForResult();
550     EXPECT_EQ(OK, rv);
551
552     scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
553         transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
554     EXPECT_FALSE(sock->IsConnected());
555
556     rv = sock->Connect(callback.callback());
557     if (rv == ERR_IO_PENDING)
558       rv = callback.WaitForResult();
559     scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo();
560     sock->GetSSLCertRequestInfo(request_info.get());
561     sock->Disconnect();
562     EXPECT_FALSE(sock->IsConnected());
563
564     return request_info;
565   }
566 };
567
568 //-----------------------------------------------------------------------------
569
570 // LogContainsSSLConnectEndEvent returns true if the given index in the given
571 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
572 // merge the first application data record with the Finished message when false
573 // starting. However, in order to avoid the server timing out the handshake,
574 // they'll give up waiting for application data and send the Finished after a
575 // timeout. This means that an SSL connect end event may appear as a socket
576 // write.
577 static bool LogContainsSSLConnectEndEvent(
578     const CapturingNetLog::CapturedEntryList& log,
579     int i) {
580   return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) ||
581          LogContainsEvent(
582              log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
583 }
584
585 }  // namespace
586
587 TEST_F(SSLClientSocketTest, Connect) {
588   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
589                                 SpawnedTestServer::kLocalhost,
590                                 base::FilePath());
591   ASSERT_TRUE(test_server.Start());
592
593   AddressList addr;
594   ASSERT_TRUE(test_server.GetAddressList(&addr));
595
596   TestCompletionCallback callback;
597   CapturingNetLog log;
598   scoped_ptr<StreamSocket> transport(
599       new TCPClientSocket(addr, &log, NetLog::Source()));
600   int rv = transport->Connect(callback.callback());
601   if (rv == ERR_IO_PENDING)
602     rv = callback.WaitForResult();
603   EXPECT_EQ(OK, rv);
604
605   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
606       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
607
608   EXPECT_FALSE(sock->IsConnected());
609
610   rv = sock->Connect(callback.callback());
611
612   CapturingNetLog::CapturedEntryList entries;
613   log.GetEntries(&entries);
614   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
615   if (rv == ERR_IO_PENDING)
616     rv = callback.WaitForResult();
617   EXPECT_EQ(OK, rv);
618   EXPECT_TRUE(sock->IsConnected());
619   log.GetEntries(&entries);
620   EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
621
622   sock->Disconnect();
623   EXPECT_FALSE(sock->IsConnected());
624 }
625
626 TEST_F(SSLClientSocketTest, ConnectExpired) {
627   SpawnedTestServer::SSLOptions ssl_options(
628       SpawnedTestServer::SSLOptions::CERT_EXPIRED);
629   SpawnedTestServer test_server(
630       SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
631   ASSERT_TRUE(test_server.Start());
632
633   cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
634
635   AddressList addr;
636   ASSERT_TRUE(test_server.GetAddressList(&addr));
637
638   TestCompletionCallback callback;
639   CapturingNetLog log;
640   scoped_ptr<StreamSocket> transport(
641       new TCPClientSocket(addr, &log, NetLog::Source()));
642   int rv = transport->Connect(callback.callback());
643   if (rv == ERR_IO_PENDING)
644     rv = callback.WaitForResult();
645   EXPECT_EQ(OK, rv);
646
647   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
648       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
649
650   EXPECT_FALSE(sock->IsConnected());
651
652   rv = sock->Connect(callback.callback());
653
654   CapturingNetLog::CapturedEntryList entries;
655   log.GetEntries(&entries);
656   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
657   if (rv == ERR_IO_PENDING)
658     rv = callback.WaitForResult();
659
660   EXPECT_EQ(ERR_CERT_DATE_INVALID, rv);
661
662   // Rather than testing whether or not the underlying socket is connected,
663   // test that the handshake has finished. This is because it may be
664   // desirable to disconnect the socket before showing a user prompt, since
665   // the user may take indefinitely long to respond.
666   log.GetEntries(&entries);
667   EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
668 }
669
670 TEST_F(SSLClientSocketTest, ConnectMismatched) {
671   SpawnedTestServer::SSLOptions ssl_options(
672       SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
673   SpawnedTestServer test_server(
674       SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
675   ASSERT_TRUE(test_server.Start());
676
677   cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
678
679   AddressList addr;
680   ASSERT_TRUE(test_server.GetAddressList(&addr));
681
682   TestCompletionCallback callback;
683   CapturingNetLog log;
684   scoped_ptr<StreamSocket> transport(
685       new TCPClientSocket(addr, &log, NetLog::Source()));
686   int rv = transport->Connect(callback.callback());
687   if (rv == ERR_IO_PENDING)
688     rv = callback.WaitForResult();
689   EXPECT_EQ(OK, rv);
690
691   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
692       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
693
694   EXPECT_FALSE(sock->IsConnected());
695
696   rv = sock->Connect(callback.callback());
697
698   CapturingNetLog::CapturedEntryList entries;
699   log.GetEntries(&entries);
700   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
701   if (rv == ERR_IO_PENDING)
702     rv = callback.WaitForResult();
703
704   EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv);
705
706   // Rather than testing whether or not the underlying socket is connected,
707   // test that the handshake has finished. This is because it may be
708   // desirable to disconnect the socket before showing a user prompt, since
709   // the user may take indefinitely long to respond.
710   log.GetEntries(&entries);
711   EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
712 }
713
714 // Attempt to connect to a page which requests a client certificate. It should
715 // return an error code on connect.
716 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
717   SpawnedTestServer::SSLOptions ssl_options;
718   ssl_options.request_client_certificate = true;
719   SpawnedTestServer test_server(
720       SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
721   ASSERT_TRUE(test_server.Start());
722
723   AddressList addr;
724   ASSERT_TRUE(test_server.GetAddressList(&addr));
725
726   TestCompletionCallback callback;
727   CapturingNetLog log;
728   scoped_ptr<StreamSocket> transport(
729       new TCPClientSocket(addr, &log, NetLog::Source()));
730   int rv = transport->Connect(callback.callback());
731   if (rv == ERR_IO_PENDING)
732     rv = callback.WaitForResult();
733   EXPECT_EQ(OK, rv);
734
735   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
736       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
737
738   EXPECT_FALSE(sock->IsConnected());
739
740   rv = sock->Connect(callback.callback());
741
742   CapturingNetLog::CapturedEntryList entries;
743   log.GetEntries(&entries);
744   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
745   if (rv == ERR_IO_PENDING)
746     rv = callback.WaitForResult();
747
748   log.GetEntries(&entries);
749   // Because we prematurely kill the handshake at CertificateRequest,
750   // the server may still send data (notably the ServerHelloDone)
751   // after the error is returned. As a result, the SSL_CONNECT may not
752   // be the last entry. See http://crbug.com/54445. We use
753   // ExpectLogContainsSomewhere instead of
754   // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
755   // extra read instead of two. This occurs before the handshake ends,
756   // so the corking logic of LogContainsSSLConnectEndEvent isn't
757   // necessary.
758   //
759   // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
760   // fixed and we can respond to the first CertificateRequest
761   // without closing the socket, add a unit test for sending the
762   // certificate. This test may still be useful as we'll want to close
763   // the socket on a timeout if the user takes a long time to pick a
764   // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
765   ExpectLogContainsSomewhere(
766       entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END);
767   EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
768   EXPECT_FALSE(sock->IsConnected());
769 }
770
771 // Connect to a server requesting optional client authentication. Send it a
772 // null certificate. It should allow the connection.
773 //
774 // TODO(davidben): Also test providing an actual certificate.
775 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
776   SpawnedTestServer::SSLOptions ssl_options;
777   ssl_options.request_client_certificate = true;
778   SpawnedTestServer test_server(
779       SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
780   ASSERT_TRUE(test_server.Start());
781
782   AddressList addr;
783   ASSERT_TRUE(test_server.GetAddressList(&addr));
784
785   TestCompletionCallback callback;
786   CapturingNetLog log;
787   scoped_ptr<StreamSocket> transport(
788       new TCPClientSocket(addr, &log, NetLog::Source()));
789   int rv = transport->Connect(callback.callback());
790   if (rv == ERR_IO_PENDING)
791     rv = callback.WaitForResult();
792   EXPECT_EQ(OK, rv);
793
794   SSLConfig ssl_config = kDefaultSSLConfig;
795   ssl_config.send_client_cert = true;
796   ssl_config.client_cert = NULL;
797
798   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
799       transport.Pass(), test_server.host_port_pair(), ssl_config));
800
801   EXPECT_FALSE(sock->IsConnected());
802
803   // Our test server accepts certificate-less connections.
804   // TODO(davidben): Add a test which requires them and verify the error.
805   rv = sock->Connect(callback.callback());
806
807   CapturingNetLog::CapturedEntryList entries;
808   log.GetEntries(&entries);
809   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
810   if (rv == ERR_IO_PENDING)
811     rv = callback.WaitForResult();
812
813   EXPECT_EQ(OK, rv);
814   EXPECT_TRUE(sock->IsConnected());
815   log.GetEntries(&entries);
816   EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
817
818   // We responded to the server's certificate request with a Certificate
819   // message with no client certificate in it.  ssl_info.client_cert_sent
820   // should be false in this case.
821   SSLInfo ssl_info;
822   sock->GetSSLInfo(&ssl_info);
823   EXPECT_FALSE(ssl_info.client_cert_sent);
824
825   sock->Disconnect();
826   EXPECT_FALSE(sock->IsConnected());
827 }
828
829 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
830 //   - Server closes an SSL connection (with a close_notify alert message).
831 //   - Server closes the underlying TCP connection directly.
832 //   - Server sends data unexpectedly.
833
834 TEST_F(SSLClientSocketTest, Read) {
835   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
836                                 SpawnedTestServer::kLocalhost,
837                                 base::FilePath());
838   ASSERT_TRUE(test_server.Start());
839
840   AddressList addr;
841   ASSERT_TRUE(test_server.GetAddressList(&addr));
842
843   TestCompletionCallback callback;
844   scoped_ptr<StreamSocket> transport(
845       new TCPClientSocket(addr, NULL, NetLog::Source()));
846   int rv = transport->Connect(callback.callback());
847   if (rv == ERR_IO_PENDING)
848     rv = callback.WaitForResult();
849   EXPECT_EQ(OK, rv);
850
851   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
852       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
853
854   rv = sock->Connect(callback.callback());
855   if (rv == ERR_IO_PENDING)
856     rv = callback.WaitForResult();
857   EXPECT_EQ(OK, rv);
858   EXPECT_TRUE(sock->IsConnected());
859
860   const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
861   scoped_refptr<IOBuffer> request_buffer(
862       new IOBuffer(arraysize(request_text) - 1));
863   memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
864
865   rv = sock->Write(
866       request_buffer.get(), arraysize(request_text) - 1, callback.callback());
867   EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
868
869   if (rv == ERR_IO_PENDING)
870     rv = callback.WaitForResult();
871   EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
872
873   scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
874   for (;;) {
875     rv = sock->Read(buf.get(), 4096, callback.callback());
876     EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
877
878     if (rv == ERR_IO_PENDING)
879       rv = callback.WaitForResult();
880
881     EXPECT_GE(rv, 0);
882     if (rv <= 0)
883       break;
884   }
885 }
886
887 // Tests that the SSLClientSocket properly handles when the underlying transport
888 // synchronously returns an error code - such as if an intermediary terminates
889 // the socket connection uncleanly.
890 // This is a regression test for http://crbug.com/238536
891 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
892   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
893                                 SpawnedTestServer::kLocalhost,
894                                 base::FilePath());
895   ASSERT_TRUE(test_server.Start());
896
897   AddressList addr;
898   ASSERT_TRUE(test_server.GetAddressList(&addr));
899
900   TestCompletionCallback callback;
901   scoped_ptr<StreamSocket> real_transport(
902       new TCPClientSocket(addr, NULL, NetLog::Source()));
903   scoped_ptr<SynchronousErrorStreamSocket> transport(
904       new SynchronousErrorStreamSocket(real_transport.Pass()));
905   int rv = callback.GetResult(transport->Connect(callback.callback()));
906   EXPECT_EQ(OK, rv);
907
908   // Disable TLS False Start to avoid handshake non-determinism.
909   SSLConfig ssl_config;
910   ssl_config.false_start_enabled = false;
911
912   SynchronousErrorStreamSocket* raw_transport = transport.get();
913   scoped_ptr<SSLClientSocket> sock(
914       CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
915                             test_server.host_port_pair(),
916                             ssl_config));
917
918   rv = callback.GetResult(sock->Connect(callback.callback()));
919   EXPECT_EQ(OK, rv);
920   EXPECT_TRUE(sock->IsConnected());
921
922   const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
923   static const int kRequestTextSize =
924       static_cast<int>(arraysize(request_text) - 1);
925   scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
926   memcpy(request_buffer->data(), request_text, kRequestTextSize);
927
928   rv = callback.GetResult(
929       sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
930   EXPECT_EQ(kRequestTextSize, rv);
931
932   // Simulate an unclean/forcible shutdown.
933   raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
934
935   scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
936
937   // Note: This test will hang if this bug has regressed. Simply checking that
938   // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
939   // result when using a dedicated task runner for NSS.
940   rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
941
942 #if !defined(USE_OPENSSL)
943   // SSLClientSocketNSS records the error exactly
944   EXPECT_EQ(ERR_CONNECTION_RESET, rv);
945 #else
946   // SSLClientSocketOpenSSL treats any errors as a simple EOF.
947   EXPECT_EQ(0, rv);
948 #endif
949 }
950
951 // Tests that the SSLClientSocket properly handles when the underlying transport
952 // asynchronously returns an error code while writing data - such as if an
953 // intermediary terminates the socket connection uncleanly.
954 // This is a regression test for http://crbug.com/249848
955 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
956   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
957                                 SpawnedTestServer::kLocalhost,
958                                 base::FilePath());
959   ASSERT_TRUE(test_server.Start());
960
961   AddressList addr;
962   ASSERT_TRUE(test_server.GetAddressList(&addr));
963
964   TestCompletionCallback callback;
965   scoped_ptr<StreamSocket> real_transport(
966       new TCPClientSocket(addr, NULL, NetLog::Source()));
967   // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
968   // is retained in order to configure additional errors.
969   scoped_ptr<SynchronousErrorStreamSocket> error_socket(
970       new SynchronousErrorStreamSocket(real_transport.Pass()));
971   SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
972   scoped_ptr<FakeBlockingStreamSocket> transport(
973       new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
974   FakeBlockingStreamSocket* raw_transport = transport.get();
975   int rv = callback.GetResult(transport->Connect(callback.callback()));
976   EXPECT_EQ(OK, rv);
977
978   // Disable TLS False Start to avoid handshake non-determinism.
979   SSLConfig ssl_config;
980   ssl_config.false_start_enabled = false;
981
982   scoped_ptr<SSLClientSocket> sock(
983       CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
984                             test_server.host_port_pair(),
985                             ssl_config));
986
987   rv = callback.GetResult(sock->Connect(callback.callback()));
988   EXPECT_EQ(OK, rv);
989   EXPECT_TRUE(sock->IsConnected());
990
991   const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
992   static const int kRequestTextSize =
993       static_cast<int>(arraysize(request_text) - 1);
994   scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
995   memcpy(request_buffer->data(), request_text, kRequestTextSize);
996
997   // Simulate an unclean/forcible shutdown on the underlying socket.
998   // However, simulate this error asynchronously.
999   raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1000   raw_transport->SetNextWriteShouldBlock();
1001
1002   // This write should complete synchronously, because the TLS ciphertext
1003   // can be created and placed into the outgoing buffers independent of the
1004   // underlying transport.
1005   rv = callback.GetResult(
1006       sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1007   EXPECT_EQ(kRequestTextSize, rv);
1008
1009   scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1010
1011   rv = sock->Read(buf.get(), 4096, callback.callback());
1012   EXPECT_EQ(ERR_IO_PENDING, rv);
1013
1014   // Now unblock the outgoing request, having it fail with the connection
1015   // being reset.
1016   raw_transport->UnblockWrite();
1017
1018   // Note: This will cause an inifite loop if this bug has regressed. Simply
1019   // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1020   // is a legitimate result when using a dedicated task runner for NSS.
1021   rv = callback.GetResult(rv);
1022
1023 #if !defined(USE_OPENSSL)
1024   // SSLClientSocketNSS records the error exactly
1025   EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1026 #else
1027   // SSLClientSocketOpenSSL treats any errors as a simple EOF.
1028   EXPECT_EQ(0, rv);
1029 #endif
1030 }
1031
1032 // Test the full duplex mode, with Read and Write pending at the same time.
1033 // This test also serves as a regression test for http://crbug.com/29815.
1034 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1035   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1036                                 SpawnedTestServer::kLocalhost,
1037                                 base::FilePath());
1038   ASSERT_TRUE(test_server.Start());
1039
1040   AddressList addr;
1041   ASSERT_TRUE(test_server.GetAddressList(&addr));
1042
1043   TestCompletionCallback callback;  // Used for everything except Write.
1044
1045   scoped_ptr<StreamSocket> transport(
1046       new TCPClientSocket(addr, NULL, NetLog::Source()));
1047   int rv = transport->Connect(callback.callback());
1048   if (rv == ERR_IO_PENDING)
1049     rv = callback.WaitForResult();
1050   EXPECT_EQ(OK, rv);
1051
1052   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1053       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1054
1055   rv = sock->Connect(callback.callback());
1056   if (rv == ERR_IO_PENDING)
1057     rv = callback.WaitForResult();
1058   EXPECT_EQ(OK, rv);
1059   EXPECT_TRUE(sock->IsConnected());
1060
1061   // Issue a "hanging" Read first.
1062   scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1063   rv = sock->Read(buf.get(), 4096, callback.callback());
1064   // We haven't written the request, so there should be no response yet.
1065   ASSERT_EQ(ERR_IO_PENDING, rv);
1066
1067   // Write the request.
1068   // The request is padded with a User-Agent header to a size that causes the
1069   // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1070   // This tests the fix for http://crbug.com/29815.
1071   std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1072   for (int i = 0; i < 3770; ++i)
1073     request_text.push_back('*');
1074   request_text.append("\r\n\r\n");
1075   scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1076
1077   TestCompletionCallback callback2;  // Used for Write only.
1078   rv = sock->Write(
1079       request_buffer.get(), request_text.size(), callback2.callback());
1080   EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1081
1082   if (rv == ERR_IO_PENDING)
1083     rv = callback2.WaitForResult();
1084   EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1085
1086   // Now get the Read result.
1087   rv = callback.WaitForResult();
1088   EXPECT_GT(rv, 0);
1089 }
1090
1091 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1092 // mode when the underlying transport is blocked on sending data. When the
1093 // underlying transport completes due to an error, it should invoke both the
1094 // Read() and Write() callbacks. If the socket is deleted by the Read()
1095 // callback, the Write() callback should not be invoked.
1096 // Regression test for http://crbug.com/232633
1097 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1098   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1099                                 SpawnedTestServer::kLocalhost,
1100                                 base::FilePath());
1101   ASSERT_TRUE(test_server.Start());
1102
1103   AddressList addr;
1104   ASSERT_TRUE(test_server.GetAddressList(&addr));
1105
1106   TestCompletionCallback callback;
1107   scoped_ptr<StreamSocket> real_transport(
1108       new TCPClientSocket(addr, NULL, NetLog::Source()));
1109   // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1110   // is retained in order to configure additional errors.
1111   scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1112       new SynchronousErrorStreamSocket(real_transport.Pass()));
1113   SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1114   scoped_ptr<FakeBlockingStreamSocket> transport(
1115       new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1116   FakeBlockingStreamSocket* raw_transport = transport.get();
1117
1118   int rv = callback.GetResult(transport->Connect(callback.callback()));
1119   EXPECT_EQ(OK, rv);
1120
1121   // Disable TLS False Start to avoid handshake non-determinism.
1122   SSLConfig ssl_config;
1123   ssl_config.false_start_enabled = false;
1124
1125   scoped_ptr<SSLClientSocket> sock =
1126       CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1127                             test_server.host_port_pair(),
1128                             ssl_config);
1129
1130   rv = callback.GetResult(sock->Connect(callback.callback()));
1131   EXPECT_EQ(OK, rv);
1132   EXPECT_TRUE(sock->IsConnected());
1133
1134   std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1135   request_text.append(20 * 1024, '*');
1136   request_text.append("\r\n\r\n");
1137   scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1138       new StringIOBuffer(request_text), request_text.size()));
1139
1140   // Simulate errors being returned from the underlying Read() and Write() ...
1141   raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1142   raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1143   // ... but have those errors returned asynchronously. Because the Write() will
1144   // return first, this will trigger the error.
1145   raw_transport->SetNextReadShouldBlock();
1146   raw_transport->SetNextWriteShouldBlock();
1147
1148   // Enqueue a Read() before calling Write(), which should "hang" due to
1149   // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1150   SSLClientSocket* raw_sock = sock.get();
1151   DeleteSocketCallback read_callback(sock.release());
1152   scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1153   rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1154
1155   // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1156   ASSERT_EQ(ERR_IO_PENDING, rv);
1157   ASSERT_FALSE(read_callback.have_result());
1158
1159 #if !defined(USE_OPENSSL)
1160   // NSS follows a pattern where a call to PR_Write will only consume as
1161   // much data as it can encode into application data records before the
1162   // internal memio buffer is full, which should only fill if writing a large
1163   // amount of data and the underlying transport is blocked. Once this happens,
1164   // NSS will return (total size of all application data records it wrote) - 1,
1165   // with the caller expected to resume with the remaining unsent data.
1166   //
1167   // This causes SSLClientSocketNSS::Write to return that it wrote some data
1168   // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1169   // get the socket in the state needed for the test below.
1170   //
1171   // This is not needed for OpenSSL, because for OpenSSL,
1172   // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1173   // SSLClientSocketOpenSSL::Write() will not return until all of
1174   // |request_buffer| has been written to the underlying BIO (although not
1175   // necessarily the underlying transport).
1176   rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1177                                           request_buffer->BytesRemaining(),
1178                                           callback.callback()));
1179   ASSERT_LT(0, rv);
1180   request_buffer->DidConsume(rv);
1181
1182   // Guard to ensure that |request_buffer| was larger than all of the internal
1183   // buffers (transport, memio, NSS) along the way - otherwise the next call
1184   // to Write() will crash with an invalid buffer.
1185   ASSERT_LT(0, request_buffer->BytesRemaining());
1186 #endif
1187
1188   // Attempt to write the remaining data. NSS will not be able to consume the
1189   // application data because the internal buffers are full, while OpenSSL will
1190   // return that its blocked because the underlying transport is blocked.
1191   rv = raw_sock->Write(request_buffer.get(),
1192                        request_buffer->BytesRemaining(),
1193                        callback.callback());
1194   ASSERT_EQ(ERR_IO_PENDING, rv);
1195   ASSERT_FALSE(callback.have_result());
1196
1197   // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1198   // call the Read() callback, deleting the socket and thus aborting calling
1199   // the Write() callback.
1200   raw_transport->UnblockWrite();
1201
1202   rv = read_callback.WaitForResult();
1203
1204 #if !defined(USE_OPENSSL)
1205   // NSS records the error exactly.
1206   EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1207 #else
1208   // OpenSSL treats any errors as a simple EOF.
1209   EXPECT_EQ(0, rv);
1210 #endif
1211
1212   // The Write callback should not have been called.
1213   EXPECT_FALSE(callback.have_result());
1214 }
1215
1216 // Tests that the SSLClientSocket does not crash if data is received on the
1217 // transport socket after a failing write. This can occur if we have a Write
1218 // error in a SPDY socket.
1219 // Regression test for http://crbug.com/335557
1220 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1221   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1222                                 SpawnedTestServer::kLocalhost,
1223                                 base::FilePath());
1224   ASSERT_TRUE(test_server.Start());
1225
1226   AddressList addr;
1227   ASSERT_TRUE(test_server.GetAddressList(&addr));
1228
1229   TestCompletionCallback callback;
1230   scoped_ptr<StreamSocket> real_transport(
1231       new TCPClientSocket(addr, NULL, NetLog::Source()));
1232   // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1233   // is retained in order to configure additional errors.
1234   scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1235       new SynchronousErrorStreamSocket(real_transport.Pass()));
1236   SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1237   scoped_ptr<FakeBlockingStreamSocket> transport(
1238       new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1239   FakeBlockingStreamSocket* raw_transport = transport.get();
1240
1241   int rv = callback.GetResult(transport->Connect(callback.callback()));
1242   EXPECT_EQ(OK, rv);
1243
1244   // Disable TLS False Start to avoid handshake non-determinism.
1245   SSLConfig ssl_config;
1246   ssl_config.false_start_enabled = false;
1247
1248   scoped_ptr<SSLClientSocket> sock(
1249       CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1250                             test_server.host_port_pair(),
1251                             ssl_config));
1252
1253   rv = callback.GetResult(sock->Connect(callback.callback()));
1254   EXPECT_EQ(OK, rv);
1255   EXPECT_TRUE(sock->IsConnected());
1256
1257   // Send a request so there is something to read from the socket.
1258   const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1259   static const int kRequestTextSize =
1260       static_cast<int>(arraysize(request_text) - 1);
1261   scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1262   memcpy(request_buffer->data(), request_text, kRequestTextSize);
1263
1264   rv = callback.GetResult(
1265       sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1266   EXPECT_EQ(kRequestTextSize, rv);
1267
1268   // Start a hanging read.
1269   TestCompletionCallback read_callback;
1270   raw_transport->SetNextReadShouldBlock();
1271   scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1272   rv = sock->Read(buf.get(), 4096, read_callback.callback());
1273   EXPECT_EQ(ERR_IO_PENDING, rv);
1274
1275   // Perform another write, but have it fail. Write a request larger than the
1276   // internal socket buffers so that the request hits the underlying transport
1277   // socket and detects the error.
1278   std::string long_request_text =
1279       "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1280   long_request_text.append(20 * 1024, '*');
1281   long_request_text.append("\r\n\r\n");
1282   scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1283       new StringIOBuffer(long_request_text), long_request_text.size()));
1284
1285   raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1286
1287   // Write as much data as possible until hitting an error. This is necessary
1288   // for NSS. PR_Write will only consume as much data as it can encode into
1289   // application data records before the internal memio buffer is full, which
1290   // should only fill if writing a large amount of data and the underlying
1291   // transport is blocked. Once this happens, NSS will return (total size of all
1292   // application data records it wrote) - 1, with the caller expected to resume
1293   // with the remaining unsent data.
1294   do {
1295     rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1296                                         long_request_buffer->BytesRemaining(),
1297                                         callback.callback()));
1298     if (rv > 0) {
1299       long_request_buffer->DidConsume(rv);
1300       // Abort if the entire buffer is ever consumed.
1301       ASSERT_LT(0, long_request_buffer->BytesRemaining());
1302     }
1303   } while (rv > 0);
1304
1305 #if !defined(USE_OPENSSL)
1306   // NSS records the error exactly.
1307   EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1308 #else
1309   // OpenSSL treats the reset as a generic protocol error.
1310   EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
1311 #endif
1312
1313   // Release the read. Some bytes should go through.
1314   raw_transport->UnblockRead();
1315   rv = read_callback.WaitForResult();
1316
1317   // Per the fix for http://crbug.com/249848, write failures currently break
1318   // reads. Change this assertion if they're changed to not collide.
1319   EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1320 }
1321
1322 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1323   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1324                                 SpawnedTestServer::kLocalhost,
1325                                 base::FilePath());
1326   ASSERT_TRUE(test_server.Start());
1327
1328   AddressList addr;
1329   ASSERT_TRUE(test_server.GetAddressList(&addr));
1330
1331   TestCompletionCallback callback;
1332   scoped_ptr<StreamSocket> transport(
1333       new TCPClientSocket(addr, NULL, NetLog::Source()));
1334   int rv = transport->Connect(callback.callback());
1335   if (rv == ERR_IO_PENDING)
1336     rv = callback.WaitForResult();
1337   EXPECT_EQ(OK, rv);
1338
1339   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1340       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1341
1342   rv = sock->Connect(callback.callback());
1343   if (rv == ERR_IO_PENDING)
1344     rv = callback.WaitForResult();
1345   EXPECT_EQ(OK, rv);
1346
1347   const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1348   scoped_refptr<IOBuffer> request_buffer(
1349       new IOBuffer(arraysize(request_text) - 1));
1350   memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1351
1352   rv = sock->Write(
1353       request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1354   EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1355
1356   if (rv == ERR_IO_PENDING)
1357     rv = callback.WaitForResult();
1358   EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1359
1360   scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1361   for (;;) {
1362     rv = sock->Read(buf.get(), 1, callback.callback());
1363     EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1364
1365     if (rv == ERR_IO_PENDING)
1366       rv = callback.WaitForResult();
1367
1368     EXPECT_GE(rv, 0);
1369     if (rv <= 0)
1370       break;
1371   }
1372 }
1373
1374 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
1375   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1376                                 SpawnedTestServer::kLocalhost,
1377                                 base::FilePath());
1378   ASSERT_TRUE(test_server.Start());
1379
1380   AddressList addr;
1381   ASSERT_TRUE(test_server.GetAddressList(&addr));
1382
1383   TestCompletionCallback callback;
1384
1385   scoped_ptr<StreamSocket> real_transport(
1386       new TCPClientSocket(addr, NULL, NetLog::Source()));
1387   scoped_ptr<ReadBufferingStreamSocket> transport(
1388       new ReadBufferingStreamSocket(real_transport.Pass()));
1389   ReadBufferingStreamSocket* raw_transport = transport.get();
1390   int rv = callback.GetResult(transport->Connect(callback.callback()));
1391   ASSERT_EQ(OK, rv);
1392
1393   scoped_ptr<SSLClientSocket> sock(
1394       CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1395                             test_server.host_port_pair(),
1396                             kDefaultSSLConfig));
1397
1398   rv = callback.GetResult(sock->Connect(callback.callback()));
1399   ASSERT_EQ(OK, rv);
1400   ASSERT_TRUE(sock->IsConnected());
1401
1402   const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
1403   scoped_refptr<IOBuffer> request_buffer(
1404       new IOBuffer(arraysize(request_text) - 1));
1405   memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1406
1407   rv = callback.GetResult(sock->Write(
1408       request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
1409   ASSERT_GT(rv, 0);
1410   ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1411
1412   // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
1413   // data (the max SSL record size) at a time. Ensure that at least 15K worth
1414   // of SSL data is buffered first. The 15K of buffered data is made up of
1415   // many smaller SSL records (the TestServer writes along 1350 byte
1416   // plaintext boundaries), although there may also be a few records that are
1417   // smaller or larger, due to timing and SSL False Start.
1418   // 15K was chosen because 15K is smaller than the 17K (max) read issued by
1419   // the SSLClientSocket implementation, and larger than the minimum amount
1420   // of ciphertext necessary to contain the 8K of plaintext requested below.
1421   raw_transport->SetBufferSize(15000);
1422
1423   scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
1424   rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
1425   ASSERT_EQ(rv, 8192);
1426 }
1427
1428 TEST_F(SSLClientSocketTest, Read_Interrupted) {
1429   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1430                                 SpawnedTestServer::kLocalhost,
1431                                 base::FilePath());
1432   ASSERT_TRUE(test_server.Start());
1433
1434   AddressList addr;
1435   ASSERT_TRUE(test_server.GetAddressList(&addr));
1436
1437   TestCompletionCallback callback;
1438   scoped_ptr<StreamSocket> transport(
1439       new TCPClientSocket(addr, NULL, NetLog::Source()));
1440   int rv = transport->Connect(callback.callback());
1441   if (rv == ERR_IO_PENDING)
1442     rv = callback.WaitForResult();
1443   EXPECT_EQ(OK, rv);
1444
1445   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1446       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1447
1448   rv = sock->Connect(callback.callback());
1449   if (rv == ERR_IO_PENDING)
1450     rv = callback.WaitForResult();
1451   EXPECT_EQ(OK, rv);
1452
1453   const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1454   scoped_refptr<IOBuffer> request_buffer(
1455       new IOBuffer(arraysize(request_text) - 1));
1456   memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1457
1458   rv = sock->Write(
1459       request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1460   EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1461
1462   if (rv == ERR_IO_PENDING)
1463     rv = callback.WaitForResult();
1464   EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1465
1466   // Do a partial read and then exit.  This test should not crash!
1467   scoped_refptr<IOBuffer> buf(new IOBuffer(512));
1468   rv = sock->Read(buf.get(), 512, callback.callback());
1469   EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
1470
1471   if (rv == ERR_IO_PENDING)
1472     rv = callback.WaitForResult();
1473
1474   EXPECT_GT(rv, 0);
1475 }
1476
1477 TEST_F(SSLClientSocketTest, Read_FullLogging) {
1478   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1479                                 SpawnedTestServer::kLocalhost,
1480                                 base::FilePath());
1481   ASSERT_TRUE(test_server.Start());
1482
1483   AddressList addr;
1484   ASSERT_TRUE(test_server.GetAddressList(&addr));
1485
1486   TestCompletionCallback callback;
1487   CapturingNetLog log;
1488   log.SetLogLevel(NetLog::LOG_ALL);
1489   scoped_ptr<StreamSocket> transport(
1490       new TCPClientSocket(addr, &log, NetLog::Source()));
1491   int rv = transport->Connect(callback.callback());
1492   if (rv == ERR_IO_PENDING)
1493     rv = callback.WaitForResult();
1494   EXPECT_EQ(OK, rv);
1495
1496   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1497       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1498
1499   rv = sock->Connect(callback.callback());
1500   if (rv == ERR_IO_PENDING)
1501     rv = callback.WaitForResult();
1502   EXPECT_EQ(OK, rv);
1503   EXPECT_TRUE(sock->IsConnected());
1504
1505   const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1506   scoped_refptr<IOBuffer> request_buffer(
1507       new IOBuffer(arraysize(request_text) - 1));
1508   memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1509
1510   rv = sock->Write(
1511       request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1512   EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1513
1514   if (rv == ERR_IO_PENDING)
1515     rv = callback.WaitForResult();
1516   EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1517
1518   CapturingNetLog::CapturedEntryList entries;
1519   log.GetEntries(&entries);
1520   size_t last_index = ExpectLogContainsSomewhereAfter(
1521       entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
1522
1523   scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1524   for (;;) {
1525     rv = sock->Read(buf.get(), 4096, callback.callback());
1526     EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1527
1528     if (rv == ERR_IO_PENDING)
1529       rv = callback.WaitForResult();
1530
1531     EXPECT_GE(rv, 0);
1532     if (rv <= 0)
1533       break;
1534
1535     log.GetEntries(&entries);
1536     last_index =
1537         ExpectLogContainsSomewhereAfter(entries,
1538                                         last_index + 1,
1539                                         NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1540                                         NetLog::PHASE_NONE);
1541   }
1542 }
1543
1544 // Regression test for http://crbug.com/42538
1545 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
1546   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1547                                 SpawnedTestServer::kLocalhost,
1548                                 base::FilePath());
1549   ASSERT_TRUE(test_server.Start());
1550
1551   AddressList addr;
1552   TestCompletionCallback callback;
1553
1554   static const unsigned char application_data[] = {
1555       0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
1556       0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
1557       0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
1558       0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
1559       0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
1560       0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
1561       0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
1562       0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
1563       0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
1564       0x0a};
1565
1566   // All reads and writes complete synchronously (async=false).
1567   MockRead data_reads[] = {
1568       MockRead(SYNCHRONOUS,
1569                reinterpret_cast<const char*>(application_data),
1570                arraysize(application_data)),
1571       MockRead(SYNCHRONOUS, OK), };
1572
1573   StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1574
1575   scoped_ptr<StreamSocket> transport(
1576       new MockTCPClientSocket(addr, NULL, &data));
1577   int rv = transport->Connect(callback.callback());
1578   if (rv == ERR_IO_PENDING)
1579     rv = callback.WaitForResult();
1580   EXPECT_EQ(OK, rv);
1581
1582   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1583       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1584
1585   rv = sock->Connect(callback.callback());
1586   if (rv == ERR_IO_PENDING)
1587     rv = callback.WaitForResult();
1588   EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
1589 }
1590
1591 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
1592   // Rather than exhaustively disabling every RC4 ciphersuite defined at
1593   // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
1594   // only disabling those cipher suites that the test server actually
1595   // implements.
1596   const uint16 kCiphersToDisable[] = {0x0005,  // TLS_RSA_WITH_RC4_128_SHA
1597   };
1598
1599   SpawnedTestServer::SSLOptions ssl_options;
1600   // Enable only RC4 on the test server.
1601   ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
1602   SpawnedTestServer test_server(
1603       SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1604   ASSERT_TRUE(test_server.Start());
1605
1606   AddressList addr;
1607   ASSERT_TRUE(test_server.GetAddressList(&addr));
1608
1609   TestCompletionCallback callback;
1610   CapturingNetLog log;
1611   scoped_ptr<StreamSocket> transport(
1612       new TCPClientSocket(addr, &log, NetLog::Source()));
1613   int rv = transport->Connect(callback.callback());
1614   if (rv == ERR_IO_PENDING)
1615     rv = callback.WaitForResult();
1616   EXPECT_EQ(OK, rv);
1617
1618   SSLConfig ssl_config;
1619   for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
1620     ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
1621
1622   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1623       transport.Pass(), test_server.host_port_pair(), ssl_config));
1624
1625   EXPECT_FALSE(sock->IsConnected());
1626
1627   rv = sock->Connect(callback.callback());
1628   CapturingNetLog::CapturedEntryList entries;
1629   log.GetEntries(&entries);
1630   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1631
1632   // NSS has special handling that maps a handshake_failure alert received
1633   // immediately after a client_hello to be a mismatched cipher suite error,
1634   // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
1635   // Secure Transport (OS X), the handshake_failure is bubbled up without any
1636   // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
1637   // indicates that no cipher suite was negotiated with the test server.
1638   if (rv == ERR_IO_PENDING)
1639     rv = callback.WaitForResult();
1640   EXPECT_TRUE(rv == ERR_SSL_VERSION_OR_CIPHER_MISMATCH ||
1641               rv == ERR_SSL_PROTOCOL_ERROR);
1642   // The exact ordering differs between SSLClientSocketNSS (which issues an
1643   // extra read) and SSLClientSocketMac (which does not). Just make sure the
1644   // error appears somewhere in the log.
1645   log.GetEntries(&entries);
1646   ExpectLogContainsSomewhere(
1647       entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
1648
1649   // We cannot test sock->IsConnected(), as the NSS implementation disconnects
1650   // the socket when it encounters an error, whereas other implementations
1651   // leave it connected.
1652   // Because this an error that the test server is mutually aware of, as opposed
1653   // to being an error such as a certificate name mismatch, which is
1654   // client-only, the exact index of the SSL connect end depends on how
1655   // quickly the test server closes the underlying socket. If the test server
1656   // closes before the IO message loop pumps messages, there may be a 0-byte
1657   // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
1658   // result, the SSL connect end event will be the second-to-last entry,
1659   // rather than the last entry.
1660   EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1) ||
1661               LogContainsSSLConnectEndEvent(entries, -2));
1662 }
1663
1664 // When creating an SSLClientSocket, it is allowed to pass in a
1665 // ClientSocketHandle that is not obtained from a client socket pool.
1666 // Here we verify that such a simple ClientSocketHandle, not associated with any
1667 // client socket pool, can be destroyed safely.
1668 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
1669   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1670                                 SpawnedTestServer::kLocalhost,
1671                                 base::FilePath());
1672   ASSERT_TRUE(test_server.Start());
1673
1674   AddressList addr;
1675   ASSERT_TRUE(test_server.GetAddressList(&addr));
1676
1677   TestCompletionCallback callback;
1678   scoped_ptr<StreamSocket> transport(
1679       new TCPClientSocket(addr, NULL, NetLog::Source()));
1680   int rv = transport->Connect(callback.callback());
1681   if (rv == ERR_IO_PENDING)
1682     rv = callback.WaitForResult();
1683   EXPECT_EQ(OK, rv);
1684
1685   scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
1686   socket_handle->SetSocket(transport.Pass());
1687
1688   scoped_ptr<SSLClientSocket> sock(
1689       socket_factory_->CreateSSLClientSocket(socket_handle.Pass(),
1690                                              test_server.host_port_pair(),
1691                                              kDefaultSSLConfig,
1692                                              context_));
1693
1694   EXPECT_FALSE(sock->IsConnected());
1695   rv = sock->Connect(callback.callback());
1696   if (rv == ERR_IO_PENDING)
1697     rv = callback.WaitForResult();
1698   EXPECT_EQ(OK, rv);
1699 }
1700
1701 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
1702 // code and different keying label results in different keying material.
1703 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
1704   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1705                                 SpawnedTestServer::kLocalhost,
1706                                 base::FilePath());
1707   ASSERT_TRUE(test_server.Start());
1708
1709   AddressList addr;
1710   ASSERT_TRUE(test_server.GetAddressList(&addr));
1711
1712   TestCompletionCallback callback;
1713
1714   scoped_ptr<StreamSocket> transport(
1715       new TCPClientSocket(addr, NULL, NetLog::Source()));
1716   int rv = transport->Connect(callback.callback());
1717   if (rv == ERR_IO_PENDING)
1718     rv = callback.WaitForResult();
1719   EXPECT_EQ(OK, rv);
1720
1721   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1722       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1723
1724   rv = sock->Connect(callback.callback());
1725   if (rv == ERR_IO_PENDING)
1726     rv = callback.WaitForResult();
1727   EXPECT_EQ(OK, rv);
1728   EXPECT_TRUE(sock->IsConnected());
1729
1730   const int kKeyingMaterialSize = 32;
1731   const char* kKeyingLabel1 = "client-socket-test-1";
1732   const char* kKeyingContext = "";
1733   unsigned char client_out1[kKeyingMaterialSize];
1734   memset(client_out1, 0, sizeof(client_out1));
1735   rv = sock->ExportKeyingMaterial(
1736       kKeyingLabel1, false, kKeyingContext, client_out1, sizeof(client_out1));
1737   EXPECT_EQ(rv, OK);
1738
1739   const char* kKeyingLabel2 = "client-socket-test-2";
1740   unsigned char client_out2[kKeyingMaterialSize];
1741   memset(client_out2, 0, sizeof(client_out2));
1742   rv = sock->ExportKeyingMaterial(
1743       kKeyingLabel2, false, kKeyingContext, client_out2, sizeof(client_out2));
1744   EXPECT_EQ(rv, OK);
1745   EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
1746 }
1747
1748 // Verifies that SSLClientSocket::ClearSessionCache can be called without
1749 // explicit NSS initialization.
1750 TEST(SSLClientSocket, ClearSessionCache) {
1751   SSLClientSocket::ClearSessionCache();
1752 }
1753
1754 // Test that the server certificates are properly retrieved from the underlying
1755 // SSL stack.
1756 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
1757   // The connection does not have to be successful.
1758   cert_verifier_->set_default_result(ERR_CERT_INVALID);
1759
1760   // Set up a test server with CERT_CHAIN_WRONG_ROOT.
1761   // This makes the server present redundant-server-chain.pem, which contains
1762   // intermediate certificates.
1763   SpawnedTestServer::SSLOptions ssl_options(
1764       SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
1765   SpawnedTestServer test_server(
1766       SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1767   ASSERT_TRUE(test_server.Start());
1768
1769   AddressList addr;
1770   ASSERT_TRUE(test_server.GetAddressList(&addr));
1771
1772   TestCompletionCallback callback;
1773   scoped_ptr<StreamSocket> transport(
1774       new TCPClientSocket(addr, NULL, NetLog::Source()));
1775   int rv = transport->Connect(callback.callback());
1776   rv = callback.GetResult(rv);
1777   EXPECT_EQ(OK, rv);
1778
1779   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1780       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1781   EXPECT_FALSE(sock->IsConnected());
1782   rv = sock->Connect(callback.callback());
1783   rv = callback.GetResult(rv);
1784
1785   EXPECT_EQ(ERR_CERT_INVALID, rv);
1786   EXPECT_TRUE(sock->IsConnected());
1787
1788   // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
1789   // certs from redundant-server-chain.pem.
1790   CertificateList server_certs =
1791       CreateCertificateListFromFile(GetTestCertsDirectory(),
1792                                     "redundant-server-chain.pem",
1793                                     X509Certificate::FORMAT_AUTO);
1794
1795   // Get the server certificate as received client side.
1796   scoped_refptr<X509Certificate> server_certificate =
1797       sock->GetUnverifiedServerCertificateChain();
1798
1799   // Get the intermediates as received  client side.
1800   const X509Certificate::OSCertHandles& server_intermediates =
1801       server_certificate->GetIntermediateCertificates();
1802
1803   // Check that the unverified server certificate chain is properly retrieved
1804   // from the underlying ssl stack.
1805   ASSERT_EQ(4U, server_certs.size());
1806
1807   EXPECT_TRUE(X509Certificate::IsSameOSCert(
1808       server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
1809
1810   ASSERT_EQ(3U, server_intermediates.size());
1811
1812   EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
1813                                             server_certs[1]->os_cert_handle()));
1814   EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
1815                                             server_certs[2]->os_cert_handle()));
1816   EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
1817                                             server_certs[3]->os_cert_handle()));
1818
1819   sock->Disconnect();
1820   EXPECT_FALSE(sock->IsConnected());
1821 }
1822
1823 // This tests that SSLInfo contains a properly re-constructed certificate
1824 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
1825 // verified, not the chain as served by the server. (They may be different.)
1826 //
1827 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
1828 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
1829 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
1830 // a self-signed root. Such a situation can occur when a new root (C2) is
1831 // cross-certified by an old root (D) and has two different versions of its
1832 // floating around. Servers may supply C2 as an intermediate, but the
1833 // SSLClientSocket should return the chain that was verified, from
1834 // verify_result, instead.
1835 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
1836   // By default, cause the CertVerifier to treat all certificates as
1837   // expired.
1838   cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
1839
1840   // We will expect SSLInfo to ultimately contain this chain.
1841   CertificateList certs =
1842       CreateCertificateListFromFile(GetTestCertsDirectory(),
1843                                     "redundant-validated-chain.pem",
1844                                     X509Certificate::FORMAT_AUTO);
1845   ASSERT_EQ(3U, certs.size());
1846
1847   X509Certificate::OSCertHandles temp_intermediates;
1848   temp_intermediates.push_back(certs[1]->os_cert_handle());
1849   temp_intermediates.push_back(certs[2]->os_cert_handle());
1850
1851   CertVerifyResult verify_result;
1852   verify_result.verified_cert = X509Certificate::CreateFromHandle(
1853       certs[0]->os_cert_handle(), temp_intermediates);
1854
1855   // Add a rule that maps the server cert (A) to the chain of A->B->C2
1856   // rather than A->B->C.
1857   cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
1858
1859   // Load and install the root for the validated chain.
1860   scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
1861       GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
1862   ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert);
1863   ScopedTestRoot scoped_root(root_cert.get());
1864
1865   // Set up a test server with CERT_CHAIN_WRONG_ROOT.
1866   SpawnedTestServer::SSLOptions ssl_options(
1867       SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
1868   SpawnedTestServer test_server(
1869       SpawnedTestServer::TYPE_HTTPS,
1870       ssl_options,
1871       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
1872   ASSERT_TRUE(test_server.Start());
1873
1874   AddressList addr;
1875   ASSERT_TRUE(test_server.GetAddressList(&addr));
1876
1877   TestCompletionCallback callback;
1878   CapturingNetLog log;
1879   scoped_ptr<StreamSocket> transport(
1880       new TCPClientSocket(addr, &log, NetLog::Source()));
1881   int rv = transport->Connect(callback.callback());
1882   if (rv == ERR_IO_PENDING)
1883     rv = callback.WaitForResult();
1884   EXPECT_EQ(OK, rv);
1885
1886   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1887       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1888   EXPECT_FALSE(sock->IsConnected());
1889   rv = sock->Connect(callback.callback());
1890
1891   CapturingNetLog::CapturedEntryList entries;
1892   log.GetEntries(&entries);
1893   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1894   if (rv == ERR_IO_PENDING)
1895     rv = callback.WaitForResult();
1896
1897   EXPECT_EQ(OK, rv);
1898   EXPECT_TRUE(sock->IsConnected());
1899   log.GetEntries(&entries);
1900   EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1901
1902   SSLInfo ssl_info;
1903   sock->GetSSLInfo(&ssl_info);
1904
1905   // Verify that SSLInfo contains the corrected re-constructed chain A -> B
1906   // -> C2.
1907   const X509Certificate::OSCertHandles& intermediates =
1908       ssl_info.cert->GetIntermediateCertificates();
1909   ASSERT_EQ(2U, intermediates.size());
1910   EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
1911                                             certs[0]->os_cert_handle()));
1912   EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
1913                                             certs[1]->os_cert_handle()));
1914   EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
1915                                             certs[2]->os_cert_handle()));
1916
1917   sock->Disconnect();
1918   EXPECT_FALSE(sock->IsConnected());
1919 }
1920
1921 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
1922   SpawnedTestServer::SSLOptions ssl_options;
1923   ssl_options.request_client_certificate = true;
1924   scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
1925   ASSERT_TRUE(request_info.get());
1926   EXPECT_EQ(0u, request_info->cert_authorities.size());
1927 }
1928
1929 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
1930   const base::FilePath::CharType kThawteFile[] =
1931       FILE_PATH_LITERAL("thawte.single.pem");
1932   const unsigned char kThawteDN[] = {
1933       0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
1934       0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
1935       0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
1936       0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
1937       0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
1938       0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
1939       0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
1940   const size_t kThawteLen = sizeof(kThawteDN);
1941
1942   const base::FilePath::CharType kDiginotarFile[] =
1943       FILE_PATH_LITERAL("diginotar_root_ca.pem");
1944   const unsigned char kDiginotarDN[] = {
1945       0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
1946       0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
1947       0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
1948       0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
1949       0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
1950       0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
1951       0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
1952       0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
1953       0x6c};
1954   const size_t kDiginotarLen = sizeof(kDiginotarDN);
1955
1956   SpawnedTestServer::SSLOptions ssl_options;
1957   ssl_options.request_client_certificate = true;
1958   ssl_options.client_authorities.push_back(
1959       GetTestClientCertsDirectory().Append(kThawteFile));
1960   ssl_options.client_authorities.push_back(
1961       GetTestClientCertsDirectory().Append(kDiginotarFile));
1962   scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
1963   ASSERT_TRUE(request_info.get());
1964   ASSERT_EQ(2u, request_info->cert_authorities.size());
1965   EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
1966             request_info->cert_authorities[0]);
1967   EXPECT_EQ(
1968       std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
1969       request_info->cert_authorities[1]);
1970 }
1971
1972 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
1973   SpawnedTestServer::SSLOptions ssl_options;
1974   ssl_options.signed_cert_timestamps_tls_ext = "test";
1975
1976   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1977                                 ssl_options,
1978                                 base::FilePath());
1979   ASSERT_TRUE(test_server.Start());
1980
1981   AddressList addr;
1982   ASSERT_TRUE(test_server.GetAddressList(&addr));
1983
1984   TestCompletionCallback callback;
1985   CapturingNetLog log;
1986   scoped_ptr<StreamSocket> transport(
1987       new TCPClientSocket(addr, &log, NetLog::Source()));
1988   int rv = transport->Connect(callback.callback());
1989   if (rv == ERR_IO_PENDING)
1990     rv = callback.WaitForResult();
1991   EXPECT_EQ(OK, rv);
1992
1993   SSLConfig ssl_config;
1994   ssl_config.signed_cert_timestamps_enabled = true;
1995
1996   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1997       transport.Pass(), test_server.host_port_pair(), ssl_config));
1998
1999   EXPECT_FALSE(sock->IsConnected());
2000
2001   rv = sock->Connect(callback.callback());
2002
2003   CapturingNetLog::CapturedEntryList entries;
2004   log.GetEntries(&entries);
2005   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2006   if (rv == ERR_IO_PENDING)
2007     rv = callback.WaitForResult();
2008   EXPECT_EQ(OK, rv);
2009   EXPECT_TRUE(sock->IsConnected());
2010   log.GetEntries(&entries);
2011   EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2012
2013 #if !defined(USE_OPENSSL)
2014   EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2015 #else
2016   // Enabling CT for OpenSSL is currently a noop.
2017   EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2018 #endif
2019
2020   sock->Disconnect();
2021   EXPECT_FALSE(sock->IsConnected());
2022 }
2023
2024 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2025 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2026   SpawnedTestServer::SSLOptions ssl_options;
2027   ssl_options.staple_ocsp_response = true;
2028   // The test server currently only knows how to generate OCSP responses
2029   // for a freshly minted certificate.
2030   ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2031
2032   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2033                                 ssl_options,
2034                                 base::FilePath());
2035   ASSERT_TRUE(test_server.Start());
2036
2037   AddressList addr;
2038   ASSERT_TRUE(test_server.GetAddressList(&addr));
2039
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);
2048
2049   SSLConfig ssl_config;
2050   // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2051   // Certificate Transparency verification regardless of whether the platform
2052   // is able to process the OCSP status itself.
2053   ssl_config.signed_cert_timestamps_enabled = true;
2054
2055   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2056       transport.Pass(), test_server.host_port_pair(), ssl_config));
2057
2058   EXPECT_FALSE(sock->IsConnected());
2059
2060   rv = sock->Connect(callback.callback());
2061
2062   CapturingNetLog::CapturedEntryList entries;
2063   log.GetEntries(&entries);
2064   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2065   if (rv == ERR_IO_PENDING)
2066     rv = callback.WaitForResult();
2067   EXPECT_EQ(OK, rv);
2068   EXPECT_TRUE(sock->IsConnected());
2069   log.GetEntries(&entries);
2070   EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2071
2072 #if !defined(USE_OPENSSL)
2073   EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2074 #else
2075   // OCSP stapling isn't currently supported in the OpenSSL socket.
2076   EXPECT_FALSE(sock->stapled_ocsp_response_received_);
2077 #endif
2078
2079   sock->Disconnect();
2080   EXPECT_FALSE(sock->IsConnected());
2081 }
2082
2083 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2084   SpawnedTestServer::SSLOptions ssl_options;
2085   ssl_options.signed_cert_timestamps_tls_ext = "test";
2086
2087   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2088                                 ssl_options,
2089                                 base::FilePath());
2090   ASSERT_TRUE(test_server.Start());
2091
2092   AddressList addr;
2093   ASSERT_TRUE(test_server.GetAddressList(&addr));
2094
2095   TestCompletionCallback callback;
2096   CapturingNetLog log;
2097   scoped_ptr<StreamSocket> transport(
2098       new TCPClientSocket(addr, &log, NetLog::Source()));
2099   int rv = transport->Connect(callback.callback());
2100   if (rv == ERR_IO_PENDING)
2101     rv = callback.WaitForResult();
2102   EXPECT_EQ(OK, rv);
2103
2104   SSLConfig ssl_config;
2105   ssl_config.signed_cert_timestamps_enabled = false;
2106
2107   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2108       transport.Pass(), test_server.host_port_pair(), ssl_config));
2109
2110   EXPECT_FALSE(sock->IsConnected());
2111
2112   rv = sock->Connect(callback.callback());
2113
2114   CapturingNetLog::CapturedEntryList entries;
2115   log.GetEntries(&entries);
2116   EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2117   if (rv == ERR_IO_PENDING)
2118     rv = callback.WaitForResult();
2119   EXPECT_EQ(OK, rv);
2120   EXPECT_TRUE(sock->IsConnected());
2121   log.GetEntries(&entries);
2122   EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2123
2124   EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2125
2126   sock->Disconnect();
2127   EXPECT_FALSE(sock->IsConnected());
2128 }
2129
2130 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2131 TEST_F(SSLClientSocketTest, ReuseStates) {
2132   SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2133                                 SpawnedTestServer::kLocalhost,
2134                                 base::FilePath());
2135   ASSERT_TRUE(test_server.Start());
2136
2137   AddressList addr;
2138   ASSERT_TRUE(test_server.GetAddressList(&addr));
2139
2140   TestCompletionCallback callback;
2141   scoped_ptr<StreamSocket> transport(
2142       new TCPClientSocket(addr, NULL, NetLog::Source()));
2143   int rv = transport->Connect(callback.callback());
2144   if (rv == ERR_IO_PENDING)
2145     rv = callback.WaitForResult();
2146   EXPECT_EQ(OK, rv);
2147
2148   scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2149       transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2150
2151   rv = sock->Connect(callback.callback());
2152   if (rv == ERR_IO_PENDING)
2153     rv = callback.WaitForResult();
2154   EXPECT_EQ(OK, rv);
2155
2156   // The socket was just connected. It should be idle because it is speaking
2157   // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2158   // returns false.
2159   EXPECT_TRUE(sock->IsConnected());
2160   EXPECT_TRUE(sock->IsConnectedAndIdle());
2161   EXPECT_FALSE(sock->WasEverUsed());
2162
2163   const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2164   const size_t kRequestLen = arraysize(kRequestText) - 1;
2165   scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2166   memcpy(request_buffer->data(), kRequestText, kRequestLen);
2167
2168   rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2169   EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2170
2171   if (rv == ERR_IO_PENDING)
2172     rv = callback.WaitForResult();
2173   EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2174
2175   // The socket has now been used.
2176   EXPECT_TRUE(sock->WasEverUsed());
2177
2178   // TODO(davidben): Read one byte to ensure the test server has responded and
2179   // then assert IsConnectedAndIdle is false. This currently doesn't work
2180   // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2181   // SSL implementation's internal buffers. Either call PR_Available and
2182   // SSL_pending, although the former isn't actually implemented or perhaps
2183   // attempt to read one byte extra.
2184 }
2185
2186 }  // namespace net