Init.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright 2017-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/ssl/Init.h>
  17. #include <mutex>
  18. #include <folly/portability/OpenSSL.h>
  19. #include <folly/ssl/detail/OpenSSLThreading.h>
  20. #include <glog/logging.h>
  21. namespace folly {
  22. namespace ssl {
  23. namespace {
  24. bool initialized_ = false;
  25. std::mutex& initMutex() {
  26. static std::mutex m;
  27. return m;
  28. }
  29. void initializeOpenSSLLocked() {
  30. if (initialized_) {
  31. return;
  32. }
  33. OPENSSL_init_ssl(0, nullptr);
  34. randomize();
  35. initialized_ = true;
  36. }
  37. void cleanupOpenSSLLocked() {
  38. if (!initialized_) {
  39. return;
  40. }
  41. OPENSSL_cleanup();
  42. initialized_ = false;
  43. }
  44. } // namespace
  45. void init() {
  46. std::lock_guard<std::mutex> g(initMutex());
  47. initializeOpenSSLLocked();
  48. }
  49. void cleanup() {
  50. std::lock_guard<std::mutex> g(initMutex());
  51. cleanupOpenSSLLocked();
  52. }
  53. void markInitialized() {
  54. std::lock_guard<std::mutex> g(initMutex());
  55. initialized_ = true;
  56. }
  57. void setLockTypesAndInit(LockTypeMapping inLockTypes) {
  58. std::lock_guard<std::mutex> g(initMutex());
  59. CHECK(!initialized_) << "OpenSSL is already initialized";
  60. detail::setLockTypes(std::move(inLockTypes));
  61. initializeOpenSSLLocked();
  62. }
  63. void setLockTypes(LockTypeMapping inLockTypes) {
  64. std::lock_guard<std::mutex> g(initMutex());
  65. if (initialized_) {
  66. // We set the locks on initialization, so if we are already initialized
  67. // this would have no affect.
  68. LOG(INFO) << "Ignoring setSSLLockTypes after initialization";
  69. return;
  70. }
  71. detail::setLockTypes(std::move(inLockTypes));
  72. }
  73. void randomize() {
  74. RAND_poll();
  75. }
  76. bool isLockDisabled(int lockId) {
  77. return detail::isSSLLockDisabled(lockId);
  78. }
  79. } // namespace ssl
  80. } // namespace folly