init.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * Copyright (c) 2020 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "init.hpp"
  19. #include "dtlstransport.hpp"
  20. #include "sctptransport.hpp"
  21. #if RTC_ENABLE_WEBSOCKET
  22. #include "tlstransport.hpp"
  23. #endif
  24. #ifdef _WIN32
  25. #include <winsock2.h>
  26. #endif
  27. #if USE_GNUTLS
  28. // Nothing to do
  29. #else
  30. #include <openssl/err.h>
  31. #include <openssl/ssl.h>
  32. #endif
  33. using std::shared_ptr;
  34. namespace rtc {
  35. std::weak_ptr<Init> Init::Weak;
  36. init_token Init::Global;
  37. std::mutex Init::Mutex;
  38. init_token Init::Token() {
  39. std::lock_guard lock(Mutex);
  40. if (!Global) {
  41. if (auto token = Weak.lock())
  42. Global = token;
  43. else
  44. Global = shared_ptr<Init>(new Init());
  45. }
  46. return Global;
  47. }
  48. void Init::Cleanup() { Global.reset(); }
  49. Init::Init() {
  50. #ifdef _WIN32
  51. WSADATA wsaData;
  52. if (WSAStartup(MAKEWORD(2, 2), &wsaData))
  53. throw std::runtime_error("WSAStartup failed, error=" + std::to_string(WSAGetLastError()));
  54. #endif
  55. #if USE_GNUTLS
  56. // Nothing to do
  57. #else
  58. OPENSSL_init_ssl(0, NULL);
  59. SSL_load_error_strings();
  60. ERR_load_crypto_strings();
  61. #endif
  62. SctpTransport::Init();
  63. DtlsTransport::Init();
  64. #if RTC_ENABLE_WEBSOCKET
  65. TlsTransport::Init();
  66. #endif
  67. }
  68. Init::~Init() {
  69. SctpTransport::Cleanup();
  70. DtlsTransport::Cleanup();
  71. #if RTC_ENABLE_WEBSOCKET
  72. TlsTransport::Cleanup();
  73. #endif
  74. #ifdef _WIN32
  75. WSACleanup();
  76. #endif
  77. }
  78. } // namespace rtc