Home | History | Annotate | Download | only in socket
      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 // This file includes code SSLClientSocketNSS::DoVerifyCertComplete() derived
      6 // from AuthCertificateCallback() in
      7 // mozilla/security/manager/ssl/src/nsNSSCallbacks.cpp.
      8 
      9 /* ***** BEGIN LICENSE BLOCK *****
     10  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
     11  *
     12  * The contents of this file are subject to the Mozilla Public License Version
     13  * 1.1 (the "License"); you may not use this file except in compliance with
     14  * the License. You may obtain a copy of the License at
     15  * http://www.mozilla.org/MPL/
     16  *
     17  * Software distributed under the License is distributed on an "AS IS" basis,
     18  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
     19  * for the specific language governing rights and limitations under the
     20  * License.
     21  *
     22  * The Original Code is the Netscape security libraries.
     23  *
     24  * The Initial Developer of the Original Code is
     25  * Netscape Communications Corporation.
     26  * Portions created by the Initial Developer are Copyright (C) 2000
     27  * the Initial Developer. All Rights Reserved.
     28  *
     29  * Contributor(s):
     30  *   Ian McGreer <mcgreer (at) netscape.com>
     31  *   Javier Delgadillo <javi (at) netscape.com>
     32  *   Kai Engert <kengert (at) redhat.com>
     33  *
     34  * Alternatively, the contents of this file may be used under the terms of
     35  * either the GNU General Public License Version 2 or later (the "GPL"), or
     36  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
     37  * in which case the provisions of the GPL or the LGPL are applicable instead
     38  * of those above. If you wish to allow use of your version of this file only
     39  * under the terms of either the GPL or the LGPL, and not to allow others to
     40  * use your version of this file under the terms of the MPL, indicate your
     41  * decision by deleting the provisions above and replace them with the notice
     42  * and other provisions required by the GPL or the LGPL. If you do not delete
     43  * the provisions above, a recipient may use your version of this file under
     44  * the terms of any one of the MPL, the GPL or the LGPL.
     45  *
     46  * ***** END LICENSE BLOCK ***** */
     47 
     48 #include "net/socket/ssl_client_socket_nss.h"
     49 
     50 #include <certdb.h>
     51 #include <hasht.h>
     52 #include <keyhi.h>
     53 #include <nspr.h>
     54 #include <nss.h>
     55 #include <ocsp.h>
     56 #include <pk11pub.h>
     57 #include <secerr.h>
     58 #include <sechash.h>
     59 #include <ssl.h>
     60 #include <sslerr.h>
     61 #include <sslproto.h>
     62 
     63 #include <algorithm>
     64 #include <limits>
     65 #include <map>
     66 
     67 #include "base/bind.h"
     68 #include "base/bind_helpers.h"
     69 #include "base/callback_helpers.h"
     70 #include "base/compiler_specific.h"
     71 #include "base/logging.h"
     72 #include "base/memory/singleton.h"
     73 #include "base/metrics/histogram.h"
     74 #include "base/single_thread_task_runner.h"
     75 #include "base/stl_util.h"
     76 #include "base/strings/string_number_conversions.h"
     77 #include "base/strings/string_util.h"
     78 #include "base/strings/stringprintf.h"
     79 #include "base/thread_task_runner_handle.h"
     80 #include "base/threading/thread_restrictions.h"
     81 #include "base/values.h"
     82 #include "crypto/ec_private_key.h"
     83 #include "crypto/nss_util.h"
     84 #include "crypto/nss_util_internal.h"
     85 #include "crypto/rsa_private_key.h"
     86 #include "crypto/scoped_nss_types.h"
     87 #include "net/base/address_list.h"
     88 #include "net/base/connection_type_histograms.h"
     89 #include "net/base/dns_util.h"
     90 #include "net/base/io_buffer.h"
     91 #include "net/base/net_errors.h"
     92 #include "net/base/net_log.h"
     93 #include "net/cert/asn1_util.h"
     94 #include "net/cert/cert_status_flags.h"
     95 #include "net/cert/cert_verifier.h"
     96 #include "net/cert/single_request_cert_verifier.h"
     97 #include "net/cert/x509_certificate_net_log_param.h"
     98 #include "net/cert/x509_util.h"
     99 #include "net/http/transport_security_state.h"
    100 #include "net/ocsp/nss_ocsp.h"
    101 #include "net/socket/client_socket_handle.h"
    102 #include "net/socket/nss_ssl_util.h"
    103 #include "net/socket/ssl_error_params.h"
    104 #include "net/ssl/ssl_cert_request_info.h"
    105 #include "net/ssl/ssl_connection_status_flags.h"
    106 #include "net/ssl/ssl_info.h"
    107 
    108 #if defined(OS_WIN)
    109 #include <windows.h>
    110 #include <wincrypt.h>
    111 
    112 #include "base/win/windows_version.h"
    113 #elif defined(OS_MACOSX)
    114 #include <Security/SecBase.h>
    115 #include <Security/SecCertificate.h>
    116 #include <Security/SecIdentity.h>
    117 
    118 #include "base/mac/mac_logging.h"
    119 #include "base/synchronization/lock.h"
    120 #include "crypto/mac_security_services_lock.h"
    121 #elif defined(USE_NSS)
    122 #include <dlfcn.h>
    123 #endif
    124 
    125 namespace net {
    126 
    127 // State machines are easier to debug if you log state transitions.
    128 // Enable these if you want to see what's going on.
    129 #if 1
    130 #define EnterFunction(x)
    131 #define LeaveFunction(x)
    132 #define GotoState(s) next_handshake_state_ = s
    133 #else
    134 #define EnterFunction(x)\
    135     VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
    136             << "; next_handshake_state " << next_handshake_state_
    137 #define LeaveFunction(x)\
    138     VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
    139             << "; next_handshake_state " << next_handshake_state_
    140 #define GotoState(s)\
    141     do {\
    142       VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
    143       next_handshake_state_ = s;\
    144     } while (0)
    145 #endif
    146 
    147 namespace {
    148 
    149 // SSL plaintext fragments are shorter than 16KB. Although the record layer
    150 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
    151 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
    152 // entire SSL record.
    153 const int kRecvBufferSize = 17 * 1024;
    154 const int kSendBufferSize = 17 * 1024;
    155 
    156 // Used by SSLClientSocketNSS::Core to indicate there is no read result
    157 // obtained by a previous operation waiting to be returned to the caller.
    158 // This constant can be any non-negative/non-zero value (eg: it does not
    159 // overlap with any value of the net::Error range, including net::OK).
    160 const int kNoPendingReadResult = 1;
    161 
    162 #if defined(OS_WIN)
    163 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
    164 // set on Windows XP without error. There is some overhead from the server
    165 // sending the OCSP response if it supports the extension, for the subset of
    166 // XP clients who will request it but be unable to use it, but this is an
    167 // acceptable trade-off for simplicity of implementation.
    168 bool IsOCSPStaplingSupported() {
    169   return true;
    170 }
    171 #elif defined(USE_NSS)
    172 typedef SECStatus
    173 (*CacheOCSPResponseFromSideChannelFunction)(
    174     CERTCertDBHandle *handle, CERTCertificate *cert, PRTime time,
    175     SECItem *encodedResponse, void *pwArg);
    176 
    177 // On Linux, we dynamically link against the system version of libnss3.so. In
    178 // order to continue working on systems without up-to-date versions of NSS we
    179 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
    180 
    181 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
    182 // runtime symbol resolution that we need.
    183 class RuntimeLibNSSFunctionPointers {
    184  public:
    185   CacheOCSPResponseFromSideChannelFunction
    186   GetCacheOCSPResponseFromSideChannelFunction() {
    187     return cache_ocsp_response_from_side_channel_;
    188   }
    189 
    190   static RuntimeLibNSSFunctionPointers* GetInstance() {
    191     return Singleton<RuntimeLibNSSFunctionPointers>::get();
    192   }
    193 
    194  private:
    195   friend struct DefaultSingletonTraits<RuntimeLibNSSFunctionPointers>;
    196 
    197   RuntimeLibNSSFunctionPointers() {
    198     cache_ocsp_response_from_side_channel_ =
    199         (CacheOCSPResponseFromSideChannelFunction)
    200         dlsym(RTLD_DEFAULT, "CERT_CacheOCSPResponseFromSideChannel");
    201   }
    202 
    203   CacheOCSPResponseFromSideChannelFunction
    204       cache_ocsp_response_from_side_channel_;
    205 };
    206 
    207 CacheOCSPResponseFromSideChannelFunction
    208 GetCacheOCSPResponseFromSideChannelFunction() {
    209   return RuntimeLibNSSFunctionPointers::GetInstance()
    210     ->GetCacheOCSPResponseFromSideChannelFunction();
    211 }
    212 
    213 bool IsOCSPStaplingSupported() {
    214   return GetCacheOCSPResponseFromSideChannelFunction() != NULL;
    215 }
    216 #else
    217 // TODO(agl): Figure out if we can plumb the OCSP response into Mac's system
    218 // certificate validation functions.
    219 bool IsOCSPStaplingSupported() {
    220   return false;
    221 }
    222 #endif
    223 
    224 class FreeCERTCertificate {
    225  public:
    226   inline void operator()(CERTCertificate* x) const {
    227     CERT_DestroyCertificate(x);
    228   }
    229 };
    230 typedef scoped_ptr_malloc<CERTCertificate, FreeCERTCertificate>
    231     ScopedCERTCertificate;
    232 
    233 #if defined(OS_WIN)
    234 
    235 // This callback is intended to be used with CertFindChainInStore. In addition
    236 // to filtering by extended/enhanced key usage, we do not show expired
    237 // certificates and require digital signature usage in the key usage
    238 // extension.
    239 //
    240 // This matches our behavior on Mac OS X and that of NSS. It also matches the
    241 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
    242 // http://blogs.msdn.com/b/askie/archive/2009/06/09/my-expired-client-certificates-no-longer-display-when-connecting-to-my-web-server-using-ie8.aspx
    243 BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
    244                                    void* find_arg) {
    245   VLOG(1) << "Calling ClientCertFindCallback from _nss";
    246   // Verify the certificate's KU is good.
    247   BYTE key_usage;
    248   if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
    249                               &key_usage, 1)) {
    250     if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
    251       return FALSE;
    252   } else {
    253     DWORD err = GetLastError();
    254     // If |err| is non-zero, it's an actual error. Otherwise the extension
    255     // just isn't present, and we treat it as if everything was allowed.
    256     if (err) {
    257       DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
    258       return FALSE;
    259     }
    260   }
    261 
    262   // Verify the current time is within the certificate's validity period.
    263   if (CertVerifyTimeValidity(NULL, cert_context->pCertInfo) != 0)
    264     return FALSE;
    265 
    266   // Verify private key metadata is associated with this certificate.
    267   DWORD size = 0;
    268   if (!CertGetCertificateContextProperty(
    269           cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) {
    270     return FALSE;
    271   }
    272 
    273   return TRUE;
    274 }
    275 
    276 #endif
    277 
    278 void DestroyCertificates(CERTCertificate** certs, size_t len) {
    279   for (size_t i = 0; i < len; i++)
    280     CERT_DestroyCertificate(certs[i]);
    281 }
    282 
    283 // Helper functions to make it possible to log events from within the
    284 // SSLClientSocketNSS::Core.
    285 void AddLogEvent(const base::WeakPtr<BoundNetLog>& net_log,
    286                  NetLog::EventType event_type) {
    287   if (!net_log)
    288     return;
    289   net_log->AddEvent(event_type);
    290 }
    291 
    292 // Helper function to make it possible to log events from within the
    293 // SSLClientSocketNSS::Core.
    294 void AddLogEventWithCallback(const base::WeakPtr<BoundNetLog>& net_log,
    295                              NetLog::EventType event_type,
    296                              const NetLog::ParametersCallback& callback) {
    297   if (!net_log)
    298     return;
    299   net_log->AddEvent(event_type, callback);
    300 }
    301 
    302 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
    303 // from within the SSLClientSocketNSS::Core.
    304 // AddByteTransferEvent expects to receive a const char*, which within the
    305 // Core is backed by an IOBuffer. If the "const char*" is bound via
    306 // base::Bind and posted to another thread, and the IOBuffer that backs that
    307 // pointer then goes out of scope on the origin thread, this would result in
    308 // an invalid read of a stale pointer.
    309 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
    310 // to the owning IOBuffer can be bound to the Callback. This ensures that the
    311 // IOBuffer will stay alive long enough to cross threads if needed.
    312 void LogByteTransferEvent(
    313     const base::WeakPtr<BoundNetLog>& net_log, NetLog::EventType event_type,
    314     int len, IOBuffer* buffer) {
    315   if (!net_log)
    316     return;
    317   net_log->AddByteTransferEvent(event_type, len, buffer->data());
    318 }
    319 
    320 // PeerCertificateChain is a helper object which extracts the certificate
    321 // chain, as given by the server, from an NSS socket and performs the needed
    322 // resource management. The first element of the chain is the leaf certificate
    323 // and the other elements are in the order given by the server.
    324 class PeerCertificateChain {
    325  public:
    326   PeerCertificateChain() {}
    327   PeerCertificateChain(const PeerCertificateChain& other);
    328   ~PeerCertificateChain();
    329   PeerCertificateChain& operator=(const PeerCertificateChain& other);
    330 
    331   // Resets the current chain, freeing any resources, and updates the current
    332   // chain to be a copy of the chain stored in |nss_fd|.
    333   // If |nss_fd| is NULL, then the current certificate chain will be freed.
    334   void Reset(PRFileDesc* nss_fd);
    335 
    336   // Returns the current certificate chain as a vector of DER-encoded
    337   // base::StringPieces. The returned vector remains valid until Reset is
    338   // called.
    339   std::vector<base::StringPiece> AsStringPieceVector() const;
    340 
    341   bool empty() const { return certs_.empty(); }
    342   size_t size() const { return certs_.size(); }
    343 
    344   CERTCertificate* operator[](size_t index) const {
    345     DCHECK_LT(index, certs_.size());
    346     return certs_[index];
    347   }
    348 
    349  private:
    350   std::vector<CERTCertificate*> certs_;
    351 };
    352 
    353 PeerCertificateChain::PeerCertificateChain(
    354     const PeerCertificateChain& other) {
    355   *this = other;
    356 }
    357 
    358 PeerCertificateChain::~PeerCertificateChain() {
    359   Reset(NULL);
    360 }
    361 
    362 PeerCertificateChain& PeerCertificateChain::operator=(
    363     const PeerCertificateChain& other) {
    364   if (this == &other)
    365     return *this;
    366 
    367   Reset(NULL);
    368   certs_.reserve(other.certs_.size());
    369   for (size_t i = 0; i < other.certs_.size(); ++i)
    370     certs_.push_back(CERT_DupCertificate(other.certs_[i]));
    371 
    372   return *this;
    373 }
    374 
    375 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) {
    376   for (size_t i = 0; i < certs_.size(); ++i)
    377     CERT_DestroyCertificate(certs_[i]);
    378   certs_.clear();
    379 
    380   if (nss_fd == NULL)
    381     return;
    382 
    383   unsigned int num_certs = 0;
    384   SECStatus rv = SSL_PeerCertificateChain(nss_fd, NULL, &num_certs, 0);
    385   DCHECK_EQ(SECSuccess, rv);
    386 
    387   // The handshake on |nss_fd| may not have completed.
    388   if (num_certs == 0)
    389     return;
    390 
    391   certs_.resize(num_certs);
    392   const unsigned int expected_num_certs = num_certs;
    393   rv = SSL_PeerCertificateChain(nss_fd, vector_as_array(&certs_),
    394                                 &num_certs, expected_num_certs);
    395   DCHECK_EQ(SECSuccess, rv);
    396   DCHECK_EQ(expected_num_certs, num_certs);
    397 }
    398 
    399 std::vector<base::StringPiece>
    400 PeerCertificateChain::AsStringPieceVector() const {
    401   std::vector<base::StringPiece> v(certs_.size());
    402   for (unsigned i = 0; i < certs_.size(); i++) {
    403     v[i] = base::StringPiece(
    404         reinterpret_cast<const char*>(certs_[i]->derCert.data),
    405         certs_[i]->derCert.len);
    406   }
    407 
    408   return v;
    409 }
    410 
    411 // HandshakeState is a helper struct used to pass handshake state between
    412 // the NSS task runner and the network task runner.
    413 //
    414 // It contains members that may be read or written on the NSS task runner,
    415 // but which also need to be read from the network task runner. The NSS task
    416 // runner will notify the network task runner whenever this state changes, so
    417 // that the network task runner can safely make a copy, which avoids the need
    418 // for locking.
    419 struct HandshakeState {
    420   HandshakeState() { Reset(); }
    421 
    422   void Reset() {
    423     next_proto_status = SSLClientSocket::kNextProtoUnsupported;
    424     next_proto.clear();
    425     server_protos.clear();
    426     channel_id_sent = false;
    427     server_cert_chain.Reset(NULL);
    428     server_cert = NULL;
    429     resumed_handshake = false;
    430     ssl_connection_status = 0;
    431   }
    432 
    433   // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
    434   // negotiated protocol stored in |next_proto|.
    435   SSLClientSocket::NextProtoStatus next_proto_status;
    436   std::string next_proto;
    437   // If the server supports NPN, the protocols supported by the server.
    438   std::string server_protos;
    439 
    440   // True if a channel ID was sent.
    441   bool channel_id_sent;
    442 
    443   // List of DER-encoded X.509 DistinguishedName of certificate authorities
    444   // allowed by the server.
    445   std::vector<std::string> cert_authorities;
    446 
    447   // Set when the handshake fully completes.
    448   //
    449   // The server certificate is first received from NSS as an NSS certificate
    450   // chain (|server_cert_chain|) and then converted into a platform-specific
    451   // X509Certificate object (|server_cert|). It's possible for some
    452   // certificates to be successfully parsed by NSS, and not by the platform
    453   // libraries (i.e.: when running within a sandbox, different parsing
    454   // algorithms, etc), so it's not safe to assume that |server_cert| will
    455   // always be non-NULL.
    456   PeerCertificateChain server_cert_chain;
    457   scoped_refptr<X509Certificate> server_cert;
    458 
    459   // True if the current handshake was the result of TLS session resumption.
    460   bool resumed_handshake;
    461 
    462   // The negotiated security parameters (TLS version, cipher, extensions) of
    463   // the SSL connection.
    464   int ssl_connection_status;
    465 };
    466 
    467 // Client-side error mapping functions.
    468 
    469 // Map NSS error code to network error code.
    470 int MapNSSClientError(PRErrorCode err) {
    471   switch (err) {
    472     case SSL_ERROR_BAD_CERT_ALERT:
    473     case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
    474     case SSL_ERROR_REVOKED_CERT_ALERT:
    475     case SSL_ERROR_EXPIRED_CERT_ALERT:
    476     case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
    477     case SSL_ERROR_UNKNOWN_CA_ALERT:
    478     case SSL_ERROR_ACCESS_DENIED_ALERT:
    479       return ERR_BAD_SSL_CLIENT_AUTH_CERT;
    480     default:
    481       return MapNSSError(err);
    482   }
    483 }
    484 
    485 // Map NSS error code from the first SSL handshake to network error code.
    486 int MapNSSClientHandshakeError(PRErrorCode err) {
    487   switch (err) {
    488     // If the server closed on us, it is a protocol error.
    489     // Some TLS-intolerant servers do this when we request TLS.
    490     case PR_END_OF_FILE_ERROR:
    491       return ERR_SSL_PROTOCOL_ERROR;
    492     default:
    493       return MapNSSClientError(err);
    494   }
    495 }
    496 
    497 }  // namespace
    498 
    499 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
    500 // able to marshal data between NSS functions and an underlying transport
    501 // socket.
    502 //
    503 // All public functions are meant to be called from the network task runner,
    504 // and any callbacks supplied will be invoked there as well, provided that
    505 // Detach() has not been called yet.
    506 //
    507 /////////////////////////////////////////////////////////////////////////////
    508 //
    509 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
    510 //
    511 // Because NSS may block on either hardware or user input during operations
    512 // such as signing, creating certificates, or locating private keys, the Core
    513 // handles all of the interactions with the underlying NSS SSL socket, so
    514 // that these blocking calls can be executed on a dedicated task runner.
    515 //
    516 // Note that the network task runner and the NSS task runner may be executing
    517 // on the same thread. If that happens, then it's more performant to try to
    518 // complete as much work as possible synchronously, even if it might block,
    519 // rather than continually PostTask-ing to the same thread.
    520 //
    521 // Because NSS functions should only be called on the NSS task runner, while
    522 // I/O resources should only be accessed on the network task runner, most
    523 // public functions are implemented via three methods, each with different
    524 // task runner affinities.
    525 //
    526 // In the single-threaded mode (where the network and NSS task runners run on
    527 // the same thread), these are all attempted synchronously, while in the
    528 // multi-threaded mode, message passing is used.
    529 //
    530 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
    531 //    DoHandshake)
    532 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
    533 //    (BufferRecv, BufferSend)
    534 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
    535 //    DoBufferSend, DoGetDomainBoundCert, OnGetDomainBoundCertComplete)
    536 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
    537 //    data from the network task runner back to NSS (BufferRecvComplete,
    538 //    BufferSendComplete, OnHandshakeIOComplete)
    539 //
    540 /////////////////////////////////////////////////////////////////////////////
    541 // Single-threaded example
    542 //
    543 // |--------------------------Network Task Runner--------------------------|
    544 //  SSLClientSocketNSS              Core               (Transport Socket)
    545 //       Read()
    546 //         |-------------------------V
    547 //                                 Read()
    548 //                                   |
    549 //                            DoPayloadRead()
    550 //                                   |
    551 //                               BufferRecv()
    552 //                                   |
    553 //                              DoBufferRecv()
    554 //                                   |-------------------------V
    555 //                                                           Read()
    556 //                                   V-------------------------|
    557 //                          BufferRecvComplete()
    558 //                                   |
    559 //                           PostOrRunCallback()
    560 //         V-------------------------|
    561 //    (Read Callback)
    562 //
    563 /////////////////////////////////////////////////////////////////////////////
    564 // Multi-threaded example:
    565 //
    566 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
    567 //  SSLClientSocketNSS          Core            Socket         Core
    568 //       Read()
    569 //         |---------------------V
    570 //                             Read()
    571 //                               |-------------------------------V
    572 //                                                             Read()
    573 //                                                               |
    574 //                                                         DoPayloadRead()
    575 //                                                               |
    576 //                                                          BufferRecv
    577 //                               V-------------------------------|
    578 //                          DoBufferRecv
    579 //                               |----------------V
    580 //                                              Read()
    581 //                               V----------------|
    582 //                        BufferRecvComplete()
    583 //                               |-------------------------------V
    584 //                                                      BufferRecvComplete()
    585 //                                                               |
    586 //                                                       PostOrRunCallback()
    587 //                               V-------------------------------|
    588 //                        PostOrRunCallback()
    589 //         V---------------------|
    590 //    (Read Callback)
    591 //
    592 /////////////////////////////////////////////////////////////////////////////
    593 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
    594  public:
    595   // Creates a new Core.
    596   //
    597   // Any calls to NSS are executed on the |nss_task_runner|, while any calls
    598   // that need to operate on the underlying transport, net log, or server
    599   // bound certificate fetching will happen on the |network_task_runner|, so
    600   // that their lifetimes match that of the owning SSLClientSocketNSS.
    601   //
    602   // The caller retains ownership of |transport|, |net_log|, and
    603   // |server_bound_cert_service|, and they will not be accessed once Detach()
    604   // has been called.
    605   Core(base::SequencedTaskRunner* network_task_runner,
    606        base::SequencedTaskRunner* nss_task_runner,
    607        ClientSocketHandle* transport,
    608        const HostPortPair& host_and_port,
    609        const SSLConfig& ssl_config,
    610        BoundNetLog* net_log,
    611        ServerBoundCertService* server_bound_cert_service);
    612 
    613   // Called on the network task runner.
    614   // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
    615   // underlying memio implementation, to the Core. Returns true if the Core
    616   // was successfully registered with the socket.
    617   bool Init(PRFileDesc* socket, memio_Private* buffers);
    618 
    619   // Called on the network task runner.
    620   // Sets the predicted certificate chain that the peer will send, for use
    621   // with the TLS CachedInfo extension. If called, it must not be called
    622   // before Init() or after Connect().
    623   void SetPredictedCertificates(
    624       const std::vector<std::string>& predicted_certificates);
    625 
    626   // Called on the network task runner.
    627   //
    628   // Attempts to perform an SSL handshake. If the handshake cannot be
    629   // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
    630   // the network task runner once the handshake has completed. Otherwise,
    631   // returns OK on success or a network error code on failure.
    632   int Connect(const CompletionCallback& callback);
    633 
    634   // Called on the network task runner.
    635   // Signals that the resources owned by the network task runner are going
    636   // away. No further callbacks will be invoked on the network task runner.
    637   // May be called at any time.
    638   void Detach();
    639 
    640   // Called on the network task runner.
    641   // Returns the current state of the underlying SSL socket. May be called at
    642   // any time.
    643   const HandshakeState& state() const { return network_handshake_state_; }
    644 
    645   // Called on the network task runner.
    646   // Read() and Write() mirror the net::Socket functions of the same name.
    647   // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
    648   // task runner at a later point, unless the caller calls Detach().
    649   int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
    650   int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
    651 
    652   // Called on the network task runner.
    653   bool IsConnected();
    654   bool HasPendingAsyncOperation();
    655   bool HasUnhandledReceivedData();
    656 
    657  private:
    658   friend class base::RefCountedThreadSafe<Core>;
    659   ~Core();
    660 
    661   enum State {
    662     STATE_NONE,
    663     STATE_HANDSHAKE,
    664     STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
    665   };
    666 
    667   bool OnNSSTaskRunner() const;
    668   bool OnNetworkTaskRunner() const;
    669 
    670   ////////////////////////////////////////////////////////////////////////////
    671   // Methods that are ONLY called on the NSS task runner:
    672   ////////////////////////////////////////////////////////////////////////////
    673 
    674   // Called by NSS during full handshakes to allow the application to
    675   // verify the certificate. Instead of verifying the certificate in the midst
    676   // of the handshake, SECSuccess is always returned and the peer's certificate
    677   // is verified afterwards.
    678   // This behaviour is an artifact of the original SSLClientSocketWin
    679   // implementation, which could not verify the peer's certificate until after
    680   // the handshake had completed, as well as bugs in NSS that prevent
    681   // SSL_RestartHandshakeAfterCertReq from working.
    682   static SECStatus OwnAuthCertHandler(void* arg,
    683                                       PRFileDesc* socket,
    684                                       PRBool checksig,
    685                                       PRBool is_server);
    686 
    687   // Callbacks called by NSS when the peer requests client certificate
    688   // authentication.
    689   // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
    690   // the arguments.
    691 #if defined(NSS_PLATFORM_CLIENT_AUTH)
    692   // When NSS has been integrated with awareness of the underlying system
    693   // cryptographic libraries, this callback allows the caller to supply a
    694   // native platform certificate and key for use by NSS. At most, one of
    695   // either (result_certs, result_private_key) or (result_nss_certificate,
    696   // result_nss_private_key) should be set.
    697   // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
    698   static SECStatus PlatformClientAuthHandler(
    699       void* arg,
    700       PRFileDesc* socket,
    701       CERTDistNames* ca_names,
    702       CERTCertList** result_certs,
    703       void** result_private_key,
    704       CERTCertificate** result_nss_certificate,
    705       SECKEYPrivateKey** result_nss_private_key);
    706 #else
    707   static SECStatus ClientAuthHandler(void* arg,
    708                                      PRFileDesc* socket,
    709                                      CERTDistNames* ca_names,
    710                                      CERTCertificate** result_certificate,
    711                                      SECKEYPrivateKey** result_private_key);
    712 #endif
    713 
    714   // Called by NSS once the handshake has completed.
    715   // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
    716   static void HandshakeCallback(PRFileDesc* socket, void* arg);
    717 
    718   // Handles an NSS error generated while handshaking or performing IO.
    719   // Returns a network error code mapped from the original NSS error.
    720   int HandleNSSError(PRErrorCode error, bool handshake_error);
    721 
    722   int DoHandshakeLoop(int last_io_result);
    723   int DoReadLoop(int result);
    724   int DoWriteLoop(int result);
    725 
    726   int DoHandshake();
    727   int DoGetDBCertComplete(int result);
    728 
    729   int DoPayloadRead();
    730   int DoPayloadWrite();
    731 
    732   bool DoTransportIO();
    733   int BufferRecv();
    734   int BufferSend();
    735 
    736   void OnRecvComplete(int result);
    737   void OnSendComplete(int result);
    738 
    739   void DoConnectCallback(int result);
    740   void DoReadCallback(int result);
    741   void DoWriteCallback(int result);
    742 
    743   // Client channel ID handler.
    744   static SECStatus ClientChannelIDHandler(
    745       void* arg,
    746       PRFileDesc* socket,
    747       SECKEYPublicKey **out_public_key,
    748       SECKEYPrivateKey **out_private_key);
    749 
    750   // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
    751   // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
    752   // and an error code otherwise.
    753   // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
    754   // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller
    755   // takes ownership of the |*cert| and |*key|.
    756   int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
    757 
    758   // Updates the NSS and platform specific certificates.
    759   void UpdateServerCert();
    760   // Updates the nss_handshake_state_ with the negotiated security parameters.
    761   void UpdateConnectionStatus();
    762   // Record histograms for channel id support during full handshakes - resumed
    763   // handshakes are ignored.
    764   void RecordChannelIDSupport();
    765   // UpdateNextProto gets any application-layer protocol that may have been
    766   // negotiated by the TLS connection.
    767   void UpdateNextProto();
    768 
    769   ////////////////////////////////////////////////////////////////////////////
    770   // Methods that are ONLY called on the network task runner:
    771   ////////////////////////////////////////////////////////////////////////////
    772   int DoBufferRecv(IOBuffer* buffer, int len);
    773   int DoBufferSend(IOBuffer* buffer, int len);
    774   int DoGetDomainBoundCert(const std::string& host);
    775 
    776   void OnGetDomainBoundCertComplete(int result);
    777   void OnHandshakeStateUpdated(const HandshakeState& state);
    778   void OnNSSBufferUpdated(int amount_in_read_buffer);
    779   void DidNSSRead(int result);
    780   void DidNSSWrite(int result);
    781   void RecordChannelIDSupportOnNetworkTaskRunner(
    782       bool negotiated_channel_id,
    783       bool channel_id_enabled,
    784       bool supports_ecc) const;
    785 
    786   ////////////////////////////////////////////////////////////////////////////
    787   // Methods that are called on both the network task runner and the NSS
    788   // task runner.
    789   ////////////////////////////////////////////////////////////////////////////
    790   void OnHandshakeIOComplete(int result);
    791   void BufferRecvComplete(IOBuffer* buffer, int result);
    792   void BufferSendComplete(int result);
    793 
    794   // PostOrRunCallback is a helper function to ensure that |callback| is
    795   // invoked on the network task runner, but only if Detach() has not yet
    796   // been called.
    797   void PostOrRunCallback(const tracked_objects::Location& location,
    798                          const base::Closure& callback);
    799 
    800   // Uses PostOrRunCallback and |weak_net_log_| to try and log a
    801   // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
    802   void AddCertProvidedEvent(int cert_count);
    803 
    804   // Sets the handshake state |channel_id_sent| flag and logs the
    805   // SSL_CHANNEL_ID_PROVIDED event.
    806   void SetChannelIDProvided();
    807 
    808   ////////////////////////////////////////////////////////////////////////////
    809   // Members that are ONLY accessed on the network task runner:
    810   ////////////////////////////////////////////////////////////////////////////
    811 
    812   // True if the owning SSLClientSocketNSS has called Detach(). No further
    813   // callbacks will be invoked nor access to members owned by the network
    814   // task runner.
    815   bool detached_;
    816 
    817   // The underlying transport to use for network IO.
    818   ClientSocketHandle* transport_;
    819   base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
    820 
    821   // The current handshake state. Mirrors |nss_handshake_state_|.
    822   HandshakeState network_handshake_state_;
    823 
    824   // The service for retrieving Channel ID keys.  May be NULL.
    825   ServerBoundCertService* server_bound_cert_service_;
    826   ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_;
    827 
    828   // The information about NSS task runner.
    829   int unhandled_buffer_size_;
    830   bool nss_waiting_read_;
    831   bool nss_waiting_write_;
    832   bool nss_is_closed_;
    833 
    834   ////////////////////////////////////////////////////////////////////////////
    835   // Members that are ONLY accessed on the NSS task runner:
    836   ////////////////////////////////////////////////////////////////////////////
    837   HostPortPair host_and_port_;
    838   SSLConfig ssl_config_;
    839 
    840   // NSS SSL socket.
    841   PRFileDesc* nss_fd_;
    842 
    843   // Buffers for the network end of the SSL state machine
    844   memio_Private* nss_bufs_;
    845 
    846   // Used by DoPayloadRead() when attempting to fill the caller's buffer with
    847   // as much data as possible, without blocking.
    848   // If DoPayloadRead() encounters an error after having read some data, stores
    849   // the results to return on the *next* call to DoPayloadRead(). A value of
    850   // kNoPendingReadResult indicates there is no pending result, otherwise 0
    851   // indicates EOF and < 0 indicates an error.
    852   int pending_read_result_;
    853   // Contains the previously observed NSS error. Only valid when
    854   // pending_read_result_ != kNoPendingReadResult.
    855   PRErrorCode pending_read_nss_error_;
    856 
    857   // The certificate chain, in DER form, that is expected to be received from
    858   // the server.
    859   std::vector<std::string> predicted_certs_;
    860 
    861   State next_handshake_state_;
    862 
    863   // True if channel ID extension was negotiated.
    864   bool channel_id_xtn_negotiated_;
    865   // True if the handshake state machine was interrupted for channel ID.
    866   bool channel_id_needed_;
    867   // True if the handshake state machine was interrupted for client auth.
    868   bool client_auth_cert_needed_;
    869   // True if NSS has called HandshakeCallback.
    870   bool handshake_callback_called_;
    871 
    872   HandshakeState nss_handshake_state_;
    873 
    874   bool transport_recv_busy_;
    875   bool transport_recv_eof_;
    876   bool transport_send_busy_;
    877 
    878   // Used by Read function.
    879   scoped_refptr<IOBuffer> user_read_buf_;
    880   int user_read_buf_len_;
    881 
    882   // Used by Write function.
    883   scoped_refptr<IOBuffer> user_write_buf_;
    884   int user_write_buf_len_;
    885 
    886   CompletionCallback user_connect_callback_;
    887   CompletionCallback user_read_callback_;
    888   CompletionCallback user_write_callback_;
    889 
    890   ////////////////////////////////////////////////////////////////////////////
    891   // Members that are accessed on both the network task runner and the NSS
    892   // task runner.
    893   ////////////////////////////////////////////////////////////////////////////
    894   scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
    895   scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
    896 
    897   // Dereferenced only on the network task runner, but bound to tasks destined
    898   // for the network task runner from the NSS task runner.
    899   base::WeakPtr<BoundNetLog> weak_net_log_;
    900 
    901   // Written on the network task runner by the |server_bound_cert_service_|,
    902   // prior to invoking OnHandshakeIOComplete.
    903   // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
    904   // on the NSS task runner.
    905   std::string domain_bound_private_key_;
    906   std::string domain_bound_cert_;
    907 
    908   DISALLOW_COPY_AND_ASSIGN(Core);
    909 };
    910 
    911 SSLClientSocketNSS::Core::Core(
    912     base::SequencedTaskRunner* network_task_runner,
    913     base::SequencedTaskRunner* nss_task_runner,
    914     ClientSocketHandle* transport,
    915     const HostPortPair& host_and_port,
    916     const SSLConfig& ssl_config,
    917     BoundNetLog* net_log,
    918     ServerBoundCertService* server_bound_cert_service)
    919     : detached_(false),
    920       transport_(transport),
    921       weak_net_log_factory_(net_log),
    922       server_bound_cert_service_(server_bound_cert_service),
    923       unhandled_buffer_size_(0),
    924       nss_waiting_read_(false),
    925       nss_waiting_write_(false),
    926       nss_is_closed_(false),
    927       host_and_port_(host_and_port),
    928       ssl_config_(ssl_config),
    929       nss_fd_(NULL),
    930       nss_bufs_(NULL),
    931       pending_read_result_(kNoPendingReadResult),
    932       pending_read_nss_error_(0),
    933       next_handshake_state_(STATE_NONE),
    934       channel_id_xtn_negotiated_(false),
    935       channel_id_needed_(false),
    936       client_auth_cert_needed_(false),
    937       handshake_callback_called_(false),
    938       transport_recv_busy_(false),
    939       transport_recv_eof_(false),
    940       transport_send_busy_(false),
    941       user_read_buf_len_(0),
    942       user_write_buf_len_(0),
    943       network_task_runner_(network_task_runner),
    944       nss_task_runner_(nss_task_runner),
    945       weak_net_log_(weak_net_log_factory_.GetWeakPtr()) {
    946 }
    947 
    948 SSLClientSocketNSS::Core::~Core() {
    949   // TODO(wtc): Send SSL close_notify alert.
    950   if (nss_fd_ != NULL) {
    951     PR_Close(nss_fd_);
    952     nss_fd_ = NULL;
    953   }
    954 }
    955 
    956 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
    957                                     memio_Private* buffers) {
    958   DCHECK(OnNetworkTaskRunner());
    959   DCHECK(!nss_fd_);
    960   DCHECK(!nss_bufs_);
    961 
    962   nss_fd_ = socket;
    963   nss_bufs_ = buffers;
    964 
    965   SECStatus rv = SECSuccess;
    966 
    967   if (!ssl_config_.next_protos.empty()) {
    968     size_t wire_length = 0;
    969     for (std::vector<std::string>::const_iterator
    970          i = ssl_config_.next_protos.begin();
    971          i != ssl_config_.next_protos.end(); ++i) {
    972       if (i->size() > 255) {
    973         LOG(WARNING) << "Ignoring overlong NPN/ALPN protocol: " << *i;
    974         continue;
    975       }
    976       wire_length += i->size();
    977       wire_length++;
    978     }
    979     scoped_ptr<uint8[]> wire_protos(new uint8[wire_length]);
    980     uint8* dst = wire_protos.get();
    981     for (std::vector<std::string>::const_iterator
    982          i = ssl_config_.next_protos.begin();
    983          i != ssl_config_.next_protos.end(); i++) {
    984       if (i->size() > 255)
    985         continue;
    986       *dst++ = i->size();
    987       memcpy(dst, i->data(), i->size());
    988       dst += i->size();
    989     }
    990     DCHECK_EQ(dst, wire_protos.get() + wire_length);
    991     rv = SSL_SetNextProtoNego(nss_fd_, wire_protos.get(), wire_length);
    992     if (rv != SECSuccess)
    993       LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoCallback", "");
    994   }
    995 
    996   rv = SSL_AuthCertificateHook(
    997       nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
    998   if (rv != SECSuccess) {
    999     LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
   1000     return false;
   1001   }
   1002 
   1003 #if defined(NSS_PLATFORM_CLIENT_AUTH)
   1004   rv = SSL_GetPlatformClientAuthDataHook(
   1005       nss_fd_, SSLClientSocketNSS::Core::PlatformClientAuthHandler,
   1006       this);
   1007 #else
   1008   rv = SSL_GetClientAuthDataHook(
   1009       nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
   1010 #endif
   1011   if (rv != SECSuccess) {
   1012     LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
   1013     return false;
   1014   }
   1015 
   1016   if (ssl_config_.channel_id_enabled) {
   1017     if (!server_bound_cert_service_) {
   1018       DVLOG(1) << "NULL server_bound_cert_service_, not enabling channel ID.";
   1019     } else if (!crypto::ECPrivateKey::IsSupported()) {
   1020       DVLOG(1) << "Elliptic Curve not supported, not enabling channel ID.";
   1021     } else if (!server_bound_cert_service_->IsSystemTimeValid()) {
   1022       DVLOG(1) << "System time is weird, not enabling channel ID.";
   1023     } else {
   1024       rv = SSL_SetClientChannelIDCallback(
   1025           nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
   1026       if (rv != SECSuccess)
   1027         LogFailedNSSFunction(*weak_net_log_, "SSL_SetClientChannelIDCallback",
   1028                              "");
   1029     }
   1030   }
   1031 
   1032   rv = SSL_HandshakeCallback(
   1033       nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
   1034   if (rv != SECSuccess) {
   1035     LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
   1036     return false;
   1037   }
   1038 
   1039   return true;
   1040 }
   1041 
   1042 void SSLClientSocketNSS::Core::SetPredictedCertificates(
   1043     const std::vector<std::string>& predicted_certs) {
   1044   if (predicted_certs.empty())
   1045     return;
   1046 
   1047   if (!OnNSSTaskRunner()) {
   1048     DCHECK(!detached_);
   1049     nss_task_runner_->PostTask(
   1050         FROM_HERE,
   1051         base::Bind(&Core::SetPredictedCertificates, this, predicted_certs));
   1052     return;
   1053   }
   1054 
   1055   DCHECK(nss_fd_);
   1056 
   1057   predicted_certs_ = predicted_certs;
   1058 
   1059   scoped_ptr<CERTCertificate*[]> certs(
   1060       new CERTCertificate*[predicted_certs.size()]);
   1061 
   1062   for (size_t i = 0; i < predicted_certs.size(); i++) {
   1063     SECItem derCert;
   1064     derCert.data = const_cast<uint8*>(reinterpret_cast<const uint8*>(
   1065         predicted_certs[i].data()));
   1066     derCert.len = predicted_certs[i].size();
   1067     certs[i] = CERT_NewTempCertificate(
   1068         CERT_GetDefaultCertDB(), &derCert, NULL /* no nickname given */,
   1069         PR_FALSE /* not permanent */, PR_TRUE /* copy DER data */);
   1070     if (!certs[i]) {
   1071       DestroyCertificates(&certs[0], i);
   1072       NOTREACHED();
   1073       return;
   1074     }
   1075   }
   1076 
   1077   SECStatus rv;
   1078 #ifdef SSL_ENABLE_CACHED_INFO
   1079   rv = SSL_SetPredictedPeerCertificates(nss_fd_, certs.get(),
   1080                                         predicted_certs.size());
   1081   DCHECK_EQ(SECSuccess, rv);
   1082 #else
   1083   rv = SECFailure;  // Not implemented.
   1084 #endif
   1085   DestroyCertificates(&certs[0], predicted_certs.size());
   1086 
   1087   if (rv != SECSuccess) {
   1088     LOG(WARNING) << "SetPredictedCertificates failed: "
   1089                  << host_and_port_.ToString();
   1090   }
   1091 }
   1092 
   1093 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
   1094   if (!OnNSSTaskRunner()) {
   1095     DCHECK(!detached_);
   1096     bool posted = nss_task_runner_->PostTask(
   1097         FROM_HERE,
   1098         base::Bind(IgnoreResult(&Core::Connect), this, callback));
   1099     return posted ? ERR_IO_PENDING : ERR_ABORTED;
   1100   }
   1101 
   1102   DCHECK(OnNSSTaskRunner());
   1103   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1104   DCHECK(user_read_callback_.is_null());
   1105   DCHECK(user_write_callback_.is_null());
   1106   DCHECK(user_connect_callback_.is_null());
   1107   DCHECK(!user_read_buf_.get());
   1108   DCHECK(!user_write_buf_.get());
   1109 
   1110   next_handshake_state_ = STATE_HANDSHAKE;
   1111   int rv = DoHandshakeLoop(OK);
   1112   if (rv == ERR_IO_PENDING) {
   1113     user_connect_callback_ = callback;
   1114   } else if (rv > OK) {
   1115     rv = OK;
   1116   }
   1117   if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
   1118     PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
   1119     return ERR_IO_PENDING;
   1120   }
   1121 
   1122   return rv;
   1123 }
   1124 
   1125 void SSLClientSocketNSS::Core::Detach() {
   1126   DCHECK(OnNetworkTaskRunner());
   1127 
   1128   detached_ = true;
   1129   transport_ = NULL;
   1130   weak_net_log_factory_.InvalidateWeakPtrs();
   1131 
   1132   network_handshake_state_.Reset();
   1133 
   1134   domain_bound_cert_request_handle_.Cancel();
   1135 }
   1136 
   1137 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
   1138                                    const CompletionCallback& callback) {
   1139   if (!OnNSSTaskRunner()) {
   1140     DCHECK(OnNetworkTaskRunner());
   1141     DCHECK(!detached_);
   1142     DCHECK(transport_);
   1143     DCHECK(!nss_waiting_read_);
   1144 
   1145     nss_waiting_read_ = true;
   1146     bool posted = nss_task_runner_->PostTask(
   1147         FROM_HERE,
   1148         base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
   1149                    buf_len, callback));
   1150     if (!posted) {
   1151       nss_is_closed_ = true;
   1152       nss_waiting_read_ = false;
   1153     }
   1154     return posted ? ERR_IO_PENDING : ERR_ABORTED;
   1155   }
   1156 
   1157   DCHECK(OnNSSTaskRunner());
   1158   DCHECK(handshake_callback_called_);
   1159   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1160   DCHECK(user_read_callback_.is_null());
   1161   DCHECK(user_connect_callback_.is_null());
   1162   DCHECK(!user_read_buf_.get());
   1163   DCHECK(nss_bufs_);
   1164 
   1165   user_read_buf_ = buf;
   1166   user_read_buf_len_ = buf_len;
   1167 
   1168   int rv = DoReadLoop(OK);
   1169   if (rv == ERR_IO_PENDING) {
   1170     if (OnNetworkTaskRunner())
   1171       nss_waiting_read_ = true;
   1172     user_read_callback_ = callback;
   1173   } else {
   1174     user_read_buf_ = NULL;
   1175     user_read_buf_len_ = 0;
   1176 
   1177     if (!OnNetworkTaskRunner()) {
   1178       PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
   1179       PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
   1180       return ERR_IO_PENDING;
   1181     } else {
   1182       DCHECK(!nss_waiting_read_);
   1183       if (rv <= 0)
   1184         nss_is_closed_ = true;
   1185     }
   1186   }
   1187 
   1188   return rv;
   1189 }
   1190 
   1191 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
   1192                                     const CompletionCallback& callback) {
   1193   if (!OnNSSTaskRunner()) {
   1194     DCHECK(OnNetworkTaskRunner());
   1195     DCHECK(!detached_);
   1196     DCHECK(transport_);
   1197     DCHECK(!nss_waiting_write_);
   1198 
   1199     nss_waiting_write_ = true;
   1200     bool posted = nss_task_runner_->PostTask(
   1201         FROM_HERE,
   1202         base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
   1203                    buf_len, callback));
   1204     if (!posted) {
   1205       nss_is_closed_ = true;
   1206       nss_waiting_write_ = false;
   1207     }
   1208     return posted ? ERR_IO_PENDING : ERR_ABORTED;
   1209   }
   1210 
   1211   DCHECK(OnNSSTaskRunner());
   1212   DCHECK(handshake_callback_called_);
   1213   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1214   DCHECK(user_write_callback_.is_null());
   1215   DCHECK(user_connect_callback_.is_null());
   1216   DCHECK(!user_write_buf_.get());
   1217   DCHECK(nss_bufs_);
   1218 
   1219   user_write_buf_ = buf;
   1220   user_write_buf_len_ = buf_len;
   1221 
   1222   int rv = DoWriteLoop(OK);
   1223   if (rv == ERR_IO_PENDING) {
   1224     if (OnNetworkTaskRunner())
   1225       nss_waiting_write_ = true;
   1226     user_write_callback_ = callback;
   1227   } else {
   1228     user_write_buf_ = NULL;
   1229     user_write_buf_len_ = 0;
   1230 
   1231     if (!OnNetworkTaskRunner()) {
   1232       PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
   1233       PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
   1234       return ERR_IO_PENDING;
   1235     } else {
   1236       DCHECK(!nss_waiting_write_);
   1237       if (rv < 0)
   1238         nss_is_closed_ = true;
   1239     }
   1240   }
   1241 
   1242   return rv;
   1243 }
   1244 
   1245 bool SSLClientSocketNSS::Core::IsConnected() {
   1246   DCHECK(OnNetworkTaskRunner());
   1247   return !nss_is_closed_;
   1248 }
   1249 
   1250 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() {
   1251   DCHECK(OnNetworkTaskRunner());
   1252   return nss_waiting_read_ || nss_waiting_write_;
   1253 }
   1254 
   1255 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() {
   1256   DCHECK(OnNetworkTaskRunner());
   1257   return unhandled_buffer_size_ != 0;
   1258 }
   1259 
   1260 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
   1261   return nss_task_runner_->RunsTasksOnCurrentThread();
   1262 }
   1263 
   1264 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
   1265   return network_task_runner_->RunsTasksOnCurrentThread();
   1266 }
   1267 
   1268 // static
   1269 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
   1270     void* arg,
   1271     PRFileDesc* socket,
   1272     PRBool checksig,
   1273     PRBool is_server) {
   1274   Core* core = reinterpret_cast<Core*>(arg);
   1275   if (!core->handshake_callback_called_) {
   1276     // Only need to turn off False Start in the initial handshake. Also, it is
   1277     // unsafe to call SSL_OptionSet in a renegotiation because the "first
   1278     // handshake" lock isn't already held, which will result in an assertion
   1279     // failure in the ssl_Get1stHandshakeLock call in SSL_OptionSet.
   1280     PRBool negotiated_extension;
   1281     SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
   1282                                                     ssl_app_layer_protocol_xtn,
   1283                                                     &negotiated_extension);
   1284     if (rv != SECSuccess || !negotiated_extension) {
   1285       rv = SSL_HandshakeNegotiatedExtension(socket,
   1286                                             ssl_next_proto_nego_xtn,
   1287                                             &negotiated_extension);
   1288     }
   1289     if (rv != SECSuccess || !negotiated_extension) {
   1290       // If the server doesn't support NPN or ALPN, then we don't do False
   1291       // Start with it.
   1292       SSL_OptionSet(socket, SSL_ENABLE_FALSE_START, PR_FALSE);
   1293     }
   1294   }
   1295 
   1296   // Tell NSS to not verify the certificate.
   1297   return SECSuccess;
   1298 }
   1299 
   1300 #if defined(NSS_PLATFORM_CLIENT_AUTH)
   1301 // static
   1302 SECStatus SSLClientSocketNSS::Core::PlatformClientAuthHandler(
   1303     void* arg,
   1304     PRFileDesc* socket,
   1305     CERTDistNames* ca_names,
   1306     CERTCertList** result_certs,
   1307     void** result_private_key,
   1308     CERTCertificate** result_nss_certificate,
   1309     SECKEYPrivateKey** result_nss_private_key) {
   1310   Core* core = reinterpret_cast<Core*>(arg);
   1311   DCHECK(core->OnNSSTaskRunner());
   1312 
   1313   core->PostOrRunCallback(
   1314       FROM_HERE,
   1315       base::Bind(&AddLogEvent, core->weak_net_log_,
   1316                  NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
   1317 
   1318   core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
   1319 #if defined(OS_WIN)
   1320   if (core->ssl_config_.send_client_cert) {
   1321     if (core->ssl_config_.client_cert) {
   1322       PCCERT_CONTEXT cert_context =
   1323           core->ssl_config_.client_cert->os_cert_handle();
   1324 
   1325       HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
   1326       DWORD key_spec = 0;
   1327       BOOL must_free = FALSE;
   1328       DWORD flags = 0;
   1329       if (base::win::GetVersion() >= base::win::VERSION_VISTA)
   1330         flags |= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
   1331 
   1332       BOOL acquired_key = CryptAcquireCertificatePrivateKey(
   1333           cert_context, flags, NULL, &crypt_prov, &key_spec, &must_free);
   1334 
   1335       if (acquired_key) {
   1336         // Should never get a cached handle back - ownership must always be
   1337         // transferred.
   1338         CHECK_EQ(must_free, TRUE);
   1339 
   1340         SECItem der_cert;
   1341         der_cert.type = siDERCertBuffer;
   1342         der_cert.data = cert_context->pbCertEncoded;
   1343         der_cert.len  = cert_context->cbCertEncoded;
   1344 
   1345         // TODO(rsleevi): Error checking for NSS allocation errors.
   1346         CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB();
   1347         CERTCertificate* user_cert = CERT_NewTempCertificate(
   1348             db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
   1349         if (!user_cert) {
   1350           // Importing the certificate can fail for reasons including a serial
   1351           // number collision. See crbug.com/97355.
   1352           core->AddCertProvidedEvent(0);
   1353           return SECFailure;
   1354         }
   1355         CERTCertList* cert_chain = CERT_NewCertList();
   1356         CERT_AddCertToListTail(cert_chain, user_cert);
   1357 
   1358         // Add the intermediates.
   1359         X509Certificate::OSCertHandles intermediates =
   1360             core->ssl_config_.client_cert->GetIntermediateCertificates();
   1361         for (X509Certificate::OSCertHandles::const_iterator it =
   1362             intermediates.begin(); it != intermediates.end(); ++it) {
   1363           der_cert.data = (*it)->pbCertEncoded;
   1364           der_cert.len = (*it)->cbCertEncoded;
   1365 
   1366           CERTCertificate* intermediate = CERT_NewTempCertificate(
   1367               db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
   1368           if (!intermediate) {
   1369             CERT_DestroyCertList(cert_chain);
   1370             core->AddCertProvidedEvent(0);
   1371             return SECFailure;
   1372           }
   1373           CERT_AddCertToListTail(cert_chain, intermediate);
   1374         }
   1375         PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>(
   1376             PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT)));
   1377         key_context->cbSize = sizeof(*key_context);
   1378         // NSS will free this context when no longer in use.
   1379         key_context->hCryptProv = crypt_prov;
   1380         key_context->dwKeySpec = key_spec;
   1381         *result_private_key = key_context;
   1382         *result_certs = cert_chain;
   1383 
   1384         int cert_count = 1 + intermediates.size();
   1385         core->AddCertProvidedEvent(cert_count);
   1386         return SECSuccess;
   1387       }
   1388       LOG(WARNING) << "Client cert found without private key";
   1389     }
   1390 
   1391     // Send no client certificate.
   1392     core->AddCertProvidedEvent(0);
   1393     return SECFailure;
   1394   }
   1395 
   1396   core->nss_handshake_state_.cert_authorities.clear();
   1397 
   1398   std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames);
   1399   for (int i = 0; i < ca_names->nnames; ++i) {
   1400     issuer_list[i].cbData = ca_names->names[i].len;
   1401     issuer_list[i].pbData = ca_names->names[i].data;
   1402     core->nss_handshake_state_.cert_authorities.push_back(std::string(
   1403         reinterpret_cast<const char*>(ca_names->names[i].data),
   1404         static_cast<size_t>(ca_names->names[i].len)));
   1405   }
   1406 
   1407   // Update the network task runner's view of the handshake state now that
   1408   // server certificate request has been recorded.
   1409   core->PostOrRunCallback(
   1410       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
   1411                             core->nss_handshake_state_));
   1412 
   1413   // Tell NSS to suspend the client authentication.  We will then abort the
   1414   // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
   1415   return SECWouldBlock;
   1416 #elif defined(OS_MACOSX)
   1417   if (core->ssl_config_.send_client_cert) {
   1418     if (core->ssl_config_.client_cert.get()) {
   1419       OSStatus os_error = noErr;
   1420       SecIdentityRef identity = NULL;
   1421       SecKeyRef private_key = NULL;
   1422       X509Certificate::OSCertHandles chain;
   1423       {
   1424         base::AutoLock lock(crypto::GetMacSecurityServicesLock());
   1425         os_error = SecIdentityCreateWithCertificate(
   1426             NULL, core->ssl_config_.client_cert->os_cert_handle(), &identity);
   1427       }
   1428       if (os_error == noErr) {
   1429         os_error = SecIdentityCopyPrivateKey(identity, &private_key);
   1430         CFRelease(identity);
   1431       }
   1432 
   1433       if (os_error == noErr) {
   1434         // TODO(rsleevi): Error checking for NSS allocation errors.
   1435         *result_certs = CERT_NewCertList();
   1436         *result_private_key = private_key;
   1437 
   1438         chain.push_back(core->ssl_config_.client_cert->os_cert_handle());
   1439         const X509Certificate::OSCertHandles& intermediates =
   1440             core->ssl_config_.client_cert->GetIntermediateCertificates();
   1441         if (!intermediates.empty())
   1442           chain.insert(chain.end(), intermediates.begin(), intermediates.end());
   1443 
   1444         for (size_t i = 0, chain_count = chain.size(); i < chain_count; ++i) {
   1445           CSSM_DATA cert_data;
   1446           SecCertificateRef cert_ref = chain[i];
   1447           os_error = SecCertificateGetData(cert_ref, &cert_data);
   1448           if (os_error != noErr)
   1449             break;
   1450 
   1451           SECItem der_cert;
   1452           der_cert.type = siDERCertBuffer;
   1453           der_cert.data = cert_data.Data;
   1454           der_cert.len = cert_data.Length;
   1455           CERTCertificate* nss_cert = CERT_NewTempCertificate(
   1456               CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE);
   1457           if (!nss_cert) {
   1458             // In the event of an NSS error, make up an OS error and reuse
   1459             // the error handling below.
   1460             os_error = errSecCreateChainFailed;
   1461             break;
   1462           }
   1463           CERT_AddCertToListTail(*result_certs, nss_cert);
   1464         }
   1465       }
   1466 
   1467       if (os_error == noErr) {
   1468         core->AddCertProvidedEvent(chain.size());
   1469         return SECSuccess;
   1470       }
   1471 
   1472       OSSTATUS_LOG(WARNING, os_error)
   1473           << "Client cert found, but could not be used";
   1474       if (*result_certs) {
   1475         CERT_DestroyCertList(*result_certs);
   1476         *result_certs = NULL;
   1477       }
   1478       if (*result_private_key)
   1479         *result_private_key = NULL;
   1480       if (private_key)
   1481         CFRelease(private_key);
   1482     }
   1483 
   1484     // Send no client certificate.
   1485     core->AddCertProvidedEvent(0);
   1486     return SECFailure;
   1487   }
   1488 
   1489   core->nss_handshake_state_.cert_authorities.clear();
   1490 
   1491   // Retrieve the cert issuers accepted by the server.
   1492   std::vector<CertPrincipal> valid_issuers;
   1493   int n = ca_names->nnames;
   1494   for (int i = 0; i < n; i++) {
   1495     core->nss_handshake_state_.cert_authorities.push_back(std::string(
   1496         reinterpret_cast<const char*>(ca_names->names[i].data),
   1497         static_cast<size_t>(ca_names->names[i].len)));
   1498   }
   1499 
   1500   // Update the network task runner's view of the handshake state now that
   1501   // server certificate request has been recorded.
   1502   core->PostOrRunCallback(
   1503       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
   1504                             core->nss_handshake_state_));
   1505 
   1506   // Tell NSS to suspend the client authentication.  We will then abort the
   1507   // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
   1508   return SECWouldBlock;
   1509 #else
   1510   return SECFailure;
   1511 #endif
   1512 }
   1513 
   1514 #elif defined(OS_IOS)
   1515 
   1516 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
   1517     void* arg,
   1518     PRFileDesc* socket,
   1519     CERTDistNames* ca_names,
   1520     CERTCertificate** result_certificate,
   1521     SECKEYPrivateKey** result_private_key) {
   1522   Core* core = reinterpret_cast<Core*>(arg);
   1523   DCHECK(core->OnNSSTaskRunner());
   1524 
   1525   core->PostOrRunCallback(
   1526       FROM_HERE,
   1527       base::Bind(&AddLogEvent, core->weak_net_log_,
   1528                  NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
   1529 
   1530   // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
   1531   LOG(WARNING) << "Client auth is not supported";
   1532 
   1533   // Never send a certificate.
   1534   core->AddCertProvidedEvent(0);
   1535   return SECFailure;
   1536 }
   1537 
   1538 #else  // NSS_PLATFORM_CLIENT_AUTH
   1539 
   1540 // static
   1541 // Based on Mozilla's NSS_GetClientAuthData.
   1542 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
   1543     void* arg,
   1544     PRFileDesc* socket,
   1545     CERTDistNames* ca_names,
   1546     CERTCertificate** result_certificate,
   1547     SECKEYPrivateKey** result_private_key) {
   1548   Core* core = reinterpret_cast<Core*>(arg);
   1549   DCHECK(core->OnNSSTaskRunner());
   1550 
   1551   core->PostOrRunCallback(
   1552       FROM_HERE,
   1553       base::Bind(&AddLogEvent, core->weak_net_log_,
   1554                  NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
   1555 
   1556   // Regular client certificate requested.
   1557   core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
   1558   void* wincx  = SSL_RevealPinArg(socket);
   1559 
   1560   if (core->ssl_config_.send_client_cert) {
   1561     // Second pass: a client certificate should have been selected.
   1562     if (core->ssl_config_.client_cert.get()) {
   1563       CERTCertificate* cert =
   1564           CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
   1565       SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
   1566       if (privkey) {
   1567         // TODO(jsorianopastor): We should wait for server certificate
   1568         // verification before sending our credentials.  See
   1569         // http://crbug.com/13934.
   1570         *result_certificate = cert;
   1571         *result_private_key = privkey;
   1572         // A cert_count of -1 means the number of certificates is unknown.
   1573         // NSS will construct the certificate chain.
   1574         core->AddCertProvidedEvent(-1);
   1575 
   1576         return SECSuccess;
   1577       }
   1578       LOG(WARNING) << "Client cert found without private key";
   1579     }
   1580     // Send no client certificate.
   1581     core->AddCertProvidedEvent(0);
   1582     return SECFailure;
   1583   }
   1584 
   1585   // First pass: client certificate is needed.
   1586   core->nss_handshake_state_.cert_authorities.clear();
   1587 
   1588   // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
   1589   // the server and save them in |cert_authorities|.
   1590   for (int i = 0; i < ca_names->nnames; i++) {
   1591     core->nss_handshake_state_.cert_authorities.push_back(std::string(
   1592         reinterpret_cast<const char*>(ca_names->names[i].data),
   1593         static_cast<size_t>(ca_names->names[i].len)));
   1594   }
   1595 
   1596   // Update the network task runner's view of the handshake state now that
   1597   // server certificate request has been recorded.
   1598   core->PostOrRunCallback(
   1599       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
   1600                             core->nss_handshake_state_));
   1601 
   1602   // Tell NSS to suspend the client authentication.  We will then abort the
   1603   // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
   1604   return SECWouldBlock;
   1605 }
   1606 #endif  // NSS_PLATFORM_CLIENT_AUTH
   1607 
   1608 // static
   1609 void SSLClientSocketNSS::Core::HandshakeCallback(
   1610     PRFileDesc* socket,
   1611     void* arg) {
   1612   Core* core = reinterpret_cast<Core*>(arg);
   1613   DCHECK(core->OnNSSTaskRunner());
   1614 
   1615   core->handshake_callback_called_ = true;
   1616 
   1617   HandshakeState* nss_state = &core->nss_handshake_state_;
   1618 
   1619   PRBool last_handshake_resumed;
   1620   SECStatus rv = SSL_HandshakeResumedSession(socket, &last_handshake_resumed);
   1621   if (rv == SECSuccess && last_handshake_resumed) {
   1622     nss_state->resumed_handshake = true;
   1623   } else {
   1624     nss_state->resumed_handshake = false;
   1625   }
   1626 
   1627   core->RecordChannelIDSupport();
   1628   core->UpdateServerCert();
   1629   core->UpdateConnectionStatus();
   1630   core->UpdateNextProto();
   1631 
   1632   // Update the network task runners view of the handshake state whenever
   1633   // a handshake has completed.
   1634   core->PostOrRunCallback(
   1635       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
   1636                             *nss_state));
   1637 }
   1638 
   1639 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error,
   1640                                              bool handshake_error) {
   1641   DCHECK(OnNSSTaskRunner());
   1642 
   1643   int net_error = handshake_error ? MapNSSClientHandshakeError(nss_error) :
   1644                                     MapNSSClientError(nss_error);
   1645 
   1646 #if defined(OS_WIN)
   1647   // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
   1648   // os_cert_handle() as an optimization. However, if the certificate
   1649   // private key is stored on a smart card, and the smart card is removed,
   1650   // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
   1651   // preventing client certificate authentication. Because the
   1652   // X509Certificate may outlive the individual SSLClientSocketNSS, due to
   1653   // caching in X509Certificate, this failure ends up preventing client
   1654   // certificate authentication with the same certificate for all future
   1655   // attempts, even after the smart card has been re-inserted. By setting
   1656   // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
   1657   // typically be freed. This allows a new HCRYPTPROV to be obtained from
   1658   // the certificate on the next attempt, which should succeed if the smart
   1659   // card has been re-inserted, or will typically prompt the user to
   1660   // re-insert the smart card if not.
   1661   if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY ||
   1662        net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) &&
   1663       ssl_config_.send_client_cert && ssl_config_.client_cert) {
   1664     CertSetCertificateContextProperty(
   1665         ssl_config_.client_cert->os_cert_handle(),
   1666         CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL);
   1667   }
   1668 #endif
   1669 
   1670   return net_error;
   1671 }
   1672 
   1673 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
   1674   DCHECK(OnNSSTaskRunner());
   1675 
   1676   int rv = last_io_result;
   1677   do {
   1678     // Default to STATE_NONE for next state.
   1679     State state = next_handshake_state_;
   1680     GotoState(STATE_NONE);
   1681 
   1682     switch (state) {
   1683       case STATE_HANDSHAKE:
   1684         rv = DoHandshake();
   1685         break;
   1686       case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
   1687         rv = DoGetDBCertComplete(rv);
   1688         break;
   1689       case STATE_NONE:
   1690       default:
   1691         rv = ERR_UNEXPECTED;
   1692         LOG(DFATAL) << "unexpected state " << state;
   1693         break;
   1694     }
   1695 
   1696     // Do the actual network I/O
   1697     bool network_moved = DoTransportIO();
   1698     if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
   1699       // In general we exit the loop if rv is ERR_IO_PENDING.  In this
   1700       // special case we keep looping even if rv is ERR_IO_PENDING because
   1701       // the transport IO may allow DoHandshake to make progress.
   1702       DCHECK(rv == OK || rv == ERR_IO_PENDING);
   1703       rv = OK;  // This causes us to stay in the loop.
   1704     }
   1705   } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
   1706   return rv;
   1707 }
   1708 
   1709 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
   1710   DCHECK(OnNSSTaskRunner());
   1711   DCHECK(handshake_callback_called_);
   1712   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1713 
   1714   if (result < 0)
   1715     return result;
   1716 
   1717   if (!nss_bufs_) {
   1718     LOG(DFATAL) << "!nss_bufs_";
   1719     int rv = ERR_UNEXPECTED;
   1720     PostOrRunCallback(
   1721         FROM_HERE,
   1722         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1723                    NetLog::TYPE_SSL_READ_ERROR,
   1724                    CreateNetLogSSLErrorCallback(rv, 0)));
   1725     return rv;
   1726   }
   1727 
   1728   bool network_moved;
   1729   int rv;
   1730   do {
   1731     rv = DoPayloadRead();
   1732     network_moved = DoTransportIO();
   1733   } while (rv == ERR_IO_PENDING && network_moved);
   1734 
   1735   return rv;
   1736 }
   1737 
   1738 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
   1739   DCHECK(OnNSSTaskRunner());
   1740   DCHECK(handshake_callback_called_);
   1741   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1742 
   1743   if (result < 0)
   1744     return result;
   1745 
   1746   if (!nss_bufs_) {
   1747     LOG(DFATAL) << "!nss_bufs_";
   1748     int rv = ERR_UNEXPECTED;
   1749     PostOrRunCallback(
   1750         FROM_HERE,
   1751         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1752                    NetLog::TYPE_SSL_READ_ERROR,
   1753                    CreateNetLogSSLErrorCallback(rv, 0)));
   1754     return rv;
   1755   }
   1756 
   1757   bool network_moved;
   1758   int rv;
   1759   do {
   1760     rv = DoPayloadWrite();
   1761     network_moved = DoTransportIO();
   1762   } while (rv == ERR_IO_PENDING && network_moved);
   1763 
   1764   LeaveFunction(rv);
   1765   return rv;
   1766 }
   1767 
   1768 int SSLClientSocketNSS::Core::DoHandshake() {
   1769   DCHECK(OnNSSTaskRunner());
   1770 
   1771   int net_error = net::OK;
   1772   SECStatus rv = SSL_ForceHandshake(nss_fd_);
   1773 
   1774   // Note: this function may be called multiple times during the handshake, so
   1775   // even though channel id and client auth are separate else cases, they can
   1776   // both be used during a single SSL handshake.
   1777   if (channel_id_needed_) {
   1778     GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
   1779     net_error = ERR_IO_PENDING;
   1780   } else if (client_auth_cert_needed_) {
   1781     net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
   1782     PostOrRunCallback(
   1783         FROM_HERE,
   1784         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1785                    NetLog::TYPE_SSL_HANDSHAKE_ERROR,
   1786                    CreateNetLogSSLErrorCallback(net_error, 0)));
   1787 
   1788     // If the handshake already succeeded (because the server requests but
   1789     // doesn't require a client cert), we need to invalidate the SSL session
   1790     // so that we won't try to resume the non-client-authenticated session in
   1791     // the next handshake.  This will cause the server to ask for a client
   1792     // cert again.
   1793     if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess)
   1794       LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError();
   1795   } else if (rv == SECSuccess) {
   1796     if (!handshake_callback_called_) {
   1797       // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=562434 -
   1798       // SSL_ForceHandshake returned SECSuccess prematurely.
   1799       rv = SECFailure;
   1800       net_error = ERR_SSL_PROTOCOL_ERROR;
   1801       PostOrRunCallback(
   1802           FROM_HERE,
   1803           base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1804                      NetLog::TYPE_SSL_HANDSHAKE_ERROR,
   1805                      CreateNetLogSSLErrorCallback(net_error, 0)));
   1806     } else {
   1807   #if defined(SSL_ENABLE_OCSP_STAPLING)
   1808       // TODO(agl): figure out how to plumb an OCSP response into the Mac
   1809       // system library and update IsOCSPStaplingSupported for Mac.
   1810       if (IsOCSPStaplingSupported()) {
   1811         const SECItemArray* ocsp_responses =
   1812             SSL_PeerStapledOCSPResponses(nss_fd_);
   1813         if (ocsp_responses->len) {
   1814   #if defined(OS_WIN)
   1815           if (nss_handshake_state_.server_cert) {
   1816             CRYPT_DATA_BLOB ocsp_response_blob;
   1817             ocsp_response_blob.cbData = ocsp_responses->items[0].len;
   1818             ocsp_response_blob.pbData = ocsp_responses->items[0].data;
   1819             BOOL ok = CertSetCertificateContextProperty(
   1820                 nss_handshake_state_.server_cert->os_cert_handle(),
   1821                 CERT_OCSP_RESPONSE_PROP_ID,
   1822                 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
   1823                 &ocsp_response_blob);
   1824             if (!ok) {
   1825               VLOG(1) << "Failed to set OCSP response property: "
   1826                       << GetLastError();
   1827             }
   1828           }
   1829   #elif defined(USE_NSS)
   1830           CacheOCSPResponseFromSideChannelFunction cache_ocsp_response =
   1831               GetCacheOCSPResponseFromSideChannelFunction();
   1832 
   1833           cache_ocsp_response(
   1834               CERT_GetDefaultCertDB(),
   1835               nss_handshake_state_.server_cert_chain[0], PR_Now(),
   1836               &ocsp_responses->items[0], NULL);
   1837   #endif
   1838         }
   1839       }
   1840   #endif
   1841     }
   1842     // Done!
   1843   } else {
   1844     PRErrorCode prerr = PR_GetError();
   1845     net_error = HandleNSSError(prerr, true);
   1846 
   1847     // Some network devices that inspect application-layer packets seem to
   1848     // inject TCP reset packets to break the connections when they see
   1849     // TLS 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
   1850     //
   1851     // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
   1852     // 1.2. We don't lose much in this fallback because the explicit IV for CBC
   1853     // mode in TLS 1.1 is approximated by record splitting in TLS 1.0. The
   1854     // fallback will be more painful for TLS 1.2 when we have GCM support.
   1855     //
   1856     // ERR_CONNECTION_RESET is a common network error, so we don't want it
   1857     // to trigger a version fallback in general, especially the TLS 1.0 ->
   1858     // SSL 3.0 fallback, which would drop TLS extensions.
   1859     if (prerr == PR_CONNECT_RESET_ERROR &&
   1860         ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1) {
   1861       net_error = ERR_SSL_PROTOCOL_ERROR;
   1862     }
   1863 
   1864     // If not done, stay in this state
   1865     if (net_error == ERR_IO_PENDING) {
   1866       GotoState(STATE_HANDSHAKE);
   1867     } else {
   1868       PostOrRunCallback(
   1869           FROM_HERE,
   1870           base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1871                      NetLog::TYPE_SSL_HANDSHAKE_ERROR,
   1872                      CreateNetLogSSLErrorCallback(net_error, prerr)));
   1873     }
   1874   }
   1875 
   1876   return net_error;
   1877 }
   1878 
   1879 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
   1880   SECStatus rv;
   1881   PostOrRunCallback(
   1882       FROM_HERE,
   1883       base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
   1884                  NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
   1885 
   1886   channel_id_needed_ = false;
   1887 
   1888   if (result != OK)
   1889     return result;
   1890 
   1891   SECKEYPublicKey* public_key;
   1892   SECKEYPrivateKey* private_key;
   1893   int error = ImportChannelIDKeys(&public_key, &private_key);
   1894   if (error != OK)
   1895     return error;
   1896 
   1897   rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
   1898   if (rv != SECSuccess)
   1899     return MapNSSError(PORT_GetError());
   1900 
   1901   SetChannelIDProvided();
   1902   GotoState(STATE_HANDSHAKE);
   1903   return OK;
   1904 }
   1905 
   1906 int SSLClientSocketNSS::Core::DoPayloadRead() {
   1907   DCHECK(OnNSSTaskRunner());
   1908   DCHECK(user_read_buf_.get());
   1909   DCHECK_GT(user_read_buf_len_, 0);
   1910 
   1911   int rv;
   1912   // If a previous greedy read resulted in an error that was not consumed (eg:
   1913   // due to the caller having read some data successfully), then return that
   1914   // pending error now.
   1915   if (pending_read_result_ != kNoPendingReadResult) {
   1916     rv = pending_read_result_;
   1917     PRErrorCode prerr = pending_read_nss_error_;
   1918     pending_read_result_ = kNoPendingReadResult;
   1919     pending_read_nss_error_ = 0;
   1920 
   1921     if (rv == 0) {
   1922       PostOrRunCallback(
   1923           FROM_HERE,
   1924           base::Bind(&LogByteTransferEvent, weak_net_log_,
   1925                      NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
   1926                      scoped_refptr<IOBuffer>(user_read_buf_)));
   1927     } else {
   1928       PostOrRunCallback(
   1929           FROM_HERE,
   1930           base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1931                      NetLog::TYPE_SSL_READ_ERROR,
   1932                      CreateNetLogSSLErrorCallback(rv, prerr)));
   1933     }
   1934     return rv;
   1935   }
   1936 
   1937   // Perform a greedy read, attempting to read as much as the caller has
   1938   // requested. In the current NSS implementation, PR_Read will return
   1939   // exactly one SSL application data record's worth of data per invocation.
   1940   // The record size is dictated by the server, and may be noticeably smaller
   1941   // than the caller's buffer. This may be as little as a single byte, if the
   1942   // server is performing 1/n-1 record splitting.
   1943   //
   1944   // However, this greedy read may result in renegotiations/re-handshakes
   1945   // happening or may lead to some data being read, followed by an EOF (such as
   1946   // a TLS close-notify). If at least some data was read, then that result
   1947   // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
   1948   // data was read, it's safe to return the error or EOF immediately.
   1949   int total_bytes_read = 0;
   1950   do {
   1951     rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
   1952                  user_read_buf_len_ - total_bytes_read);
   1953     if (rv > 0)
   1954       total_bytes_read += rv;
   1955   } while (total_bytes_read < user_read_buf_len_ && rv > 0);
   1956   int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   1957   PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
   1958                                           amount_in_read_buffer));
   1959 
   1960   if (total_bytes_read == user_read_buf_len_) {
   1961     // The caller's entire request was satisfied without error. No further
   1962     // processing needed.
   1963     rv = total_bytes_read;
   1964   } else {
   1965     // Otherwise, an error occurred (rv <= 0). The error needs to be handled
   1966     // immediately, while the NSPR/NSS errors are still available in
   1967     // thread-local storage. However, the handled/remapped error code should
   1968     // only be returned if no application data was already read; if it was, the
   1969     // error code should be deferred until the next call of DoPayloadRead.
   1970     //
   1971     // If no data was read, |*next_result| will point to the return value of
   1972     // this function. If at least some data was read, |*next_result| will point
   1973     // to |pending_read_error_|, to be returned in a future call to
   1974     // DoPayloadRead() (e.g.: after the current data is handled).
   1975     int* next_result = &rv;
   1976     if (total_bytes_read > 0) {
   1977       pending_read_result_ = rv;
   1978       rv = total_bytes_read;
   1979       next_result = &pending_read_result_;
   1980     }
   1981 
   1982     if (client_auth_cert_needed_) {
   1983       *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
   1984       pending_read_nss_error_ = 0;
   1985     } else if (*next_result < 0) {
   1986       // If *next_result == 0, then that indicates EOF, and no special error
   1987       // handling is needed.
   1988       pending_read_nss_error_ = PR_GetError();
   1989       *next_result = HandleNSSError(pending_read_nss_error_, false);
   1990       if (rv > 0 && *next_result == ERR_IO_PENDING) {
   1991         // If at least some data was read from PR_Read(), do not treat
   1992         // insufficient data as an error to return in the next call to
   1993         // DoPayloadRead() - instead, let the call fall through to check
   1994         // PR_Read() again. This is because DoTransportIO() may complete
   1995         // in between the next call to DoPayloadRead(), and thus it is
   1996         // important to check PR_Read() on subsequent invocations to see
   1997         // if a complete record may now be read.
   1998         pending_read_nss_error_ = 0;
   1999         pending_read_result_ = kNoPendingReadResult;
   2000       }
   2001     }
   2002   }
   2003 
   2004   DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
   2005 
   2006   if (rv >= 0) {
   2007     PostOrRunCallback(
   2008         FROM_HERE,
   2009         base::Bind(&LogByteTransferEvent, weak_net_log_,
   2010                    NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
   2011                    scoped_refptr<IOBuffer>(user_read_buf_)));
   2012   } else if (rv != ERR_IO_PENDING) {
   2013     PostOrRunCallback(
   2014         FROM_HERE,
   2015         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   2016                    NetLog::TYPE_SSL_READ_ERROR,
   2017                    CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
   2018     pending_read_nss_error_ = 0;
   2019   }
   2020   return rv;
   2021 }
   2022 
   2023 int SSLClientSocketNSS::Core::DoPayloadWrite() {
   2024   DCHECK(OnNSSTaskRunner());
   2025 
   2026   DCHECK(user_write_buf_.get());
   2027 
   2028   int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   2029   int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
   2030   int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   2031   // PR_Write could potentially consume the unhandled data in the memio read
   2032   // buffer if a renegotiation is in progress. If the buffer is consumed,
   2033   // notify the latest buffer size to NetworkRunner.
   2034   if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
   2035     PostOrRunCallback(
   2036         FROM_HERE,
   2037         base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
   2038   }
   2039   if (rv >= 0) {
   2040     PostOrRunCallback(
   2041         FROM_HERE,
   2042         base::Bind(&LogByteTransferEvent, weak_net_log_,
   2043                    NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
   2044                    scoped_refptr<IOBuffer>(user_write_buf_)));
   2045     return rv;
   2046   }
   2047   PRErrorCode prerr = PR_GetError();
   2048   if (prerr == PR_WOULD_BLOCK_ERROR)
   2049     return ERR_IO_PENDING;
   2050 
   2051   rv = HandleNSSError(prerr, false);
   2052   PostOrRunCallback(
   2053       FROM_HERE,
   2054       base::Bind(&AddLogEventWithCallback, weak_net_log_,
   2055                  NetLog::TYPE_SSL_WRITE_ERROR,
   2056                  CreateNetLogSSLErrorCallback(rv, prerr)));
   2057   return rv;
   2058 }
   2059 
   2060 // Do as much network I/O as possible between the buffer and the
   2061 // transport socket. Return true if some I/O performed, false
   2062 // otherwise (error or ERR_IO_PENDING).
   2063 bool SSLClientSocketNSS::Core::DoTransportIO() {
   2064   DCHECK(OnNSSTaskRunner());
   2065 
   2066   bool network_moved = false;
   2067   if (nss_bufs_ != NULL) {
   2068     int rv;
   2069     // Read and write as much data as we can. The loop is neccessary
   2070     // because Write() may return synchronously.
   2071     do {
   2072       rv = BufferSend();
   2073       if (rv != ERR_IO_PENDING && rv != 0)
   2074         network_moved = true;
   2075     } while (rv > 0);
   2076     if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
   2077       network_moved = true;
   2078   }
   2079   return network_moved;
   2080 }
   2081 
   2082 int SSLClientSocketNSS::Core::BufferRecv() {
   2083   DCHECK(OnNSSTaskRunner());
   2084 
   2085   if (transport_recv_busy_)
   2086     return ERR_IO_PENDING;
   2087 
   2088   // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
   2089   // determine how much data NSS wants to read. If NSS was not blocked,
   2090   // this will return 0.
   2091   int requested = memio_GetReadRequest(nss_bufs_);
   2092   if (requested == 0) {
   2093     // This is not a perfect match of error codes, as no operation is
   2094     // actually pending. However, returning 0 would be interpreted as a
   2095     // possible sign of EOF, which is also an inappropriate match.
   2096     return ERR_IO_PENDING;
   2097   }
   2098 
   2099   char* buf;
   2100   int nb = memio_GetReadParams(nss_bufs_, &buf);
   2101   int rv;
   2102   if (!nb) {
   2103     // buffer too full to read into, so no I/O possible at moment
   2104     rv = ERR_IO_PENDING;
   2105   } else {
   2106     scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
   2107     if (OnNetworkTaskRunner()) {
   2108       rv = DoBufferRecv(read_buffer.get(), nb);
   2109     } else {
   2110       bool posted = network_task_runner_->PostTask(
   2111           FROM_HERE,
   2112           base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
   2113                      nb));
   2114       rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
   2115     }
   2116 
   2117     if (rv == ERR_IO_PENDING) {
   2118       transport_recv_busy_ = true;
   2119     } else {
   2120       if (rv > 0) {
   2121         memcpy(buf, read_buffer->data(), rv);
   2122       } else if (rv == 0) {
   2123         transport_recv_eof_ = true;
   2124       }
   2125       memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
   2126     }
   2127   }
   2128   return rv;
   2129 }
   2130 
   2131 // Return 0 if nss_bufs_ was empty,
   2132 // > 0 for bytes transferred immediately,
   2133 // < 0 for error (or the non-error ERR_IO_PENDING).
   2134 int SSLClientSocketNSS::Core::BufferSend() {
   2135   DCHECK(OnNSSTaskRunner());
   2136 
   2137   if (transport_send_busy_)
   2138     return ERR_IO_PENDING;
   2139 
   2140   const char* buf1;
   2141   const char* buf2;
   2142   unsigned int len1, len2;
   2143   memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2);
   2144   const unsigned int len = len1 + len2;
   2145 
   2146   int rv = 0;
   2147   if (len) {
   2148     scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
   2149     memcpy(send_buffer->data(), buf1, len1);
   2150     memcpy(send_buffer->data() + len1, buf2, len2);
   2151 
   2152     if (OnNetworkTaskRunner()) {
   2153       rv = DoBufferSend(send_buffer.get(), len);
   2154     } else {
   2155       bool posted = network_task_runner_->PostTask(
   2156           FROM_HERE,
   2157           base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
   2158                      len));
   2159       rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
   2160     }
   2161 
   2162     if (rv == ERR_IO_PENDING) {
   2163       transport_send_busy_ = true;
   2164     } else {
   2165       memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
   2166     }
   2167   }
   2168 
   2169   return rv;
   2170 }
   2171 
   2172 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
   2173   DCHECK(OnNSSTaskRunner());
   2174 
   2175   if (next_handshake_state_ == STATE_HANDSHAKE) {
   2176     OnHandshakeIOComplete(result);
   2177     return;
   2178   }
   2179 
   2180   // Network layer received some data, check if client requested to read
   2181   // decrypted data.
   2182   if (!user_read_buf_.get())
   2183     return;
   2184 
   2185   int rv = DoReadLoop(result);
   2186   if (rv != ERR_IO_PENDING)
   2187     DoReadCallback(rv);
   2188 }
   2189 
   2190 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
   2191   DCHECK(OnNSSTaskRunner());
   2192 
   2193   if (next_handshake_state_ == STATE_HANDSHAKE) {
   2194     OnHandshakeIOComplete(result);
   2195     return;
   2196   }
   2197 
   2198   // OnSendComplete may need to call DoPayloadRead while the renegotiation
   2199   // handshake is in progress.
   2200   int rv_read = ERR_IO_PENDING;
   2201   int rv_write = ERR_IO_PENDING;
   2202   bool network_moved;
   2203   do {
   2204     if (user_read_buf_.get())
   2205       rv_read = DoPayloadRead();
   2206     if (user_write_buf_.get())
   2207       rv_write = DoPayloadWrite();
   2208     network_moved = DoTransportIO();
   2209   } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
   2210            (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
   2211 
   2212   // If the parent SSLClientSocketNSS is deleted during the processing of the
   2213   // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
   2214   // will be detached (and possibly deleted). Guard against deletion by taking
   2215   // an extra reference, then check if the Core was detached before invoking the
   2216   // next callback.
   2217   scoped_refptr<Core> guard(this);
   2218   if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
   2219     DoReadCallback(rv_read);
   2220 
   2221   if (OnNetworkTaskRunner() && detached_)
   2222     return;
   2223 
   2224   if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
   2225     DoWriteCallback(rv_write);
   2226 }
   2227 
   2228 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
   2229 // handshake. This requires network IO, which in turn calls
   2230 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
   2231 // winds its way through the state machine and ends up being passed to the
   2232 // callback. For Read() and Write(), that's what we want. But for Connect(),
   2233 // the caller expects OK (i.e. 0) for success.
   2234 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
   2235   DCHECK(OnNSSTaskRunner());
   2236   DCHECK_NE(rv, ERR_IO_PENDING);
   2237   DCHECK(!user_connect_callback_.is_null());
   2238 
   2239   base::Closure c = base::Bind(
   2240       base::ResetAndReturn(&user_connect_callback_),
   2241       rv > OK ? OK : rv);
   2242   PostOrRunCallback(FROM_HERE, c);
   2243 }
   2244 
   2245 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
   2246   DCHECK(OnNSSTaskRunner());
   2247   DCHECK_NE(ERR_IO_PENDING, rv);
   2248   DCHECK(!user_read_callback_.is_null());
   2249 
   2250   user_read_buf_ = NULL;
   2251   user_read_buf_len_ = 0;
   2252   int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   2253   // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
   2254   // the network task runner.
   2255   PostOrRunCallback(
   2256       FROM_HERE,
   2257       base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
   2258   PostOrRunCallback(
   2259       FROM_HERE,
   2260       base::Bind(&Core::DidNSSRead, this, rv));
   2261   PostOrRunCallback(
   2262       FROM_HERE,
   2263       base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
   2264 }
   2265 
   2266 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
   2267   DCHECK(OnNSSTaskRunner());
   2268   DCHECK_NE(ERR_IO_PENDING, rv);
   2269   DCHECK(!user_write_callback_.is_null());
   2270 
   2271   // Since Run may result in Write being called, clear |user_write_callback_|
   2272   // up front.
   2273   user_write_buf_ = NULL;
   2274   user_write_buf_len_ = 0;
   2275   // Update buffer status because DoWriteLoop called DoTransportIO which may
   2276   // perform read operations.
   2277   int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   2278   // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
   2279   // the network task runner.
   2280   PostOrRunCallback(
   2281       FROM_HERE,
   2282       base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
   2283   PostOrRunCallback(
   2284       FROM_HERE,
   2285       base::Bind(&Core::DidNSSWrite, this, rv));
   2286   PostOrRunCallback(
   2287       FROM_HERE,
   2288       base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
   2289 }
   2290 
   2291 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
   2292     void* arg,
   2293     PRFileDesc* socket,
   2294     SECKEYPublicKey **out_public_key,
   2295     SECKEYPrivateKey **out_private_key) {
   2296   Core* core = reinterpret_cast<Core*>(arg);
   2297   DCHECK(core->OnNSSTaskRunner());
   2298 
   2299   core->PostOrRunCallback(
   2300       FROM_HERE,
   2301       base::Bind(&AddLogEvent, core->weak_net_log_,
   2302                  NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
   2303 
   2304   // We have negotiated the TLS channel ID extension.
   2305   core->channel_id_xtn_negotiated_ = true;
   2306   std::string host = core->host_and_port_.host();
   2307   int error = ERR_UNEXPECTED;
   2308   if (core->OnNetworkTaskRunner()) {
   2309     error = core->DoGetDomainBoundCert(host);
   2310   } else {
   2311     bool posted = core->network_task_runner_->PostTask(
   2312         FROM_HERE,
   2313         base::Bind(
   2314             IgnoreResult(&Core::DoGetDomainBoundCert),
   2315             core, host));
   2316     error = posted ? ERR_IO_PENDING : ERR_ABORTED;
   2317   }
   2318 
   2319   if (error == ERR_IO_PENDING) {
   2320     // Asynchronous case.
   2321     core->channel_id_needed_ = true;
   2322     return SECWouldBlock;
   2323   }
   2324 
   2325   core->PostOrRunCallback(
   2326       FROM_HERE,
   2327       base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
   2328                  NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
   2329   SECStatus rv = SECSuccess;
   2330   if (error == OK) {
   2331     // Synchronous success.
   2332     int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
   2333     if (result == OK)
   2334       core->SetChannelIDProvided();
   2335     else
   2336       rv = SECFailure;
   2337   } else {
   2338     rv = SECFailure;
   2339   }
   2340 
   2341   return rv;
   2342 }
   2343 
   2344 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
   2345                                                   SECKEYPrivateKey** key) {
   2346   // Set the certificate.
   2347   SECItem cert_item;
   2348   cert_item.data = (unsigned char*) domain_bound_cert_.data();
   2349   cert_item.len = domain_bound_cert_.size();
   2350   ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
   2351                                                      &cert_item,
   2352                                                      NULL,
   2353                                                      PR_FALSE,
   2354                                                      PR_TRUE));
   2355   if (cert == NULL)
   2356     return MapNSSError(PORT_GetError());
   2357 
   2358   // Set the private key.
   2359   if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
   2360           ServerBoundCertService::kEPKIPassword,
   2361           reinterpret_cast<const unsigned char*>(
   2362               domain_bound_private_key_.data()),
   2363           domain_bound_private_key_.size(),
   2364           &cert->subjectPublicKeyInfo,
   2365           false,
   2366           false,
   2367           key,
   2368           public_key)) {
   2369     int error = MapNSSError(PORT_GetError());
   2370     return error;
   2371   }
   2372 
   2373   return OK;
   2374 }
   2375 
   2376 void SSLClientSocketNSS::Core::UpdateServerCert() {
   2377   nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
   2378   nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
   2379       nss_handshake_state_.server_cert_chain.AsStringPieceVector());
   2380   if (nss_handshake_state_.server_cert.get()) {
   2381     // Since this will be called asynchronously on another thread, it needs to
   2382     // own a reference to the certificate.
   2383     NetLog::ParametersCallback net_log_callback =
   2384         base::Bind(&NetLogX509CertificateCallback,
   2385                    nss_handshake_state_.server_cert);
   2386     PostOrRunCallback(
   2387         FROM_HERE,
   2388         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   2389                    NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
   2390                    net_log_callback));
   2391   }
   2392 }
   2393 
   2394 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
   2395   SSLChannelInfo channel_info;
   2396   SECStatus ok = SSL_GetChannelInfo(nss_fd_,
   2397                                     &channel_info, sizeof(channel_info));
   2398   if (ok == SECSuccess &&
   2399       channel_info.length == sizeof(channel_info) &&
   2400       channel_info.cipherSuite) {
   2401     nss_handshake_state_.ssl_connection_status |=
   2402         (static_cast<int>(channel_info.cipherSuite) &
   2403          SSL_CONNECTION_CIPHERSUITE_MASK) <<
   2404         SSL_CONNECTION_CIPHERSUITE_SHIFT;
   2405 
   2406     nss_handshake_state_.ssl_connection_status |=
   2407         (static_cast<int>(channel_info.compressionMethod) &
   2408          SSL_CONNECTION_COMPRESSION_MASK) <<
   2409         SSL_CONNECTION_COMPRESSION_SHIFT;
   2410 
   2411     // NSS 3.14.x doesn't have a version macro for TLS 1.2 (because NSS didn't
   2412     // support it yet), so use 0x0303 directly.
   2413     int version = SSL_CONNECTION_VERSION_UNKNOWN;
   2414     if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) {
   2415       // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
   2416       // version 2.
   2417       version = SSL_CONNECTION_VERSION_SSL2;
   2418     } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
   2419       version = SSL_CONNECTION_VERSION_SSL3;
   2420     } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_1_TLS) {
   2421       version = SSL_CONNECTION_VERSION_TLS1;
   2422     } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_1) {
   2423       version = SSL_CONNECTION_VERSION_TLS1_1;
   2424     } else if (channel_info.protocolVersion == 0x0303) {
   2425       version = SSL_CONNECTION_VERSION_TLS1_2;
   2426     }
   2427     nss_handshake_state_.ssl_connection_status |=
   2428         (version & SSL_CONNECTION_VERSION_MASK) <<
   2429         SSL_CONNECTION_VERSION_SHIFT;
   2430   }
   2431 
   2432   PRBool peer_supports_renego_ext;
   2433   ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
   2434                                         &peer_supports_renego_ext);
   2435   if (ok == SECSuccess) {
   2436     if (!peer_supports_renego_ext) {
   2437       nss_handshake_state_.ssl_connection_status |=
   2438           SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
   2439       // Log an informational message if the server does not support secure
   2440       // renegotiation (RFC 5746).
   2441       VLOG(1) << "The server " << host_and_port_.ToString()
   2442               << " does not support the TLS renegotiation_info extension.";
   2443     }
   2444     UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
   2445                               peer_supports_renego_ext, 2);
   2446 
   2447     // We would like to eliminate fallback to SSLv3 for non-buggy servers
   2448     // because of security concerns. For example, Google offers forward
   2449     // secrecy with ECDHE but that requires TLS 1.0. An attacker can block
   2450     // TLSv1 connections and force us to downgrade to SSLv3 and remove forward
   2451     // secrecy.
   2452     //
   2453     // Yngve from Opera has suggested using the renegotiation extension as an
   2454     // indicator that SSLv3 fallback was mistaken:
   2455     // tools.ietf.org/html/draft-pettersen-tls-version-rollback-removal-00 .
   2456     //
   2457     // As a first step, measure how often clients perform version fallback
   2458     // while the server advertises support secure renegotiation.
   2459     if (ssl_config_.version_fallback &&
   2460         channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
   2461       UMA_HISTOGRAM_BOOLEAN("Net.SSLv3FallbackToRenegoPatchedServer",
   2462                             peer_supports_renego_ext == PR_TRUE);
   2463     }
   2464   }
   2465 
   2466   if (ssl_config_.version_fallback) {
   2467     nss_handshake_state_.ssl_connection_status |=
   2468         SSL_CONNECTION_VERSION_FALLBACK;
   2469   }
   2470 }
   2471 
   2472 void SSLClientSocketNSS::Core::UpdateNextProto() {
   2473   uint8 buf[256];
   2474   SSLNextProtoState state;
   2475   unsigned buf_len;
   2476 
   2477   SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
   2478   if (rv != SECSuccess)
   2479     return;
   2480 
   2481   nss_handshake_state_.next_proto =
   2482       std::string(reinterpret_cast<char*>(buf), buf_len);
   2483   switch (state) {
   2484     case SSL_NEXT_PROTO_NEGOTIATED:
   2485     case SSL_NEXT_PROTO_SELECTED:
   2486       nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
   2487       break;
   2488     case SSL_NEXT_PROTO_NO_OVERLAP:
   2489       nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
   2490       break;
   2491     case SSL_NEXT_PROTO_NO_SUPPORT:
   2492       nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
   2493       break;
   2494     default:
   2495       NOTREACHED();
   2496       break;
   2497   }
   2498 }
   2499 
   2500 void SSLClientSocketNSS::Core::RecordChannelIDSupport() {
   2501   DCHECK(OnNSSTaskRunner());
   2502   if (nss_handshake_state_.resumed_handshake)
   2503     return;
   2504 
   2505   // Copy the NSS task runner-only state to the network task runner and
   2506   // log histograms from there, since the histograms also need access to the
   2507   // network task runner state.
   2508   PostOrRunCallback(
   2509       FROM_HERE,
   2510       base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner,
   2511                  this,
   2512                  channel_id_xtn_negotiated_,
   2513                  ssl_config_.channel_id_enabled,
   2514                  crypto::ECPrivateKey::IsSupported()));
   2515 }
   2516 
   2517 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
   2518     bool negotiated_channel_id,
   2519     bool channel_id_enabled,
   2520     bool supports_ecc) const {
   2521   DCHECK(OnNetworkTaskRunner());
   2522 
   2523   // Since this enum is used for a histogram, do not change or re-use values.
   2524   enum {
   2525     DISABLED = 0,
   2526     CLIENT_ONLY = 1,
   2527     CLIENT_AND_SERVER = 2,
   2528     CLIENT_NO_ECC = 3,
   2529     CLIENT_BAD_SYSTEM_TIME = 4,
   2530     CLIENT_NO_SERVER_BOUND_CERT_SERVICE = 5,
   2531     DOMAIN_BOUND_CERT_USAGE_MAX
   2532   } supported = DISABLED;
   2533   if (negotiated_channel_id) {
   2534     supported = CLIENT_AND_SERVER;
   2535   } else if (channel_id_enabled) {
   2536     if (!server_bound_cert_service_)
   2537       supported = CLIENT_NO_SERVER_BOUND_CERT_SERVICE;
   2538     else if (!supports_ecc)
   2539       supported = CLIENT_NO_ECC;
   2540     else if (!server_bound_cert_service_->IsSystemTimeValid())
   2541       supported = CLIENT_BAD_SYSTEM_TIME;
   2542     else
   2543       supported = CLIENT_ONLY;
   2544   }
   2545   UMA_HISTOGRAM_ENUMERATION("DomainBoundCerts.Support", supported,
   2546                             DOMAIN_BOUND_CERT_USAGE_MAX);
   2547 }
   2548 
   2549 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
   2550   DCHECK(OnNetworkTaskRunner());
   2551   DCHECK_GT(len, 0);
   2552 
   2553   if (detached_)
   2554     return ERR_ABORTED;
   2555 
   2556   int rv = transport_->socket()->Read(
   2557       read_buffer, len,
   2558       base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
   2559                  scoped_refptr<IOBuffer>(read_buffer)));
   2560 
   2561   if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
   2562     nss_task_runner_->PostTask(
   2563         FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
   2564                               scoped_refptr<IOBuffer>(read_buffer), rv));
   2565     return rv;
   2566   }
   2567 
   2568   return rv;
   2569 }
   2570 
   2571 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
   2572   DCHECK(OnNetworkTaskRunner());
   2573   DCHECK_GT(len, 0);
   2574 
   2575   if (detached_)
   2576     return ERR_ABORTED;
   2577 
   2578   int rv = transport_->socket()->Write(
   2579       send_buffer, len,
   2580       base::Bind(&Core::BufferSendComplete,
   2581                  base::Unretained(this)));
   2582 
   2583   if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
   2584     nss_task_runner_->PostTask(
   2585         FROM_HERE,
   2586         base::Bind(&Core::BufferSendComplete, this, rv));
   2587     return rv;
   2588   }
   2589 
   2590   return rv;
   2591 }
   2592 
   2593 int SSLClientSocketNSS::Core::DoGetDomainBoundCert(const std::string& host) {
   2594   DCHECK(OnNetworkTaskRunner());
   2595 
   2596   if (detached_)
   2597     return ERR_FAILED;
   2598 
   2599   weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
   2600 
   2601   int rv = server_bound_cert_service_->GetDomainBoundCert(
   2602       host,
   2603       &domain_bound_private_key_,
   2604       &domain_bound_cert_,
   2605       base::Bind(&Core::OnGetDomainBoundCertComplete, base::Unretained(this)),
   2606       &domain_bound_cert_request_handle_);
   2607 
   2608   if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
   2609     nss_task_runner_->PostTask(
   2610         FROM_HERE,
   2611         base::Bind(&Core::OnHandshakeIOComplete, this, rv));
   2612     return ERR_IO_PENDING;
   2613   }
   2614 
   2615   return rv;
   2616 }
   2617 
   2618 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
   2619     const HandshakeState& state) {
   2620   DCHECK(OnNetworkTaskRunner());
   2621   network_handshake_state_ = state;
   2622 }
   2623 
   2624 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
   2625   DCHECK(OnNetworkTaskRunner());
   2626   unhandled_buffer_size_ = amount_in_read_buffer;
   2627 }
   2628 
   2629 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
   2630   DCHECK(OnNetworkTaskRunner());
   2631   DCHECK(nss_waiting_read_);
   2632   nss_waiting_read_ = false;
   2633   if (result <= 0)
   2634     nss_is_closed_ = true;
   2635 }
   2636 
   2637 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
   2638   DCHECK(OnNetworkTaskRunner());
   2639   DCHECK(nss_waiting_write_);
   2640   nss_waiting_write_ = false;
   2641   if (result < 0)
   2642     nss_is_closed_ = true;
   2643 }
   2644 
   2645 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
   2646   if (!OnNSSTaskRunner()) {
   2647     if (detached_)
   2648       return;
   2649 
   2650     nss_task_runner_->PostTask(
   2651         FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
   2652     return;
   2653   }
   2654 
   2655   DCHECK(OnNSSTaskRunner());
   2656 
   2657   memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
   2658   transport_send_busy_ = false;
   2659   OnSendComplete(result);
   2660 }
   2661 
   2662 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
   2663   if (!OnNSSTaskRunner()) {
   2664     if (detached_)
   2665       return;
   2666 
   2667     nss_task_runner_->PostTask(
   2668         FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
   2669     return;
   2670   }
   2671 
   2672   DCHECK(OnNSSTaskRunner());
   2673 
   2674   int rv = DoHandshakeLoop(result);
   2675   if (rv != ERR_IO_PENDING)
   2676     DoConnectCallback(rv);
   2677 }
   2678 
   2679 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result) {
   2680   DVLOG(1) << __FUNCTION__ << " " << result;
   2681   DCHECK(OnNetworkTaskRunner());
   2682 
   2683   OnHandshakeIOComplete(result);
   2684 }
   2685 
   2686 void SSLClientSocketNSS::Core::BufferRecvComplete(
   2687     IOBuffer* read_buffer,
   2688     int result) {
   2689   DCHECK(read_buffer);
   2690 
   2691   if (!OnNSSTaskRunner()) {
   2692     if (detached_)
   2693       return;
   2694 
   2695     nss_task_runner_->PostTask(
   2696         FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
   2697                               scoped_refptr<IOBuffer>(read_buffer), result));
   2698     return;
   2699   }
   2700 
   2701   DCHECK(OnNSSTaskRunner());
   2702 
   2703   if (result > 0) {
   2704     char* buf;
   2705     int nb = memio_GetReadParams(nss_bufs_, &buf);
   2706     CHECK_GE(nb, result);
   2707     memcpy(buf, read_buffer->data(), result);
   2708   } else if (result == 0) {
   2709     transport_recv_eof_ = true;
   2710   }
   2711 
   2712   memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
   2713   transport_recv_busy_ = false;
   2714   OnRecvComplete(result);
   2715 }
   2716 
   2717 void SSLClientSocketNSS::Core::PostOrRunCallback(
   2718     const tracked_objects::Location& location,
   2719     const base::Closure& task) {
   2720   if (!OnNetworkTaskRunner()) {
   2721     network_task_runner_->PostTask(
   2722         FROM_HERE,
   2723         base::Bind(&Core::PostOrRunCallback, this, location, task));
   2724     return;
   2725   }
   2726 
   2727   if (detached_ || task.is_null())
   2728     return;
   2729   task.Run();
   2730 }
   2731 
   2732 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
   2733   PostOrRunCallback(
   2734       FROM_HERE,
   2735       base::Bind(&AddLogEventWithCallback, weak_net_log_,
   2736                  NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
   2737                  NetLog::IntegerCallback("cert_count", cert_count)));
   2738 }
   2739 
   2740 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
   2741   PostOrRunCallback(
   2742       FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
   2743                             NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
   2744   nss_handshake_state_.channel_id_sent = true;
   2745   // Update the network task runner's view of the handshake state now that
   2746   // channel id has been sent.
   2747   PostOrRunCallback(
   2748       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
   2749                             nss_handshake_state_));
   2750 }
   2751 
   2752 SSLClientSocketNSS::SSLClientSocketNSS(
   2753     base::SequencedTaskRunner* nss_task_runner,
   2754     ClientSocketHandle* transport_socket,
   2755     const HostPortPair& host_and_port,
   2756     const SSLConfig& ssl_config,
   2757     const SSLClientSocketContext& context)
   2758     : nss_task_runner_(nss_task_runner),
   2759       transport_(transport_socket),
   2760       host_and_port_(host_and_port),
   2761       ssl_config_(ssl_config),
   2762       cert_verifier_(context.cert_verifier),
   2763       server_bound_cert_service_(context.server_bound_cert_service),
   2764       ssl_session_cache_shard_(context.ssl_session_cache_shard),
   2765       completed_handshake_(false),
   2766       next_handshake_state_(STATE_NONE),
   2767       nss_fd_(NULL),
   2768       net_log_(transport_socket->socket()->NetLog()),
   2769       transport_security_state_(context.transport_security_state),
   2770       valid_thread_id_(base::kInvalidThreadId) {
   2771   EnterFunction("");
   2772   InitCore();
   2773   LeaveFunction("");
   2774 }
   2775 
   2776 SSLClientSocketNSS::~SSLClientSocketNSS() {
   2777   EnterFunction("");
   2778   Disconnect();
   2779   LeaveFunction("");
   2780 }
   2781 
   2782 // static
   2783 void SSLClientSocket::ClearSessionCache() {
   2784   // SSL_ClearSessionCache can't be called before NSS is initialized.  Don't
   2785   // bother initializing NSS just to clear an empty SSL session cache.
   2786   if (!NSS_IsInitialized())
   2787     return;
   2788 
   2789   SSL_ClearSessionCache();
   2790 }
   2791 
   2792 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
   2793   EnterFunction("");
   2794   ssl_info->Reset();
   2795   if (core_->state().server_cert_chain.empty() ||
   2796       !core_->state().server_cert_chain[0]) {
   2797     return false;
   2798   }
   2799 
   2800   ssl_info->cert_status = server_cert_verify_result_.cert_status;
   2801   ssl_info->cert = server_cert_verify_result_.verified_cert;
   2802   ssl_info->connection_status =
   2803       core_->state().ssl_connection_status;
   2804   ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
   2805   for (HashValueVector::const_iterator i = side_pinned_public_keys_.begin();
   2806        i != side_pinned_public_keys_.end(); ++i) {
   2807     ssl_info->public_key_hashes.push_back(*i);
   2808   }
   2809   ssl_info->is_issued_by_known_root =
   2810       server_cert_verify_result_.is_issued_by_known_root;
   2811   ssl_info->client_cert_sent =
   2812       ssl_config_.send_client_cert && ssl_config_.client_cert.get();
   2813   ssl_info->channel_id_sent = WasChannelIDSent();
   2814 
   2815   PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
   2816       core_->state().ssl_connection_status);
   2817   SSLCipherSuiteInfo cipher_info;
   2818   SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
   2819                                         &cipher_info, sizeof(cipher_info));
   2820   if (ok == SECSuccess) {
   2821     ssl_info->security_bits = cipher_info.effectiveKeyBits;
   2822   } else {
   2823     ssl_info->security_bits = -1;
   2824     LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
   2825                 << " for cipherSuite " << cipher_suite;
   2826   }
   2827 
   2828   ssl_info->handshake_type = core_->state().resumed_handshake ?
   2829       SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
   2830 
   2831   LeaveFunction("");
   2832   return true;
   2833 }
   2834 
   2835 void SSLClientSocketNSS::GetSSLCertRequestInfo(
   2836     SSLCertRequestInfo* cert_request_info) {
   2837   EnterFunction("");
   2838   // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair
   2839   cert_request_info->host_and_port = host_and_port_.ToString();
   2840   cert_request_info->cert_authorities = core_->state().cert_authorities;
   2841   LeaveFunction("");
   2842 }
   2843 
   2844 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
   2845                                              bool has_context,
   2846                                              const base::StringPiece& context,
   2847                                              unsigned char* out,
   2848                                              unsigned int outlen) {
   2849   if (!IsConnected())
   2850     return ERR_SOCKET_NOT_CONNECTED;
   2851 
   2852   // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
   2853   // the midst of a handshake.
   2854   SECStatus result = SSL_ExportKeyingMaterial(
   2855       nss_fd_, label.data(), label.size(), has_context,
   2856       reinterpret_cast<const unsigned char*>(context.data()),
   2857       context.length(), out, outlen);
   2858   if (result != SECSuccess) {
   2859     LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
   2860     return MapNSSError(PORT_GetError());
   2861   }
   2862   return OK;
   2863 }
   2864 
   2865 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
   2866   if (!IsConnected())
   2867     return ERR_SOCKET_NOT_CONNECTED;
   2868   unsigned char buf[64];
   2869   unsigned int len;
   2870   SECStatus result = SSL_GetChannelBinding(nss_fd_,
   2871                                            SSL_CHANNEL_BINDING_TLS_UNIQUE,
   2872                                            buf, &len, arraysize(buf));
   2873   if (result != SECSuccess) {
   2874     LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
   2875     return MapNSSError(PORT_GetError());
   2876   }
   2877   out->assign(reinterpret_cast<char*>(buf), len);
   2878   return OK;
   2879 }
   2880 
   2881 SSLClientSocket::NextProtoStatus
   2882 SSLClientSocketNSS::GetNextProto(std::string* proto,
   2883                                  std::string* server_protos) {
   2884   *proto = core_->state().next_proto;
   2885   *server_protos = core_->state().server_protos;
   2886   return core_->state().next_proto_status;
   2887 }
   2888 
   2889 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
   2890   EnterFunction("");
   2891   DCHECK(transport_.get());
   2892   // It is an error to create an SSLClientSocket whose context has no
   2893   // TransportSecurityState.
   2894   DCHECK(transport_security_state_);
   2895   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   2896   DCHECK(user_connect_callback_.is_null());
   2897   DCHECK(!callback.is_null());
   2898 
   2899   EnsureThreadIdAssigned();
   2900 
   2901   net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
   2902 
   2903   int rv = Init();
   2904   if (rv != OK) {
   2905     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   2906     return rv;
   2907   }
   2908 
   2909   rv = InitializeSSLOptions();
   2910   if (rv != OK) {
   2911     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   2912     return rv;
   2913   }
   2914 
   2915   rv = InitializeSSLPeerName();
   2916   if (rv != OK) {
   2917     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   2918     return rv;
   2919   }
   2920 
   2921   GotoState(STATE_HANDSHAKE);
   2922 
   2923   rv = DoHandshakeLoop(OK);
   2924   if (rv == ERR_IO_PENDING) {
   2925     user_connect_callback_ = callback;
   2926   } else {
   2927     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   2928   }
   2929 
   2930   LeaveFunction("");
   2931   return rv > OK ? OK : rv;
   2932 }
   2933 
   2934 void SSLClientSocketNSS::Disconnect() {
   2935   EnterFunction("");
   2936 
   2937   CHECK(CalledOnValidThread());
   2938 
   2939   // Shut down anything that may call us back.
   2940   core_->Detach();
   2941   verifier_.reset();
   2942   transport_->socket()->Disconnect();
   2943 
   2944   // Reset object state.
   2945   user_connect_callback_.Reset();
   2946   server_cert_verify_result_.Reset();
   2947   completed_handshake_   = false;
   2948   start_cert_verification_time_ = base::TimeTicks();
   2949   InitCore();
   2950 
   2951   LeaveFunction("");
   2952 }
   2953 
   2954 bool SSLClientSocketNSS::IsConnected() const {
   2955   EnterFunction("");
   2956   bool ret = completed_handshake_ &&
   2957              (core_->HasPendingAsyncOperation() ||
   2958               (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
   2959               transport_->socket()->IsConnected());
   2960   LeaveFunction("");
   2961   return ret;
   2962 }
   2963 
   2964 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
   2965   EnterFunction("");
   2966   bool ret = completed_handshake_ &&
   2967              !core_->HasPendingAsyncOperation() &&
   2968              !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
   2969              transport_->socket()->IsConnectedAndIdle();
   2970   LeaveFunction("");
   2971   return ret;
   2972 }
   2973 
   2974 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
   2975   return transport_->socket()->GetPeerAddress(address);
   2976 }
   2977 
   2978 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
   2979   return transport_->socket()->GetLocalAddress(address);
   2980 }
   2981 
   2982 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
   2983   return net_log_;
   2984 }
   2985 
   2986 void SSLClientSocketNSS::SetSubresourceSpeculation() {
   2987   if (transport_.get() && transport_->socket()) {
   2988     transport_->socket()->SetSubresourceSpeculation();
   2989   } else {
   2990     NOTREACHED();
   2991   }
   2992 }
   2993 
   2994 void SSLClientSocketNSS::SetOmniboxSpeculation() {
   2995   if (transport_.get() && transport_->socket()) {
   2996     transport_->socket()->SetOmniboxSpeculation();
   2997   } else {
   2998     NOTREACHED();
   2999   }
   3000 }
   3001 
   3002 bool SSLClientSocketNSS::WasEverUsed() const {
   3003   if (transport_.get() && transport_->socket()) {
   3004     return transport_->socket()->WasEverUsed();
   3005   }
   3006   NOTREACHED();
   3007   return false;
   3008 }
   3009 
   3010 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
   3011   if (transport_.get() && transport_->socket()) {
   3012     return transport_->socket()->UsingTCPFastOpen();
   3013   }
   3014   NOTREACHED();
   3015   return false;
   3016 }
   3017 
   3018 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
   3019                              const CompletionCallback& callback) {
   3020   DCHECK(core_.get());
   3021   DCHECK(!callback.is_null());
   3022 
   3023   EnterFunction(buf_len);
   3024   int rv = core_->Read(buf, buf_len, callback);
   3025   LeaveFunction(rv);
   3026 
   3027   return rv;
   3028 }
   3029 
   3030 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
   3031                               const CompletionCallback& callback) {
   3032   DCHECK(core_.get());
   3033   DCHECK(!callback.is_null());
   3034 
   3035   EnterFunction(buf_len);
   3036   int rv = core_->Write(buf, buf_len, callback);
   3037   LeaveFunction(rv);
   3038 
   3039   return rv;
   3040 }
   3041 
   3042 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
   3043   return transport_->socket()->SetReceiveBufferSize(size);
   3044 }
   3045 
   3046 bool SSLClientSocketNSS::SetSendBufferSize(int32 size) {
   3047   return transport_->socket()->SetSendBufferSize(size);
   3048 }
   3049 
   3050 int SSLClientSocketNSS::Init() {
   3051   EnterFunction("");
   3052   // Initialize the NSS SSL library in a threadsafe way.  This also
   3053   // initializes the NSS base library.
   3054   EnsureNSSSSLInit();
   3055   if (!NSS_IsInitialized())
   3056     return ERR_UNEXPECTED;
   3057 #if defined(USE_NSS) || defined(OS_IOS)
   3058   if (ssl_config_.cert_io_enabled) {
   3059     // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
   3060     // loop by MessageLoopForIO::current().
   3061     // X509Certificate::Verify() runs on a worker thread of CertVerifier.
   3062     EnsureNSSHttpIOInit();
   3063   }
   3064 #endif
   3065 
   3066   LeaveFunction("");
   3067   return OK;
   3068 }
   3069 
   3070 void SSLClientSocketNSS::InitCore() {
   3071   core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
   3072                    nss_task_runner_.get(),
   3073                    transport_.get(),
   3074                    host_and_port_,
   3075                    ssl_config_,
   3076                    &net_log_,
   3077                    server_bound_cert_service_);
   3078 }
   3079 
   3080 int SSLClientSocketNSS::InitializeSSLOptions() {
   3081   // Transport connected, now hook it up to nss
   3082   nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
   3083   if (nss_fd_ == NULL) {
   3084     return ERR_OUT_OF_MEMORY;  // TODO(port): map NSPR error code.
   3085   }
   3086 
   3087   // Grab pointer to buffers
   3088   memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
   3089 
   3090   /* Create SSL state machine */
   3091   /* Push SSL onto our fake I/O socket */
   3092   nss_fd_ = SSL_ImportFD(NULL, nss_fd_);
   3093   if (nss_fd_ == NULL) {
   3094     LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
   3095     return ERR_OUT_OF_MEMORY;  // TODO(port): map NSPR/NSS error code.
   3096   }
   3097   // TODO(port): set more ssl options!  Check errors!
   3098 
   3099   int rv;
   3100 
   3101   rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
   3102   if (rv != SECSuccess) {
   3103     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
   3104     return ERR_UNEXPECTED;
   3105   }
   3106 
   3107   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
   3108   if (rv != SECSuccess) {
   3109     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
   3110     return ERR_UNEXPECTED;
   3111   }
   3112 
   3113   // Don't do V2 compatible hellos because they don't support TLS extensions.
   3114   rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
   3115   if (rv != SECSuccess) {
   3116     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
   3117     return ERR_UNEXPECTED;
   3118   }
   3119 
   3120   SSLVersionRange version_range;
   3121   version_range.min = ssl_config_.version_min;
   3122   version_range.max = ssl_config_.version_max;
   3123   rv = SSL_VersionRangeSet(nss_fd_, &version_range);
   3124   if (rv != SECSuccess) {
   3125     LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
   3126     return ERR_NO_SSL_VERSIONS_ENABLED;
   3127   }
   3128 
   3129   for (std::vector<uint16>::const_iterator it =
   3130            ssl_config_.disabled_cipher_suites.begin();
   3131        it != ssl_config_.disabled_cipher_suites.end(); ++it) {
   3132     // This will fail if the specified cipher is not implemented by NSS, but
   3133     // the failure is harmless.
   3134     SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
   3135   }
   3136 
   3137   // Support RFC 5077
   3138   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
   3139   if (rv != SECSuccess) {
   3140     LogFailedNSSFunction(
   3141         net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
   3142   }
   3143 
   3144   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START, PR_FALSE);
   3145   if (rv != SECSuccess)
   3146     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
   3147 
   3148   // We allow servers to request renegotiation. Since we're a client,
   3149   // prohibiting this is rather a waste of time. Only servers are in a
   3150   // position to prevent renegotiation attacks.
   3151   // http://extendedsubset.com/?p=8
   3152 
   3153   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
   3154                      SSL_RENEGOTIATE_TRANSITIONAL);
   3155   if (rv != SECSuccess) {
   3156     LogFailedNSSFunction(
   3157         net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
   3158   }
   3159 
   3160   rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
   3161   if (rv != SECSuccess)
   3162     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
   3163 
   3164 // Added in NSS 3.15
   3165 #ifdef SSL_ENABLE_OCSP_STAPLING
   3166   if (IsOCSPStaplingSupported()) {
   3167     rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, PR_TRUE);
   3168     if (rv != SECSuccess) {
   3169       LogFailedNSSFunction(net_log_, "SSL_OptionSet",
   3170                            "SSL_ENABLE_OCSP_STAPLING");
   3171     }
   3172   }
   3173 #endif
   3174 
   3175 // Chromium patch to libssl
   3176 #ifdef SSL_ENABLE_CACHED_INFO
   3177   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_CACHED_INFO,
   3178                      ssl_config_.cached_info_enabled);
   3179   if (rv != SECSuccess)
   3180     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO");
   3181 #endif
   3182 
   3183   rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
   3184   if (rv != SECSuccess) {
   3185     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
   3186     return ERR_UNEXPECTED;
   3187   }
   3188 
   3189   if (!core_->Init(nss_fd_, nss_bufs))
   3190     return ERR_UNEXPECTED;
   3191 
   3192   // Tell SSL the hostname we're trying to connect to.
   3193   SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
   3194 
   3195   // Tell SSL we're a client; needed if not letting NSPR do socket I/O
   3196   SSL_ResetHandshake(nss_fd_, PR_FALSE);
   3197 
   3198   return OK;
   3199 }
   3200 
   3201 int SSLClientSocketNSS::InitializeSSLPeerName() {
   3202   // Tell NSS who we're connected to
   3203   IPEndPoint peer_address;
   3204   int err = transport_->socket()->GetPeerAddress(&peer_address);
   3205   if (err != OK)
   3206     return err;
   3207 
   3208   SockaddrStorage storage;
   3209   if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
   3210     return ERR_UNEXPECTED;
   3211 
   3212   PRNetAddr peername;
   3213   memset(&peername, 0, sizeof(peername));
   3214   DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
   3215   size_t len = std::min(static_cast<size_t>(storage.addr_len),
   3216                         sizeof(peername));
   3217   memcpy(&peername, storage.addr, len);
   3218 
   3219   // Adjust the address family field for BSD, whose sockaddr
   3220   // structure has a one-byte length and one-byte address family
   3221   // field at the beginning.  PRNetAddr has a two-byte address
   3222   // family field at the beginning.
   3223   peername.raw.family = storage.addr->sa_family;
   3224 
   3225   memio_SetPeerName(nss_fd_, &peername);
   3226 
   3227   // Set the peer ID for session reuse.  This is necessary when we create an
   3228   // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
   3229   // rather than the destination server's address in that case.
   3230   std::string peer_id = host_and_port_.ToString();
   3231   // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
   3232   // This will cause session cache misses between sockets with different values
   3233   // of ssl_session_cache_shard_ and this is used to partition the session cache
   3234   // for incognito mode.
   3235   if (!ssl_session_cache_shard_.empty()) {
   3236     peer_id += "/" + ssl_session_cache_shard_;
   3237   }
   3238   SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
   3239   if (rv != SECSuccess)
   3240     LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
   3241 
   3242   return OK;
   3243 }
   3244 
   3245 void SSLClientSocketNSS::DoConnectCallback(int rv) {
   3246   EnterFunction(rv);
   3247   DCHECK_NE(ERR_IO_PENDING, rv);
   3248   DCHECK(!user_connect_callback_.is_null());
   3249 
   3250   base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
   3251   LeaveFunction("");
   3252 }
   3253 
   3254 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
   3255   EnterFunction(result);
   3256   int rv = DoHandshakeLoop(result);
   3257   if (rv != ERR_IO_PENDING) {
   3258     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   3259     DoConnectCallback(rv);
   3260   }
   3261   LeaveFunction("");
   3262 }
   3263 
   3264 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
   3265   EnterFunction(last_io_result);
   3266   int rv = last_io_result;
   3267   do {
   3268     // Default to STATE_NONE for next state.
   3269     // (This is a quirk carried over from the windows
   3270     // implementation.  It makes reading the logs a bit harder.)
   3271     // State handlers can and often do call GotoState just
   3272     // to stay in the current state.
   3273     State state = next_handshake_state_;
   3274     GotoState(STATE_NONE);
   3275     switch (state) {
   3276       case STATE_HANDSHAKE:
   3277         rv = DoHandshake();
   3278         break;
   3279       case STATE_HANDSHAKE_COMPLETE:
   3280         rv = DoHandshakeComplete(rv);
   3281         break;
   3282       case STATE_VERIFY_CERT:
   3283         DCHECK(rv == OK);
   3284         rv = DoVerifyCert(rv);
   3285         break;
   3286       case STATE_VERIFY_CERT_COMPLETE:
   3287         rv = DoVerifyCertComplete(rv);
   3288         break;
   3289       case STATE_NONE:
   3290       default:
   3291         rv = ERR_UNEXPECTED;
   3292         LOG(DFATAL) << "unexpected state " << state;
   3293         break;
   3294     }
   3295   } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
   3296   LeaveFunction("");
   3297   return rv;
   3298 }
   3299 
   3300 int SSLClientSocketNSS::DoHandshake() {
   3301   EnterFunction("");
   3302   int rv = core_->Connect(
   3303       base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
   3304                  base::Unretained(this)));
   3305   GotoState(STATE_HANDSHAKE_COMPLETE);
   3306 
   3307   LeaveFunction(rv);
   3308   return rv;
   3309 }
   3310 
   3311 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
   3312   EnterFunction(result);
   3313 
   3314   if (result == OK) {
   3315     // SSL handshake is completed. Let's verify the certificate.
   3316     GotoState(STATE_VERIFY_CERT);
   3317     // Done!
   3318   }
   3319   set_channel_id_sent(core_->state().channel_id_sent);
   3320 
   3321   LeaveFunction(result);
   3322   return result;
   3323 }
   3324 
   3325 
   3326 int SSLClientSocketNSS::DoVerifyCert(int result) {
   3327   DCHECK(!core_->state().server_cert_chain.empty());
   3328   DCHECK(core_->state().server_cert_chain[0]);
   3329 
   3330   GotoState(STATE_VERIFY_CERT_COMPLETE);
   3331 
   3332   // If the certificate is expected to be bad we can use the expectation as
   3333   // the cert status.
   3334   base::StringPiece der_cert(
   3335       reinterpret_cast<char*>(
   3336           core_->state().server_cert_chain[0]->derCert.data),
   3337       core_->state().server_cert_chain[0]->derCert.len);
   3338   CertStatus cert_status;
   3339   if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
   3340     DCHECK(start_cert_verification_time_.is_null());
   3341     VLOG(1) << "Received an expected bad cert with status: " << cert_status;
   3342     server_cert_verify_result_.Reset();
   3343     server_cert_verify_result_.cert_status = cert_status;
   3344     server_cert_verify_result_.verified_cert = core_->state().server_cert;
   3345     return OK;
   3346   }
   3347 
   3348   // We may have failed to create X509Certificate object if we are
   3349   // running inside sandbox.
   3350   if (!core_->state().server_cert.get()) {
   3351     server_cert_verify_result_.Reset();
   3352     server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
   3353     return ERR_CERT_INVALID;
   3354   }
   3355 
   3356   start_cert_verification_time_ = base::TimeTicks::Now();
   3357 
   3358   int flags = 0;
   3359   if (ssl_config_.rev_checking_enabled)
   3360     flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
   3361   if (ssl_config_.verify_ev_cert)
   3362     flags |= CertVerifier::VERIFY_EV_CERT;
   3363   if (ssl_config_.cert_io_enabled)
   3364     flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
   3365   if (ssl_config_.rev_checking_required_local_anchors)
   3366     flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
   3367   verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
   3368   return verifier_->Verify(
   3369       core_->state().server_cert.get(),
   3370       host_and_port_.host(),
   3371       flags,
   3372       SSLConfigService::GetCRLSet().get(),
   3373       &server_cert_verify_result_,
   3374       base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
   3375                  base::Unretained(this)),
   3376       net_log_);
   3377 }
   3378 
   3379 // Derived from AuthCertificateCallback() in
   3380 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
   3381 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
   3382   verifier_.reset();
   3383 
   3384   if (!start_cert_verification_time_.is_null()) {
   3385     base::TimeDelta verify_time =
   3386         base::TimeTicks::Now() - start_cert_verification_time_;
   3387     if (result == OK)
   3388         UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
   3389     else
   3390         UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
   3391   }
   3392 
   3393   // We used to remember the intermediate CA certs in the NSS database
   3394   // persistently.  However, NSS opens a connection to the SQLite database
   3395   // during NSS initialization and doesn't close the connection until NSS
   3396   // shuts down.  If the file system where the database resides is gone,
   3397   // the database connection goes bad.  What's worse, the connection won't
   3398   // recover when the file system comes back.  Until this NSS or SQLite bug
   3399   // is fixed, we need to  avoid using the NSS database for non-essential
   3400   // purposes.  See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
   3401   // http://crbug.com/15630 for more info.
   3402 
   3403   // TODO(hclam): Skip logging if server cert was expected to be bad because
   3404   // |server_cert_verify_result_| doesn't contain all the information about
   3405   // the cert.
   3406   if (result == OK)
   3407     LogConnectionTypeMetrics();
   3408 
   3409   completed_handshake_ = true;
   3410 
   3411 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) && !defined(OS_IOS)
   3412   // Take care of any mandates for public key pinning.
   3413   //
   3414   // Pinning is only enabled for official builds to make sure that others don't
   3415   // end up with pins that cannot be easily updated.
   3416   //
   3417   // TODO(agl): We might have an issue here where a request for foo.example.com
   3418   // merges into a SPDY connection to www.example.com, and gets a different
   3419   // certificate.
   3420 
   3421   // Perform pin validation if, and only if, all these conditions obtain:
   3422   //
   3423   // * a TransportSecurityState object is available;
   3424   // * the server's certificate chain is valid (or suffers from only a minor
   3425   //   error);
   3426   // * the server's certificate chain chains up to a known root (i.e. not a
   3427   //   user-installed trust anchor); and
   3428   // * the build is recent (very old builds should fail open so that users
   3429   //   have some chance to recover).
   3430   //
   3431   const CertStatus cert_status = server_cert_verify_result_.cert_status;
   3432   if (transport_security_state_ &&
   3433       (result == OK ||
   3434        (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
   3435       server_cert_verify_result_.is_issued_by_known_root &&
   3436       TransportSecurityState::IsBuildTimely()) {
   3437     bool sni_available =
   3438         ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1 ||
   3439         ssl_config_.version_fallback;
   3440     const std::string& host = host_and_port_.host();
   3441 
   3442     TransportSecurityState::DomainState domain_state;
   3443     if (transport_security_state_->GetDomainState(host, sni_available,
   3444                                                   &domain_state) &&
   3445         domain_state.HasPublicKeyPins()) {
   3446       if (!domain_state.CheckPublicKeyPins(
   3447               server_cert_verify_result_.public_key_hashes)) {
   3448         result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
   3449         UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", false);
   3450         TransportSecurityState::ReportUMAOnPinFailure(host);
   3451       } else {
   3452         UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true);
   3453       }
   3454     }
   3455   }
   3456 #endif
   3457 
   3458   // Exit DoHandshakeLoop and return the result to the caller to Connect.
   3459   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   3460   return result;
   3461 }
   3462 
   3463 void SSLClientSocketNSS::LogConnectionTypeMetrics() const {
   3464   UpdateConnectionTypeHistograms(CONNECTION_SSL);
   3465   int ssl_version = SSLConnectionStatusToVersion(
   3466       core_->state().ssl_connection_status);
   3467   switch (ssl_version) {
   3468     case SSL_CONNECTION_VERSION_SSL2:
   3469       UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2);
   3470       break;
   3471     case SSL_CONNECTION_VERSION_SSL3:
   3472       UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3);
   3473       break;
   3474     case SSL_CONNECTION_VERSION_TLS1:
   3475       UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1);
   3476       break;
   3477     case SSL_CONNECTION_VERSION_TLS1_1:
   3478       UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_1);
   3479       break;
   3480     case SSL_CONNECTION_VERSION_TLS1_2:
   3481       UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_2);
   3482       break;
   3483   };
   3484 }
   3485 
   3486 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
   3487   base::AutoLock auto_lock(lock_);
   3488   if (valid_thread_id_ != base::kInvalidThreadId)
   3489     return;
   3490   valid_thread_id_ = base::PlatformThread::CurrentId();
   3491 }
   3492 
   3493 bool SSLClientSocketNSS::CalledOnValidThread() const {
   3494   EnsureThreadIdAssigned();
   3495   base::AutoLock auto_lock(lock_);
   3496   return valid_thread_id_ == base::PlatformThread::CurrentId();
   3497 }
   3498 
   3499 ServerBoundCertService* SSLClientSocketNSS::GetServerBoundCertService() const {
   3500   return server_bound_cert_service_;
   3501 }
   3502 
   3503 }  // namespace net
   3504