Merge issue-48-tls-smtp: TLS client stream and SMTP submission (closes #48)
This commit is contained in:
commit
d51dd171ef
8 files changed
+2787
-1
No files matched your search
@@ -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
@@ -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