仅当 SSL_CTX_new() 失败时才会出现此问题。如果 mosquitto_sub 在同一台机器上运行良好,这似乎不太可能。尝试将“tlsv1”、“tlsv1.1”作为 tls_opts_set 的其他选项。您还可以尝试修补 mosquitto 客户端库,以获取有关 openssl 为何不满意的更多信息:
diff --git a/lib/net_mosq.c b/lib/net_mosq.c
index 08f24d9..d4c57fd 100644
--- a/lib/net_mosq.c
+++ b/lib/net_mosq.c
@@ -409,6 +409,8 @@ int _mosquitto_socket_connect(struct mosquitto *mosq, const char *host, uint16_t
#ifdef WITH_TLS
int ret;
BIO *bio;
+ int e;
+ char ebuf[256];
#endif
if(!mosq || !host || !port) return MOSQ_ERR_INVAL;
@@ -441,6 +443,11 @@ int _mosquitto_socket_connect(struct mosquitto *mosq, const char *host, uint16_t
#endif
if(!mosq->ssl_ctx){
_mosquitto_log_printf(mosq, MOSQ_LOG_ERR, "Error: Unable to create TLS context.");
+ e = ERR_get_error();
+ while(e){
+ _mosquitto_log_printf(mosq, MOSQ_LOG_ERR, "OpenSSL Error: %s", ERR_error_string(e, ebuf));
+ e = ERR_get_error();
+ }
COMPAT_CLOSE(sock);
return MOSQ_ERR_TLS;
}
重现问题的示例代码:
#include <stdio.h>
#include <mosquitto.h>
void my_log_callback(struct mosquitto *mosq, void *obj, int level, const char *str)
{
printf("LOG: %s\n", str);
}
int main(int argc, char *argv[])
{
struct mosquitto *mosq = NULL;
int rc;
printf("Calling connect before lib init, this should fail.\n");
mosq = mosquitto_new(NULL, true, NULL);
mosquitto_log_callback_set(mosq, my_log_callback);
mosquitto_tls_set(mosq, "mosquitto.org.crt", NULL, NULL, NULL, NULL);
rc = mosquitto_connect(mosq, "test.mosquitto.org", 8883, 60);
printf("connect returned %d\n", rc);
mosquitto_destroy(mosq);
mosquitto_lib_init();
printf("Calling connect after lib init, this should be fine.\n");
mosq = mosquitto_new(NULL, true, NULL);
mosquitto_log_callback_set(mosq, my_log_callback);
mosquitto_tls_set(mosq, "mosquitto.org.crt", NULL, NULL, NULL, NULL);
rc = mosquitto_connect(mosq, "test.mosquitto.org", 8883, 60);
printf("connect returned %d\n", rc);
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
printf("Calling connect after lib cleanup, this should fail.\n");
mosq = mosquitto_new(NULL, true, NULL);
mosquitto_log_callback_set(mosq, my_log_callback);
mosquitto_tls_set(mosq, "mosquitto.org.crt", NULL, NULL, NULL, NULL);
rc = mosquitto_connect(mosq, "test.mosquitto.org", 8883, 60);
printf("connect returned %d\n", rc);
mosquitto_destroy(mosq);
return 0;
}
这将产生输出:
Calling connect before lib init, this should fail.
LOG: Error: Unable to create TLS context.
LOG: OpenSSL Error: error:140A90A1:lib(20):func(169):reason(161)
connect returned 8
Calling connect after lib init, this should be fine.
LOG: Client mosq/7v?>w@YfTKk\U=;sO] sending CONNECT
connect returned 0
Calling connect after lib cleanup, this should fail.
LOG: Error: Unable to create TLS context.
LOG: OpenSSL Error: error:140A90F1:lib(20):func(169):reason(241)
connect returned 8
最终的 OpenSSL 错误与您的相同,因此您需要检查是否已取消初始化 openssl。这是 mosquitto_lib_cleanup() 所做的事情,但它可能是您的代码完全独立于 libmosquitto 所做的事情。