lock.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */
  2. /*
  3. * Copyright 2016 Red Hat, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. #include <openssl/crypto.h>
  18. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  19. #include <pthread.h>
  20. static pthread_mutex_t *locks;
  21. static void
  22. locking_cb(int mode, int type, const char *file, int line)
  23. {
  24. if (mode & CRYPTO_LOCK)
  25. pthread_mutex_lock(&(locks[type]));
  26. else
  27. pthread_mutex_unlock(&(locks[type]));
  28. }
  29. static void
  30. thread_id_cb(CRYPTO_THREADID *tid)
  31. {
  32. CRYPTO_THREADID_set_numeric(tid, (unsigned long)pthread_self());
  33. }
  34. static void __attribute__((constructor))
  35. locking_setup(void)
  36. {
  37. int i;
  38. /* Check if somebody else has set a locking callback already. */
  39. if (CRYPTO_get_locking_callback())
  40. return;
  41. locks = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
  42. if (!locks)
  43. return;
  44. for (i = 0; i < CRYPTO_num_locks(); i++) {
  45. if (pthread_mutex_init(&(locks[i]), NULL) != 0) {
  46. for (int n = 0; n < i; n++)
  47. pthread_mutex_destroy(&(locks[n]));
  48. OPENSSL_free(locks);
  49. locks = NULL;
  50. return;
  51. }
  52. }
  53. CRYPTO_set_locking_callback(locking_cb);
  54. CRYPTO_THREADID_set_callback(thread_id_cb);
  55. }
  56. #endif /* OpenSSL < 1.1.0 */