SSL 读取和 SSL 写入同时进行

2023-12-27

我有两个线程,mainThread and recvThread.

On recvThread, 我打电话SSL_read(ssl, readBuffer, sizeof(readBuffer))。这会阻塞线程,直到收到数据。

然后,于mainThread我被告知需要发送一些数据。所以,我打电话SSL_write(ssl, someData, sizeof(someData)).

有时,这效果很好。其他时候,这会失败并出现奇怪的内部错误消息。我的猜测是,当 SSL_read 发生在同一台计算机上时,我无法调用 SSL_writessl语境。这对我来说完全有道理,但我该如何解决它呢?

我做吗recvThread做类似的事情:

SSL * ssl;
std::string data;
boost::mutex dataMutex;

while (recvThreadShouldBeRunning) {
    char readBuffer[100];
    auto nRead = SSL_read(ssl, readBuffer, sizeof(readBuffer)); //Non-blocking call to SSL_read.

    // Do something with nRead (handle errors, use data)

    {
        auto dataLock = boost::unique_lock<boost::mutex>(dataMutex);
        if (data.length() > 0)
        {
            SSL_write(ssl, data.c_str(), data.length());
        }
    }
    sleep(50);
}

然后当我需要发送一些东西时...

{
    auto dataLock = boost::unique_lock<boost::mutex>(dataMutex);
    data = "some data";
}

这似乎会起作用,但我认为这对我的问题来说是一个相当丑陋的解决方案。有没有办法以某种方式SSL_lock() SSL_wait_on_data() SSL_unlock()?或者这是最好的方法吗?

解决此类问题的标准方法是什么?

谢谢你的时间。


文档中的引用似乎包含了答案:

OpenSSL 可以安全地用于多线程应用程序,前提是至少设置了两个回调函数:locking_function 和 threadid_func。

locking_function(int mode, int n, const char *file, int line)需要对共享数据结构执行锁定。 (请注意,OpenSSL 使用许多全局数据结构,只要多个线程使用 OpenSSL,这些数据结构就会隐式共享。)如果未设置,多线程应用程序将随机崩溃。

locking_function()必须能够处理最多CRYPTO_num_locks()不同的互斥锁。它设置第 n 个锁,如果mode & CRYPTO_LOCK,否则释放它。

file and line是设置锁定的函数的文件号。它们对于调试很有用。

-- 线程-OpenSSL http://www.openssl.org/docs/crypto/threads.html.

使用锁定相关函数的示例(github) https://github.com/openssl/openssl/blob/master/crypto/threads/mttest.c:

crypto/threads/mttest.c 显示了 Solaris、Irix 和 Win32 上的回调函数的示例。

-- 线程-OpenSSL http://www.openssl.org/docs/crypto/threads.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SSL 读取和 SSL 写入同时进行 的相关文章

随机推荐