636 lines
17 KiB
C++
636 lines
17 KiB
C++
#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
|