Home | History | Annotate | Download | only in crypto
      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 #include "crypto/openssl_util.h"
      6 
      7 #include <openssl/err.h>
      8 #include <openssl/ssl.h>
      9 
     10 #include "base/logging.h"
     11 #include "base/memory/scoped_vector.h"
     12 #include "base/memory/singleton.h"
     13 #include "base/strings/string_piece.h"
     14 #include "base/synchronization/lock.h"
     15 #include "build/build_config.h"
     16 
     17 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
     18 #include <cpu-features.h>
     19 #endif
     20 
     21 namespace crypto {
     22 
     23 namespace {
     24 
     25 unsigned long CurrentThreadId() {
     26   return static_cast<unsigned long>(base::PlatformThread::CurrentId());
     27 }
     28 
     29 // Singleton for initializing and cleaning up the OpenSSL library.
     30 class OpenSSLInitSingleton {
     31  public:
     32   static OpenSSLInitSingleton* GetInstance() {
     33     // We allow the SSL environment to leak for multiple reasons:
     34     //   -  it is used from a non-joinable worker thread that is not stopped on
     35     //      shutdown, hence may still be using OpenSSL library after the AtExit
     36     //      runner has completed.
     37     //   -  There are other OpenSSL related singletons (e.g. the client socket
     38     //      context) who's cleanup depends on the global environment here, but
     39     //      we can't control the order the AtExit handlers will run in so
     40     //      allowing the global environment to leak at least ensures it is
     41     //      available for those other singletons to reliably cleanup.
     42     return Singleton<OpenSSLInitSingleton,
     43                LeakySingletonTraits<OpenSSLInitSingleton> >::get();
     44   }
     45  private:
     46   friend struct DefaultSingletonTraits<OpenSSLInitSingleton>;
     47   OpenSSLInitSingleton() {
     48     SSL_load_error_strings();
     49     SSL_library_init();
     50     OpenSSL_add_all_algorithms();
     51     int num_locks = CRYPTO_num_locks();
     52     locks_.reserve(num_locks);
     53     for (int i = 0; i < num_locks; ++i)
     54       locks_.push_back(new base::Lock());
     55     CRYPTO_set_locking_callback(LockingCallback);
     56     CRYPTO_set_id_callback(CurrentThreadId);
     57 
     58 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
     59     const bool has_neon =
     60         (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
     61     if (has_neon)
     62       CRYPTO_set_NEON_capable(1);
     63 #endif
     64   }
     65 
     66   ~OpenSSLInitSingleton() {
     67     CRYPTO_set_locking_callback(NULL);
     68     EVP_cleanup();
     69     ERR_free_strings();
     70   }
     71 
     72   static void LockingCallback(int mode, int n, const char* file, int line) {
     73     OpenSSLInitSingleton::GetInstance()->OnLockingCallback(mode, n, file, line);
     74   }
     75 
     76   void OnLockingCallback(int mode, int n, const char* file, int line) {
     77     CHECK_LT(static_cast<size_t>(n), locks_.size());
     78     if (mode & CRYPTO_LOCK)
     79       locks_[n]->Acquire();
     80     else
     81       locks_[n]->Release();
     82   }
     83 
     84   // These locks are used and managed by OpenSSL via LockingCallback().
     85   ScopedVector<base::Lock> locks_;
     86 
     87   DISALLOW_COPY_AND_ASSIGN(OpenSSLInitSingleton);
     88 };
     89 
     90 // Callback routine for OpenSSL to print error messages. |str| is a
     91 // NULL-terminated string of length |len| containing diagnostic information
     92 // such as the library, function and reason for the error, the file and line
     93 // where the error originated, plus potentially any context-specific
     94 // information about the error. |context| contains a pointer to user-supplied
     95 // data, which is currently unused.
     96 // If this callback returns a value <= 0, OpenSSL will stop processing the
     97 // error queue and return, otherwise it will continue calling this function
     98 // until all errors have been removed from the queue.
     99 int OpenSSLErrorCallback(const char* str, size_t len, void* context) {
    100   DVLOG(1) << "\t" << base::StringPiece(str, len);
    101   return 1;
    102 }
    103 
    104 }  // namespace
    105 
    106 void EnsureOpenSSLInit() {
    107   (void)OpenSSLInitSingleton::GetInstance();
    108 }
    109 
    110 void ClearOpenSSLERRStack(const tracked_objects::Location& location) {
    111   if (logging::DEBUG_MODE && VLOG_IS_ON(1)) {
    112     int error_num = ERR_peek_error();
    113     if (error_num == 0)
    114       return;
    115 
    116     std::string message;
    117     location.Write(true, true, &message);
    118     DVLOG(1) << "OpenSSL ERR_get_error stack from " << message;
    119     ERR_print_errors_cb(&OpenSSLErrorCallback, NULL);
    120   } else {
    121     ERR_clear_error();
    122   }
    123 }
    124 
    125 }  // namespace crypto
    126