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 // OpenSSL binding for SSLClientSocket. The class layout and general principle
      6 // of operation is derived from SSLClientSocketNSS.
      7 
      8 #include "net/socket/ssl_client_socket_openssl.h"
      9 
     10 #include <openssl/err.h>
     11 #include <openssl/opensslv.h>
     12 #include <openssl/ssl.h>
     13 
     14 #include "base/bind.h"
     15 #include "base/callback_helpers.h"
     16 #include "base/memory/singleton.h"
     17 #include "base/metrics/histogram.h"
     18 #include "base/synchronization/lock.h"
     19 #include "crypto/openssl_util.h"
     20 #include "net/base/net_errors.h"
     21 #include "net/cert/cert_verifier.h"
     22 #include "net/cert/single_request_cert_verifier.h"
     23 #include "net/cert/x509_certificate_net_log_param.h"
     24 #include "net/socket/ssl_error_params.h"
     25 #include "net/ssl/openssl_client_key_store.h"
     26 #include "net/ssl/ssl_cert_request_info.h"
     27 #include "net/ssl/ssl_connection_status_flags.h"
     28 #include "net/ssl/ssl_info.h"
     29 
     30 namespace net {
     31 
     32 namespace {
     33 
     34 // Enable this to see logging for state machine state transitions.
     35 #if 0
     36 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
     37                            " jump to state " << s; \
     38                            next_handshake_state_ = s; } while (0)
     39 #else
     40 #define GotoState(s) next_handshake_state_ = s
     41 #endif
     42 
     43 const int kSessionCacheTimeoutSeconds = 60 * 60;
     44 const size_t kSessionCacheMaxEntires = 1024;
     45 
     46 // This constant can be any non-negative/non-zero value (eg: it does not
     47 // overlap with any value of the net::Error range, including net::OK).
     48 const int kNoPendingReadResult = 1;
     49 
     50 // If a client doesn't have a list of protocols that it supports, but
     51 // the server supports NPN, choosing "http/1.1" is the best answer.
     52 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
     53 
     54 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
     55 // This method doesn't seem to have made it into the OpenSSL headers.
     56 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
     57 #endif
     58 
     59 // Used for encoding the |connection_status| field of an SSLInfo object.
     60 int EncodeSSLConnectionStatus(int cipher_suite,
     61                               int compression,
     62                               int version) {
     63   return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
     64           SSL_CONNECTION_CIPHERSUITE_SHIFT) |
     65          ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
     66           SSL_CONNECTION_COMPRESSION_SHIFT) |
     67          ((version & SSL_CONNECTION_VERSION_MASK) <<
     68           SSL_CONNECTION_VERSION_SHIFT);
     69 }
     70 
     71 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
     72 // this SSL connection.
     73 int GetNetSSLVersion(SSL* ssl) {
     74   switch (SSL_version(ssl)) {
     75     case SSL2_VERSION:
     76       return SSL_CONNECTION_VERSION_SSL2;
     77     case SSL3_VERSION:
     78       return SSL_CONNECTION_VERSION_SSL3;
     79     case TLS1_VERSION:
     80       return SSL_CONNECTION_VERSION_TLS1;
     81     case 0x0302:
     82       return SSL_CONNECTION_VERSION_TLS1_1;
     83     case 0x0303:
     84       return SSL_CONNECTION_VERSION_TLS1_2;
     85     default:
     86       return SSL_CONNECTION_VERSION_UNKNOWN;
     87   }
     88 }
     89 
     90 int MapOpenSSLErrorSSL() {
     91   // Walk down the error stack to find the SSLerr generated reason.
     92   unsigned long error_code;
     93   do {
     94     error_code = ERR_get_error();
     95     if (error_code == 0)
     96       return ERR_SSL_PROTOCOL_ERROR;
     97   } while (ERR_GET_LIB(error_code) != ERR_LIB_SSL);
     98 
     99   DVLOG(1) << "OpenSSL SSL error, reason: " << ERR_GET_REASON(error_code)
    100            << ", name: " << ERR_error_string(error_code, NULL);
    101   switch (ERR_GET_REASON(error_code)) {
    102     case SSL_R_READ_TIMEOUT_EXPIRED:
    103       return ERR_TIMED_OUT;
    104     case SSL_R_BAD_RESPONSE_ARGUMENT:
    105       return ERR_INVALID_ARGUMENT;
    106     case SSL_R_UNKNOWN_CERTIFICATE_TYPE:
    107     case SSL_R_UNKNOWN_CIPHER_TYPE:
    108     case SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE:
    109     case SSL_R_UNKNOWN_PKEY_TYPE:
    110     case SSL_R_UNKNOWN_REMOTE_ERROR_TYPE:
    111     case SSL_R_UNKNOWN_SSL_VERSION:
    112       return ERR_NOT_IMPLEMENTED;
    113     case SSL_R_UNSUPPORTED_SSL_VERSION:
    114     case SSL_R_NO_CIPHER_MATCH:
    115     case SSL_R_NO_SHARED_CIPHER:
    116     case SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY:
    117     case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
    118     case SSL_R_UNSUPPORTED_PROTOCOL:
    119       return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
    120     case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
    121     case SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE:
    122     case SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED:
    123     case SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED:
    124     case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
    125     case SSL_R_TLSV1_ALERT_ACCESS_DENIED:
    126     case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
    127       return ERR_BAD_SSL_CLIENT_AUTH_CERT;
    128     case SSL_R_BAD_DECOMPRESSION:
    129     case SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE:
    130       return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
    131     case SSL_R_SSLV3_ALERT_BAD_RECORD_MAC:
    132       return ERR_SSL_BAD_RECORD_MAC_ALERT;
    133     case SSL_R_TLSV1_ALERT_DECRYPT_ERROR:
    134       return ERR_SSL_DECRYPT_ERROR_ALERT;
    135     case SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:
    136       return ERR_SSL_UNSAFE_NEGOTIATION;
    137     case SSL_R_WRONG_NUMBER_OF_KEY_BITS:
    138       return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
    139     // SSL_R_UNKNOWN_PROTOCOL is reported if premature application data is
    140     // received (see http://crbug.com/42538), and also if all the protocol
    141     // versions supported by the server were disabled in this socket instance.
    142     // Mapped to ERR_SSL_PROTOCOL_ERROR for compatibility with other SSL sockets
    143     // in the former scenario.
    144     case SSL_R_UNKNOWN_PROTOCOL:
    145     case SSL_R_SSL_HANDSHAKE_FAILURE:
    146     case SSL_R_DECRYPTION_FAILED:
    147     case SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC:
    148     case SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG:
    149     case SSL_R_DIGEST_CHECK_FAILED:
    150     case SSL_R_DUPLICATE_COMPRESSION_ID:
    151     case SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER:
    152     case SSL_R_ENCRYPTED_LENGTH_TOO_LONG:
    153     case SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST:
    154     case SSL_R_EXCESSIVE_MESSAGE_SIZE:
    155     case SSL_R_EXTRA_DATA_IN_MESSAGE:
    156     case SSL_R_GOT_A_FIN_BEFORE_A_CCS:
    157     case SSL_R_ILLEGAL_PADDING:
    158     case SSL_R_INVALID_CHALLENGE_LENGTH:
    159     case SSL_R_INVALID_COMMAND:
    160     case SSL_R_INVALID_PURPOSE:
    161     case SSL_R_INVALID_STATUS_RESPONSE:
    162     case SSL_R_INVALID_TICKET_KEYS_LENGTH:
    163     case SSL_R_KEY_ARG_TOO_LONG:
    164     case SSL_R_READ_WRONG_PACKET_TYPE:
    165     case SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE:
    166     // TODO(joth): SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE may be returned from the
    167     // server after receiving ClientHello if there's no common supported cipher.
    168     // Ideally we'd map that specific case to ERR_SSL_VERSION_OR_CIPHER_MISMATCH
    169     // to match the NSS implementation. See also http://goo.gl/oMtZW
    170     case SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE:
    171     case SSL_R_SSLV3_ALERT_NO_CERTIFICATE:
    172     case SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER:
    173     case SSL_R_TLSV1_ALERT_DECODE_ERROR:
    174     case SSL_R_TLSV1_ALERT_DECRYPTION_FAILED:
    175     case SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION:
    176     case SSL_R_TLSV1_ALERT_INTERNAL_ERROR:
    177     case SSL_R_TLSV1_ALERT_NO_RENEGOTIATION:
    178     case SSL_R_TLSV1_ALERT_RECORD_OVERFLOW:
    179     case SSL_R_TLSV1_ALERT_USER_CANCELLED:
    180       return ERR_SSL_PROTOCOL_ERROR;
    181     default:
    182       LOG(WARNING) << "Unmapped error reason: " << ERR_GET_REASON(error_code);
    183       return ERR_FAILED;
    184   }
    185 }
    186 
    187 // Converts an OpenSSL error code into a net error code, walking the OpenSSL
    188 // error stack if needed. Note that |tracer| is not currently used in the
    189 // implementation, but is passed in anyway as this ensures the caller will clear
    190 // any residual codes left on the error stack.
    191 int MapOpenSSLError(int err, const crypto::OpenSSLErrStackTracer& tracer) {
    192   switch (err) {
    193     case SSL_ERROR_WANT_READ:
    194     case SSL_ERROR_WANT_WRITE:
    195       return ERR_IO_PENDING;
    196     case SSL_ERROR_SYSCALL:
    197       LOG(ERROR) << "OpenSSL SYSCALL error, earliest error code in "
    198                     "error queue: " << ERR_peek_error() << ", errno: "
    199                  << errno;
    200       return ERR_SSL_PROTOCOL_ERROR;
    201     case SSL_ERROR_SSL:
    202       return MapOpenSSLErrorSSL();
    203     default:
    204       // TODO(joth): Implement full mapping.
    205       LOG(WARNING) << "Unknown OpenSSL error " << err;
    206       return ERR_SSL_PROTOCOL_ERROR;
    207   }
    208 }
    209 
    210 // We do certificate verification after handshake, so we disable the default
    211 // by registering a no-op verify function.
    212 int NoOpVerifyCallback(X509_STORE_CTX*, void *) {
    213   DVLOG(3) << "skipping cert verify";
    214   return 1;
    215 }
    216 
    217 // OpenSSL manages a cache of SSL_SESSION, this class provides the application
    218 // side policy for that cache about session re-use: we retain one session per
    219 // unique HostPortPair, per shard.
    220 class SSLSessionCache {
    221  public:
    222   SSLSessionCache() {}
    223 
    224   void OnSessionAdded(const HostPortPair& host_and_port,
    225                       const std::string& shard,
    226                       SSL_SESSION* session) {
    227     // Declare the session cleaner-upper before the lock, so any call into
    228     // OpenSSL to free the session will happen after the lock is released.
    229     crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
    230     base::AutoLock lock(lock_);
    231 
    232     DCHECK_EQ(0U, session_map_.count(session));
    233     const std::string cache_key = GetCacheKey(host_and_port, shard);
    234 
    235     std::pair<HostPortMap::iterator, bool> res =
    236         host_port_map_.insert(std::make_pair(cache_key, session));
    237     if (!res.second) {  // Already exists: replace old entry.
    238       session_to_free.reset(res.first->second);
    239       session_map_.erase(session_to_free.get());
    240       res.first->second = session;
    241     }
    242     DVLOG(2) << "Adding session " << session << " => "
    243              << cache_key << ", new entry = " << res.second;
    244     DCHECK(host_port_map_[cache_key] == session);
    245     session_map_[session] = res.first;
    246     DCHECK_EQ(host_port_map_.size(), session_map_.size());
    247     DCHECK_LE(host_port_map_.size(), kSessionCacheMaxEntires);
    248   }
    249 
    250   void OnSessionRemoved(SSL_SESSION* session) {
    251     // Declare the session cleaner-upper before the lock, so any call into
    252     // OpenSSL to free the session will happen after the lock is released.
    253     crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
    254     base::AutoLock lock(lock_);
    255 
    256     SessionMap::iterator it = session_map_.find(session);
    257     if (it == session_map_.end())
    258       return;
    259     DVLOG(2) << "Remove session " << session << " => " << it->second->first;
    260     DCHECK(it->second->second == session);
    261     host_port_map_.erase(it->second);
    262     session_map_.erase(it);
    263     session_to_free.reset(session);
    264     DCHECK_EQ(host_port_map_.size(), session_map_.size());
    265   }
    266 
    267   // Looks up the host:port in the cache, and if a session is found it is added
    268   // to |ssl|, returning true on success.
    269   bool SetSSLSession(SSL* ssl, const HostPortPair& host_and_port,
    270                      const std::string& shard) {
    271     base::AutoLock lock(lock_);
    272     const std::string cache_key = GetCacheKey(host_and_port, shard);
    273     HostPortMap::iterator it = host_port_map_.find(cache_key);
    274     if (it == host_port_map_.end())
    275       return false;
    276     DVLOG(2) << "Lookup session: " << it->second << " => " << cache_key;
    277     SSL_SESSION* session = it->second;
    278     DCHECK(session);
    279     DCHECK(session_map_[session] == it);
    280     // Ideally we'd release |lock_| before calling into OpenSSL here, however
    281     // that opens a small risk |session| will go out of scope before it is used.
    282     // Alternatively we would take a temporary local refcount on |session|,
    283     // except OpenSSL does not provide a public API for adding a ref (c.f.
    284     // SSL_SESSION_free which decrements the ref).
    285     return SSL_set_session(ssl, session) == 1;
    286   }
    287 
    288   // Flush removes all entries from the cache. This is called when a client
    289   // certificate is added.
    290   void Flush() {
    291     for (HostPortMap::iterator i = host_port_map_.begin();
    292          i != host_port_map_.end(); i++) {
    293       SSL_SESSION_free(i->second);
    294     }
    295     host_port_map_.clear();
    296     session_map_.clear();
    297   }
    298 
    299  private:
    300   static std::string GetCacheKey(const HostPortPair& host_and_port,
    301                                  const std::string& shard) {
    302     return host_and_port.ToString() + "/" + shard;
    303   }
    304 
    305   // A pair of maps to allow bi-directional lookups between host:port and an
    306   // associated session.
    307   typedef std::map<std::string, SSL_SESSION*> HostPortMap;
    308   typedef std::map<SSL_SESSION*, HostPortMap::iterator> SessionMap;
    309   HostPortMap host_port_map_;
    310   SessionMap session_map_;
    311 
    312   // Protects access to both the above maps.
    313   base::Lock lock_;
    314 
    315   DISALLOW_COPY_AND_ASSIGN(SSLSessionCache);
    316 };
    317 
    318 class SSLContext {
    319  public:
    320   static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
    321   SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
    322   SSLSessionCache* session_cache() { return &session_cache_; }
    323 
    324   SSLClientSocketOpenSSL* GetClientSocketFromSSL(SSL* ssl) {
    325     DCHECK(ssl);
    326     SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
    327         SSL_get_ex_data(ssl, ssl_socket_data_index_));
    328     DCHECK(socket);
    329     return socket;
    330   }
    331 
    332   bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
    333     return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
    334   }
    335 
    336  private:
    337   friend struct DefaultSingletonTraits<SSLContext>;
    338 
    339   SSLContext() {
    340     crypto::EnsureOpenSSLInit();
    341     ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
    342     DCHECK_NE(ssl_socket_data_index_, -1);
    343     ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
    344     SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), NoOpVerifyCallback, NULL);
    345     SSL_CTX_set_session_cache_mode(ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT);
    346     SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallbackStatic);
    347     SSL_CTX_sess_set_remove_cb(ssl_ctx_.get(), RemoveSessionCallbackStatic);
    348     SSL_CTX_set_timeout(ssl_ctx_.get(), kSessionCacheTimeoutSeconds);
    349     SSL_CTX_sess_set_cache_size(ssl_ctx_.get(), kSessionCacheMaxEntires);
    350     SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
    351 #if defined(OPENSSL_NPN_NEGOTIATED)
    352     // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
    353     // It would be better if the callback were not a global setting,
    354     // but that is an OpenSSL issue.
    355     SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
    356                                      NULL);
    357 #endif
    358   }
    359 
    360   static int NewSessionCallbackStatic(SSL* ssl, SSL_SESSION* session) {
    361     return GetInstance()->NewSessionCallback(ssl, session);
    362   }
    363 
    364   int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
    365     SSLClientSocketOpenSSL* socket = GetClientSocketFromSSL(ssl);
    366     session_cache_.OnSessionAdded(socket->host_and_port(),
    367                                   socket->ssl_session_cache_shard(),
    368                                   session);
    369     return 1;  // 1 => We took ownership of |session|.
    370   }
    371 
    372   static void RemoveSessionCallbackStatic(SSL_CTX* ctx, SSL_SESSION* session) {
    373     return GetInstance()->RemoveSessionCallback(ctx, session);
    374   }
    375 
    376   void RemoveSessionCallback(SSL_CTX* ctx, SSL_SESSION* session) {
    377     DCHECK(ctx == ssl_ctx());
    378     session_cache_.OnSessionRemoved(session);
    379   }
    380 
    381   static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
    382     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
    383     CHECK(socket);
    384     return socket->ClientCertRequestCallback(ssl, x509, pkey);
    385   }
    386 
    387   static int SelectNextProtoCallback(SSL* ssl,
    388                                      unsigned char** out, unsigned char* outlen,
    389                                      const unsigned char* in,
    390                                      unsigned int inlen, void* arg) {
    391     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
    392     return socket->SelectNextProtoCallback(out, outlen, in, inlen);
    393   }
    394 
    395   // This is the index used with SSL_get_ex_data to retrieve the owner
    396   // SSLClientSocketOpenSSL object from an SSL instance.
    397   int ssl_socket_data_index_;
    398 
    399   // session_cache_ must appear before |ssl_ctx_| because the destruction of
    400   // |ssl_ctx_| may trigger callbacks into |session_cache_|. Therefore,
    401   // |session_cache_| must be destructed after |ssl_ctx_|.
    402   SSLSessionCache session_cache_;
    403   crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free> ssl_ctx_;
    404 };
    405 
    406 // Utility to construct the appropriate set & clear masks for use the OpenSSL
    407 // options and mode configuration functions. (SSL_set_options etc)
    408 struct SslSetClearMask {
    409   SslSetClearMask() : set_mask(0), clear_mask(0) {}
    410   void ConfigureFlag(long flag, bool state) {
    411     (state ? set_mask : clear_mask) |= flag;
    412     // Make sure we haven't got any intersection in the set & clear options.
    413     DCHECK_EQ(0, set_mask & clear_mask) << flag << ":" << state;
    414   }
    415   long set_mask;
    416   long clear_mask;
    417 };
    418 
    419 }  // namespace
    420 
    421 // static
    422 void SSLClientSocket::ClearSessionCache() {
    423   SSLContext* context = SSLContext::GetInstance();
    424   context->session_cache()->Flush();
    425 }
    426 
    427 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
    428     ClientSocketHandle* transport_socket,
    429     const HostPortPair& host_and_port,
    430     const SSLConfig& ssl_config,
    431     const SSLClientSocketContext& context)
    432     : transport_send_busy_(false),
    433       transport_recv_busy_(false),
    434       transport_recv_eof_(false),
    435       weak_factory_(this),
    436       pending_read_error_(kNoPendingReadResult),
    437       completed_handshake_(false),
    438       client_auth_cert_needed_(false),
    439       cert_verifier_(context.cert_verifier),
    440       ssl_(NULL),
    441       transport_bio_(NULL),
    442       transport_(transport_socket),
    443       host_and_port_(host_and_port),
    444       ssl_config_(ssl_config),
    445       ssl_session_cache_shard_(context.ssl_session_cache_shard),
    446       trying_cached_session_(false),
    447       next_handshake_state_(STATE_NONE),
    448       npn_status_(kNextProtoUnsupported),
    449       net_log_(transport_socket->socket()->NetLog()) {
    450 }
    451 
    452 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
    453   Disconnect();
    454 }
    455 
    456 bool SSLClientSocketOpenSSL::Init() {
    457   DCHECK(!ssl_);
    458   DCHECK(!transport_bio_);
    459 
    460   SSLContext* context = SSLContext::GetInstance();
    461   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
    462 
    463   ssl_ = SSL_new(context->ssl_ctx());
    464   if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
    465     return false;
    466 
    467   if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
    468     return false;
    469 
    470   trying_cached_session_ =
    471       context->session_cache()->SetSSLSession(ssl_, host_and_port_,
    472                                               ssl_session_cache_shard_);
    473 
    474   BIO* ssl_bio = NULL;
    475   // 0 => use default buffer sizes.
    476   if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
    477     return false;
    478   DCHECK(ssl_bio);
    479   DCHECK(transport_bio_);
    480 
    481   SSL_set_bio(ssl_, ssl_bio, ssl_bio);
    482 
    483   // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
    484   // set everything we care about to an absolute value.
    485   SslSetClearMask options;
    486   options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
    487   bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
    488   options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
    489   bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
    490                        ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
    491   options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
    492 #if defined(SSL_OP_NO_TLSv1_1)
    493   bool tls1_1_enabled =
    494       (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
    495        ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
    496   options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
    497 #endif
    498 #if defined(SSL_OP_NO_TLSv1_2)
    499   bool tls1_2_enabled =
    500       (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
    501        ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
    502   options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
    503 #endif
    504 
    505 #if defined(SSL_OP_NO_COMPRESSION)
    506   options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
    507 #endif
    508 
    509   // TODO(joth): Set this conditionally, see http://crbug.com/55410
    510   options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
    511 
    512   SSL_set_options(ssl_, options.set_mask);
    513   SSL_clear_options(ssl_, options.clear_mask);
    514 
    515   // Same as above, this time for the SSL mode.
    516   SslSetClearMask mode;
    517 
    518 #if defined(SSL_MODE_RELEASE_BUFFERS)
    519   mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
    520 #endif
    521 
    522 #if defined(SSL_MODE_SMALL_BUFFERS)
    523   mode.ConfigureFlag(SSL_MODE_SMALL_BUFFERS, true);
    524 #endif
    525 
    526   SSL_set_mode(ssl_, mode.set_mask);
    527   SSL_clear_mode(ssl_, mode.clear_mask);
    528 
    529   // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
    530   // textual name with SSL_set_cipher_list because there is no public API to
    531   // directly remove a cipher by ID.
    532   STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
    533   DCHECK(ciphers);
    534   // See SSLConfig::disabled_cipher_suites for description of the suites
    535   // disabled by default. Note that !SHA384 only removes HMAC-SHA384 cipher
    536   // suites, not GCM cipher suites with SHA384 as the handshake hash.
    537   std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA384:!aECDH");
    538   // Walk through all the installed ciphers, seeing if any need to be
    539   // appended to the cipher removal |command|.
    540   for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
    541     const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
    542     const uint16 id = SSL_CIPHER_get_id(cipher);
    543     // Remove any ciphers with a strength of less than 80 bits. Note the NSS
    544     // implementation uses "effective" bits here but OpenSSL does not provide
    545     // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
    546     // both of which are greater than 80 anyway.
    547     bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
    548     if (!disable) {
    549       disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
    550                           ssl_config_.disabled_cipher_suites.end(), id) !=
    551                     ssl_config_.disabled_cipher_suites.end();
    552     }
    553     if (disable) {
    554        const char* name = SSL_CIPHER_get_name(cipher);
    555        DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
    556                 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
    557        command.append(":!");
    558        command.append(name);
    559      }
    560   }
    561   int rv = SSL_set_cipher_list(ssl_, command.c_str());
    562   // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
    563   // This will almost certainly result in the socket failing to complete the
    564   // handshake at which point the appropriate error is bubbled up to the client.
    565   LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
    566                               "returned " << rv;
    567   return true;
    568 }
    569 
    570 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
    571                                                       X509** x509,
    572                                                       EVP_PKEY** pkey) {
    573   DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
    574   DCHECK(ssl == ssl_);
    575   DCHECK(*x509 == NULL);
    576   DCHECK(*pkey == NULL);
    577 
    578   if (!ssl_config_.send_client_cert) {
    579     // First pass: we know that a client certificate is needed, but we do not
    580     // have one at hand.
    581     client_auth_cert_needed_ = true;
    582     STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
    583     for (int i = 0; i < sk_X509_NAME_num(authorities); i++) {
    584       X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
    585       unsigned char* str = NULL;
    586       int length = i2d_X509_NAME(ca_name, &str);
    587       cert_authorities_.push_back(std::string(
    588           reinterpret_cast<const char*>(str),
    589           static_cast<size_t>(length)));
    590       OPENSSL_free(str);
    591     }
    592 
    593     return -1;  // Suspends handshake.
    594   }
    595 
    596   // Second pass: a client certificate should have been selected.
    597   if (ssl_config_.client_cert.get()) {
    598     // A note about ownership: FetchClientCertPrivateKey() increments
    599     // the reference count of the EVP_PKEY. Ownership of this reference
    600     // is passed directly to OpenSSL, which will release the reference
    601     // using EVP_PKEY_free() when the SSL object is destroyed.
    602     OpenSSLClientKeyStore::ScopedEVP_PKEY privkey;
    603     if (OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
    604             ssl_config_.client_cert.get(), &privkey)) {
    605       // TODO(joth): (copied from NSS) We should wait for server certificate
    606       // verification before sending our credentials. See http://crbug.com/13934
    607       *x509 = X509Certificate::DupOSCertHandle(
    608           ssl_config_.client_cert->os_cert_handle());
    609       *pkey = privkey.release();
    610       return 1;
    611     }
    612     LOG(WARNING) << "Client cert found without private key";
    613   }
    614 
    615   // Send no client certificate.
    616   return 0;
    617 }
    618 
    619 // SSLClientSocket methods
    620 
    621 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
    622   ssl_info->Reset();
    623   if (!server_cert_.get())
    624     return false;
    625 
    626   ssl_info->cert = server_cert_verify_result_.verified_cert;
    627   ssl_info->cert_status = server_cert_verify_result_.cert_status;
    628   ssl_info->is_issued_by_known_root =
    629       server_cert_verify_result_.is_issued_by_known_root;
    630   ssl_info->public_key_hashes =
    631     server_cert_verify_result_.public_key_hashes;
    632   ssl_info->client_cert_sent =
    633       ssl_config_.send_client_cert && ssl_config_.client_cert.get();
    634   ssl_info->channel_id_sent = WasChannelIDSent();
    635 
    636   const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
    637   CHECK(cipher);
    638   ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
    639   const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
    640 
    641   ssl_info->connection_status = EncodeSSLConnectionStatus(
    642       SSL_CIPHER_get_id(cipher),
    643       compression ? compression->type : 0,
    644       GetNetSSLVersion(ssl_));
    645 
    646   bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
    647   if (!peer_supports_renego_ext)
    648     ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
    649   UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
    650                             implicit_cast<int>(peer_supports_renego_ext), 2);
    651 
    652   if (ssl_config_.version_fallback)
    653     ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
    654 
    655   ssl_info->handshake_type = SSL_session_reused(ssl_) ?
    656       SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
    657 
    658   DVLOG(3) << "Encoded connection status: cipher suite = "
    659       << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
    660       << " version = "
    661       << SSLConnectionStatusToVersion(ssl_info->connection_status);
    662   return true;
    663 }
    664 
    665 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
    666     SSLCertRequestInfo* cert_request_info) {
    667   cert_request_info->host_and_port = host_and_port_.ToString();
    668   cert_request_info->cert_authorities = cert_authorities_;
    669 }
    670 
    671 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
    672     const base::StringPiece& label,
    673     bool has_context, const base::StringPiece& context,
    674     unsigned char* out, unsigned int outlen) {
    675   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
    676 
    677   int rv = SSL_export_keying_material(
    678       ssl_, out, outlen, const_cast<char*>(label.data()),
    679       label.size(),
    680       reinterpret_cast<unsigned char*>(const_cast<char*>(context.data())),
    681       context.length(),
    682       context.length() > 0);
    683 
    684   if (rv != 1) {
    685     int ssl_error = SSL_get_error(ssl_, rv);
    686     LOG(ERROR) << "Failed to export keying material;"
    687                << " returned " << rv
    688                << ", SSL error code " << ssl_error;
    689     return MapOpenSSLError(ssl_error, err_tracer);
    690   }
    691   return OK;
    692 }
    693 
    694 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
    695   return ERR_NOT_IMPLEMENTED;
    696 }
    697 
    698 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
    699     std::string* proto, std::string* server_protos) {
    700   *proto = npn_proto_;
    701   *server_protos = server_protos_;
    702   return npn_status_;
    703 }
    704 
    705 ServerBoundCertService*
    706 SSLClientSocketOpenSSL::GetServerBoundCertService() const {
    707   return NULL;
    708 }
    709 
    710 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
    711   // Since Run may result in Read being called, clear |user_read_callback_|
    712   // up front.
    713   user_read_buf_ = NULL;
    714   user_read_buf_len_ = 0;
    715   base::ResetAndReturn(&user_read_callback_).Run(rv);
    716 }
    717 
    718 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
    719   // Since Run may result in Write being called, clear |user_write_callback_|
    720   // up front.
    721   user_write_buf_ = NULL;
    722   user_write_buf_len_ = 0;
    723   base::ResetAndReturn(&user_write_callback_).Run(rv);
    724 }
    725 
    726 // StreamSocket implementation.
    727 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
    728   net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
    729 
    730   // Set up new ssl object.
    731   if (!Init()) {
    732     int result = ERR_UNEXPECTED;
    733     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, result);
    734     return result;
    735   }
    736 
    737   // Set SSL to client mode. Handshake happens in the loop below.
    738   SSL_set_connect_state(ssl_);
    739 
    740   GotoState(STATE_HANDSHAKE);
    741   int rv = DoHandshakeLoop(net::OK);
    742   if (rv == ERR_IO_PENDING) {
    743     user_connect_callback_ = callback;
    744   } else {
    745     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
    746   }
    747 
    748   return rv > OK ? OK : rv;
    749 }
    750 
    751 void SSLClientSocketOpenSSL::Disconnect() {
    752   if (ssl_) {
    753     // Calling SSL_shutdown prevents the session from being marked as
    754     // unresumable.
    755     SSL_shutdown(ssl_);
    756     SSL_free(ssl_);
    757     ssl_ = NULL;
    758   }
    759   if (transport_bio_) {
    760     BIO_free_all(transport_bio_);
    761     transport_bio_ = NULL;
    762   }
    763 
    764   // Shut down anything that may call us back.
    765   verifier_.reset();
    766   transport_->socket()->Disconnect();
    767 
    768   // Null all callbacks, delete all buffers.
    769   transport_send_busy_ = false;
    770   send_buffer_ = NULL;
    771   transport_recv_busy_ = false;
    772   transport_recv_eof_ = false;
    773   recv_buffer_ = NULL;
    774 
    775   user_connect_callback_.Reset();
    776   user_read_callback_.Reset();
    777   user_write_callback_.Reset();
    778   user_read_buf_         = NULL;
    779   user_read_buf_len_     = 0;
    780   user_write_buf_        = NULL;
    781   user_write_buf_len_    = 0;
    782 
    783   server_cert_verify_result_.Reset();
    784   completed_handshake_ = false;
    785 
    786   cert_authorities_.clear();
    787   client_auth_cert_needed_ = false;
    788 }
    789 
    790 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
    791   int rv = last_io_result;
    792   do {
    793     // Default to STATE_NONE for next state.
    794     // (This is a quirk carried over from the windows
    795     // implementation.  It makes reading the logs a bit harder.)
    796     // State handlers can and often do call GotoState just
    797     // to stay in the current state.
    798     State state = next_handshake_state_;
    799     GotoState(STATE_NONE);
    800     switch (state) {
    801       case STATE_HANDSHAKE:
    802         rv = DoHandshake();
    803         break;
    804       case STATE_VERIFY_CERT:
    805         DCHECK(rv == OK);
    806         rv = DoVerifyCert(rv);
    807        break;
    808       case STATE_VERIFY_CERT_COMPLETE:
    809         rv = DoVerifyCertComplete(rv);
    810         break;
    811       case STATE_NONE:
    812       default:
    813         rv = ERR_UNEXPECTED;
    814         NOTREACHED() << "unexpected state" << state;
    815         break;
    816     }
    817 
    818     bool network_moved = DoTransportIO();
    819     if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
    820       // In general we exit the loop if rv is ERR_IO_PENDING.  In this
    821       // special case we keep looping even if rv is ERR_IO_PENDING because
    822       // the transport IO may allow DoHandshake to make progress.
    823       rv = OK;  // This causes us to stay in the loop.
    824     }
    825   } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
    826   return rv;
    827 }
    828 
    829 int SSLClientSocketOpenSSL::DoHandshake() {
    830   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
    831   int net_error = net::OK;
    832   int rv = SSL_do_handshake(ssl_);
    833 
    834   if (client_auth_cert_needed_) {
    835     net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
    836     // If the handshake already succeeded (because the server requests but
    837     // doesn't require a client cert), we need to invalidate the SSL session
    838     // so that we won't try to resume the non-client-authenticated session in
    839     // the next handshake.  This will cause the server to ask for a client
    840     // cert again.
    841     if (rv == 1) {
    842       // Remove from session cache but don't clear this connection.
    843       SSL_SESSION* session = SSL_get_session(ssl_);
    844       if (session) {
    845         int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
    846         LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
    847       }
    848     }
    849   } else if (rv == 1) {
    850     if (trying_cached_session_ && logging::DEBUG_MODE) {
    851       DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
    852                << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
    853     }
    854     // SSL handshake is completed.  Let's verify the certificate.
    855     const bool got_cert = !!UpdateServerCert();
    856     DCHECK(got_cert);
    857     net_log_.AddEvent(
    858         NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
    859         base::Bind(&NetLogX509CertificateCallback,
    860                    base::Unretained(server_cert_.get())));
    861     GotoState(STATE_VERIFY_CERT);
    862   } else {
    863     int ssl_error = SSL_get_error(ssl_, rv);
    864     net_error = MapOpenSSLError(ssl_error, err_tracer);
    865 
    866     // If not done, stay in this state
    867     if (net_error == ERR_IO_PENDING) {
    868       GotoState(STATE_HANDSHAKE);
    869     } else {
    870       LOG(ERROR) << "handshake failed; returned " << rv
    871                  << ", SSL error code " << ssl_error
    872                  << ", net_error " << net_error;
    873       net_log_.AddEvent(
    874           NetLog::TYPE_SSL_HANDSHAKE_ERROR,
    875           CreateNetLogSSLErrorCallback(net_error, ssl_error));
    876     }
    877   }
    878   return net_error;
    879 }
    880 
    881 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
    882 // server supports NPN, selects a protocol from the list that the server
    883 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
    884 // callback can assume that |in| is syntactically valid.
    885 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
    886                                                     unsigned char* outlen,
    887                                                     const unsigned char* in,
    888                                                     unsigned int inlen) {
    889 #if defined(OPENSSL_NPN_NEGOTIATED)
    890   if (ssl_config_.next_protos.empty()) {
    891     *out = reinterpret_cast<uint8*>(
    892         const_cast<char*>(kDefaultSupportedNPNProtocol));
    893     *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
    894     npn_status_ = kNextProtoUnsupported;
    895     return SSL_TLSEXT_ERR_OK;
    896   }
    897 
    898   // Assume there's no overlap between our protocols and the server's list.
    899   npn_status_ = kNextProtoNoOverlap;
    900 
    901   // For each protocol in server preference order, see if we support it.
    902   for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
    903     for (std::vector<std::string>::const_iterator
    904              j = ssl_config_.next_protos.begin();
    905          j != ssl_config_.next_protos.end(); ++j) {
    906       if (in[i] == j->size() &&
    907           memcmp(&in[i + 1], j->data(), in[i]) == 0) {
    908         // We found a match.
    909         *out = const_cast<unsigned char*>(in) + i + 1;
    910         *outlen = in[i];
    911         npn_status_ = kNextProtoNegotiated;
    912         break;
    913       }
    914     }
    915     if (npn_status_ == kNextProtoNegotiated)
    916       break;
    917   }
    918 
    919   // If we didn't find a protocol, we select the first one from our list.
    920   if (npn_status_ == kNextProtoNoOverlap) {
    921     *out = reinterpret_cast<uint8*>(const_cast<char*>(
    922         ssl_config_.next_protos[0].data()));
    923     *outlen = ssl_config_.next_protos[0].size();
    924   }
    925 
    926   npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
    927   server_protos_.assign(reinterpret_cast<const char*>(in), inlen);
    928   DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
    929 #endif
    930   return SSL_TLSEXT_ERR_OK;
    931 }
    932 
    933 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
    934   DCHECK(server_cert_.get());
    935   GotoState(STATE_VERIFY_CERT_COMPLETE);
    936 
    937   CertStatus cert_status;
    938   if (ssl_config_.IsAllowedBadCert(server_cert_.get(), &cert_status)) {
    939     VLOG(1) << "Received an expected bad cert with status: " << cert_status;
    940     server_cert_verify_result_.Reset();
    941     server_cert_verify_result_.cert_status = cert_status;
    942     server_cert_verify_result_.verified_cert = server_cert_;
    943     return OK;
    944   }
    945 
    946   int flags = 0;
    947   if (ssl_config_.rev_checking_enabled)
    948     flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
    949   if (ssl_config_.verify_ev_cert)
    950     flags |= CertVerifier::VERIFY_EV_CERT;
    951   if (ssl_config_.cert_io_enabled)
    952     flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
    953   if (ssl_config_.rev_checking_required_local_anchors)
    954     flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
    955   verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
    956   return verifier_->Verify(
    957       server_cert_.get(),
    958       host_and_port_.host(),
    959       flags,
    960       NULL /* no CRL set */,
    961       &server_cert_verify_result_,
    962       base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
    963                  base::Unretained(this)),
    964       net_log_);
    965 }
    966 
    967 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
    968   verifier_.reset();
    969 
    970   if (result == OK) {
    971     // TODO(joth): Work out if we need to remember the intermediate CA certs
    972     // when the server sends them to us, and do so here.
    973   } else {
    974     DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
    975              << " (" << result << ")";
    976   }
    977 
    978   completed_handshake_ = true;
    979   // Exit DoHandshakeLoop and return the result to the caller to Connect.
    980   DCHECK_EQ(STATE_NONE, next_handshake_state_);
    981   return result;
    982 }
    983 
    984 X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
    985   if (server_cert_.get())
    986     return server_cert_.get();
    987 
    988   crypto::ScopedOpenSSL<X509, X509_free> cert(SSL_get_peer_certificate(ssl_));
    989   if (!cert.get()) {
    990     LOG(WARNING) << "SSL_get_peer_certificate returned NULL";
    991     return NULL;
    992   }
    993 
    994   // Unlike SSL_get_peer_certificate, SSL_get_peer_cert_chain does not
    995   // increment the reference so sk_X509_free does not need to be called.
    996   STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl_);
    997   X509Certificate::OSCertHandles intermediates;
    998   if (chain) {
    999     for (int i = 0; i < sk_X509_num(chain); ++i)
   1000       intermediates.push_back(sk_X509_value(chain, i));
   1001   }
   1002   server_cert_ = X509Certificate::CreateFromHandle(cert.get(), intermediates);
   1003   DCHECK(server_cert_.get());
   1004 
   1005   return server_cert_.get();
   1006 }
   1007 
   1008 bool SSLClientSocketOpenSSL::DoTransportIO() {
   1009   bool network_moved = false;
   1010   int rv;
   1011   // Read and write as much data as possible. The loop is necessary because
   1012   // Write() may return synchronously.
   1013   do {
   1014     rv = BufferSend();
   1015     if (rv != ERR_IO_PENDING && rv != 0)
   1016       network_moved = true;
   1017   } while (rv > 0);
   1018   if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
   1019     network_moved = true;
   1020   return network_moved;
   1021 }
   1022 
   1023 int SSLClientSocketOpenSSL::BufferSend(void) {
   1024   if (transport_send_busy_)
   1025     return ERR_IO_PENDING;
   1026 
   1027   if (!send_buffer_.get()) {
   1028     // Get a fresh send buffer out of the send BIO.
   1029     size_t max_read = BIO_ctrl_pending(transport_bio_);
   1030     if (!max_read)
   1031       return 0;  // Nothing pending in the OpenSSL write BIO.
   1032     send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
   1033     int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
   1034     DCHECK_GT(read_bytes, 0);
   1035     CHECK_EQ(static_cast<int>(max_read), read_bytes);
   1036   }
   1037 
   1038   int rv = transport_->socket()->Write(
   1039       send_buffer_.get(),
   1040       send_buffer_->BytesRemaining(),
   1041       base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
   1042                  base::Unretained(this)));
   1043   if (rv == ERR_IO_PENDING) {
   1044     transport_send_busy_ = true;
   1045   } else {
   1046     TransportWriteComplete(rv);
   1047   }
   1048   return rv;
   1049 }
   1050 
   1051 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
   1052   transport_send_busy_ = false;
   1053   TransportWriteComplete(result);
   1054   OnSendComplete(result);
   1055 }
   1056 
   1057 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
   1058   DCHECK(ERR_IO_PENDING != result);
   1059   if (result < 0) {
   1060     // Got a socket write error; close the BIO to indicate this upward.
   1061     DVLOG(1) << "TransportWriteComplete error " << result;
   1062     (void)BIO_shutdown_wr(transport_bio_);
   1063     BIO_set_mem_eof_return(transport_bio_, 0);
   1064     send_buffer_ = NULL;
   1065   } else {
   1066     DCHECK(send_buffer_.get());
   1067     send_buffer_->DidConsume(result);
   1068     DCHECK_GE(send_buffer_->BytesRemaining(), 0);
   1069     if (send_buffer_->BytesRemaining() <= 0)
   1070       send_buffer_ = NULL;
   1071   }
   1072 }
   1073 
   1074 int SSLClientSocketOpenSSL::BufferRecv(void) {
   1075   if (transport_recv_busy_)
   1076     return ERR_IO_PENDING;
   1077 
   1078   // Determine how much was requested from |transport_bio_| that was not
   1079   // actually available.
   1080   size_t requested = BIO_ctrl_get_read_request(transport_bio_);
   1081   if (requested == 0) {
   1082     // This is not a perfect match of error codes, as no operation is
   1083     // actually pending. However, returning 0 would be interpreted as
   1084     // a possible sign of EOF, which is also an inappropriate match.
   1085     return ERR_IO_PENDING;
   1086   }
   1087 
   1088   // Known Issue: While only reading |requested| data is the more correct
   1089   // implementation, it has the downside of resulting in frequent reads:
   1090   // One read for the SSL record header (~5 bytes) and one read for the SSL
   1091   // record body. Rather than issuing these reads to the underlying socket
   1092   // (and constantly allocating new IOBuffers), a single Read() request to
   1093   // fill |transport_bio_| is issued. As long as an SSL client socket cannot
   1094   // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
   1095   // traffic, this over-subscribed Read()ing will not cause issues.
   1096   size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
   1097   if (!max_write)
   1098     return ERR_IO_PENDING;
   1099 
   1100   recv_buffer_ = new IOBuffer(max_write);
   1101   int rv = transport_->socket()->Read(
   1102       recv_buffer_.get(),
   1103       max_write,
   1104       base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
   1105                  base::Unretained(this)));
   1106   if (rv == ERR_IO_PENDING) {
   1107     transport_recv_busy_ = true;
   1108   } else {
   1109     TransportReadComplete(rv);
   1110   }
   1111   return rv;
   1112 }
   1113 
   1114 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
   1115   TransportReadComplete(result);
   1116   OnRecvComplete(result);
   1117 }
   1118 
   1119 void SSLClientSocketOpenSSL::TransportReadComplete(int result) {
   1120   DCHECK(ERR_IO_PENDING != result);
   1121   if (result <= 0) {
   1122     DVLOG(1) << "TransportReadComplete result " << result;
   1123     // Received 0 (end of file) or an error. Either way, bubble it up to the
   1124     // SSL layer via the BIO. TODO(joth): consider stashing the error code, to
   1125     // relay up to the SSL socket client (i.e. via DoReadCallback).
   1126     if (result == 0)
   1127       transport_recv_eof_ = true;
   1128     BIO_set_mem_eof_return(transport_bio_, 0);
   1129     (void)BIO_shutdown_wr(transport_bio_);
   1130   } else {
   1131     DCHECK(recv_buffer_.get());
   1132     int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
   1133     // A write into a memory BIO should always succeed.
   1134     CHECK_EQ(result, ret);
   1135   }
   1136   recv_buffer_ = NULL;
   1137   transport_recv_busy_ = false;
   1138 }
   1139 
   1140 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
   1141   if (!user_connect_callback_.is_null()) {
   1142     CompletionCallback c = user_connect_callback_;
   1143     user_connect_callback_.Reset();
   1144     c.Run(rv > OK ? OK : rv);
   1145   }
   1146 }
   1147 
   1148 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
   1149   int rv = DoHandshakeLoop(result);
   1150   if (rv != ERR_IO_PENDING) {
   1151     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   1152     DoConnectCallback(rv);
   1153   }
   1154 }
   1155 
   1156 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
   1157   if (next_handshake_state_ == STATE_HANDSHAKE) {
   1158     // In handshake phase.
   1159     OnHandshakeIOComplete(result);
   1160     return;
   1161   }
   1162 
   1163   // OnSendComplete may need to call DoPayloadRead while the renegotiation
   1164   // handshake is in progress.
   1165   int rv_read = ERR_IO_PENDING;
   1166   int rv_write = ERR_IO_PENDING;
   1167   bool network_moved;
   1168   do {
   1169     if (user_read_buf_.get())
   1170       rv_read = DoPayloadRead();
   1171     if (user_write_buf_.get())
   1172       rv_write = DoPayloadWrite();
   1173     network_moved = DoTransportIO();
   1174   } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
   1175            (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
   1176 
   1177   // Performing the Read callback may cause |this| to be deleted. If this
   1178   // happens, the Write callback should not be invoked. Guard against this by
   1179   // holding a WeakPtr to |this| and ensuring it's still valid.
   1180   base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
   1181   if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
   1182     DoReadCallback(rv_read);
   1183 
   1184   if (!guard.get())
   1185     return;
   1186 
   1187   if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
   1188     DoWriteCallback(rv_write);
   1189 }
   1190 
   1191 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
   1192   if (next_handshake_state_ == STATE_HANDSHAKE) {
   1193     // In handshake phase.
   1194     OnHandshakeIOComplete(result);
   1195     return;
   1196   }
   1197 
   1198   // Network layer received some data, check if client requested to read
   1199   // decrypted data.
   1200   if (!user_read_buf_.get())
   1201     return;
   1202 
   1203   int rv = DoReadLoop(result);
   1204   if (rv != ERR_IO_PENDING)
   1205     DoReadCallback(rv);
   1206 }
   1207 
   1208 bool SSLClientSocketOpenSSL::IsConnected() const {
   1209   // If the handshake has not yet completed.
   1210   if (!completed_handshake_)
   1211     return false;
   1212   // If an asynchronous operation is still pending.
   1213   if (user_read_buf_.get() || user_write_buf_.get())
   1214     return true;
   1215 
   1216   return transport_->socket()->IsConnected();
   1217 }
   1218 
   1219 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
   1220   // If the handshake has not yet completed.
   1221   if (!completed_handshake_)
   1222     return false;
   1223   // If an asynchronous operation is still pending.
   1224   if (user_read_buf_.get() || user_write_buf_.get())
   1225     return false;
   1226   // If there is data waiting to be sent, or data read from the network that
   1227   // has not yet been consumed.
   1228   if (BIO_ctrl_pending(transport_bio_) > 0 ||
   1229       BIO_ctrl_wpending(transport_bio_) > 0) {
   1230     return false;
   1231   }
   1232 
   1233   return transport_->socket()->IsConnectedAndIdle();
   1234 }
   1235 
   1236 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
   1237   return transport_->socket()->GetPeerAddress(addressList);
   1238 }
   1239 
   1240 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
   1241   return transport_->socket()->GetLocalAddress(addressList);
   1242 }
   1243 
   1244 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
   1245   return net_log_;
   1246 }
   1247 
   1248 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
   1249   if (transport_.get() && transport_->socket()) {
   1250     transport_->socket()->SetSubresourceSpeculation();
   1251   } else {
   1252     NOTREACHED();
   1253   }
   1254 }
   1255 
   1256 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
   1257   if (transport_.get() && transport_->socket()) {
   1258     transport_->socket()->SetOmniboxSpeculation();
   1259   } else {
   1260     NOTREACHED();
   1261   }
   1262 }
   1263 
   1264 bool SSLClientSocketOpenSSL::WasEverUsed() const {
   1265   if (transport_.get() && transport_->socket())
   1266     return transport_->socket()->WasEverUsed();
   1267 
   1268   NOTREACHED();
   1269   return false;
   1270 }
   1271 
   1272 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
   1273   if (transport_.get() && transport_->socket())
   1274     return transport_->socket()->UsingTCPFastOpen();
   1275 
   1276   NOTREACHED();
   1277   return false;
   1278 }
   1279 
   1280 // Socket methods
   1281 
   1282 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
   1283                                  int buf_len,
   1284                                  const CompletionCallback& callback) {
   1285   user_read_buf_ = buf;
   1286   user_read_buf_len_ = buf_len;
   1287 
   1288   int rv = DoReadLoop(OK);
   1289 
   1290   if (rv == ERR_IO_PENDING) {
   1291     user_read_callback_ = callback;
   1292   } else {
   1293     user_read_buf_ = NULL;
   1294     user_read_buf_len_ = 0;
   1295   }
   1296 
   1297   return rv;
   1298 }
   1299 
   1300 int SSLClientSocketOpenSSL::DoReadLoop(int result) {
   1301   if (result < 0)
   1302     return result;
   1303 
   1304   bool network_moved;
   1305   int rv;
   1306   do {
   1307     rv = DoPayloadRead();
   1308     network_moved = DoTransportIO();
   1309   } while (rv == ERR_IO_PENDING && network_moved);
   1310 
   1311   return rv;
   1312 }
   1313 
   1314 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
   1315                                   int buf_len,
   1316                                   const CompletionCallback& callback) {
   1317   user_write_buf_ = buf;
   1318   user_write_buf_len_ = buf_len;
   1319 
   1320   int rv = DoWriteLoop(OK);
   1321 
   1322   if (rv == ERR_IO_PENDING) {
   1323     user_write_callback_ = callback;
   1324   } else {
   1325     user_write_buf_ = NULL;
   1326     user_write_buf_len_ = 0;
   1327   }
   1328 
   1329   return rv;
   1330 }
   1331 
   1332 int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
   1333   if (result < 0)
   1334     return result;
   1335 
   1336   bool network_moved;
   1337   int rv;
   1338   do {
   1339     rv = DoPayloadWrite();
   1340     network_moved = DoTransportIO();
   1341   } while (rv == ERR_IO_PENDING && network_moved);
   1342 
   1343   return rv;
   1344 }
   1345 
   1346 bool SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
   1347   return transport_->socket()->SetReceiveBufferSize(size);
   1348 }
   1349 
   1350 bool SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
   1351   return transport_->socket()->SetSendBufferSize(size);
   1352 }
   1353 
   1354 int SSLClientSocketOpenSSL::DoPayloadRead() {
   1355   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
   1356 
   1357   int rv;
   1358   if (pending_read_error_ != kNoPendingReadResult) {
   1359     rv = pending_read_error_;
   1360     pending_read_error_ = kNoPendingReadResult;
   1361     if (rv == 0) {
   1362       net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
   1363                                     rv, user_read_buf_->data());
   1364     }
   1365     return rv;
   1366   }
   1367 
   1368   int total_bytes_read = 0;
   1369   do {
   1370     rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
   1371                   user_read_buf_len_ - total_bytes_read);
   1372     if (rv > 0)
   1373       total_bytes_read += rv;
   1374   } while (total_bytes_read < user_read_buf_len_ && rv > 0);
   1375 
   1376   if (total_bytes_read == user_read_buf_len_) {
   1377     rv = total_bytes_read;
   1378   } else {
   1379     // Otherwise, an error occurred (rv <= 0). The error needs to be handled
   1380     // immediately, while the OpenSSL errors are still available in
   1381     // thread-local storage. However, the handled/remapped error code should
   1382     // only be returned if no application data was already read; if it was, the
   1383     // error code should be deferred until the next call of DoPayloadRead.
   1384     //
   1385     // If no data was read, |*next_result| will point to the return value of
   1386     // this function. If at least some data was read, |*next_result| will point
   1387     // to |pending_read_error_|, to be returned in a future call to
   1388     // DoPayloadRead() (e.g.: after the current data is handled).
   1389     int *next_result = &rv;
   1390     if (total_bytes_read > 0) {
   1391       pending_read_error_ = rv;
   1392       rv = total_bytes_read;
   1393       next_result = &pending_read_error_;
   1394     }
   1395 
   1396     if (client_auth_cert_needed_) {
   1397       *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
   1398     } else if (*next_result < 0) {
   1399       int err = SSL_get_error(ssl_, *next_result);
   1400       *next_result = MapOpenSSLError(err, err_tracer);
   1401       if (rv > 0 && *next_result == ERR_IO_PENDING) {
   1402           // If at least some data was read from SSL_read(), do not treat
   1403           // insufficient data as an error to return in the next call to
   1404           // DoPayloadRead() - instead, let the call fall through to check
   1405           // SSL_read() again. This is because DoTransportIO() may complete
   1406           // in between the next call to DoPayloadRead(), and thus it is
   1407           // important to check SSL_read() on subsequent invocations to see
   1408           // if a complete record may now be read.
   1409         *next_result = kNoPendingReadResult;
   1410       }
   1411     }
   1412   }
   1413 
   1414   if (rv >= 0) {
   1415     net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
   1416                                   user_read_buf_->data());
   1417   }
   1418   return rv;
   1419 }
   1420 
   1421 int SSLClientSocketOpenSSL::DoPayloadWrite() {
   1422   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
   1423   int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
   1424 
   1425   if (rv >= 0) {
   1426     net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
   1427                                   user_write_buf_->data());
   1428     return rv;
   1429   }
   1430 
   1431   int err = SSL_get_error(ssl_, rv);
   1432   return MapOpenSSLError(err, err_tracer);
   1433 }
   1434 
   1435 }  // namespace net
   1436