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