Merge issue-48-tls-smtp: TLS client stream and SMTP submission (closes #48)

This commit is contained in:
faumaray committed 2026-12-03 16:39:02 +03:00
commit d51dd171ef
8 files changed
+2787 -1

No files matched your search

+11 -1
View File
@@ -31,7 +31,10 @@ namespace Void::Net
io_error = 9,
redirect_blocked = 10,
payload_too_large = 11,
headers_too_large = 12
headers_too_large = 12,
smtp_rejected = 13,
auth_failed = 14,
tls_required = 15
};
[[nodiscard]] inline Void::Result::Error
@@ -71,6 +74,13 @@ namespace Void::Net
case NetErrorCode::headers_too_large:
kind = ErrorKind::exhausted;
break;
case NetErrorCode::smtp_rejected:
case NetErrorCode::auth_failed:
kind = ErrorKind::conflict;
break;
case NetErrorCode::tls_required:
kind = ErrorKind::invalid_argument;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kNetErrorDomain,
+112
View File
@@ -0,0 +1,112 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Net
{
enum class SmtpSecurity {
/// TLS from the first byte (typically port 465).
implicit_tls,
/// Plaintext greeting/EHLO, then a required STARTTLS upgrade
/// (typically port 587 or 25).
starttls_required,
};
struct SmtpCredentials {
std::string username{};
std::string password{};
};
struct SmtpLimits {
/// Maximum raw message body accepted by `send()`.
std::uint64_t max_message_bytes{10ULL * 1024ULL * 1024ULL};
/// Maximum bytes in one complete (possibly multi-line) reply.
std::uint64_t max_response_bytes{64ULL * 1024ULL};
/// Maximum bytes in one reply line.
std::size_t max_line_bytes{4096};
/// Maximum recipients accepted by `send()`.
std::size_t max_recipients{100};
};
struct SmtpOptions {
std::string host{};
std::uint16_t port{587};
SmtpSecurity security{SmtpSecurity::starttls_required};
/// Identity verified against the server certificate; defaults
/// to `host`. Peer and hostname verification are always on.
std::string server_name{};
/// PEM trust store; empty uses the system default store.
std::string ca_file{};
/// Credentials are sent with AUTH PLAIN and only over TLS.
std::optional<SmtpCredentials> credentials{};
/// Name announced in EHLO.
std::string client_domain{"localhost"};
std::chrono::milliseconds connect_timeout{
std::chrono::seconds{10}};
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
SmtpLimits limits{};
std::stop_token stop{};
};
struct SmtpMessage {
std::string from{};
std::vector<std::string> recipients{};
std::string data{};
};
/// Synchronous SMTP submission client over a verified TLS connection.
///
/// Supports implicit TLS and STARTTLS-required dialogue, AUTH PLAIN
/// (TLS only), MAIL/RCPT/DATA with CRLF normalization and dot-stuffing,
/// bounded replies, bounded message size, deadlines, and cancellation.
/// A failed send invalidates the client.
class SmtpClient final
{
public:
SmtpClient() noexcept;
~SmtpClient() noexcept;
SmtpClient(SmtpClient&&) noexcept;
SmtpClient& operator=(SmtpClient&&) noexcept;
SmtpClient(const SmtpClient&) = delete;
SmtpClient& operator=(const SmtpClient&) = delete;
/// Connect, greet, negotiate TLS (when required), authenticate
/// (when credentials are configured), and prepare submission.
[[nodiscard]] static Void::Result::Result<SmtpClient>
connect(SmtpOptions options);
/// Convenience: connect, send one message, then QUIT.
[[nodiscard]] static Void::Result::Result<void>
submit(SmtpOptions options, const SmtpMessage& message);
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool secure() const noexcept;
[[nodiscard]] Void::Result::Result<void>
send(const SmtpMessage& message);
/// Send QUIT (best effort) and close the connection.
[[nodiscard]] Void::Result::Result<void> quit();
void close() noexcept;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit SmtpClient(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::Net
+117
View File
@@ -0,0 +1,117 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
namespace Void::Net
{
/// Options for a verified TLS client stream.
///
/// Peer and hostname verification are always enabled; there is no
/// insecure mode and no fallback to plaintext when the handshake fails.
/// `server_name` is the identity checked against the peer certificate
/// (and sent as SNI when it is a DNS name); it defaults to `host`.
/// `ca_file` selects an explicit PEM trust store; when empty the system
/// default trust store is used.
struct TlsClientOptions {
std::string host{};
std::uint16_t port{443};
std::string server_name{};
std::string ca_file{};
std::chrono::milliseconds connect_timeout{
std::chrono::seconds{10}};
std::chrono::milliseconds handshake_timeout{
std::chrono::seconds{10}};
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
std::stop_token stop{};
};
/// Synchronous TLS client stream over a TCP socket (POSIX, OpenSSL).
///
/// `connect()` establishes TCP and completes a verified TLS handshake.
/// `connect_plain()` establishes TCP only, for protocols that negotiate
/// TLS in-band (SMTP STARTTLS, IMAP STARTTLS, ...); call `start_tls()`
/// after the plaintext negotiation. A failed `start_tls()` closes the
/// stream, so a caller can never continue on an unauthenticated channel.
///
/// Reads and writes accept an optional per-operation timeout (zero uses
/// `TlsClientOptions::io_timeout`) and an optional stop token (empty uses
/// `TlsClientOptions::stop`). Timeouts and cancellation interrupt the
/// operation without closing the stream.
class TlsClientStream final
{
public:
TlsClientStream() noexcept;
~TlsClientStream() noexcept;
TlsClientStream(TlsClientStream&&) noexcept;
TlsClientStream& operator=(TlsClientStream&&) noexcept;
TlsClientStream(const TlsClientStream&) = delete;
TlsClientStream& operator=(const TlsClientStream&) = delete;
/// Resolve, connect, and complete a verified TLS handshake.
[[nodiscard]] static Void::Result::Result<TlsClientStream>
connect(TlsClientOptions options);
/// Connect TCP without starting TLS (STARTTLS plaintext phase).
[[nodiscard]] static Void::Result::Result<TlsClientStream>
connect_plain(TlsClientOptions options);
/// Take ownership of an already connected socket and start TLS
/// immediately. `native_socket` must be a connected TCP socket.
[[nodiscard]] static Void::Result::Result<TlsClientStream>
adopt(int native_socket, TlsClientOptions options);
/// Complete the verified TLS handshake on a stream created by
/// `connect_plain()` (or a plaintext `adopt()`). On failure the
/// stream is closed and `valid()` becomes false.
[[nodiscard]] Void::Result::Result<void> start_tls();
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool secure() const noexcept;
[[nodiscard]] int native_handle() const noexcept;
/// Read up to `destination.size()` bytes. Returns 0 on orderly EOF.
[[nodiscard]] Void::Result::Result<std::size_t>
read(std::span<std::byte> destination,
std::chrono::milliseconds timeout = {},
std::stop_token stop = {});
/// Write up to `source.size()` bytes (a positive result may be a
/// partial write).
[[nodiscard]] Void::Result::Result<std::size_t>
write(std::span<const std::byte> source,
std::chrono::milliseconds timeout = {},
std::stop_token stop = {});
/// Write every byte, retrying partial writes.
[[nodiscard]] Void::Result::Result<void>
write_all(std::span<const std::byte> source,
std::chrono::milliseconds timeout = {},
std::stop_token stop = {});
[[nodiscard]] Void::Result::Result<void>
write_all(std::string_view text,
std::chrono::milliseconds timeout = {},
std::stop_token stop = {});
/// Send TLS close_notify (best effort) and close the socket.
[[nodiscard]] Void::Result::Result<void> shutdown();
void close() noexcept;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit TlsClientStream(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::Net
+635
View File
@@ -0,0 +1,635 @@
#include <Void/Net/Smtp.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Tls.hpp>
#include <Void/Text/Base64.hpp>
#include <algorithm>
#include <array>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <format>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Net
{
namespace
{
[[nodiscard]] std::string upper_ascii(std::string_view text)
{
std::string out{text};
for (char& c : out) {
c = static_cast<char>(
std::toupper(static_cast<unsigned char>(c)));
}
return out;
}
[[nodiscard]] std::string_view trimmed(std::string_view text) noexcept
{
constexpr std::string_view whitespace = " \t\r\n";
const std::size_t begin = text.find_first_not_of(whitespace);
if (begin == std::string_view::npos) {
return {};
}
const std::size_t end = text.find_last_not_of(whitespace);
return text.substr(begin, end - begin + 1);
}
[[nodiscard]] bool has_control(std::string_view text) noexcept
{
return std::ranges::any_of(text, [](char c) {
const auto value = static_cast<unsigned char>(c);
return value < 0x20U || value == 0x7FU;
});
}
[[nodiscard]] Void::Result::Result<void>
validate_address(std::string_view field, std::string_view value)
{
if (value.empty()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
std::format("SMTP: {} must not be empty", field))};
}
if (has_control(value) || value.find('<') != std::string_view::npos ||
value.find('>') != std::string_view::npos) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
std::format("SMTP: {} contains invalid characters",
field))};
}
return {};
}
struct SmtpReply {
int code{0};
std::vector<std::string> lines{};
};
[[nodiscard]] std::string
reply_summary(const SmtpReply& reply)
{
if (reply.lines.empty()) {
return std::to_string(reply.code);
}
return std::format("{} {}", reply.code, reply.lines.front());
}
[[nodiscard]] Void::Result::Error
rejected_error(std::string_view context,
const SmtpReply& reply)
{
return make_net_error(
NetErrorCode::smtp_rejected,
std::format("SMTP: {} rejected: {}", context,
reply_summary(reply)));
}
[[nodiscard]] std::string encode_data(std::string_view data)
{
std::string out;
out.reserve(data.size() + data.size() / 16U + 8U);
bool line_start = true;
for (std::size_t i = 0; i < data.size(); ++i) {
const char c = data[i];
if (line_start && c == '.') {
out.push_back('.');
}
if (c == '\r') {
if (i + 1U < data.size() && data[i + 1U] == '\n') {
++i;
}
out += "\r\n";
line_start = true;
continue;
}
if (c == '\n') {
out += "\r\n";
line_start = true;
continue;
}
out.push_back(c);
line_start = false;
}
if (!line_start) {
out += "\r\n";
}
out += ".\r\n";
return out;
}
} // namespace
struct SmtpClient::Impl {
TlsClientStream stream;
SmtpOptions options;
std::string pending{};
std::vector<std::string> capabilities{};
Impl(TlsClientStream s, SmtpOptions o)
: stream(std::move(s)), options(std::move(o))
{
}
[[nodiscard]] Void::Result::Result<std::string> read_line()
{
for (;;) {
const std::size_t end = pending.find("\r\n");
if (end != std::string::npos) {
std::string line = pending.substr(0, end);
pending.erase(0, end + 2U);
if (line.size() >
options.limits.max_line_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
std::format("SMTP: reply line exceeds {} "
"bytes",
options.limits
.max_line_bytes))};
}
return line;
}
if (pending.size() >
options.limits.max_line_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: reply line too long")};
}
std::array<std::byte, 1024> chunk{};
auto count = stream.read(chunk, options.io_timeout,
options.stop);
if (!count.has_value()) {
return std::unexpected{
std::move(count.error())};
}
if (*count == 0) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: server closed the connection")};
}
pending.append(
reinterpret_cast<const char*>(chunk.data()),
*count);
}
}
[[nodiscard]] Void::Result::Result<SmtpReply> read_reply()
{
SmtpReply reply;
std::uint64_t total = 0;
for (;;) {
auto line = read_line();
if (!line.has_value()) {
return std::unexpected{
std::move(line.error())};
}
total += line->size() + 2U;
if (total >
options.limits.max_response_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
std::format("SMTP: reply exceeds {} bytes",
options.limits
.max_response_bytes))};
}
if (line->size() < 3U) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: malformed reply")};
}
int code = 0;
const char* begin = line->data();
const char* finish = begin + 3;
const auto parsed =
std::from_chars(begin, finish, code);
if (parsed.ec != std::errc{} ||
parsed.ptr != finish || code < 100 ||
code > 599) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: malformed reply code")};
}
const char separator =
line->size() > 3U ? (*line)[3] : ' ';
if (separator != '-' && separator != ' ') {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: malformed reply separator")};
}
if (!reply.lines.empty() &&
reply.code != code) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"SMTP: inconsistent multi-line reply")};
}
reply.code = code;
reply.lines.push_back(
line->size() > 4U ? line->substr(4)
: std::string{});
if (separator == ' ') {
return reply;
}
}
}
[[nodiscard]] Void::Result::Result<void>
command(std::string_view line)
{
std::string wire{line};
wire += "\r\n";
return stream.write_all(wire, options.io_timeout,
options.stop);
}
[[nodiscard]] Void::Result::Result<SmtpReply>
command_reply(std::string_view line)
{
auto sent = command(line);
if (!sent.has_value()) {
return std::unexpected{std::move(sent.error())};
}
return read_reply();
}
[[nodiscard]] bool
has_capability(std::string_view name) const
{
const std::string wanted = upper_ascii(name);
return std::ranges::any_of(
capabilities, [&](const std::string& capability) {
return capability == wanted ||
capability.starts_with(wanted + " ") ||
capability.starts_with(wanted + "=");
});
}
[[nodiscard]] bool auth_plain_supported() const
{
for (const auto& capability : capabilities) {
if (!capability.starts_with("AUTH ") &&
!capability.starts_with("AUTH=")) {
continue;
}
std::string mechanisms = capability.substr(5);
std::ranges::replace(mechanisms, '=', ' ');
std::size_t begin = 0;
while (begin < mechanisms.size()) {
const std::size_t end =
mechanisms.find(' ', begin);
const std::string_view mechanism{
mechanisms.data() + begin,
(end == std::string::npos ? mechanisms.size()
: end) -
begin};
if (mechanism == "PLAIN") {
return true;
}
if (end == std::string::npos) {
break;
}
begin = end + 1U;
}
}
return false;
}
[[nodiscard]] std::optional<std::uint64_t>
server_size_limit() const
{
for (const auto& capability : capabilities) {
if (!capability.starts_with("SIZE")) {
continue;
}
if (capability.size() == 4U) {
return std::nullopt;
}
if (capability[4] != ' ') {
continue;
}
std::uint64_t limit = 0;
const char* begin = capability.data() + 5;
const char* end =
capability.data() + capability.size();
const auto parsed =
std::from_chars(begin, end, limit);
if (parsed.ec == std::errc{} &&
parsed.ptr == end) {
return limit;
}
}
return std::nullopt;
}
[[nodiscard]] Void::Result::Result<void> ehlo()
{
auto reply =
command_reply("EHLO " + options.client_domain);
if (!reply.has_value()) {
return std::unexpected{std::move(reply.error())};
}
if (reply->code != 250) {
return std::unexpected{
rejected_error("EHLO", *reply)};
}
capabilities.clear();
for (std::size_t i = 1; i < reply->lines.size(); ++i) {
const std::string_view capability =
trimmed(reply->lines[i]);
if (!capability.empty()) {
capabilities.push_back(
upper_ascii(capability));
}
}
return {};
}
[[nodiscard]] Void::Result::Result<void> authenticate()
{
if (!options.credentials.has_value()) {
return {};
}
if (!stream.secure()) {
// Credentials are never sent on a plaintext channel.
return std::unexpected{make_net_error(
NetErrorCode::tls_required,
"SMTP: refusing to send credentials without TLS")};
}
if (!auth_plain_supported()) {
return std::unexpected{make_net_error(
NetErrorCode::auth_failed,
"SMTP: server does not advertise AUTH PLAIN")};
}
std::string payload;
payload.reserve(1U + options.credentials->username.size() +
1U +
options.credentials->password.size());
payload.push_back('\0');
payload += options.credentials->username;
payload.push_back('\0');
payload += options.credentials->password;
const std::string token =
Void::Encoding::Base64::encode(payload);
auto reply = command_reply("AUTH PLAIN " + token);
if (!reply.has_value()) {
return std::unexpected{std::move(reply.error())};
}
if (reply->code != 235) {
return std::unexpected{make_net_error(
NetErrorCode::auth_failed,
std::format("SMTP: authentication failed: {}",
reply_summary(*reply)))};
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
expect(const SmtpReply& reply, int code,
std::string_view context)
{
if (reply.code != code) {
return std::unexpected{
rejected_error(context, reply)};
}
return {};
}
};
SmtpClient::SmtpClient() noexcept = default;
SmtpClient::SmtpClient(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
SmtpClient::~SmtpClient() noexcept = default;
SmtpClient::SmtpClient(SmtpClient&&) noexcept = default;
SmtpClient& SmtpClient::operator=(SmtpClient&&) noexcept = default;
bool SmtpClient::valid() const noexcept
{
return m_impl != nullptr && m_impl->stream.valid();
}
bool SmtpClient::secure() const noexcept
{
return m_impl != nullptr && m_impl->stream.secure();
}
Void::Result::Result<SmtpClient>
SmtpClient::connect(SmtpOptions options)
{
if (options.host.empty() || options.port == 0) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"SMTP: connect requires a host and port")};
}
TlsClientOptions tls;
tls.host = options.host;
tls.port = options.port;
tls.server_name = options.server_name;
tls.ca_file = options.ca_file;
tls.connect_timeout = options.connect_timeout;
tls.io_timeout = options.io_timeout;
tls.stop = options.stop;
auto stream =
options.security == SmtpSecurity::implicit_tls
? TlsClientStream::connect(std::move(tls))
: TlsClientStream::connect_plain(std::move(tls));
if (!stream.has_value()) {
return std::unexpected{std::move(stream.error())};
}
auto impl =
std::make_unique<Impl>(std::move(*stream), std::move(options));
auto greeting = impl->read_reply();
if (!greeting.has_value()) {
return std::unexpected{std::move(greeting.error())};
}
if (greeting->code != 220) {
return std::unexpected{
rejected_error("greeting", *greeting)};
}
auto hello = impl->ehlo();
if (!hello.has_value()) {
return std::unexpected{std::move(hello.error())};
}
if (impl->options.security ==
SmtpSecurity::starttls_required) {
if (!impl->has_capability("STARTTLS")) {
return std::unexpected{make_net_error(
NetErrorCode::tls_required,
"SMTP: server does not advertise STARTTLS")};
}
auto reply = impl->command_reply("STARTTLS");
if (!reply.has_value()) {
return std::unexpected{std::move(reply.error())};
}
if (reply->code != 220) {
return std::unexpected{
rejected_error("STARTTLS", *reply)};
}
auto upgraded = impl->stream.start_tls();
if (!upgraded.has_value()) {
return std::unexpected{std::move(upgraded.error())};
}
auto hello_again = impl->ehlo();
if (!hello_again.has_value()) {
return std::unexpected{
std::move(hello_again.error())};
}
}
auto authenticated = impl->authenticate();
if (!authenticated.has_value()) {
return std::unexpected{std::move(authenticated.error())};
}
return SmtpClient{std::move(impl)};
}
Void::Result::Result<void>
SmtpClient::send(const SmtpMessage& message)
{
if (!valid()) {
return std::unexpected{make_net_error(
NetErrorCode::io_error, "SMTP: client is not connected")};
}
auto& impl = *m_impl;
const auto fail =
[&](Void::Result::Error error)
-> Void::Result::Result<void> {
impl.stream.close();
return std::unexpected{std::move(error)};
};
auto valid_from = validate_address("from", message.from);
if (!valid_from.has_value()) {
return std::unexpected{std::move(valid_from.error())};
}
if (message.recipients.empty()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"SMTP: at least one recipient is required")};
}
if (message.recipients.size() >
impl.options.limits.max_recipients) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
std::format("SMTP: {} recipients exceeds limit {}",
message.recipients.size(),
impl.options.limits.max_recipients))};
}
for (const auto& recipient : message.recipients) {
auto valid_recipient =
validate_address("recipient", recipient);
if (!valid_recipient.has_value()) {
return std::unexpected{
std::move(valid_recipient.error())};
}
}
if (message.data.size() >
impl.options.limits.max_message_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::payload_too_large,
std::format("SMTP: message {} bytes exceeds limit {}",
message.data.size(),
impl.options.limits.max_message_bytes))};
}
if (const auto server_limit = impl.server_size_limit();
server_limit.has_value() && *server_limit > 0 &&
message.data.size() > *server_limit) {
return std::unexpected{make_net_error(
NetErrorCode::payload_too_large,
std::format("SMTP: message {} bytes exceeds server SIZE {}",
message.data.size(), *server_limit))};
}
auto mail = impl.command_reply("MAIL FROM:<" +
message.from + ">");
if (!mail.has_value()) {
return fail(std::move(mail.error()));
}
if (mail->code != 250) {
return fail(rejected_error("MAIL FROM", *mail));
}
for (const auto& recipient : message.recipients) {
auto rcpt =
impl.command_reply("RCPT TO:<" + recipient + ">");
if (!rcpt.has_value()) {
return fail(std::move(rcpt.error()));
}
if (rcpt->code != 250 && rcpt->code != 251) {
return fail(rejected_error("RCPT TO", *rcpt));
}
}
auto data = impl.command_reply("DATA");
if (!data.has_value()) {
return fail(std::move(data.error()));
}
if (data->code != 354) {
return fail(rejected_error("DATA", *data));
}
const std::string encoded = encode_data(message.data);
auto written = impl.stream.write_all(encoded,
impl.options.io_timeout,
impl.options.stop);
if (!written.has_value()) {
return fail(std::move(written.error()));
}
auto accepted = impl.read_reply();
if (!accepted.has_value()) {
return fail(std::move(accepted.error()));
}
if (accepted->code != 250) {
return fail(rejected_error("message body", *accepted));
}
return {};
}
Void::Result::Result<void> SmtpClient::quit()
{
if (m_impl == nullptr) {
return {};
}
auto& impl = *m_impl;
Void::Result::Result<void> result{};
if (impl.stream.valid()) {
auto reply = impl.command_reply("QUIT");
if (!reply.has_value()) {
result = std::unexpected{std::move(reply.error())};
} else if (reply->code != 221) {
result = std::unexpected{
rejected_error("QUIT", *reply)};
}
}
auto closed = impl.stream.shutdown();
if (result.has_value() && !closed.has_value()) {
result = std::unexpected{std::move(closed.error())};
}
return result;
}
void SmtpClient::close() noexcept
{
if (m_impl != nullptr) {
m_impl->stream.close();
}
}
Void::Result::Result<void>
SmtpClient::submit(SmtpOptions options,
const SmtpMessage& message)
{
auto client = connect(std::move(options));
if (!client.has_value()) {
return std::unexpected{std::move(client.error())};
}
auto sent = client->send(message);
if (!sent.has_value()) {
client->close();
return std::unexpected{std::move(sent.error())};
}
return client->quit();
}
} // namespace Void::Net
+872
View File
@@ -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
+189
View File
@@ -0,0 +1,189 @@
#pragma once
// Shared test-only support for loopback TLS/SMTP fixtures.
#include <Void/Testing/Assert.hpp>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio>
#include <filesystem>
#include <memory>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
namespace Void::Testing::NetSupport
{
inline std::filesystem::path make_scratch_dir(std::string_view prefix)
{
static unsigned counter = 0;
auto path = std::filesystem::temp_directory_path() /
(std::string{prefix} + std::to_string(::getpid()) + "_" +
std::to_string(counter++));
std::filesystem::create_directories(path);
return path;
}
struct ScratchDir {
std::filesystem::path path;
explicit ScratchDir(std::string_view prefix)
: path(make_scratch_dir(prefix))
{
}
ScratchDir(const ScratchDir&) = delete;
ScratchDir& operator=(const ScratchDir&) = delete;
~ScratchDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
struct GeneratedCert {
std::filesystem::path cert_file;
std::filesystem::path key_file;
};
inline GeneratedCert
generate_self_signed_cert(const std::filesystem::path& dir,
const char* san_value, const char* tag)
{
using PkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using X509Ptr = std::unique_ptr<X509, decltype(&X509_free)>;
using ExtPtr =
std::unique_ptr<X509_EXTENSION, decltype(&X509_EXTENSION_free)>;
PkeyPtr pkey{EVP_RSA_gen(2048), &EVP_PKEY_free};
Void::Testing::require(static_cast<bool>(pkey));
X509Ptr cert{X509_new(), &X509_free};
Void::Testing::require(static_cast<bool>(cert));
X509_set_version(cert.get(), 2);
ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), 1);
X509_gmtime_adj(X509_get_notBefore(cert.get()), -60);
X509_gmtime_adj(X509_get_notAfter(cert.get()), 3600);
X509_set_pubkey(cert.get(), pkey.get());
X509_NAME* name = X509_get_subject_name(cert.get());
X509_NAME_add_entry_by_txt(
name, "CN", MBSTRING_ASC,
reinterpret_cast<const unsigned char*>("127.0.0.1"), -1, -1, 0);
X509_set_issuer_name(cert.get(), name);
X509V3_CTX ctx{};
X509V3_set_ctx_nodb(&ctx);
X509V3_set_ctx(&ctx, cert.get(), cert.get(), nullptr, nullptr, 0);
ExtPtr ext{X509V3_EXT_conf_nid(nullptr, &ctx, NID_subject_alt_name,
const_cast<char*>(san_value)),
&X509_EXTENSION_free};
Void::Testing::require(static_cast<bool>(ext));
Void::Testing::require(X509_add_ext(cert.get(), ext.get(), -1) == 1);
Void::Testing::require(
X509_sign(cert.get(), pkey.get(), EVP_sha256()) > 0);
const auto cert_path = dir / (std::string{"cert_"} + tag + ".pem");
const auto key_path = dir / (std::string{"key_"} + tag + ".pem");
FILE* cf = std::fopen(cert_path.c_str(), "wb");
Void::Testing::require(cf != nullptr);
Void::Testing::require(PEM_write_X509(cf, cert.get()) == 1);
std::fclose(cf);
FILE* kf = std::fopen(key_path.c_str(), "wb");
Void::Testing::require(kf != nullptr);
Void::Testing::require(PEM_write_PrivateKey(
kf, pkey.get(), nullptr, nullptr, 0,
nullptr, nullptr) == 1);
std::fclose(kf);
return GeneratedCert{cert_path, key_path};
}
/// Bound TCP listener on 127.0.0.1 with an ephemeral port.
struct LoopbackListener {
int fd{-1};
std::uint16_t port{0};
LoopbackListener()
{
fd = ::socket(AF_INET, SOCK_STREAM, 0);
Void::Testing::require(fd >= 0);
int yes = 1;
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(yes));
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
address.sin_port = 0;
Void::Testing::require(
::bind(fd, reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == 0);
socklen_t length = sizeof(address);
Void::Testing::require(
::getsockname(fd, reinterpret_cast<sockaddr*>(&address),
&length) == 0);
port = ntohs(address.sin_port);
Void::Testing::require(::listen(fd, 4) == 0);
}
LoopbackListener(const LoopbackListener&) = delete;
LoopbackListener& operator=(const LoopbackListener&) = delete;
~LoopbackListener()
{
if (fd >= 0) {
::close(fd);
}
}
[[nodiscard]] int accept_one() const
{
return ::accept(fd, nullptr, nullptr);
}
};
inline bool write_all(int fd, std::string_view data)
{
while (!data.empty()) {
const ssize_t written =
::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
if (written <= 0) {
if (written < 0 && errno == EINTR) {
continue;
}
return false;
}
data.remove_prefix(static_cast<std::size_t>(written));
}
return true;
}
/// Read until `delimiter` is found or `max_bytes` is exceeded.
inline std::string read_until(int fd, std::string_view delimiter,
std::size_t max_bytes)
{
std::string buffer;
while (buffer.find(delimiter) == std::string::npos &&
buffer.size() <= max_bytes) {
char chunk[1024];
const ssize_t count = ::recv(fd, chunk, sizeof(chunk), 0);
if (count <= 0) {
break;
}
buffer.append(chunk, static_cast<std::size_t>(count));
}
return buffer;
}
} // namespace Void::Testing::NetSupport
+472
View File
@@ -0,0 +1,472 @@
#include <Void/Net/Http.hpp>
#include <Void/Net/Smtp.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Text/Base64.hpp>
#include "../../helpers/NetTlsSupport.hpp"
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace
{
using namespace std::chrono_literals;
using Void::Testing::NetSupport::GeneratedCert;
using Void::Testing::NetSupport::LoopbackListener;
using Void::Testing::NetSupport::ScratchDir;
enum class SmtpMode {
implicit_tls,
starttls,
starttls_rejected,
no_starttls,
auth_fail,
stall,
};
struct FakeSmtpServer {
LoopbackListener listener;
SSL_CTX* ctx{nullptr};
std::thread worker;
std::vector<std::string> commands;
std::string message_data;
bool starttls_attempted{false};
FakeSmtpServer(const GeneratedCert& cert, SmtpMode mode)
{
ctx = SSL_CTX_new(TLS_server_method());
Void::Testing::require(ctx != nullptr);
Void::Testing::require(
SSL_CTX_use_certificate_file(
ctx, cert.cert_file.c_str(), SSL_FILETYPE_PEM) == 1);
Void::Testing::require(
SSL_CTX_use_PrivateKey_file(
ctx, cert.key_file.c_str(), SSL_FILETYPE_PEM) == 1);
worker = std::thread([this, mode] { serve(mode); });
}
FakeSmtpServer(const FakeSmtpServer&) = delete;
FakeSmtpServer& operator=(const FakeSmtpServer&) = delete;
void join()
{
if (worker.joinable()) {
worker.join();
}
}
~FakeSmtpServer()
{
join();
if (ctx != nullptr) {
SSL_CTX_free(ctx);
}
}
void serve(SmtpMode mode)
{
const int connection = listener.accept_one();
if (connection < 0) {
return;
}
if (mode == SmtpMode::stall) {
char byte = 0;
while (::recv(connection, &byte, 1, 0) > 0) {
}
::close(connection);
return;
}
SSL* ssl = nullptr;
bool tls = false;
if (mode == SmtpMode::implicit_tls ||
mode == SmtpMode::auth_fail) {
ssl = SSL_new(ctx);
SSL_set_fd(ssl, connection);
const int accepted = SSL_accept(ssl);
if (accepted != 1) {
SSL_free(ssl);
::close(connection);
return;
}
tls = true;
}
std::string pending;
const auto send = [&](std::string_view text) {
if (tls) {
(void)SSL_write(ssl, text.data(),
static_cast<int>(text.size()));
} else {
(void)Void::Testing::NetSupport::write_all(
connection, text);
}
};
const auto read_line = [&]() -> std::optional<std::string> {
for (;;) {
const std::size_t end = pending.find("\r\n");
if (end != std::string::npos) {
std::string line = pending.substr(0, end);
pending.erase(0, end + 2);
return line;
}
char buffer[1024];
const int count =
tls ? SSL_read(ssl, buffer,
static_cast<int>(sizeof(buffer)))
: static_cast<int>(::recv(
connection, buffer, sizeof(buffer), 0));
if (count <= 0) {
return std::nullopt;
}
pending.append(buffer,
static_cast<std::size_t>(count));
}
};
send("220 fake ESMTP\r\n");
for (;;) {
auto line = read_line();
if (!line.has_value()) {
break;
}
commands.push_back(*line);
if (line->starts_with("EHLO")) {
if (!tls && (mode == SmtpMode::starttls ||
mode == SmtpMode::starttls_rejected)) {
send("250-fake\r\n250-STARTTLS\r\n"
"250 SIZE 1048576\r\n");
} else {
send("250-fake\r\n250-AUTH PLAIN\r\n"
"250 SIZE 1048576\r\n");
}
} else if (line->starts_with("STARTTLS")) {
starttls_attempted = true;
if (mode == SmtpMode::starttls_rejected) {
send("454 TLS not available\r\n");
} else {
send("220 go ahead\r\n");
ssl = SSL_new(ctx);
SSL_set_fd(ssl, connection);
if (SSL_accept(ssl) != 1) {
break;
}
tls = true;
}
} else if (line->starts_with("AUTH ")) {
if (mode == SmtpMode::auth_fail) {
send("535 bad credentials\r\n");
} else {
send("235 authenticated\r\n");
}
} else if (line->starts_with("MAIL")) {
send("250 ok\r\n");
} else if (line->starts_with("RCPT")) {
send("250 ok\r\n");
} else if (line->starts_with("DATA")) {
send("354 send it\r\n");
std::string data;
for (;;) {
auto body_line = read_line();
if (!body_line.has_value()) {
break;
}
if (*body_line == ".") {
break;
}
if (body_line->starts_with("..")) {
data += body_line->substr(1);
} else {
data += *body_line;
}
data += "\r\n";
}
message_data = std::move(data);
send("250 queued\r\n");
} else if (line->starts_with("QUIT")) {
send("221 bye\r\n");
break;
} else {
send("250 ok\r\n");
}
}
if (ssl != nullptr) {
SSL_shutdown(ssl);
SSL_free(ssl);
}
::close(connection);
}
};
[[nodiscard]] Void::Net::SmtpOptions
make_options(std::uint16_t port, std::string ca_file = {})
{
Void::Net::SmtpOptions options;
options.host = "127.0.0.1";
options.port = port;
options.ca_file = std::move(ca_file);
options.connect_timeout = 2s;
options.io_timeout = 5s;
return options;
}
[[nodiscard]] std::string expected_auth_token()
{
std::string payload;
payload.push_back('\0');
payload += "user";
payload.push_back('\0');
payload += "pass";
return Void::Encoding::Base64::encode(payload);
}
[[nodiscard]] bool contains_command(
const std::vector<std::string>& commands, std::string_view prefix)
{
for (const auto& command : commands) {
if (command.starts_with(prefix)) {
return true;
}
}
return false;
}
} // namespace
Void::Testing::Test smtp_starttls_submission_authenticates_and_dot_stuffs()
{
ScratchDir scratch{"void_smtp_starttls_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtp");
FakeSmtpServer server{cert, SmtpMode::starttls};
auto options = make_options(server.listener.port, cert.cert_file.string());
options.credentials = Void::Net::SmtpCredentials{.username = "user",
.password = "pass"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(client.has_value());
Void::Testing::expect(client->secure());
Void::Net::SmtpMessage message;
message.from = "sender@example.test";
message.recipients = {"one@example.test", "two@example.test"};
message.data = "Subject: hi\r\n\r\n.first line\nsecond line\r\nthird";
auto sent = client->send(message);
Void::Testing::require(sent.has_value());
Void::Testing::require(client->quit().has_value());
server.join();
Void::Testing::expect(server.starttls_attempted);
Void::Testing::expect(contains_command(
server.commands, "AUTH PLAIN " + expected_auth_token()));
Void::Testing::expect(contains_command(server.commands,
"MAIL FROM:<sender@example.test>"));
Void::Testing::expect(contains_command(
server.commands, "RCPT TO:<one@example.test>"));
Void::Testing::expect(contains_command(
server.commands, "RCPT TO:<two@example.test>"));
Void::Testing::expect(contains_command(server.commands, "DATA"));
Void::Testing::expect_eq(
server.message_data,
std::string{"Subject: hi\r\n\r\n.first line\r\nsecond line\r\n"
"third\r\n"});
}
Void::Testing::Test smtp_implicit_tls_submission()
{
ScratchDir scratch{"void_smtp_implicit_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtpimp");
FakeSmtpServer server{cert, SmtpMode::implicit_tls};
auto options = make_options(server.listener.port, cert.cert_file.string());
options.security = Void::Net::SmtpSecurity::implicit_tls;
options.credentials = Void::Net::SmtpCredentials{.username = "user",
.password = "pass"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(client.has_value());
Void::Testing::expect(client->secure());
Void::Net::SmtpMessage message;
message.from = "a@example.test";
message.recipients = {"b@example.test"};
message.data = "hello\r\n";
Void::Testing::require(client->send(message).has_value());
Void::Testing::require(client->quit().has_value());
server.join();
Void::Testing::expect(contains_command(
server.commands, "AUTH PLAIN " + expected_auth_token()));
Void::Testing::expect_eq(server.message_data,
std::string{"hello\r\n"});
}
Void::Testing::Test smtp_never_sends_credentials_without_starttls()
{
ScratchDir scratch{"void_smtp_downgrade_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtpdg");
// Server does not advertise STARTTLS: the client must fail before AUTH.
{
FakeSmtpServer server{cert, SmtpMode::no_starttls};
auto options =
make_options(server.listener.port, cert.cert_file.string());
options.credentials = Void::Net::SmtpCredentials{
.username = "user", .password = "pass"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::tls_required));
server.join();
Void::Testing::expect(
!contains_command(server.commands, "AUTH"));
Void::Testing::expect(
!contains_command(server.commands, "MAIL"));
}
// Server advertises STARTTLS but rejects it: no credentials either.
{
FakeSmtpServer server{cert, SmtpMode::starttls_rejected};
auto options =
make_options(server.listener.port, cert.cert_file.string());
options.credentials = Void::Net::SmtpCredentials{
.username = "user", .password = "pass"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::smtp_rejected));
server.join();
Void::Testing::expect(server.starttls_attempted);
Void::Testing::expect(
!contains_command(server.commands, "AUTH"));
}
}
Void::Testing::Test smtp_rejects_oversized_messages()
{
ScratchDir scratch{"void_smtp_oversize_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtpbig");
// Client-side bound.
{
FakeSmtpServer server{cert, SmtpMode::implicit_tls};
auto options =
make_options(server.listener.port, cert.cert_file.string());
options.security = Void::Net::SmtpSecurity::implicit_tls;
options.limits.max_message_bytes = 16;
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(client.has_value());
Void::Net::SmtpMessage message;
message.from = "a@example.test";
message.recipients = {"b@example.test"};
message.data = std::string(17, 'x');
auto sent = client->send(message);
Void::Testing::require(!sent.has_value());
Void::Testing::expect_eq(
sent.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::payload_too_large));
client->close();
server.join();
Void::Testing::expect(
!contains_command(server.commands, "MAIL"));
}
// Server SIZE capability bound (server advertises SIZE 1048576).
{
FakeSmtpServer server{cert, SmtpMode::implicit_tls};
auto options =
make_options(server.listener.port, cert.cert_file.string());
options.security = Void::Net::SmtpSecurity::implicit_tls;
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(client.has_value());
Void::Net::SmtpMessage message;
message.from = "a@example.test";
message.recipients = {"b@example.test"};
message.data = std::string(1048577, 'x');
auto sent = client->send(message);
Void::Testing::require(!sent.has_value());
Void::Testing::expect_eq(
sent.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::payload_too_large));
client->close();
server.join();
}
}
Void::Testing::Test smtp_auth_failure_is_reported()
{
ScratchDir scratch{"void_smtp_auth_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtpauth");
FakeSmtpServer server{cert, SmtpMode::auth_fail};
auto options = make_options(server.listener.port, cert.cert_file.string());
options.security = Void::Net::SmtpSecurity::implicit_tls;
options.credentials = Void::Net::SmtpCredentials{.username = "user",
.password = "wrong"};
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::auth_failed));
server.join();
}
Void::Testing::Test smtp_trust_and_cancellation()
{
ScratchDir scratch{"void_smtp_trust_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "smtptrust");
// Untrusted certificate: TLS failure, never plaintext fallback.
{
FakeSmtpServer server{cert, SmtpMode::implicit_tls};
auto options = make_options(server.listener.port);
options.security = Void::Net::SmtpSecurity::implicit_tls;
auto client = Void::Net::SmtpClient::connect(options);
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::tls_error));
server.join();
}
// Cancellation while waiting for the greeting.
{
FakeSmtpServer server{cert, SmtpMode::stall};
auto options = make_options(server.listener.port);
std::stop_source stop;
options.stop = stop.get_token();
std::jthread killer([&stop] {
std::this_thread::sleep_for(50ms);
stop.request_stop();
});
const auto start = std::chrono::steady_clock::now();
auto client = Void::Net::SmtpClient::connect(options);
const auto elapsed = std::chrono::steady_clock::now() - start;
killer.join();
Void::Testing::require(!client.has_value());
Void::Testing::expect_eq(
client.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::cancelled));
Void::Testing::expect(elapsed < 3s);
server.join();
}
}
+379
View File
@@ -0,0 +1,379 @@
#include <Void/Net/Http.hpp>
#include <Void/Net/Tls.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include "../../helpers/NetTlsSupport.hpp"
#include <openssl/ssl.h>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <span>
#include <stop_token>
#include <string>
#include <thread>
#include <utility>
#include <vector>
namespace
{
using namespace std::chrono_literals;
using Void::Testing::NetSupport::GeneratedCert;
using Void::Testing::NetSupport::LoopbackListener;
using Void::Testing::NetSupport::ScratchDir;
struct TlsServer {
LoopbackListener listener;
SSL_CTX* ctx{nullptr};
std::thread worker;
TlsServer(const GeneratedCert& cert,
std::function<void(SSL*)> behavior)
{
ctx = SSL_CTX_new(TLS_server_method());
Void::Testing::require(ctx != nullptr);
Void::Testing::require(
SSL_CTX_use_certificate_file(
ctx, cert.cert_file.c_str(), SSL_FILETYPE_PEM) == 1);
Void::Testing::require(
SSL_CTX_use_PrivateKey_file(
ctx, cert.key_file.c_str(), SSL_FILETYPE_PEM) == 1);
worker = std::thread(
[this, behavior = std::move(behavior)] {
const int connection = listener.accept_one();
if (connection < 0) {
return;
}
SSL* ssl = SSL_new(ctx);
SSL_set_fd(ssl, connection);
if (SSL_accept(ssl) == 1) {
behavior(ssl);
SSL_shutdown(ssl);
}
SSL_free(ssl);
::close(connection);
});
}
TlsServer(const TlsServer&) = delete;
TlsServer& operator=(const TlsServer&) = delete;
~TlsServer()
{
if (worker.joinable()) {
worker.join();
}
if (ctx != nullptr) {
SSL_CTX_free(ctx);
}
}
};
/// Accepts a TCP connection and never speaks TLS, so handshake waits.
struct StallServer {
LoopbackListener listener;
std::thread worker;
StallServer()
{
worker = std::thread([this] {
const int connection = listener.accept_one();
if (connection < 0) {
return;
}
char byte = 0;
while (::recv(connection, &byte, 1, 0) > 0) {
}
::close(connection);
});
}
StallServer(const StallServer&) = delete;
StallServer& operator=(const StallServer&) = delete;
~StallServer()
{
if (worker.joinable()) {
worker.join();
}
}
};
[[nodiscard]] Void::Net::TlsClientOptions
make_options(std::uint16_t port, std::string ca_file = {})
{
Void::Net::TlsClientOptions options;
options.host = "127.0.0.1";
options.port = port;
options.ca_file = std::move(ca_file);
options.connect_timeout = 2s;
options.handshake_timeout = 5s;
options.io_timeout = 5s;
return options;
}
[[nodiscard]] std::string read_text(Void::Net::TlsClientStream& stream,
std::size_t expected)
{
std::string text;
std::vector<std::byte> buffer(expected);
while (text.size() < expected) {
auto span = std::span<std::byte>{buffer}.subspan(
text.size());
auto result = stream.read(span, 5s);
Void::Testing::require(result.has_value());
if (*result == 0) {
break;
}
text.append(reinterpret_cast<const char*>(span.data()),
*result);
}
return text;
}
} // namespace
Void::Testing::Test tls_client_verifies_trust_store_and_hostname()
{
ScratchDir scratch{"void_tls_trust_"};
const auto good = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "good");
// a) Untrusted self-signed peer is rejected by the default trust store.
{
TlsServer server{good, [](SSL* ssl) {
const char* text = "untrusted";
(void)SSL_write(ssl, text, 9);
}};
auto stream = Void::Net::TlsClientStream::connect(
make_options(server.listener.port));
Void::Testing::require(!stream.has_value());
Void::Testing::expect_eq(
stream.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::tls_error));
}
// b) Trusted CA + matching IP SAN succeeds.
{
TlsServer server{good, [](SSL* ssl) {
const char* text = "trusted-ok";
(void)SSL_write(ssl, text, 10);
}};
auto stream = Void::Net::TlsClientStream::connect(
make_options(server.listener.port, good.cert_file.string()));
Void::Testing::require(stream.has_value());
Void::Testing::expect(stream->secure());
Void::Testing::expect_eq(read_text(*stream, 10),
std::string{"trusted-ok"});
}
// c) Trusted CA but hostname mismatch is still rejected.
{
TlsServer server{good, [](SSL* ssl) {
const char* text = "mismatch";
(void)SSL_write(ssl, text, 8);
}};
auto options =
make_options(server.listener.port, good.cert_file.string());
options.server_name = "wrong.invalid";
auto stream = Void::Net::TlsClientStream::connect(options);
Void::Testing::require(!stream.has_value());
Void::Testing::expect_eq(
stream.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::tls_error));
}
// d) An unreadable trust store is a hard failure, never a downgrade.
{
TlsServer server{good, [](SSL* ssl) {
const char* text = "bad-store";
(void)SSL_write(ssl, text, 9);
}};
auto stream = Void::Net::TlsClientStream::connect(
make_options(server.listener.port,
(scratch.path / "missing-ca.pem").string()));
Void::Testing::require(!stream.has_value());
Void::Testing::expect_eq(
stream.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::tls_error));
}
}
Void::Testing::Test tls_client_never_falls_back_to_plaintext()
{
// A plain TCP peer speaking garbage must fail the handshake and leave
// the stream closed, not usable in plaintext.
LoopbackListener listener;
std::thread worker([&listener] {
const int connection = listener.accept_one();
if (connection < 0) {
return;
}
const std::string garbage = "this is not a TLS server hello";
(void)::send(connection, garbage.data(), garbage.size(),
MSG_NOSIGNAL);
char buffer[64];
while (::recv(connection, buffer, sizeof(buffer), 0) > 0) {
}
::close(connection);
});
auto stream = Void::Net::TlsClientStream::connect(
make_options(listener.port));
Void::Testing::require(!stream.has_value());
Void::Testing::expect_eq(
stream.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::tls_error));
worker.join();
}
Void::Testing::Test tls_client_deadline_and_cancellation()
{
// Handshake deadline.
{
StallServer server;
auto options = make_options(server.listener.port);
options.handshake_timeout = 100ms;
const auto start = std::chrono::steady_clock::now();
auto stream = Void::Net::TlsClientStream::connect(options);
const auto elapsed = std::chrono::steady_clock::now() - start;
Void::Testing::require(!stream.has_value());
Void::Testing::expect_eq(
stream.error().code().value,
static_cast<std::int32_t>(Void::Net::NetErrorCode::timeout));
Void::Testing::expect(elapsed < 3s);
}
// Cancellation while the handshake is waiting.
{
StallServer server;
auto options = make_options(server.listener.port);
std::stop_source stop;
options.stop = stop.get_token();
std::jthread killer([&stop] {
std::this_thread::sleep_for(50ms);
stop.request_stop();
});
const auto start = std::chrono::steady_clock::now();
auto stream = Void::Net::TlsClientStream::connect(options);
const auto elapsed = std::chrono::steady_clock::now() - start;
killer.join();
Void::Testing::require(!stream.has_value());
Void::Testing::expect_eq(
stream.error().code().value,
static_cast<std::int32_t>(
Void::Net::NetErrorCode::cancelled));
Void::Testing::expect(elapsed < 3s);
}
}
Void::Testing::Test tls_client_partial_writes_complete()
{
ScratchDir scratch{"void_tls_write_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "write");
constexpr std::size_t kTotal = 4U * 1024U * 1024U;
std::atomic<std::size_t> received{0};
std::atomic<bool> done{false};
TlsServer server{
cert, [&received, &done](SSL* ssl) {
std::vector<char> buffer(8U * 1024U);
while (received.load(std::memory_order_acquire) < kTotal) {
const int count =
SSL_read(ssl, buffer.data(),
static_cast<int>(buffer.size()));
if (count <= 0) {
break;
}
received.fetch_add(static_cast<std::size_t>(count),
std::memory_order_acq_rel);
std::this_thread::sleep_for(1ms);
}
done.store(true, std::memory_order_release);
}};
auto stream = Void::Net::TlsClientStream::connect(
make_options(server.listener.port, cert.cert_file.string()));
Void::Testing::require(stream.has_value());
std::vector<std::byte> payload(kTotal);
for (std::size_t i = 0; i < kTotal; ++i) {
payload[i] = static_cast<std::byte>(i & 0xFFU);
}
auto written = stream->write_all(payload, 10s);
Void::Testing::expect(written.has_value());
const auto deadline = std::chrono::steady_clock::now() + 10s;
while (!done.load(std::memory_order_acquire) &&
std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(2ms);
}
Void::Testing::expect_eq(received.load(std::memory_order_acquire),
kTotal);
(void)stream->shutdown();
}
Void::Testing::Test tls_client_starttls_upgrade()
{
ScratchDir scratch{"void_tls_starttls_"};
const auto cert = Void::Testing::NetSupport::generate_self_signed_cert(
scratch.path, "IP:127.0.0.1", "starttls");
LoopbackListener listener;
SSL_CTX* ctx = SSL_CTX_new(TLS_server_method());
Void::Testing::require(ctx != nullptr);
Void::Testing::require(SSL_CTX_use_certificate_file(
ctx, cert.cert_file.c_str(),
SSL_FILETYPE_PEM) == 1);
Void::Testing::require(SSL_CTX_use_PrivateKey_file(
ctx, cert.key_file.c_str(),
SSL_FILETYPE_PEM) == 1);
std::thread worker([&listener, ctx] {
const int connection = listener.accept_one();
if (connection < 0) {
return;
}
auto greeting =
Void::Testing::NetSupport::read_until(connection, "\r\n", 256);
if (greeting.starts_with("HELLO")) {
(void)Void::Testing::NetSupport::write_all(connection,
"READY\r\n");
}
SSL* ssl = SSL_new(ctx);
SSL_set_fd(ssl, connection);
if (SSL_accept(ssl) == 1) {
char buffer[64];
const int count = SSL_read(ssl, buffer, sizeof(buffer));
if (count > 0) {
(void)SSL_write(ssl, buffer, count);
}
SSL_shutdown(ssl);
}
SSL_free(ssl);
::close(connection);
});
auto options = make_options(listener.port, cert.cert_file.string());
auto stream = Void::Net::TlsClientStream::connect_plain(options);
Void::Testing::require(stream.has_value());
Void::Testing::expect(!stream->secure());
Void::Testing::require(
stream->write_all(std::string_view{"HELLO\r\n"}).has_value());
Void::Testing::expect_eq(read_text(*stream, 7),
std::string{"READY\r\n"});
auto upgraded = stream->start_tls();
Void::Testing::require(upgraded.has_value());
Void::Testing::expect(stream->secure());
Void::Testing::require(
stream->write_all(std::string_view{"secure"}).has_value());
Void::Testing::expect_eq(read_text(*stream, 6),
std::string{"secure"});
worker.join();
SSL_CTX_free(ctx);
}