blob: 2349d42db3f91354bcbb4d4feb91d93c0ede3c44 [file] [log] [blame]
Alex Vakulenkof6024732016-01-22 16:52:43 -08001// 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
Darren Krahn16334162016-03-01 14:38:19 -08007#if defined(OPENSSL_IS_BORINGSSL)
Alex Vakulenkof6024732016-01-22 16:52:43 -08008#include <openssl/cpu.h>
Alex Vakulenko45779222016-03-17 10:36:19 -07009#else
10#include <openssl/ssl.h>
Darren Krahn16334162016-03-01 14:38:19 -080011#endif
Alex Vakulenko45779222016-03-17 10:36:19 -070012#include <openssl/crypto.h>
Luis Hector Chavez94ffa552016-05-25 15:29:35 -070013#include <openssl/err.h>
Alex Vakulenko24854742016-01-22 16:55:13 -080014#include <stddef.h>
15#include <stdint.h>
Alex Vakulenkof6024732016-01-22 16:52:43 -080016
Jay Civelli3a83cdd2017-03-22 17:31:44 -070017#include <string>
18
Alex Vakulenkof6024732016-01-22 16:52:43 -080019#include "base/logging.h"
Alex Vakulenkof6024732016-01-22 16:52:43 -080020#include "base/strings/string_piece.h"
Alex Vakulenkof6024732016-01-22 16:52:43 -080021
22namespace crypto {
23
24namespace {
25
Alex Vakulenkof6024732016-01-22 16:52:43 -080026// 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.
35int 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
42void EnsureOpenSSLInit() {
Luis Hector Chavez94ffa552016-05-25 15:29:35 -070043#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
Alex Vakulenkof6024732016-01-22 16:52:43 -080049}
50
51void ClearOpenSSLERRStack(const tracked_objects::Location& location) {
Jay Civelli3a83cdd2017-03-22 17:31:44 -070052 if (DCHECK_IS_ON() && VLOG_IS_ON(1)) {
Alex Vakulenkof6024732016-01-22 16:52:43 -080053 uint32_t error_num = ERR_peek_error();
54 if (error_num == 0)
55 return;
56
57 std::string message;
58 location.Write(true, true, &message);
59 DVLOG(1) << "OpenSSL ERR_get_error stack from " << message;
60 ERR_print_errors_cb(&OpenSSLErrorCallback, NULL);
61 } else {
62 ERR_clear_error();
63 }
64}
65
66} // namespace crypto