• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #if defined(OPENSSL_IS_BORINGSSL)
8 #include <openssl/cpu.h>
9 #else
10 #include <openssl/ssl.h>
11 #endif
12 #include <openssl/crypto.h>
13 #include <openssl/err.h>
14 #include <stddef.h>
15 #include <stdint.h>
16 
17 #include "base/logging.h"
18 #include "base/strings/string_piece.h"
19 
20 namespace crypto {
21 
22 namespace {
23 
24 // Callback routine for OpenSSL to print error messages. |str| is a
25 // NULL-terminated string of length |len| containing diagnostic information
26 // such as the library, function and reason for the error, the file and line
27 // where the error originated, plus potentially any context-specific
28 // information about the error. |context| contains a pointer to user-supplied
29 // data, which is currently unused.
30 // If this callback returns a value <= 0, OpenSSL will stop processing the
31 // error queue and return, otherwise it will continue calling this function
32 // until all errors have been removed from the queue.
OpenSSLErrorCallback(const char * str,size_t len,void * context)33 int OpenSSLErrorCallback(const char* str, size_t len, void* context) {
34   DVLOG(1) << "\t" << base::StringPiece(str, len);
35   return 1;
36 }
37 
38 }  // namespace
39 
EnsureOpenSSLInit()40 void EnsureOpenSSLInit() {
41 #if defined(OPENSSL_IS_BORINGSSL)
42   // CRYPTO_library_init may be safely called concurrently.
43   CRYPTO_library_init();
44 #else
45   SSL_library_init();
46 #endif
47 }
48 
ClearOpenSSLERRStack(const tracked_objects::Location & location)49 void ClearOpenSSLERRStack(const tracked_objects::Location& location) {
50   if (logging::DEBUG_MODE && VLOG_IS_ON(1)) {
51     uint32_t error_num = ERR_peek_error();
52     if (error_num == 0)
53       return;
54 
55     std::string message;
56     location.Write(true, true, &message);
57     DVLOG(1) << "OpenSSL ERR_get_error stack from " << message;
58     ERR_print_errors_cb(&OpenSSLErrorCallback, NULL);
59   } else {
60     ERR_clear_error();
61   }
62 }
63 
64 }  // namespace crypto
65