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