diff --git a/Libraries/LibCrypto/OpenSSL.h b/Libraries/LibCrypto/OpenSSL.h index 3f344395aba..196f38c052d 100644 --- a/Libraries/LibCrypto/OpenSSL.h +++ b/Libraries/LibCrypto/OpenSSL.h @@ -40,100 +40,68 @@ namespace Crypto { _temporary_result; \ }) +#define OPENSSL_WRAPPER_CLASS(class_name, openssl_type, openssl_prefix) \ + AK_MAKE_NONCOPYABLE(class_name); \ + \ +public: \ + static ErrorOr wrap(openssl_type* ptr) \ + { \ + return class_name(OPENSSL_TRY_PTR(ptr)); \ + } \ + \ + ~class_name() \ + { \ + openssl_prefix##_free(m_ptr); \ + } \ + \ + class_name(class_name&& other) \ + : m_ptr(other.leak_ptr()) \ + { \ + } \ + \ + class_name& operator=(class_name&& other) \ + { \ + class_name ptr(move(other)); \ + swap(m_ptr, ptr.m_ptr); \ + return *this; \ + } \ + \ + openssl_type const* ptr() const { return m_ptr; } \ + openssl_type* ptr() { return m_ptr; } \ + \ +private: \ + [[nodiscard]] openssl_type* leak_ptr() \ + { \ + return exchange(m_ptr, nullptr); \ + } \ + \ + explicit class_name(openssl_type* ptr) \ + : m_ptr(ptr) \ + { \ + } \ + \ + openssl_type* m_ptr { nullptr }; + class OpenSSL_PKEY { - AK_MAKE_NONCOPYABLE(OpenSSL_PKEY); + OPENSSL_WRAPPER_CLASS(OpenSSL_PKEY, EVP_PKEY, EVP_PKEY); public: - static ErrorOr wrap(EVP_PKEY* ptr) - { - return OpenSSL_PKEY(OPENSSL_TRY_PTR(ptr)); - } - static ErrorOr create() { return OpenSSL_PKEY(OPENSSL_TRY_PTR(EVP_PKEY_new())); } - - ~OpenSSL_PKEY() - { - EVP_PKEY_free(m_ptr); - } - - OpenSSL_PKEY(OpenSSL_PKEY&& other) - : m_ptr(other.leak_ptr()) - { - } - - OpenSSL_PKEY& operator=(OpenSSL_PKEY&& other) - { - OpenSSL_PKEY ptr(move(other)); - swap(m_ptr, ptr.m_ptr); - return *this; - } - - EVP_PKEY const* ptr() const { return m_ptr; } - EVP_PKEY* ptr() { return m_ptr; } - -private: - [[nodiscard]] EVP_PKEY* leak_ptr() - { - return exchange(m_ptr, nullptr); - } - - explicit OpenSSL_PKEY(EVP_PKEY* ptr) - : m_ptr(ptr) - { - } - - EVP_PKEY* m_ptr { nullptr }; }; class OpenSSL_MD_CTX { - AK_MAKE_NONCOPYABLE(OpenSSL_MD_CTX); + OPENSSL_WRAPPER_CLASS(OpenSSL_MD_CTX, EVP_MD_CTX, EVP_MD_CTX); public: - static ErrorOr wrap(EVP_MD_CTX* ptr) - { - return OpenSSL_MD_CTX(OPENSSL_TRY_PTR(ptr)); - } - static ErrorOr create() { return OpenSSL_MD_CTX(OPENSSL_TRY_PTR(EVP_MD_CTX_new())); } - - OpenSSL_MD_CTX(OpenSSL_MD_CTX&& other) - : m_ptr(other.leak_ptr()) - { - } - - OpenSSL_MD_CTX& operator=(OpenSSL_MD_CTX&& other) - { - OpenSSL_MD_CTX ptr(move(other)); - swap(m_ptr, ptr.m_ptr); - return *this; - } - - ~OpenSSL_MD_CTX() - { - EVP_MD_CTX_free(m_ptr); - } - - EVP_MD_CTX const* ptr() const { return m_ptr; } - EVP_MD_CTX* ptr() { return m_ptr; } - -private: - [[nodiscard]] EVP_MD_CTX* leak_ptr() - { - return exchange(m_ptr, nullptr); - } - - explicit OpenSSL_MD_CTX(EVP_MD_CTX* ptr) - : m_ptr(ptr) - { - } - - EVP_MD_CTX* m_ptr { nullptr }; }; +#undef OPENSSL_WRAPPER_CLASS + }