Lucas Eckels | 9bd90e6 | 2012-08-06 15:07:02 -0700 | [diff] [blame] | 1 | /***************************************************************************** |
| 2 | * _ _ ____ _ |
| 3 | * Project ___| | | | _ \| | |
| 4 | * / __| | | | |_) | | |
| 5 | * | (__| |_| | _ <| |___ |
| 6 | * \___|\___/|_| \_\_____| |
| 7 | * |
| 8 | * |
| 9 | * Example source code to show one way to set the necessary OpenSSL locking |
| 10 | * callbacks if you want to do multi-threaded transfers with HTTPS/FTPS with |
| 11 | * libcurl built to use OpenSSL. |
| 12 | * |
| 13 | * This is not a complete stand-alone example. |
| 14 | * |
| 15 | * Author: Jeremy Brown |
| 16 | */ |
| 17 | |
| 18 | |
| 19 | #include <stdio.h> |
| 20 | #include <pthread.h> |
| 21 | #include <openssl/err.h> |
| 22 | |
| 23 | #define MUTEX_TYPE pthread_mutex_t |
| 24 | #define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL) |
| 25 | #define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x)) |
| 26 | #define MUTEX_LOCK(x) pthread_mutex_lock(&(x)) |
| 27 | #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x)) |
| 28 | #define THREAD_ID pthread_self( ) |
| 29 | |
| 30 | |
| 31 | void handle_error(const char *file, int lineno, const char *msg){ |
| 32 | fprintf(stderr, "** %s:%d %s\n", file, lineno, msg); |
| 33 | ERR_print_errors_fp(stderr); |
| 34 | /* exit(-1); */ |
| 35 | } |
| 36 | |
| 37 | /* This array will store all of the mutexes available to OpenSSL. */ |
| 38 | static MUTEX_TYPE *mutex_buf= NULL; |
| 39 | |
| 40 | |
| 41 | static void locking_function(int mode, int n, const char * file, int line) |
| 42 | { |
| 43 | if (mode & CRYPTO_LOCK) |
| 44 | MUTEX_LOCK(mutex_buf[n]); |
| 45 | else |
| 46 | MUTEX_UNLOCK(mutex_buf[n]); |
| 47 | } |
| 48 | |
| 49 | static unsigned long id_function(void) |
| 50 | { |
| 51 | return ((unsigned long)THREAD_ID); |
| 52 | } |
| 53 | |
| 54 | int thread_setup(void) |
| 55 | { |
| 56 | int i; |
| 57 | |
| 58 | mutex_buf = malloc(CRYPTO_num_locks( ) * sizeof(MUTEX_TYPE)); |
| 59 | if (!mutex_buf) |
| 60 | return 0; |
| 61 | for (i = 0; i < CRYPTO_num_locks( ); i++) |
| 62 | MUTEX_SETUP(mutex_buf[i]); |
| 63 | CRYPTO_set_id_callback(id_function); |
| 64 | CRYPTO_set_locking_callback(locking_function); |
| 65 | return 1; |
| 66 | } |
| 67 | |
| 68 | int thread_cleanup(void) |
| 69 | { |
| 70 | int i; |
| 71 | |
| 72 | if (!mutex_buf) |
| 73 | return 0; |
| 74 | CRYPTO_set_id_callback(NULL); |
| 75 | CRYPTO_set_locking_callback(NULL); |
| 76 | for (i = 0; i < CRYPTO_num_locks( ); i++) |
| 77 | MUTEX_CLEANUP(mutex_buf[i]); |
| 78 | free(mutex_buf); |
| 79 | mutex_buf = NULL; |
| 80 | return 1; |
| 81 | } |