Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr and OpenSSL's STACK_OF(X509)*

I use some using statements and unique_ptr to work with OpenSSL, as suggested in another question. Without, code becomes really ugly and I am not so much a fan of goto statements.

So far I have changed my code as far as possible. Here are examples, what I use:

using BIO_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>;
using X509_ptr = std::unique_ptr<X509, decltype(&::X509_free)>;
using EVP_PKEY_ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
using PKCS7_ptr = std::unique_ptr<PKCS7, decltype(&::PKCS7_free)>;
...

BIO_ptr tbio(BIO_new_file(some_filename, "r"), ::BIO_free);

Now I have the need of a STACK_OF(X509) and I do not know, if this is also possible with unique_ptr. I am looking for something similar to below, but this is not working.

using STACK_OF_X509_ptr = std::unique_ptr<STACK_OF(X509), decltype(&::sk_X509_free)>;

I also tried the Functor:

struct StackX509Deleter {
    void operator()(STACK_OF(X509) *ptr) {
        sk_X509_free(ptr);
    }
};

using STACK_OF_X509_ptr = std::unique_ptr<STACK_OF(X509), StackX509Deleter>;

STACK_OF_X509_ptr chain(loadIntermediate(cert.string()));

The compiler accepts this and the application runs. Just one question: In other unique_ptrs as shown above, I always had specified a second argument, so I bet I am missing something:

STACK_OF_X509_ptr chain(loadIntermediate(cert.string()),  ??????);

How do I use C++ unique_ptr and OpenSSL's STACK_OF(X509)*?

like image 645
Christian Rößner Avatar asked Jul 01 '16 12:07

Christian Rößner


1 Answers

I defined a regular function:

void stackOfX509Deleter(STACK_OF(X509) *ptr) {
    sk_X509_free(ptr);
}

Then I use it in my code:

using STACK_OF_X509_ptr = std::unique_ptr<STACK_OF(X509),
    decltype(&stackOfX509Deleter)>;

STACK_OF_X509_ptr chain(loadIntermediate(cert.string()),
                    stackOfX509Deleter);
like image 187
Christian Rößner Avatar answered Nov 17 '22 08:11

Christian Rößner