Libssl Segfaults on python3.6 With Threading
openssl1.0.0 和 openssl1.0.1 使用Python3.6的绑定:
1 25 |
import ctypes import logging ssl_library = ctypes.cdll.LoadLibrary('libeay32.dll') except Exception: ssl_library = ctypes.cdll.LoadLibrary('libssl.so') def check_result(val, func, args): if val == 0: raise ValueError else: return ctypes.c_void_p(val) # ssl_library.EC_KEY_new.restype = ctypes.c_void_p ssl_library.EC_KEY_new_by_curve_name.restype = ctypes.c_void_p ssl_library.EC_KEY_new_by_curve_name.errcheck = check_result k = ssl_library.EC_KEY_new_by_curve_name(NID_secp256k1) if ssl_library.EC_KEY_generate_key(k) != 1: raise Exception("internal error") ssl_library.EC_KEY_free(k) |
---|
这段代码在多线程的时候会出现segmentation fault error; google一下发现
EC_KEY_generate_key
并不是线程安全的;于是:
1 18 |
openssl_locks = [threading.Lock() for _ in range(ssl_library.CRYPTO_num_locks())] openssl_locking_function = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_int) openssl_threadid_function = ctypes.CFUNCTYPE(ctypes.c_ulong) @openssl_locking_function def openssl_lock(mode, type, file, line): if (mode & CRYPTO_LOCK) != 0: openssl_locks[type].acquire() else: openssl_locks[type].release() @openssl_threadid_function |
---|