|
| 1 | +/** |
| 2 | + * \file |
| 3 | + * \author Jakub Antonín Štigler <[email protected]> |
| 4 | + * \brief Wrapper around BIO from OpenSSL. (header file) |
| 5 | + * \date 2025 |
| 6 | + * |
| 7 | + * Copyright: (C) 2023 CESNET, z.s.p.o. |
| 8 | + * SPDX-License-Identifier: BSD-3-Clause |
| 9 | + */ |
| 10 | + |
| 11 | +#pragma once |
| 12 | + |
| 13 | +#include <memory> |
| 14 | + |
| 15 | +#include <openssl/bio.h> |
| 16 | + |
| 17 | +#include "../UniqueFd.hpp" |
| 18 | +#include "throw_ssl_err.hpp" |
| 19 | + |
| 20 | +namespace tcp_in { |
| 21 | +namespace tls { |
| 22 | + |
| 23 | +namespace dealloc { |
| 24 | + |
| 25 | +/** Deleter for `BIO` from OpenSSL. Can be used for example in `std::unique_ptr` */ |
| 26 | +class SslBio { |
| 27 | +public: |
| 28 | + void operator()(BIO *bio) { BIO_free(bio); } |
| 29 | +}; |
| 30 | + |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * @brief Wrapper around `BIO` from OpenSSL. |
| 35 | + * |
| 36 | + * This is basically extension of file descriptor used in OpenSSL. |
| 37 | + */ |
| 38 | +class SslBio : public std::unique_ptr<BIO, dealloc::SslBio> { |
| 39 | +public: |
| 40 | + /** Unique pointer of `BIO`. This is base class for `SslBio`. */ |
| 41 | + using SelfPtr = std::unique_ptr<BIO, dealloc::SslBio>; |
| 42 | + |
| 43 | + /** |
| 44 | + * @brief Construct `SslBio` by taking ownership of the given `BIO`. |
| 45 | + * @param bio Underlaying `BIO`. This will take ownership of it. |
| 46 | + * @throws If `bio` is `nullptr`. |
| 47 | + */ |
| 48 | + SslBio(BIO *bio) : SelfPtr(bio) { |
| 49 | + if (!get()) { |
| 50 | + throw_ssl_err("Failed to create bio."); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @brief Constructs new `SslBio` for the given `BIO_METHOD`. |
| 56 | + * @param method Method created for example by `BIO_s_socket()`. |
| 57 | + * @throws On failure. |
| 58 | + */ |
| 59 | + SslBio(const BIO_METHOD *method) : SslBio(BIO_new(method)) { } |
| 60 | + /** |
| 61 | + * @brief Construct `SslBio` server listening at the given port (and address). |
| 62 | + * @param host_port Port and optionally also address of the server. `[address:]port`. |
| 63 | + * @throws On failure. |
| 64 | + */ |
| 65 | + SslBio(const char *host_port) : SslBio(BIO_new_accept(host_port)) { } |
| 66 | + |
| 67 | + /** |
| 68 | + * @brief Set file descriptor of the bio. |
| 69 | + * @param fd File descriptor for the bio. This will NOT take ownership of the file descriptor. |
| 70 | + */ |
| 71 | + void set_fd(int fd) noexcept { BIO_set_fd(get(), fd, BIO_NOCLOSE); } |
| 72 | +}; |
| 73 | + |
| 74 | + |
| 75 | +} // namespace tls |
| 76 | +} // namespace tcp_in |
0 commit comments