1// Copyright (c) 2011 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/ssl.h>
11#include <openssl/err.h>
12#ifdef ANDROID
13#include <string>
14#endif
15
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/cert_verifier.h"
21#include "net/base/net_errors.h"
22#include "net/base/openssl_private_key_store.h"
23#include "net/base/ssl_cert_request_info.h"
24#include "net/base/ssl_connection_status_flags.h"
25#include "net/base/ssl_info.h"
26#include "net/socket/ssl_error_params.h"
27
28namespace net {
29
30namespace {
31
32// Enable this to see logging for state machine state transitions.
33#if 0
34#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
35                           " jump to state " << s; \
36                           next_handshake_state_ = s; } while (0)
37#else
38#define GotoState(s) next_handshake_state_ = s
39#endif
40
41const size_t kMaxRecvBufferSize = 4096;
42const int kSessionCacheTimeoutSeconds = 60 * 60;
43const size_t kSessionCacheMaxEntires = 1024;
44
45#if OPENSSL_VERSION_NUMBER < 0x1000100fL
46// This method was first included in OpenSSL 1.0.1.
47unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
48#endif
49
50// Used for encoding the |connection_status| field of an SSLInfo object.
51int EncodeSSLConnectionStatus(int cipher_suite,
52                              int compression,
53                              int version) {
54  return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
55          SSL_CONNECTION_CIPHERSUITE_SHIFT) |
56         ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
57          SSL_CONNECTION_COMPRESSION_SHIFT) |
58         ((version & SSL_CONNECTION_VERSION_MASK) <<
59          SSL_CONNECTION_VERSION_SHIFT);
60}
61
62// Returns the net SSL version number (see ssl_connection_status_flags.h) for
63// this SSL connection.
64int GetNetSSLVersion(SSL* ssl) {
65  switch (SSL_version(ssl)) {
66    case SSL2_VERSION:
67      return SSL_CONNECTION_VERSION_SSL2;
68    case SSL3_VERSION:
69      return SSL_CONNECTION_VERSION_SSL3;
70    case TLS1_VERSION:
71      return SSL_CONNECTION_VERSION_TLS1;
72    case 0x0302:
73      return SSL_CONNECTION_VERSION_TLS1_1;
74    case 0x0303:
75      return SSL_CONNECTION_VERSION_TLS1_2;
76    default:
77      return SSL_CONNECTION_VERSION_UNKNOWN;
78  }
79}
80
81int MapOpenSSLErrorSSL() {
82  // Walk down the error stack to find the SSLerr generated reason.
83  unsigned long error_code;
84  do {
85    error_code = ERR_get_error();
86    if (error_code == 0)
87      return ERR_SSL_PROTOCOL_ERROR;
88  } while (ERR_GET_LIB(error_code) != ERR_LIB_SSL);
89
90  DVLOG(1) << "OpenSSL SSL error, reason: " << ERR_GET_REASON(error_code)
91           << ", name: " << ERR_error_string(error_code, NULL);
92  switch (ERR_GET_REASON(error_code)) {
93    case SSL_R_READ_TIMEOUT_EXPIRED:
94      return ERR_TIMED_OUT;
95    case SSL_R_BAD_RESPONSE_ARGUMENT:
96      return ERR_INVALID_ARGUMENT;
97    case SSL_R_UNKNOWN_CERTIFICATE_TYPE:
98    case SSL_R_UNKNOWN_CIPHER_TYPE:
99    case SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE:
100    case SSL_R_UNKNOWN_PKEY_TYPE:
101    case SSL_R_UNKNOWN_REMOTE_ERROR_TYPE:
102    case SSL_R_UNKNOWN_SSL_VERSION:
103      return ERR_NOT_IMPLEMENTED;
104    case SSL_R_UNSUPPORTED_SSL_VERSION:
105    case SSL_R_NO_CIPHER_MATCH:
106    case SSL_R_NO_SHARED_CIPHER:
107    case SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY:
108    case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
109      return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
110    case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
111    case SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE:
112    case SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED:
113    case SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED:
114    case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
115    case SSL_R_TLSV1_ALERT_ACCESS_DENIED:
116    case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
117      return ERR_BAD_SSL_CLIENT_AUTH_CERT;
118    case SSL_R_BAD_DECOMPRESSION:
119    case SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE:
120      return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
121    case SSL_R_SSLV3_ALERT_BAD_RECORD_MAC:
122      return ERR_SSL_BAD_RECORD_MAC_ALERT;
123    case SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:
124      return ERR_SSL_UNSAFE_NEGOTIATION;
125    case SSL_R_WRONG_NUMBER_OF_KEY_BITS:
126      return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
127    // SSL_R_UNKNOWN_PROTOCOL is reported if premature application data is
128    // received (see http://crbug.com/42538), and also if all the protocol
129    // versions supported by the server were disabled in this socket instance.
130    // Mapped to ERR_SSL_PROTOCOL_ERROR for compatibility with other SSL sockets
131    // in the former scenario.
132    case SSL_R_UNKNOWN_PROTOCOL:
133    case SSL_R_SSL_HANDSHAKE_FAILURE:
134    case SSL_R_DECRYPTION_FAILED:
135    case SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC:
136    case SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG:
137    case SSL_R_DIGEST_CHECK_FAILED:
138    case SSL_R_DUPLICATE_COMPRESSION_ID:
139    case SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER:
140    case SSL_R_ENCRYPTED_LENGTH_TOO_LONG:
141    case SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST:
142    case SSL_R_EXCESSIVE_MESSAGE_SIZE:
143    case SSL_R_EXTRA_DATA_IN_MESSAGE:
144    case SSL_R_GOT_A_FIN_BEFORE_A_CCS:
145    case SSL_R_ILLEGAL_PADDING:
146    case SSL_R_INVALID_CHALLENGE_LENGTH:
147    case SSL_R_INVALID_COMMAND:
148    case SSL_R_INVALID_PURPOSE:
149    case SSL_R_INVALID_STATUS_RESPONSE:
150    case SSL_R_INVALID_TICKET_KEYS_LENGTH:
151    case SSL_R_KEY_ARG_TOO_LONG:
152    case SSL_R_READ_WRONG_PACKET_TYPE:
153    case SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE:
154    // TODO(joth): SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE may be returned from the
155    // server after receiving ClientHello if there's no common supported cipher.
156    // Ideally we'd map that specific case to ERR_SSL_VERSION_OR_CIPHER_MISMATCH
157    // to match the NSS implementation. See also http://goo.gl/oMtZW
158    case SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE:
159    case SSL_R_SSLV3_ALERT_NO_CERTIFICATE:
160    case SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER:
161    case SSL_R_TLSV1_ALERT_DECODE_ERROR:
162    case SSL_R_TLSV1_ALERT_DECRYPTION_FAILED:
163    case SSL_R_TLSV1_ALERT_DECRYPT_ERROR:
164    case SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION:
165    case SSL_R_TLSV1_ALERT_INTERNAL_ERROR:
166    case SSL_R_TLSV1_ALERT_NO_RENEGOTIATION:
167    case SSL_R_TLSV1_ALERT_RECORD_OVERFLOW:
168    case SSL_R_TLSV1_ALERT_USER_CANCELLED:
169      return ERR_SSL_PROTOCOL_ERROR;
170    default:
171      LOG(WARNING) << "Unmapped error reason: " << ERR_GET_REASON(error_code);
172      return ERR_FAILED;
173  }
174}
175
176// Converts an OpenSSL error code into a net error code, walking the OpenSSL
177// error stack if needed. Note that |tracer| is not currently used in the
178// implementation, but is passed in anyway as this ensures the caller will clear
179// any residual codes left on the error stack.
180int MapOpenSSLError(int err, const crypto::OpenSSLErrStackTracer& tracer) {
181  switch (err) {
182    case SSL_ERROR_WANT_READ:
183    case SSL_ERROR_WANT_WRITE:
184      return ERR_IO_PENDING;
185    case SSL_ERROR_SYSCALL:
186      DVLOG(1) << "OpenSSL SYSCALL error, errno " << errno;
187      return ERR_SSL_PROTOCOL_ERROR;
188    case SSL_ERROR_SSL:
189      return MapOpenSSLErrorSSL();
190    default:
191      // TODO(joth): Implement full mapping.
192      LOG(WARNING) << "Unknown OpenSSL error " << err;
193      return ERR_SSL_PROTOCOL_ERROR;
194  }
195}
196
197// We do certificate verification after handshake, so we disable the default
198// by registering a no-op verify function.
199int NoOpVerifyCallback(X509_STORE_CTX*, void *) {
200  DVLOG(3) << "skipping cert verify";
201  return 1;
202}
203
204// OpenSSL manages a cache of SSL_SESSION, this class provides the application
205// side policy for that cache about session re-use: we retain one session per
206// unique HostPortPair.
207class SSLSessionCache {
208 public:
209  SSLSessionCache() {}
210
211  void OnSessionAdded(const HostPortPair& host_and_port, SSL_SESSION* session) {
212    // Declare the session cleaner-upper before the lock, so any call into
213    // OpenSSL to free the session will happen after the lock is released.
214    crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
215    base::AutoLock lock(lock_);
216
217    DCHECK_EQ(0U, session_map_.count(session));
218    std::pair<HostPortMap::iterator, bool> res =
219        host_port_map_.insert(std::make_pair(host_and_port, session));
220    if (!res.second) {  // Already exists: replace old entry.
221      session_to_free.reset(res.first->second);
222      session_map_.erase(session_to_free.get());
223      res.first->second = session;
224    }
225    DVLOG(2) << "Adding session " << session << " => "
226             << host_and_port.ToString() << ", new entry = " << res.second;
227    DCHECK(host_port_map_[host_and_port] == session);
228    session_map_[session] = res.first;
229    DCHECK_EQ(host_port_map_.size(), session_map_.size());
230    DCHECK_LE(host_port_map_.size(), kSessionCacheMaxEntires);
231  }
232
233  void OnSessionRemoved(SSL_SESSION* session) {
234    // Declare the session cleaner-upper before the lock, so any call into
235    // OpenSSL to free the session will happen after the lock is released.
236    crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
237    base::AutoLock lock(lock_);
238
239    SessionMap::iterator it = session_map_.find(session);
240    if (it == session_map_.end())
241      return;
242    DVLOG(2) << "Remove session " << session << " => "
243             << it->second->first.ToString();
244    DCHECK(it->second->second == session);
245    host_port_map_.erase(it->second);
246    session_map_.erase(it);
247    session_to_free.reset(session);
248    DCHECK_EQ(host_port_map_.size(), session_map_.size());
249  }
250
251  // Looks up the host:port in the cache, and if a session is found it is added
252  // to |ssl|, returning true on success.
253  bool SetSSLSession(SSL* ssl, const HostPortPair& host_and_port) {
254    base::AutoLock lock(lock_);
255    HostPortMap::iterator it = host_port_map_.find(host_and_port);
256    if (it == host_port_map_.end())
257      return false;
258    DVLOG(2) << "Lookup session: " << it->second << " => "
259             << host_and_port.ToString();
260    SSL_SESSION* session = it->second;
261    DCHECK(session);
262    DCHECK(session_map_[session] == it);
263    // Ideally we'd release |lock_| before calling into OpenSSL here, however
264    // that opens a small risk |session| will go out of scope before it is used.
265    // Alternatively we would take a temporary local refcount on |session|,
266    // except OpenSSL does not provide a public API for adding a ref (c.f.
267    // SSL_SESSION_free which decrements the ref).
268    return SSL_set_session(ssl, session) == 1;
269  }
270
271 private:
272  // A pair of maps to allow bi-directional lookups between host:port and an
273  // associated session.
274  // TODO(joth): When client certificates are implemented we should key the
275  // cache on the client certificate used in addition to the host-port pair.
276  typedef std::map<HostPortPair, SSL_SESSION*> HostPortMap;
277  typedef std::map<SSL_SESSION*, HostPortMap::iterator> SessionMap;
278  HostPortMap host_port_map_;
279  SessionMap session_map_;
280
281  // Protects access to both the above maps.
282  base::Lock lock_;
283
284  DISALLOW_COPY_AND_ASSIGN(SSLSessionCache);
285};
286
287class SSLContext {
288 public:
289  static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
290  SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
291  SSLSessionCache* session_cache() { return &session_cache_; }
292
293  SSLClientSocketOpenSSL* GetClientSocketFromSSL(SSL* ssl) {
294    DCHECK(ssl);
295    SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
296        SSL_get_ex_data(ssl, ssl_socket_data_index_));
297    DCHECK(socket);
298    return socket;
299  }
300
301  bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
302    return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
303  }
304
305 private:
306  friend struct DefaultSingletonTraits<SSLContext>;
307
308  SSLContext() {
309    crypto::EnsureOpenSSLInit();
310    ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
311    DCHECK_NE(ssl_socket_data_index_, -1);
312    ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
313    SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), NoOpVerifyCallback, NULL);
314    SSL_CTX_set_session_cache_mode(ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT);
315    SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallbackStatic);
316    SSL_CTX_sess_set_remove_cb(ssl_ctx_.get(), RemoveSessionCallbackStatic);
317    SSL_CTX_set_timeout(ssl_ctx_.get(), kSessionCacheTimeoutSeconds);
318    SSL_CTX_sess_set_cache_size(ssl_ctx_.get(), kSessionCacheMaxEntires);
319    SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
320#if defined(OPENSSL_NPN_NEGOTIATED)
321    // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
322    // It would be better if the callback were not a global setting,
323    // but that is an OpenSSL issue.
324    SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
325                                     NULL);
326#endif
327  }
328
329  static int NewSessionCallbackStatic(SSL* ssl, SSL_SESSION* session) {
330    return GetInstance()->NewSessionCallback(ssl, session);
331  }
332
333  int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
334    SSLClientSocketOpenSSL* socket = GetClientSocketFromSSL(ssl);
335    session_cache_.OnSessionAdded(socket->host_and_port(), session);
336    return 1;  // 1 => We took ownership of |session|.
337  }
338
339  static void RemoveSessionCallbackStatic(SSL_CTX* ctx, SSL_SESSION* session) {
340    return GetInstance()->RemoveSessionCallback(ctx, session);
341  }
342
343  void RemoveSessionCallback(SSL_CTX* ctx, SSL_SESSION* session) {
344    DCHECK(ctx == ssl_ctx());
345    session_cache_.OnSessionRemoved(session);
346  }
347
348  static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
349    SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
350    CHECK(socket);
351    return socket->ClientCertRequestCallback(ssl, x509, pkey);
352  }
353
354  static int SelectNextProtoCallback(SSL* ssl,
355                                     unsigned char** out, unsigned char* outlen,
356                                     const unsigned char* in,
357                                     unsigned int inlen, void* arg) {
358    SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
359    return socket->SelectNextProtoCallback(out, outlen, in, inlen);
360  }
361
362  // This is the index used with SSL_get_ex_data to retrieve the owner
363  // SSLClientSocketOpenSSL object from an SSL instance.
364  int ssl_socket_data_index_;
365
366  crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free> ssl_ctx_;
367  SSLSessionCache session_cache_;
368};
369
370// Utility to construct the appropriate set & clear masks for use the OpenSSL
371// options and mode configuration functions. (SSL_set_options etc)
372struct SslSetClearMask {
373  SslSetClearMask() : set_mask(0), clear_mask(0) {}
374  void ConfigureFlag(long flag, bool state) {
375    (state ? set_mask : clear_mask) |= flag;
376    // Make sure we haven't got any intersection in the set & clear options.
377    DCHECK_EQ(0, set_mask & clear_mask) << flag << ":" << state;
378  }
379  long set_mask;
380  long clear_mask;
381};
382
383}  // namespace
384
385SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
386    ClientSocketHandle* transport_socket,
387    const HostPortPair& host_and_port,
388    const SSLConfig& ssl_config,
389    CertVerifier* cert_verifier)
390    : ALLOW_THIS_IN_INITIALIZER_LIST(buffer_send_callback_(
391          this, &SSLClientSocketOpenSSL::BufferSendComplete)),
392      ALLOW_THIS_IN_INITIALIZER_LIST(buffer_recv_callback_(
393          this, &SSLClientSocketOpenSSL::BufferRecvComplete)),
394      transport_send_busy_(false),
395      transport_recv_busy_(false),
396      user_connect_callback_(NULL),
397      user_read_callback_(NULL),
398      user_write_callback_(NULL),
399      completed_handshake_(false),
400      client_auth_cert_needed_(false),
401      cert_verifier_(cert_verifier),
402      ALLOW_THIS_IN_INITIALIZER_LIST(handshake_io_callback_(
403          this, &SSLClientSocketOpenSSL::OnHandshakeIOComplete)),
404      ssl_(NULL),
405      transport_bio_(NULL),
406      transport_(transport_socket),
407      host_and_port_(host_and_port),
408      ssl_config_(ssl_config),
409      trying_cached_session_(false),
410      npn_status_(kNextProtoUnsupported),
411      net_log_(transport_socket->socket()->NetLog()) {
412}
413
414SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
415  Disconnect();
416}
417
418bool SSLClientSocketOpenSSL::Init() {
419  DCHECK(!ssl_);
420  DCHECK(!transport_bio_);
421
422  SSLContext* context = SSLContext::GetInstance();
423  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
424
425  ssl_ = SSL_new(context->ssl_ctx());
426  if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
427    return false;
428
429  if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
430    return false;
431
432  trying_cached_session_ =
433      context->session_cache()->SetSSLSession(ssl_, host_and_port_);
434
435  BIO* ssl_bio = NULL;
436  // 0 => use default buffer sizes.
437  if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
438    return false;
439  DCHECK(ssl_bio);
440  DCHECK(transport_bio_);
441
442  SSL_set_bio(ssl_, ssl_bio, ssl_bio);
443
444  // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
445  // set everything we care about to an absolute value.
446  SslSetClearMask options;
447  options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
448  options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl_config_.ssl3_enabled);
449  options.ConfigureFlag(SSL_OP_NO_TLSv1, !ssl_config_.tls1_enabled);
450#ifdef SSL_OP_NO_TLSv1_1
451  options.ConfigureFlag(SSL_OP_NO_TLSv1_1, true);
452#endif
453#ifdef SSL_OP_NO_TLSv1_2
454  options.ConfigureFlag(SSL_OP_NO_TLSv1_2, true);
455#endif
456
457#if defined(SSL_OP_NO_COMPRESSION)
458  // If TLS was disabled also disable compression, to provide maximum site
459  // compatibility in the case of protocol fallback. See http://crbug.com/31628
460#ifdef ANDROID
461  options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
462#else
463  options.ConfigureFlag(SSL_OP_NO_COMPRESSION, !ssl_config_.tls1_enabled);
464#endif
465#endif
466
467  // TODO(joth): Set this conditionally, see http://crbug.com/55410
468  options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
469
470  SSL_set_options(ssl_, options.set_mask);
471  SSL_clear_options(ssl_, options.clear_mask);
472
473  // Same as above, this time for the SSL mode.
474  SslSetClearMask mode;
475
476#if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
477  mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
478                     ssl_config_.false_start_enabled &&
479                     !SSLConfigService::IsKnownFalseStartIncompatibleServer(
480                         host_and_port_.host()));
481#endif
482
483#if defined(SSL_MODE_RELEASE_BUFFERS)
484  mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
485#endif
486
487#if defined(SSL_MODE_SMALL_BUFFERS)
488  mode.ConfigureFlag(SSL_MODE_SMALL_BUFFERS, true);
489#endif
490
491  SSL_set_mode(ssl_, mode.set_mask);
492  SSL_clear_mode(ssl_, mode.clear_mask);
493
494  // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
495  // textual name with SSL_set_cipher_list because there is no public API to
496  // directly remove a cipher by ID.
497  STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
498  DCHECK(ciphers);
499  // See SSLConfig::disabled_cipher_suites for description of the suites
500  // disabled by default.
501  std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA");
502  // Walk through all the installed ciphers, seeing if any need to be
503  // appended to the cipher removal |command|.
504  for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
505    const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
506    const uint16 id = SSL_CIPHER_get_id(cipher);
507    // Remove any ciphers with a strength of less than 80 bits. Note the NSS
508    // implementation uses "effective" bits here but OpenSSL does not provide
509    // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
510    // both of which are greater than 80 anyway.
511    bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
512    if (!disable) {
513      disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
514                          ssl_config_.disabled_cipher_suites.end(), id) !=
515                    ssl_config_.disabled_cipher_suites.end();
516    }
517    if (disable) {
518       const char* name = SSL_CIPHER_get_name(cipher);
519       DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
520                << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
521       command.append(":!");
522       command.append(name);
523     }
524  }
525  int rv = SSL_set_cipher_list(ssl_, command.c_str());
526  // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
527  // This will almost certainly result in the socket failing to complete the
528  // handshake at which point the appropriate error is bubbled up to the client.
529  LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
530                              "returned " << rv;
531  return true;
532}
533
534int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
535                                                      X509** x509,
536                                                      EVP_PKEY** pkey) {
537  DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
538  DCHECK(ssl == ssl_);
539  DCHECK(*x509 == NULL);
540  DCHECK(*pkey == NULL);
541
542  if (!ssl_config_.send_client_cert) {
543    client_auth_cert_needed_ = true;
544    return -1;  // Suspends handshake.
545  }
546
547  // Second pass: a client certificate should have been selected.
548  if (ssl_config_.client_cert) {
549    EVP_PKEY* privkey = OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(
550        X509_PUBKEY_get(X509_get_X509_PUBKEY(
551            ssl_config_.client_cert->os_cert_handle())));
552    if (privkey) {
553      CRYPTO_add(&privkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
554      // TODO(joth): (copied from NSS) We should wait for server certificate
555      // verification before sending our credentials. See http://crbug.com/13934
556      *x509 = X509Certificate::DupOSCertHandle(
557          ssl_config_.client_cert->os_cert_handle());
558      *pkey = privkey;
559      return 1;
560    }
561    LOG(WARNING) << "Client cert found without private key";
562  }
563
564  // Send no client certificate.
565  return 0;
566}
567
568// SSLClientSocket methods
569
570void SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
571  ssl_info->Reset();
572  if (!server_cert_)
573    return;
574
575  ssl_info->cert = server_cert_;
576  ssl_info->cert_status = server_cert_verify_result_.cert_status;
577  ssl_info->is_issued_by_known_root =
578      server_cert_verify_result_.is_issued_by_known_root;
579  ssl_info->public_key_hashes =
580    server_cert_verify_result_.public_key_hashes;
581
582  const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
583  CHECK(cipher);
584  ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
585  const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
586
587  ssl_info->connection_status = EncodeSSLConnectionStatus(
588      SSL_CIPHER_get_id(cipher),
589      compression ? compression->type : 0,
590      GetNetSSLVersion(ssl_));
591
592  bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
593  if (!peer_supports_renego_ext)
594    ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
595  UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
596                            implicit_cast<int>(peer_supports_renego_ext), 2);
597
598  if (ssl_config_.ssl3_fallback)
599    ssl_info->connection_status |= SSL_CONNECTION_SSL3_FALLBACK;
600
601  DVLOG(3) << "Encoded connection status: cipher suite = "
602      << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
603      << " compression = "
604      << SSLConnectionStatusToCompression(ssl_info->connection_status)
605      << " version = "
606      << SSLConnectionStatusToVersion(ssl_info->connection_status);
607}
608
609void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
610    SSLCertRequestInfo* cert_request_info) {
611  cert_request_info->host_and_port = host_and_port_.ToString();
612  cert_request_info->client_certs = client_certs_;
613}
614
615SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
616    std::string* proto) {
617  *proto = npn_proto_;
618  return npn_status_;
619}
620
621void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
622  // Since Run may result in Read being called, clear |user_read_callback_|
623  // up front.
624  CompletionCallback* c = user_read_callback_;
625  user_read_callback_ = NULL;
626  user_read_buf_ = NULL;
627  user_read_buf_len_ = 0;
628  c->Run(rv);
629}
630
631void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
632  // Since Run may result in Write being called, clear |user_write_callback_|
633  // up front.
634  CompletionCallback* c = user_write_callback_;
635  user_write_callback_ = NULL;
636  user_write_buf_ = NULL;
637  user_write_buf_len_ = 0;
638  c->Run(rv);
639}
640
641// ClientSocket methods
642
643#ifdef ANDROID
644// TODO(kristianm): handle the case when wait_for_connect is true
645// (sync requests)
646#endif
647int SSLClientSocketOpenSSL::Connect(CompletionCallback* callback
648#ifdef ANDROID
649                                    , bool wait_for_connect
650                                    , bool valid_uid
651                                    , uid_t calling_uid
652#endif
653                                   ) {
654  net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL);
655
656  // Set up new ssl object.
657  if (!Init()) {
658    int result = ERR_UNEXPECTED;
659    net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, result);
660    return result;
661  }
662
663  // Set SSL to client mode. Handshake happens in the loop below.
664  SSL_set_connect_state(ssl_);
665
666  GotoState(STATE_HANDSHAKE);
667  int rv = DoHandshakeLoop(net::OK);
668  if (rv == ERR_IO_PENDING) {
669    user_connect_callback_ = callback;
670  } else {
671    net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
672  }
673
674  return rv > OK ? OK : rv;
675}
676
677void SSLClientSocketOpenSSL::Disconnect() {
678  if (ssl_) {
679    SSL_free(ssl_);
680    ssl_ = NULL;
681  }
682  if (transport_bio_) {
683    BIO_free_all(transport_bio_);
684    transport_bio_ = NULL;
685  }
686
687  // Shut down anything that may call us back (through buffer_send_callback_,
688  // buffer_recv_callback, or handshake_io_callback_).
689  verifier_.reset();
690  transport_->socket()->Disconnect();
691
692  // Null all callbacks, delete all buffers.
693  transport_send_busy_ = false;
694  send_buffer_ = NULL;
695  transport_recv_busy_ = false;
696  recv_buffer_ = NULL;
697
698  user_connect_callback_ = NULL;
699  user_read_callback_    = NULL;
700  user_write_callback_   = NULL;
701  user_read_buf_         = NULL;
702  user_read_buf_len_     = 0;
703  user_write_buf_        = NULL;
704  user_write_buf_len_    = 0;
705
706  server_cert_verify_result_.Reset();
707  completed_handshake_ = false;
708
709  client_certs_.clear();
710  client_auth_cert_needed_ = false;
711}
712
713int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
714  bool network_moved;
715  int rv = last_io_result;
716  do {
717    // Default to STATE_NONE for next state.
718    // (This is a quirk carried over from the windows
719    // implementation.  It makes reading the logs a bit harder.)
720    // State handlers can and often do call GotoState just
721    // to stay in the current state.
722    State state = next_handshake_state_;
723    GotoState(STATE_NONE);
724    switch (state) {
725      case STATE_NONE:
726        // we're just pumping data between the buffer and the network
727        break;
728      case STATE_HANDSHAKE:
729        rv = DoHandshake();
730        break;
731      case STATE_VERIFY_CERT:
732        DCHECK(rv == OK);
733        rv = DoVerifyCert(rv);
734       break;
735      case STATE_VERIFY_CERT_COMPLETE:
736        rv = DoVerifyCertComplete(rv);
737        break;
738      default:
739        rv = ERR_UNEXPECTED;
740        NOTREACHED() << "unexpected state" << state;
741        break;
742    }
743
744    // To avoid getting an ERR_IO_PENDING here after handshake complete.
745    if (next_handshake_state_ == STATE_NONE)
746      break;
747
748    // Do the actual network I/O.
749    network_moved = DoTransportIO();
750  } while ((rv != ERR_IO_PENDING || network_moved) &&
751            next_handshake_state_ != STATE_NONE);
752  return rv;
753}
754
755int SSLClientSocketOpenSSL::DoHandshake() {
756  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
757  int net_error = net::OK;
758  int rv = SSL_do_handshake(ssl_);
759
760  if (client_auth_cert_needed_) {
761    net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
762    // If the handshake already succeeded (because the server requests but
763    // doesn't require a client cert), we need to invalidate the SSL session
764    // so that we won't try to resume the non-client-authenticated session in
765    // the next handshake.  This will cause the server to ask for a client
766    // cert again.
767    if (rv == 1) {
768      // Remove from session cache but don't clear this connection.
769      SSL_SESSION* session = SSL_get_session(ssl_);
770      if (session) {
771        int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
772        LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
773      }
774    }
775  } else if (rv == 1) {
776    if (trying_cached_session_ && logging::DEBUG_MODE) {
777      DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
778               << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
779    }
780    // SSL handshake is completed.  Let's verify the certificate.
781    const bool got_cert = !!UpdateServerCert();
782    DCHECK(got_cert);
783    GotoState(STATE_VERIFY_CERT);
784  } else {
785    int ssl_error = SSL_get_error(ssl_, rv);
786    net_error = MapOpenSSLError(ssl_error, err_tracer);
787
788    // If not done, stay in this state
789    if (net_error == ERR_IO_PENDING) {
790      GotoState(STATE_HANDSHAKE);
791    } else {
792      LOG(ERROR) << "handshake failed; returned " << rv
793                 << ", SSL error code " << ssl_error
794                 << ", net_error " << net_error;
795      net_log_.AddEvent(
796          NetLog::TYPE_SSL_HANDSHAKE_ERROR,
797          make_scoped_refptr(new SSLErrorParams(net_error, ssl_error)));
798    }
799  }
800  return net_error;
801}
802
803int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
804                                                    unsigned char* outlen,
805                                                    const unsigned char* in,
806                                                    unsigned int inlen) {
807#if defined(OPENSSL_NPN_NEGOTIATED)
808  if (ssl_config_.next_protos.empty()) {
809    *out = reinterpret_cast<uint8*>(const_cast<char*>("http/1.1"));
810    *outlen = 8;
811    npn_status_ = SSLClientSocket::kNextProtoUnsupported;
812    return SSL_TLSEXT_ERR_OK;
813  }
814
815  int status = SSL_select_next_proto(
816      out, outlen, in, inlen,
817      reinterpret_cast<const unsigned char*>(ssl_config_.next_protos.data()),
818      ssl_config_.next_protos.size());
819
820  npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
821  switch (status) {
822    case OPENSSL_NPN_UNSUPPORTED:
823      npn_status_ = SSLClientSocket::kNextProtoUnsupported;
824      break;
825    case OPENSSL_NPN_NEGOTIATED:
826      npn_status_ = SSLClientSocket::kNextProtoNegotiated;
827      break;
828    case OPENSSL_NPN_NO_OVERLAP:
829      npn_status_ = SSLClientSocket::kNextProtoNoOverlap;
830      break;
831    default:
832      NOTREACHED() << status;
833      break;
834  }
835  DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
836#endif
837  return SSL_TLSEXT_ERR_OK;
838}
839
840int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
841  DCHECK(server_cert_);
842  GotoState(STATE_VERIFY_CERT_COMPLETE);
843  int flags = 0;
844
845  if (ssl_config_.rev_checking_enabled)
846    flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED;
847  if (ssl_config_.verify_ev_cert)
848    flags |= X509Certificate::VERIFY_EV_CERT;
849  verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
850  return verifier_->Verify(server_cert_, host_and_port_.host(), flags,
851                           &server_cert_verify_result_,
852                           &handshake_io_callback_);
853}
854
855int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
856  verifier_.reset();
857
858  if (result == OK) {
859    // TODO(joth): Work out if we need to remember the intermediate CA certs
860    // when the server sends them to us, and do so here.
861  } else {
862    DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
863             << " (" << result << ")";
864  }
865
866  // If we have been explicitly told to accept this certificate, override the
867  // result of verifier_.Verify.
868  // Eventually, we should cache the cert verification results so that we don't
869  // need to call verifier_.Verify repeatedly.  But for now we need to do this.
870  // Alternatively, we could use the cert's status that we stored along with
871  // the cert in the allowed_bad_certs vector.
872  if (IsCertificateError(result) &&
873      ssl_config_.IsAllowedBadCert(server_cert_)) {
874    VLOG(1) << "accepting bad SSL certificate, as user told us to";
875    result = OK;
876  }
877
878  completed_handshake_ = true;
879  // Exit DoHandshakeLoop and return the result to the caller to Connect.
880  DCHECK_EQ(STATE_NONE, next_handshake_state_);
881  return result;
882}
883
884X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
885  if (server_cert_)
886    return server_cert_;
887
888  crypto::ScopedOpenSSL<X509, X509_free> cert(SSL_get_peer_certificate(ssl_));
889  if (!cert.get()) {
890    LOG(WARNING) << "SSL_get_peer_certificate returned NULL";
891    return NULL;
892  }
893
894  // Unlike SSL_get_peer_certificate, SSL_get_peer_cert_chain does not
895  // increment the reference so sk_X509_free does not need to be called.
896  STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl_);
897  X509Certificate::OSCertHandles intermediates;
898  if (chain) {
899    for (int i = 0; i < sk_X509_num(chain); ++i)
900      intermediates.push_back(sk_X509_value(chain, i));
901  }
902  server_cert_ = X509Certificate::CreateFromHandle(
903      cert.get(), X509Certificate::SOURCE_FROM_NETWORK, intermediates);
904  DCHECK(server_cert_);
905
906  return server_cert_;
907}
908
909bool SSLClientSocketOpenSSL::DoTransportIO() {
910  bool network_moved = false;
911  int nsent = BufferSend();
912  int nreceived = BufferRecv();
913  network_moved = (nsent > 0 || nreceived >= 0);
914  return network_moved;
915}
916
917int SSLClientSocketOpenSSL::BufferSend(void) {
918  if (transport_send_busy_)
919    return ERR_IO_PENDING;
920
921  if (!send_buffer_) {
922    // Get a fresh send buffer out of the send BIO.
923    size_t max_read = BIO_ctrl_pending(transport_bio_);
924    if (max_read > 0) {
925      send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
926      int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
927      DCHECK_GT(read_bytes, 0);
928      CHECK_EQ(static_cast<int>(max_read), read_bytes);
929    }
930  }
931
932  int rv = 0;
933  while (send_buffer_) {
934    rv = transport_->socket()->Write(send_buffer_,
935                                     send_buffer_->BytesRemaining(),
936                                     &buffer_send_callback_);
937    if (rv == ERR_IO_PENDING) {
938      transport_send_busy_ = true;
939      return rv;
940    }
941    TransportWriteComplete(rv);
942  }
943  return rv;
944}
945
946void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
947  transport_send_busy_ = false;
948  TransportWriteComplete(result);
949  OnSendComplete(result);
950}
951
952void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
953  DCHECK(ERR_IO_PENDING != result);
954  if (result < 0) {
955    // Got a socket write error; close the BIO to indicate this upward.
956    DVLOG(1) << "TransportWriteComplete error " << result;
957    (void)BIO_shutdown_wr(transport_bio_);
958    send_buffer_ = NULL;
959  } else {
960    DCHECK(send_buffer_);
961    send_buffer_->DidConsume(result);
962    DCHECK_GE(send_buffer_->BytesRemaining(), 0);
963    if (send_buffer_->BytesRemaining() <= 0)
964      send_buffer_ = NULL;
965  }
966}
967
968int SSLClientSocketOpenSSL::BufferRecv(void) {
969  if (transport_recv_busy_)
970    return ERR_IO_PENDING;
971
972  size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
973  if (max_write > kMaxRecvBufferSize)
974    max_write = kMaxRecvBufferSize;
975
976  if (!max_write)
977    return ERR_IO_PENDING;
978
979  recv_buffer_ = new IOBuffer(max_write);
980  int rv = transport_->socket()->Read(recv_buffer_, max_write,
981                                      &buffer_recv_callback_);
982  if (rv == ERR_IO_PENDING) {
983    transport_recv_busy_ = true;
984  } else {
985    TransportReadComplete(rv);
986  }
987  return rv;
988}
989
990void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
991  TransportReadComplete(result);
992  OnRecvComplete(result);
993}
994
995void SSLClientSocketOpenSSL::TransportReadComplete(int result) {
996  DCHECK(ERR_IO_PENDING != result);
997  if (result <= 0) {
998    DVLOG(1) << "TransportReadComplete result " << result;
999    // Received 0 (end of file) or an error. Either way, bubble it up to the
1000    // SSL layer via the BIO. TODO(joth): consider stashing the error code, to
1001    // relay up to the SSL socket client (i.e. via DoReadCallback).
1002    BIO_set_mem_eof_return(transport_bio_, 0);
1003    (void)BIO_shutdown_wr(transport_bio_);
1004  } else {
1005    DCHECK(recv_buffer_);
1006    int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1007    // A write into a memory BIO should always succeed.
1008    CHECK_EQ(result, ret);
1009  }
1010  recv_buffer_ = NULL;
1011  transport_recv_busy_ = false;
1012}
1013
1014void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1015  CompletionCallback* c = user_connect_callback_;
1016  user_connect_callback_ = NULL;
1017  c->Run(rv > OK ? OK : rv);
1018}
1019
1020void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1021  int rv = DoHandshakeLoop(result);
1022  if (rv != ERR_IO_PENDING) {
1023    net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1024    DoConnectCallback(rv);
1025  }
1026}
1027
1028void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1029  if (next_handshake_state_ != STATE_NONE) {
1030    // In handshake phase.
1031    OnHandshakeIOComplete(result);
1032    return;
1033  }
1034
1035  // OnSendComplete may need to call DoPayloadRead while the renegotiation
1036  // handshake is in progress.
1037  int rv_read = ERR_IO_PENDING;
1038  int rv_write = ERR_IO_PENDING;
1039  bool network_moved;
1040  do {
1041      if (user_read_buf_)
1042          rv_read = DoPayloadRead();
1043      if (user_write_buf_)
1044          rv_write = DoPayloadWrite();
1045      network_moved = DoTransportIO();
1046  } while (rv_read == ERR_IO_PENDING &&
1047           rv_write == ERR_IO_PENDING &&
1048           network_moved);
1049
1050  if (user_read_buf_ && rv_read != ERR_IO_PENDING)
1051      DoReadCallback(rv_read);
1052  if (user_write_buf_ && rv_write != ERR_IO_PENDING)
1053      DoWriteCallback(rv_write);
1054}
1055
1056void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1057  if (next_handshake_state_ != STATE_NONE) {
1058    // In handshake phase.
1059    OnHandshakeIOComplete(result);
1060    return;
1061  }
1062
1063  // Network layer received some data, check if client requested to read
1064  // decrypted data.
1065  if (!user_read_buf_)
1066    return;
1067
1068  int rv = DoReadLoop(result);
1069  if (rv != ERR_IO_PENDING)
1070    DoReadCallback(rv);
1071}
1072
1073bool SSLClientSocketOpenSSL::IsConnected() const {
1074  bool ret = completed_handshake_ && transport_->socket()->IsConnected();
1075  return ret;
1076}
1077
1078bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
1079  bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
1080  return ret;
1081}
1082
1083int SSLClientSocketOpenSSL::GetPeerAddress(AddressList* addressList) const {
1084  return transport_->socket()->GetPeerAddress(addressList);
1085}
1086
1087int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
1088  return transport_->socket()->GetLocalAddress(addressList);
1089}
1090
1091const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
1092  return net_log_;
1093}
1094
1095void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
1096  if (transport_.get() && transport_->socket()) {
1097    transport_->socket()->SetSubresourceSpeculation();
1098  } else {
1099    NOTREACHED();
1100  }
1101}
1102
1103void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
1104  if (transport_.get() && transport_->socket()) {
1105    transport_->socket()->SetOmniboxSpeculation();
1106  } else {
1107    NOTREACHED();
1108  }
1109}
1110
1111bool SSLClientSocketOpenSSL::WasEverUsed() const {
1112  if (transport_.get() && transport_->socket())
1113    return transport_->socket()->WasEverUsed();
1114
1115  NOTREACHED();
1116  return false;
1117}
1118
1119bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
1120  if (transport_.get() && transport_->socket())
1121    return transport_->socket()->UsingTCPFastOpen();
1122
1123  NOTREACHED();
1124  return false;
1125}
1126
1127// Socket methods
1128
1129int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
1130                                 int buf_len,
1131                                 CompletionCallback* callback) {
1132  user_read_buf_ = buf;
1133  user_read_buf_len_ = buf_len;
1134
1135  int rv = DoReadLoop(OK);
1136
1137  if (rv == ERR_IO_PENDING) {
1138    user_read_callback_ = callback;
1139  } else {
1140    user_read_buf_ = NULL;
1141    user_read_buf_len_ = 0;
1142  }
1143
1144  return rv;
1145}
1146
1147int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1148  if (result < 0)
1149    return result;
1150
1151  bool network_moved;
1152  int rv;
1153  do {
1154    rv = DoPayloadRead();
1155    network_moved = DoTransportIO();
1156  } while (rv == ERR_IO_PENDING && network_moved);
1157
1158  return rv;
1159}
1160
1161int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
1162                                  int buf_len,
1163                                  CompletionCallback* callback) {
1164  user_write_buf_ = buf;
1165  user_write_buf_len_ = buf_len;
1166
1167  int rv = DoWriteLoop(OK);
1168
1169  if (rv == ERR_IO_PENDING) {
1170    user_write_callback_ = callback;
1171  } else {
1172    user_write_buf_ = NULL;
1173    user_write_buf_len_ = 0;
1174  }
1175
1176  return rv;
1177}
1178
1179int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1180  if (result < 0)
1181    return result;
1182
1183  bool network_moved;
1184  int rv;
1185  do {
1186    rv = DoPayloadWrite();
1187    network_moved = DoTransportIO();
1188  } while (rv == ERR_IO_PENDING && network_moved);
1189
1190  return rv;
1191}
1192
1193bool SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
1194  return transport_->socket()->SetReceiveBufferSize(size);
1195}
1196
1197bool SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
1198  return transport_->socket()->SetSendBufferSize(size);
1199}
1200
1201int SSLClientSocketOpenSSL::DoPayloadRead() {
1202  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1203  int rv = SSL_read(ssl_, user_read_buf_->data(), user_read_buf_len_);
1204  // We don't need to invalidate the non-client-authenticated SSL session
1205  // because the server will renegotiate anyway.
1206  if (client_auth_cert_needed_)
1207    return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1208
1209  if (rv >= 0)
1210    return rv;
1211
1212  int err = SSL_get_error(ssl_, rv);
1213  return MapOpenSSLError(err, err_tracer);
1214}
1215
1216int SSLClientSocketOpenSSL::DoPayloadWrite() {
1217  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1218  int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1219
1220  if (rv >= 0)
1221    return rv;
1222
1223  int err = SSL_get_error(ssl_, rv);
1224  return MapOpenSSLError(err, err_tracer);
1225}
1226
1227}  // namespace net
1228