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