c++ - 如何从 OpenSSL 释放 SSL 连接?

标签 c++ c linux memory openssl

以下代码是否正确释放了所有分配的内存?

void foo(){
    //set up connection
    SSL *ssl = NULL;
    SSL_METHOD *method = (SSL_METHOD *)SSLv23_client_method();
    SSL_CTX *ctx = SSL_CTX_new(method);
    BIO *bio = BIO_new_ssl_connect(ctx);
    BIO_get_ssl(bio, &ssl);
    BIO_set_conn_hostname(bio, "facebook.com:443");

    doConnect(ssl, ctx, bio);
    ...
    doFree(ssl, ctx, bio);
}

void doConnect(SSL *ssl, SSL_CTX *ctx, BIO *bio){
    BIO_reset(bio); //this is here in case we are trying to reconnect
    if (BIO_do_connect(connection->bio) <= 0){
        while ( BIO_should_retry(connection->bio)){
            if (BIO_do_connect(connection->bio) > 0){
                break;
            } 
        }
        //error handeling in case BIO_should_retry returns false omitted.
    }
    if (SSL_get_verify_result(connection->ssl) != X509_V_OK){
        // Handle the failed verification
    }
    int socket = BIO_get_fd(bio, NULL);
}

void doFree(SSL *ssl, SSL_CTX *ctx, BIO *bio){
    BIO_free_all(bio); //is this right?
}

我想知道这是否是释放内存的正确方法的原因是因为我目前正在获取以下堆栈跟踪,但我不知道我是否不正确地释放了内存或者它是否是某种其他类型的错误(valgrind 不报告任何内存错误,它只是在此处停止)。

(gdb) bt
#0  0x040010c2 in ?? () from /lib/ld-linux.so.2
#1  0x06a13a0b in write () at ../sysdeps/unix/syscall-template.S:82
#2  0x04153ae9 in ?? () from /lib/i386-linux-gnu/libcrypto.so.1.0.0
#3  0x041508e4 in BIO_write () from /lib/i386-linux-gnu/libcrypto.so.1.0.0
#4  0x040771f1 in ?? () from /lib/i386-linux-gnu/libssl.so.1.0.0
#5  0x040775ff in ?? () from /lib/i386-linux-gnu/libssl.so.1.0.0
#6  0x04078d2f in ?? () from /lib/i386-linux-gnu/libssl.so.1.0.0
#7  0x04077a64 in ?? () from /lib/i386-linux-gnu/libssl.so.1.0.0
#8  0x04074bde in ?? () from /lib/i386-linux-gnu/libssl.so.1.0.0
#9  0x0408eed1 in SSL_shutdown () from /lib/i386-linux-gnu/libssl.so.1.0.0
#10 0x0409b175 in ?? () from /lib/i386-linux-gnu/libssl.so.1.0.0
#11 0x04150638 in BIO_free () from /lib/i386-linux-gnu/libcrypto.so.1.0.0
#12 0x041511c4 in BIO_free_all () from /lib/i386-linux-gnu/libcrypto.so.1.0.0

最佳答案

这可能是因为您的代码没有调用 SSL_library_init();。添加那个,包含一个 main 并删除对 connection 的引用,这一切都对我有用。

如果没有 SSL_library_init();,它会在 BIO_should_retry 中崩溃,因为 bioNULL

关于c++ - 如何从 OpenSSL 释放 SSL 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21082917/

相关文章:

c++ - cloud9 c++开发环境如何添加c++库

c - 变量的范围。内部工作基础

c - 桥接两个文件描述符

java - 无法运行程序 "mvn"错误=2,没有这样的文件或目录

c# - 通过网络进行命令行控制

c++ - (第二学期 C++)(家庭作业)链表建议

c++ - 链表中的运算符重载 <<

c - malloc() 调用后双重释放或损坏(快速停止)

c - 为什么Linux内核中没有wait_event_..._irqsave()函数或宏?

linux - 使用 EC2 专用 AMI 的 Putty 出现 SSH 错误