cryptothread.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <pthread.h>
  2. #include <openssl/crypto.h>
  3. #include "cryptothread.h"
  4. static pthread_mutex_t *crypto_locks;
  5. static long *lock_count;
  6. void init_crypto_locks(void){
  7. crypto_locks = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
  8. if(!crypto_locks)
  9. exit(1);
  10. lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
  11. if(!lock_count)
  12. exit(1);
  13. for (int i = 0; i < CRYPTO_num_locks(); i++) {
  14. lock_count[i] = 0;
  15. pthread_mutex_init(&(crypto_locks[i]), NULL);
  16. }
  17. CRYPTO_THREADID_set_callback(pthreads_thread_id);
  18. CRYPTO_set_locking_callback(pthreads_locking_callback);
  19. }
  20. void crypto_locks_cleanup(void){
  21. int i;
  22. CRYPTO_set_locking_callback(NULL);
  23. for (i = 0; i < CRYPTO_num_locks(); i++) {
  24. pthread_mutex_destroy(&(crypto_locks[i]));
  25. }
  26. OPENSSL_free(crypto_locks);
  27. OPENSSL_free(lock_count);
  28. }
  29. /** If the mode is CRYPTO_LOCK, the lock indicated by type will be acquired, otherwise it will be released */
  30. void pthreads_locking_callback(int mode, int type, const char *file, int line){
  31. if(mode & CRYPTO_LOCK){
  32. pthread_mutex_lock(&(crypto_locks[type]));
  33. lock_count[type]++;
  34. } else {
  35. pthread_mutex_unlock(&(crypto_locks[type]));
  36. }
  37. }
  38. void pthreads_thread_id(CRYPTO_THREADID *tid){
  39. CRYPTO_THREADID_set_numeric(tid, (unsigned long)pthread_self());
  40. }