Net: add TLS client stream and SMTP submission (closes #48)
This commit is contained in:
1 parent
72148da7b2
commit
44686a4444
8 files changed
+2787
-1
No files matched your search
+872
@@ -0,0 +1,872 @@
|
||||
#include <Void/Net/Tls.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <openssl/x509v3.h>
|
||||
|
||||
#if !defined(_WIN32)
|
||||
#include <arpa/inet.h>
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
namespace
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
effective_timeout(std::chrono::milliseconds requested,
|
||||
std::chrono::milliseconds fallback) noexcept
|
||||
{
|
||||
return requested.count() > 0 ? requested : fallback;
|
||||
}
|
||||
|
||||
[[nodiscard]] Clock::time_point
|
||||
deadline_for(std::chrono::milliseconds timeout) noexcept
|
||||
{
|
||||
if (timeout.count() <= 0) {
|
||||
return Clock::time_point::max();
|
||||
}
|
||||
return Clock::now() + timeout;
|
||||
}
|
||||
|
||||
[[nodiscard]] int poll_timeout_ms(Clock::time_point deadline) noexcept
|
||||
{
|
||||
if (deadline == Clock::time_point::max()) {
|
||||
return -1;
|
||||
}
|
||||
const auto left = deadline - Clock::now();
|
||||
if (left <= Clock::duration::zero()) {
|
||||
return 0;
|
||||
}
|
||||
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(left);
|
||||
if (std::chrono::duration_cast<Clock::duration>(ms) < left) {
|
||||
ms += std::chrono::milliseconds{1};
|
||||
}
|
||||
return static_cast<int>(std::clamp<long long>(
|
||||
ms.count(), 0, std::numeric_limits<int>::max()));
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string openssl_error_text()
|
||||
{
|
||||
const unsigned long code = ERR_get_error();
|
||||
if (code == 0) {
|
||||
return "no OpenSSL error detail";
|
||||
}
|
||||
char buffer[256];
|
||||
ERR_error_string_n(code, buffer, sizeof(buffer));
|
||||
return std::string{buffer};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error
|
||||
cancelled_error(std::string_view operation)
|
||||
{
|
||||
return make_net_error(
|
||||
NetErrorCode::cancelled,
|
||||
std::format("Net: TLS {} cancelled", operation));
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error
|
||||
timeout_error(std::string_view operation)
|
||||
{
|
||||
return make_net_error(
|
||||
NetErrorCode::timeout,
|
||||
std::format("Net: TLS {} timed out", operation));
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
wait_fd(int fd, short events, Clock::time_point deadline,
|
||||
std::stop_token stop, std::string_view operation)
|
||||
{
|
||||
for (;;) {
|
||||
if (stop.stop_requested()) {
|
||||
return std::unexpected{cancelled_error(operation)};
|
||||
}
|
||||
pollfd descriptor{.fd = fd, .events = events, .revents = 0};
|
||||
int wait_ms = poll_timeout_ms(deadline);
|
||||
if (stop.stop_possible() &&
|
||||
(wait_ms < 0 || wait_ms > 50)) {
|
||||
// Keep cancellation latency bounded without closing the
|
||||
// stream; poll again after the slice.
|
||||
wait_ms = 50;
|
||||
}
|
||||
const int rc = ::poll(&descriptor, 1, wait_ms);
|
||||
if (rc < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TLS poll failed: {}",
|
||||
std::strerror(errno)))};
|
||||
}
|
||||
if (rc == 0) {
|
||||
if (Clock::now() >= deadline) {
|
||||
return std::unexpected{timeout_error(operation)};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if ((descriptor.revents & events) != 0 ||
|
||||
(descriptor.revents & (POLLHUP | POLLERR | POLLNVAL)) !=
|
||||
0) {
|
||||
// Let the caller perform the I/O and report the real
|
||||
// error; POLLHUP still delivers buffered data and EOF.
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<int>
|
||||
tcp_connect(const TlsClientOptions& options,
|
||||
Clock::time_point deadline)
|
||||
{
|
||||
if (options.host.empty() || options.port == 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net: TLS connect requires a host and port")};
|
||||
}
|
||||
addrinfo hints{};
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
addrinfo* addresses = nullptr;
|
||||
const std::string service = std::to_string(options.port);
|
||||
const int resolved =
|
||||
::getaddrinfo(options.host.c_str(), service.c_str(), &hints,
|
||||
&addresses);
|
||||
if (resolved != 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::connect_failed,
|
||||
std::format("Net: TLS resolve '{}': {}", options.host,
|
||||
gai_strerror(resolved)))};
|
||||
}
|
||||
std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> guard{
|
||||
addresses, &freeaddrinfo};
|
||||
|
||||
Void::Result::Error last = make_net_error(
|
||||
NetErrorCode::connect_failed,
|
||||
std::format("Net: TLS connect to '{}:{}' failed", options.host,
|
||||
options.port));
|
||||
for (addrinfo* address = addresses; address != nullptr;
|
||||
address = address->ai_next) {
|
||||
#ifdef SOCK_CLOEXEC
|
||||
const int fd =
|
||||
::socket(address->ai_family,
|
||||
address->ai_socktype | SOCK_CLOEXEC,
|
||||
address->ai_protocol);
|
||||
#else
|
||||
const int fd =
|
||||
::socket(address->ai_family, address->ai_socktype,
|
||||
address->ai_protocol);
|
||||
#endif
|
||||
if (fd < 0) {
|
||||
continue;
|
||||
}
|
||||
const int flags = ::fcntl(fd, F_GETFL, 0);
|
||||
if (flags < 0 ||
|
||||
::fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
|
||||
::close(fd);
|
||||
continue;
|
||||
}
|
||||
if (::connect(fd, address->ai_addr, address->ai_addrlen) ==
|
||||
0) {
|
||||
return fd;
|
||||
}
|
||||
if (errno != EINPROGRESS && errno != EINTR) {
|
||||
last = make_net_error(
|
||||
NetErrorCode::connect_failed,
|
||||
std::format("Net: TLS connect failed: {}",
|
||||
std::strerror(errno)));
|
||||
::close(fd);
|
||||
continue;
|
||||
}
|
||||
const auto waited =
|
||||
wait_fd(fd, POLLOUT, deadline, options.stop, "connect");
|
||||
if (!waited.has_value()) {
|
||||
::close(fd);
|
||||
return std::unexpected{std::move(waited.error())};
|
||||
}
|
||||
int socket_error = 0;
|
||||
socklen_t length = sizeof(socket_error);
|
||||
if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error,
|
||||
&length) != 0 ||
|
||||
socket_error != 0) {
|
||||
const int code =
|
||||
socket_error != 0 ? socket_error : errno;
|
||||
last = make_net_error(
|
||||
NetErrorCode::connect_failed,
|
||||
std::format("Net: TLS connect failed: {}",
|
||||
std::strerror(code)));
|
||||
::close(fd);
|
||||
continue;
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
return std::unexpected{std::move(last)};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_ip_literal(std::string_view host) noexcept
|
||||
{
|
||||
std::string text{host};
|
||||
if (text.size() >= 2 && text.front() == '[' &&
|
||||
text.back() == ']') {
|
||||
text = text.substr(1, text.size() - 2);
|
||||
}
|
||||
unsigned char storage[sizeof(in6_addr)]{};
|
||||
return ::inet_pton(AF_INET, text.c_str(), storage) == 1 ||
|
||||
::inet_pton(AF_INET6, text.c_str(), storage) == 1;
|
||||
}
|
||||
[[nodiscard]] std::string
|
||||
verification_name(const TlsClientOptions& options)
|
||||
{
|
||||
std::string name = options.server_name.empty() ? options.host
|
||||
: options.server_name;
|
||||
if (name.size() >= 2 && name.front() == '[' &&
|
||||
name.back() == ']') {
|
||||
name = name.substr(1, name.size() - 2);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
#endif
|
||||
} // namespace
|
||||
|
||||
struct TlsClientStream::Impl {
|
||||
int fd{-1};
|
||||
SSL_CTX* ctx{nullptr};
|
||||
SSL* ssl{nullptr};
|
||||
bool secure{false};
|
||||
std::chrono::milliseconds io_timeout{
|
||||
std::chrono::seconds{30}};
|
||||
std::chrono::milliseconds handshake_timeout{
|
||||
std::chrono::seconds{10}};
|
||||
std::stop_token stop{};
|
||||
std::string server_name{};
|
||||
std::string ca_file{};
|
||||
|
||||
~Impl() noexcept { close_all(); }
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept { return fd >= 0; }
|
||||
|
||||
void close_all() noexcept
|
||||
{
|
||||
if (ssl != nullptr) {
|
||||
SSL_free(ssl);
|
||||
ssl = nullptr;
|
||||
}
|
||||
if (ctx != nullptr) {
|
||||
SSL_CTX_free(ctx);
|
||||
ctx = nullptr;
|
||||
}
|
||||
#if !defined(_WIN32)
|
||||
if (fd >= 0) {
|
||||
(void)::shutdown(fd, SHUT_RDWR);
|
||||
(void)::close(fd);
|
||||
}
|
||||
#endif
|
||||
fd = -1;
|
||||
secure = false;
|
||||
}
|
||||
};
|
||||
|
||||
TlsClientStream::TlsClientStream() noexcept = default;
|
||||
TlsClientStream::TlsClientStream(std::unique_ptr<Impl> impl) noexcept
|
||||
: m_impl(std::move(impl))
|
||||
{
|
||||
}
|
||||
TlsClientStream::~TlsClientStream() noexcept = default;
|
||||
TlsClientStream::TlsClientStream(TlsClientStream&&) noexcept = default;
|
||||
TlsClientStream&
|
||||
TlsClientStream::operator=(TlsClientStream&&) noexcept = default;
|
||||
|
||||
bool TlsClientStream::valid() const noexcept
|
||||
{
|
||||
return m_impl != nullptr && m_impl->valid();
|
||||
}
|
||||
|
||||
bool TlsClientStream::secure() const noexcept
|
||||
{
|
||||
return m_impl != nullptr && m_impl->secure;
|
||||
}
|
||||
|
||||
int TlsClientStream::native_handle() const noexcept
|
||||
{
|
||||
return m_impl != nullptr ? m_impl->fd : -1;
|
||||
}
|
||||
|
||||
#if defined(_WIN32)
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::connect(TlsClientOptions)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TlsClientStream is not implemented on Windows")};
|
||||
}
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::connect_plain(TlsClientOptions)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TlsClientStream is not implemented on Windows")};
|
||||
}
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::adopt(int, TlsClientOptions)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TlsClientStream is not implemented on Windows")};
|
||||
}
|
||||
Void::Result::Result<void> TlsClientStream::start_tls()
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TlsClientStream is not implemented on Windows")};
|
||||
}
|
||||
Void::Result::Result<std::size_t>
|
||||
TlsClientStream::read(std::span<std::byte>, std::chrono::milliseconds,
|
||||
std::stop_token)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
Void::Result::Result<std::size_t>
|
||||
TlsClientStream::write(std::span<const std::byte>,
|
||||
std::chrono::milliseconds, std::stop_token)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
Void::Result::Result<void>
|
||||
TlsClientStream::write_all(std::span<const std::byte>,
|
||||
std::chrono::milliseconds, std::stop_token)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
Void::Result::Result<void>
|
||||
TlsClientStream::write_all(std::string_view, std::chrono::milliseconds,
|
||||
std::stop_token)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
Void::Result::Result<void> TlsClientStream::shutdown()
|
||||
{
|
||||
if (m_impl != nullptr) {
|
||||
m_impl->close_all();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
void TlsClientStream::close() noexcept
|
||||
{
|
||||
if (m_impl != nullptr) {
|
||||
m_impl->close_all();
|
||||
}
|
||||
}
|
||||
#else
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::connect(TlsClientOptions options)
|
||||
{
|
||||
const auto timeout =
|
||||
effective_timeout(options.connect_timeout,
|
||||
std::chrono::seconds{10});
|
||||
auto fd = tcp_connect(options, deadline_for(timeout));
|
||||
if (!fd.has_value()) {
|
||||
return std::unexpected{std::move(fd.error())};
|
||||
}
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->fd = *fd;
|
||||
impl->io_timeout = options.io_timeout;
|
||||
impl->handshake_timeout = options.handshake_timeout;
|
||||
impl->stop = options.stop;
|
||||
impl->server_name = verification_name(options);
|
||||
impl->ca_file = std::move(options.ca_file);
|
||||
TlsClientStream stream{std::move(impl)};
|
||||
auto started = stream.start_tls();
|
||||
if (!started.has_value()) {
|
||||
return std::unexpected{std::move(started.error())};
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::connect_plain(TlsClientOptions options)
|
||||
{
|
||||
const auto timeout =
|
||||
effective_timeout(options.connect_timeout,
|
||||
std::chrono::seconds{10});
|
||||
auto fd = tcp_connect(options, deadline_for(timeout));
|
||||
if (!fd.has_value()) {
|
||||
return std::unexpected{std::move(fd.error())};
|
||||
}
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->fd = *fd;
|
||||
impl->io_timeout = options.io_timeout;
|
||||
impl->handshake_timeout = options.handshake_timeout;
|
||||
impl->stop = options.stop;
|
||||
impl->server_name = verification_name(options);
|
||||
impl->ca_file = std::move(options.ca_file);
|
||||
return TlsClientStream{std::move(impl)};
|
||||
}
|
||||
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::adopt(int native_socket, TlsClientOptions options)
|
||||
{
|
||||
if (native_socket < 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net: TLS adopt requires an open socket")};
|
||||
}
|
||||
const int flags = ::fcntl(native_socket, F_GETFL, 0);
|
||||
if (flags < 0 ||
|
||||
::fcntl(native_socket, F_SETFL, flags | O_NONBLOCK) < 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TLS adopt failed to configure socket: {}",
|
||||
std::strerror(errno)))};
|
||||
}
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->fd = native_socket;
|
||||
impl->io_timeout = options.io_timeout;
|
||||
impl->handshake_timeout = options.handshake_timeout;
|
||||
impl->stop = options.stop;
|
||||
impl->server_name = verification_name(options);
|
||||
impl->ca_file = std::move(options.ca_file);
|
||||
TlsClientStream stream{std::move(impl)};
|
||||
auto started = stream.start_tls();
|
||||
if (!started.has_value()) {
|
||||
return std::unexpected{std::move(started.error())};
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
Void::Result::Result<void> TlsClientStream::start_tls()
|
||||
{
|
||||
if (m_impl == nullptr || !m_impl->valid()) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
auto& impl = *m_impl;
|
||||
if (impl.secure) {
|
||||
return {};
|
||||
}
|
||||
if (impl.ctx != nullptr || impl.ssl != nullptr) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net: TLS handshake already attempted")};
|
||||
}
|
||||
|
||||
impl.ctx = SSL_CTX_new(TLS_client_method());
|
||||
if (impl.ctx == nullptr) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS failed to create context: " +
|
||||
openssl_error_text())};
|
||||
}
|
||||
if (SSL_CTX_set_min_proto_version(impl.ctx, TLS1_2_VERSION) != 1) {
|
||||
const auto error = make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS failed to require TLS 1.2: " + openssl_error_text());
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
SSL_CTX_set_verify(impl.ctx, SSL_VERIFY_PEER, nullptr);
|
||||
// The trust store is always applied; a failure is fatal and never
|
||||
// downgrades verification.
|
||||
const int loaded =
|
||||
impl.ca_file.empty()
|
||||
? SSL_CTX_set_default_verify_paths(impl.ctx)
|
||||
: SSL_CTX_load_verify_locations(impl.ctx,
|
||||
impl.ca_file.c_str(), nullptr);
|
||||
if (loaded != 1) {
|
||||
const auto error = make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
std::format("Net: TLS failed to load trust store{}: {}",
|
||||
impl.ca_file.empty()
|
||||
? std::string{}
|
||||
: " '" + impl.ca_file + "'",
|
||||
openssl_error_text()));
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
|
||||
impl.ssl = SSL_new(impl.ctx);
|
||||
if (impl.ssl == nullptr) {
|
||||
const auto error = make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS failed to create session: " +
|
||||
openssl_error_text());
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
if (SSL_set_fd(impl.ssl, impl.fd) != 1) {
|
||||
const auto error = make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS failed to attach socket: " +
|
||||
openssl_error_text());
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
(void)SSL_set_mode(impl.ssl,
|
||||
SSL_MODE_ENABLE_PARTIAL_WRITE |
|
||||
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
|
||||
if (!is_ip_literal(impl.server_name) &&
|
||||
SSL_set_tlsext_host_name(impl.ssl,
|
||||
impl.server_name.c_str()) != 1) {
|
||||
const auto error = make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS failed to set SNI hostname: " +
|
||||
openssl_error_text());
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
X509_VERIFY_PARAM* param = SSL_get0_param(impl.ssl);
|
||||
if (param == nullptr) {
|
||||
const auto error = make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS X509 verification parameters unavailable");
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
X509_VERIFY_PARAM_set_hostflags(param,
|
||||
X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
|
||||
const int set_name =
|
||||
is_ip_literal(impl.server_name)
|
||||
? X509_VERIFY_PARAM_set1_ip_asc(param,
|
||||
impl.server_name.c_str())
|
||||
: X509_VERIFY_PARAM_set1_host(param,
|
||||
impl.server_name.c_str(),
|
||||
impl.server_name.size());
|
||||
if (set_name != 1) {
|
||||
const auto error = make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS failed to set peer verification target");
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
|
||||
const auto deadline =
|
||||
deadline_for(effective_timeout({}, impl.handshake_timeout));
|
||||
for (;;) {
|
||||
if (impl.stop.stop_requested()) {
|
||||
const auto error = cancelled_error("handshake");
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
ERR_clear_error();
|
||||
const int rc = SSL_connect(impl.ssl);
|
||||
if (rc == 1) {
|
||||
break;
|
||||
}
|
||||
const int error_code = SSL_get_error(impl.ssl, rc);
|
||||
if (error_code == SSL_ERROR_WANT_READ ||
|
||||
error_code == SSL_ERROR_WANT_WRITE) {
|
||||
const auto waited = wait_fd(
|
||||
impl.fd,
|
||||
error_code == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT,
|
||||
deadline, impl.stop, "handshake");
|
||||
if (!waited.has_value()) {
|
||||
const auto error = waited.error();
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (error_code == SSL_ERROR_SYSCALL && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
const long verify = SSL_get_verify_result(impl.ssl);
|
||||
std::string detail = openssl_error_text();
|
||||
if (verify != X509_V_OK) {
|
||||
detail += std::format(" (certificate verify: {})",
|
||||
X509_verify_cert_error_string(verify));
|
||||
}
|
||||
const auto error = make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS handshake failed: " + detail);
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
const long verify = SSL_get_verify_result(impl.ssl);
|
||||
if (verify != X509_V_OK) {
|
||||
const auto error = make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
std::format("Net: TLS peer verification failed: {}",
|
||||
X509_verify_cert_error_string(verify)));
|
||||
impl.close_all();
|
||||
return std::unexpected{error};
|
||||
}
|
||||
impl.secure = true;
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t>
|
||||
TlsClientStream::read(std::span<std::byte> destination,
|
||||
std::chrono::milliseconds timeout,
|
||||
std::stop_token stop)
|
||||
{
|
||||
if (m_impl == nullptr || !m_impl->valid()) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
if (destination.empty()) {
|
||||
return 0;
|
||||
}
|
||||
auto& impl = *m_impl;
|
||||
const auto deadline =
|
||||
deadline_for(effective_timeout(timeout, impl.io_timeout));
|
||||
const std::stop_token token =
|
||||
stop.stop_possible() ? stop : impl.stop;
|
||||
for (;;) {
|
||||
if (token.stop_requested()) {
|
||||
return std::unexpected{cancelled_error("read")};
|
||||
}
|
||||
if (impl.secure) {
|
||||
ERR_clear_error();
|
||||
const int rc = SSL_read(
|
||||
impl.ssl, destination.data(),
|
||||
static_cast<int>(std::min<std::size_t>(
|
||||
destination.size(),
|
||||
static_cast<std::size_t>(INT_MAX))));
|
||||
if (rc > 0) {
|
||||
return static_cast<std::size_t>(rc);
|
||||
}
|
||||
const int error_code = SSL_get_error(impl.ssl, rc);
|
||||
if (error_code == SSL_ERROR_WANT_READ ||
|
||||
error_code == SSL_ERROR_WANT_WRITE) {
|
||||
auto waited = wait_fd(
|
||||
impl.fd,
|
||||
error_code == SSL_ERROR_WANT_READ ? POLLIN
|
||||
: POLLOUT,
|
||||
deadline, token, "read");
|
||||
if (!waited.has_value()) {
|
||||
return std::unexpected{std::move(waited.error())};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (error_code == SSL_ERROR_ZERO_RETURN) {
|
||||
return 0;
|
||||
}
|
||||
if (error_code == SSL_ERROR_SYSCALL) {
|
||||
if (errno == EINTR || errno == EAGAIN ||
|
||||
errno == EWOULDBLOCK) {
|
||||
continue;
|
||||
}
|
||||
if (rc == 0) {
|
||||
return 0;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TLS read failed: {}",
|
||||
std::strerror(errno)))};
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS read failed: " + openssl_error_text())};
|
||||
}
|
||||
const ssize_t rc = ::recv(impl.fd, destination.data(),
|
||||
destination.size(), 0);
|
||||
if (rc > 0) {
|
||||
return static_cast<std::size_t>(rc);
|
||||
}
|
||||
if (rc == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
auto waited = wait_fd(impl.fd, POLLIN, deadline, token,
|
||||
"read");
|
||||
if (!waited.has_value()) {
|
||||
return std::unexpected{std::move(waited.error())};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TCP read failed: {}",
|
||||
std::strerror(errno)))};
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t>
|
||||
TlsClientStream::write(std::span<const std::byte> source,
|
||||
std::chrono::milliseconds timeout,
|
||||
std::stop_token stop)
|
||||
{
|
||||
if (m_impl == nullptr || !m_impl->valid()) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
if (source.empty()) {
|
||||
return 0;
|
||||
}
|
||||
auto& impl = *m_impl;
|
||||
const auto deadline =
|
||||
deadline_for(effective_timeout(timeout, impl.io_timeout));
|
||||
const std::stop_token token =
|
||||
stop.stop_possible() ? stop : impl.stop;
|
||||
for (;;) {
|
||||
if (token.stop_requested()) {
|
||||
return std::unexpected{cancelled_error("write")};
|
||||
}
|
||||
if (impl.secure) {
|
||||
ERR_clear_error();
|
||||
const int rc = SSL_write(
|
||||
impl.ssl, source.data(),
|
||||
static_cast<int>(std::min<std::size_t>(
|
||||
source.size(),
|
||||
static_cast<std::size_t>(INT_MAX))));
|
||||
if (rc > 0) {
|
||||
return static_cast<std::size_t>(rc);
|
||||
}
|
||||
const int error_code = SSL_get_error(impl.ssl, rc);
|
||||
if (error_code == SSL_ERROR_WANT_READ ||
|
||||
error_code == SSL_ERROR_WANT_WRITE) {
|
||||
auto waited = wait_fd(
|
||||
impl.fd,
|
||||
error_code == SSL_ERROR_WANT_READ ? POLLIN
|
||||
: POLLOUT,
|
||||
deadline, token, "write");
|
||||
if (!waited.has_value()) {
|
||||
return std::unexpected{std::move(waited.error())};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (error_code == SSL_ERROR_SYSCALL) {
|
||||
if (errno == EINTR || errno == EAGAIN ||
|
||||
errno == EWOULDBLOCK) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TLS write failed: {}",
|
||||
std::strerror(errno)))};
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS write failed: " + openssl_error_text())};
|
||||
}
|
||||
#ifdef MSG_NOSIGNAL
|
||||
constexpr int flags = MSG_NOSIGNAL;
|
||||
#else
|
||||
constexpr int flags = 0;
|
||||
#endif
|
||||
const ssize_t rc =
|
||||
::send(impl.fd, source.data(), source.size(), flags);
|
||||
if (rc > 0) {
|
||||
return static_cast<std::size_t>(rc);
|
||||
}
|
||||
if (rc < 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (rc < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
|
||||
auto waited = wait_fd(impl.fd, POLLOUT, deadline, token,
|
||||
"write");
|
||||
if (!waited.has_value()) {
|
||||
return std::unexpected{std::move(waited.error())};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TCP write failed: {}",
|
||||
std::strerror(errno)))};
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
TlsClientStream::write_all(std::span<const std::byte> source,
|
||||
std::chrono::milliseconds timeout,
|
||||
std::stop_token stop)
|
||||
{
|
||||
while (!source.empty()) {
|
||||
auto written = write(source, timeout, stop);
|
||||
if (!written.has_value()) {
|
||||
return std::unexpected{std::move(written.error())};
|
||||
}
|
||||
if (*written == 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
"Net: TLS write made no progress")};
|
||||
}
|
||||
source = source.subspan(*written);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
TlsClientStream::write_all(std::string_view text,
|
||||
std::chrono::milliseconds timeout,
|
||||
std::stop_token stop)
|
||||
{
|
||||
return write_all(
|
||||
std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(text.data()),
|
||||
text.size()},
|
||||
timeout, stop);
|
||||
}
|
||||
|
||||
Void::Result::Result<void> TlsClientStream::shutdown()
|
||||
{
|
||||
if (m_impl == nullptr) {
|
||||
return {};
|
||||
}
|
||||
auto& impl = *m_impl;
|
||||
Void::Result::Result<void> result{};
|
||||
if (impl.secure && impl.ssl != nullptr) {
|
||||
const auto deadline =
|
||||
deadline_for(effective_timeout({}, impl.io_timeout));
|
||||
for (;;) {
|
||||
ERR_clear_error();
|
||||
const int rc = SSL_shutdown(impl.ssl);
|
||||
if (rc >= 0) {
|
||||
break;
|
||||
}
|
||||
const int error_code = SSL_get_error(impl.ssl, rc);
|
||||
if (error_code == SSL_ERROR_WANT_READ ||
|
||||
error_code == SSL_ERROR_WANT_WRITE) {
|
||||
auto waited = wait_fd(
|
||||
impl.fd,
|
||||
error_code == SSL_ERROR_WANT_READ ? POLLIN
|
||||
: POLLOUT,
|
||||
deadline, impl.stop, "shutdown");
|
||||
if (!waited.has_value()) {
|
||||
result = std::unexpected{
|
||||
std::move(waited.error())};
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
impl.close_all();
|
||||
return result;
|
||||
}
|
||||
|
||||
void TlsClientStream::close() noexcept
|
||||
{
|
||||
if (m_impl != nullptr) {
|
||||
m_impl->close_all();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
} // namespace Void::Net
|
||||
Reference in new issue
Block a user