1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9 *
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.se/docs/copyright.html.
13 *
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 * SPDX-License-Identifier: curl
22 *
23 ***************************************************************************/
24 /* <DESC>
25 * one way to set the necessary OpenSSL locking callbacks if you want to do
26 * multi-threaded transfers with HTTPS/FTPS with libcurl built to use OpenSSL.
27 * </DESC>
28 */
29 /*
30 * This is not a complete stand-alone example.
31 *
32 * Author: Jeremy Brown
33 */
34
35 #include <stdio.h>
36 #include <pthread.h>
37 #include <openssl/err.h>
38
39 #define MUTEX_TYPE pthread_mutex_t
40 #define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
41 #define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
42 #define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
43 #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
44 #define THREAD_ID pthread_self()
45
46
handle_error(const char * file,int lineno,const char * msg)47 void handle_error(const char *file, int lineno, const char *msg)
48 {
49 fprintf(stderr, "** %s:%d %s\n", file, lineno, msg);
50 ERR_print_errors_fp(stderr);
51 /* exit(-1); */
52 }
53
54 /* This array will store all of the mutexes available to OpenSSL. */
55 static MUTEX_TYPE *mutex_buf = NULL;
56
locking_function(int mode,int n,const char * file,int line)57 static void locking_function(int mode, int n, const char *file, int line)
58 {
59 if(mode & CRYPTO_LOCK)
60 MUTEX_LOCK(mutex_buf[n]);
61 else
62 MUTEX_UNLOCK(mutex_buf[n]);
63 }
64
id_function(void)65 static unsigned long id_function(void)
66 {
67 return ((unsigned long)THREAD_ID);
68 }
69
thread_setup(void)70 int thread_setup(void)
71 {
72 int i;
73
74 mutex_buf = malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
75 if(!mutex_buf)
76 return 0;
77 for(i = 0; i < CRYPTO_num_locks(); i++)
78 MUTEX_SETUP(mutex_buf[i]);
79 CRYPTO_set_id_callback(id_function);
80 CRYPTO_set_locking_callback(locking_function);
81 return 1;
82 }
83
thread_cleanup(void)84 int thread_cleanup(void)
85 {
86 int i;
87
88 if(!mutex_buf)
89 return 0;
90 CRYPTO_set_id_callback(NULL);
91 CRYPTO_set_locking_callback(NULL);
92 for(i = 0; i < CRYPTO_num_locks(); i++)
93 MUTEX_CLEANUP(mutex_buf[i]);
94 free(mutex_buf);
95 mutex_buf = NULL;
96 return 1;
97 }
98