ssl.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2009, Digium, Inc.
  5. *
  6. * Russell Bryant <russell@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*!
  19. * \file
  20. * \brief Common OpenSSL support code
  21. *
  22. * \author Russell Bryant <russell@digium.com>
  23. */
  24. #include "asterisk.h"
  25. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  26. #ifdef HAVE_OPENSSL
  27. #include <openssl/ssl.h>
  28. #include <openssl/err.h>
  29. #endif
  30. #include "asterisk/_private.h" /* ast_ssl_init() */
  31. #include "asterisk/utils.h"
  32. #include "asterisk/lock.h"
  33. #ifdef HAVE_OPENSSL
  34. static ast_mutex_t *ssl_locks;
  35. static int ssl_num_locks;
  36. static unsigned long ssl_threadid(void)
  37. {
  38. return (unsigned long)pthread_self();
  39. }
  40. static void ssl_lock(int mode, int n, const char *file, int line)
  41. {
  42. if (n < 0 || n >= ssl_num_locks) {
  43. ast_log(LOG_ERROR, "OpenSSL is full of LIES!!! - "
  44. "ssl_num_locks '%d' - n '%d'\n",
  45. ssl_num_locks, n);
  46. return;
  47. }
  48. if (mode & CRYPTO_LOCK) {
  49. ast_mutex_lock(&ssl_locks[n]);
  50. } else {
  51. ast_mutex_unlock(&ssl_locks[n]);
  52. }
  53. }
  54. #endif /* HAVE_OPENSSL */
  55. /*!
  56. * \internal
  57. * \brief Common OpenSSL initialization for all of Asterisk.
  58. */
  59. int ast_ssl_init(void)
  60. {
  61. #ifdef HAVE_OPENSSL
  62. unsigned int i;
  63. SSL_library_init();
  64. SSL_load_error_strings();
  65. ERR_load_crypto_strings();
  66. ERR_load_BIO_strings();
  67. OpenSSL_add_all_algorithms();
  68. /* Make OpenSSL thread-safe. */
  69. CRYPTO_set_id_callback(ssl_threadid);
  70. ssl_num_locks = CRYPTO_num_locks();
  71. if (!(ssl_locks = ast_calloc(ssl_num_locks, sizeof(ssl_locks[0])))) {
  72. return -1;
  73. }
  74. for (i = 0; i < ssl_num_locks; i++) {
  75. ast_mutex_init(&ssl_locks[i]);
  76. }
  77. CRYPTO_set_locking_callback(ssl_lock);
  78. #endif /* HAVE_OPENSSL */
  79. return 0;
  80. }