cryptothread.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* Name: cryptothread.c
  2. * Author: Cecylia Bocovich <cbocovic@uwaterloo.ca>
  3. *
  4. * This function contains the code necessary for using OpenSSL in a thread-safe
  5. * manner.
  6. */
  7. #include <pthread.h>
  8. #include <openssl/crypto.h>
  9. #include "cryptothread.h"
  10. static pthread_mutex_t *crypto_locks;
  11. static long *lock_count;
  12. void init_crypto_locks(void){
  13. crypto_locks = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
  14. if(!crypto_locks)
  15. exit(1);
  16. lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
  17. if(!lock_count)
  18. exit(1);
  19. for (int i = 0; i < CRYPTO_num_locks(); i++) {
  20. lock_count[i] = 0;
  21. pthread_mutex_init(&(crypto_locks[i]), NULL);
  22. }
  23. CRYPTO_THREADID_set_callback(pthreads_thread_id);
  24. CRYPTO_set_locking_callback(pthreads_locking_callback);
  25. }
  26. void crypto_locks_cleanup(void){
  27. int i;
  28. CRYPTO_set_locking_callback(NULL);
  29. for (i = 0; i < CRYPTO_num_locks(); i++) {
  30. pthread_mutex_destroy(&(crypto_locks[i]));
  31. }
  32. OPENSSL_free(crypto_locks);
  33. OPENSSL_free(lock_count);
  34. }
  35. /** If the mode is CRYPTO_LOCK, the lock indicated by type will be acquired, otherwise it will be released */
  36. void pthreads_locking_callback(int mode, int type, const char *file, int line){
  37. if(mode & CRYPTO_LOCK){
  38. pthread_mutex_lock(&(crypto_locks[type]));
  39. lock_count[type]++;
  40. } else {
  41. pthread_mutex_unlock(&(crypto_locks[type]));
  42. }
  43. }
  44. void pthreads_thread_id(CRYPTO_THREADID *tid){
  45. CRYPTO_THREADID_set_numeric(tid, (unsigned long)pthread_self());
  46. }