首页 > 解决方案 > 如何以新的方式编写线程安全的 OpenSSL 代码?

问题描述

我正在学习如何使用 OpenSSL 编写多线程 DTLS 服务器。我一直在查看文档,如果我设置CRYPTO_set_id_callbackCRYPTO_set_locking_callback. 我正在使用 OpenSSL 1.1.1c,当我查看时crypto.h,我发现:

/*
 * The old locking functions have been removed completely without compatibility
 * macros. This is because the old functions either could not properly report
 * errors, or the returned error values were not clearly documented.
 * Replacing the locking functions with no-ops would cause race condition
 * issues in the affected applications. It is far better for them to fail at
 * compile time.
 * On the other hand, the locking callbacks are no longer used.  Consequently,
 * the callback management functions can be safely replaced with no-op macros.
 */
#  define CRYPTO_num_locks()            (1)
#  define CRYPTO_set_locking_callback(func)
#  define CRYPTO_get_locking_callback()         (NULL)
#  define CRYPTO_set_add_lock_callback(func)
#  define CRYPTO_get_add_lock_callback()        (NULL)

所以,我看起来这个方法已经过时了。我应该怎么做才能确保我的 OpenSSL 代码是线程安全的?

- 在研究了更多之后,我发现了这个:Tutorial on Using OpenSSL with pthreads。我还找到了https://www.openssl.org/docs/man1.0.2/man3/CRYPTO_THREADID_set_callback.html。但是,CRYPTO_THREADID_set_callback()也是无操作!看起来我只能用正确的标志编译 OpenSSL。

标签: c++multithreadingopensslthread-safety

解决方案


实际上,您不再需要在 OpenSSL 1.1.0 及更高版本中设置锁。

使用 OpenSSL 编程 OpenSSL 是线程安全的吗?

可以,但有一些限制;例如,一个 SSL 连接不能同时被多个线程使用。大多数 OpenSSL 对象都是如此。

对于 1.1.0 及更高版本,您无需再做任何事情。

对于 1.1.0 之前的版本,您的应用程序需要设置线程回调函数。为此,您的应用程序必须调用 CRYPTO_set_locking_callback(3) 和 CRYPTO_THREADID_set... API 之一。有关详细信息,请参阅 OpenSSL 线程手册页以及源代码分发中 INSTALL 文件中的“多线程注意事项”。

您可以在此处查看 OpenSSL 常见问题解答!


推荐阅读