Files
BARANTMail/SMTPServer.cpp
T
Brad Arant cd5e0a9905 Add real IMAP4rev1/POP3 implementations, DKIM/DMARC/SPF, SpamAssassin delivery hook
IMAP (RFC 3501): LOGIN through UID, previously all stubs except
CAPABILITY/LOGOUT/a partial APPEND. Multi-folder support with per-folder
UID/flag indexing (new MailFolder class, backed by .uidvalidity/.uidnext/
.imapindex sidecar files), ENVELOPE support (new MessageHeaders class:
header parsing, address-list parsing, IMAP quoting), and shared
cursor-based argument parsing (new IMAPArgs class: sequence sets, flag
lists, dates, folder-name normalization, and path-traversal protection
via isValidFolderName - a bare ".." folder name would otherwise resolve
into a sibling user's mailbox directory).

POP3 (RFC 1939): USER through QUIT, previously only CAPA. Added UIDL.
POP3 handlers use cursor-based parsing throughout rather than indexed
access - ZString's copy constructor doesn't copy its `list` field, and
POP3's dispatch passes the request by value, so indexed access into a
copy was silently reading nothing.

SMTP: DMARC evaluation added to the DATA-terminator path (DKIM
verification + alignment/policy, Authentication-Results header,
conditional rejection matching RFC 7489 6.3's p=reject + sampled pct=).
AUTH LOGIN now handles RFC 4954's optional inline initial response
(e.g. Python smtplib's "AUTH LOGIN <base64>" in one line) instead of
only the exact three-line form. Outbound relay now forces IPv4
(AF_INET) instead of AF_UNSPEC - this server's IPv4 has a correct PTR
record and SPF coverage, its IPv6 doesn't, and Gmail was rejecting
outbound mail with 550 5.7.25 as a result.

Delivery pipeline: local delivery now runs the message through
SpamAssassin (new SpamAssassinFilter class, speaking spamd's PROCESS
protocol directly over a raw socket - fails open/delivers unscanned if
spamd is unreachable) instead of a plain hardlink, since scanning can
tag/modify content.

BARANTMailConfig: extracted config loading into its own class.

compile: (see individual file changes - build script adjustments to
match the above).

Deliberately excluded from this commit: barantmail.log/
barantmail-service.log (operational logs, not source - barantmail.log
in particular was the runaway 55GB/12.9GB file from a busy-loop bug
fixed separately in ServerCore) and barantmail.cfg (this server's own
live deployment config, matching how APIServer's equivalent
config also stays untracked).
2026-09-03 05:24:22 +00:00

102 lines
4.3 KiB
C++

#include "SMTPServer.h"
#include "Log.h"
#include "SendMail.h"
#include "SpamAssassinFilter.h"
#include "File.h"
#include <thread>
namespace mail {
SMTPServer::SMTPServer(core::EPoll &ePoll, std::string hostName, MailFileSystem &mailFileSystem,
core::IPAddress ipAddress, core::TLSInfo *tlsInfo, bool watchQueue,
DKIMSigner *dkimSigner)
: core::TCPServer(ePoll, ipAddress, tlsInfo, " ", 1, "SMTP Server"), core::INotify(ePoll), ePoll(ePoll), hostName(hostName), mailFileSystem(mailFileSystem), dkimSigner(dkimSigner) {
commands.add(_smtp_auth, "AUTH");
commands.add(_smtp_data, "DATA");
commands.add(_smtp_ehlo, "EHLO");
commands.add(_smtp_expn, "EXPN");
commands.add(_smtp_helo, "HELO");
commands.add(_smtp_help, "HELP");
commands.add(_smtp_mail, "MAIL");
commands.add(_smtp_noop, "NOOP");
commands.add(_smtp_quit, "QUIT");
commands.add(_smtp_rcpt, "RCPT");
commands.add(_smtp_rset, "RSET");
commands.add(_smtp_vrfy, "VRFY");
if (watchQueue) {
processExisting();
wd = addWatch(mailFileSystem.getQueuePath());
}
}
SMTPSession * SMTPServer::getSocketAccept(core::EPoll &ePoll) {
return new SMTPSession(ePoll, *this);
}
void SMTPServer::sessionErrorHandler(std::string errorString, std::stringstream &out) {
out << "252 " << errorString << CRLF;
}
void SMTPServer::inCreate(coreutils::ZString &name) {
coreutils::Log(coreutils::LOG_DEBUG_2) << "inCreate; [" << name << "]";
name.split("|");
// Three parts now: messageid|recipient|sender - see
// __SMTP_DATA::queueMail()'s own doc comment for why the sender
// had to be added alongside the recipient.
if(name.getList().size() > 2) {
bool exists = mailFileSystem.ifMailBoxExists(name[1]);
coreutils::MString path;
path << mailFileSystem.getMailBoxPath(name[1]) << "/Inbox/" << name[0];
coreutils::MString from;
from << mailFileSystem.getQueuePath() << "/" << name;
if(exists) {
// Scanned on the way into the recipient's own Inbox, not the
// outbound relay path below - spamd's added X-Spam-* headers
// are for whatever reads this recipient's mailbox, and a
// message this server relays onward gets scored by ITS
// destination's own filtering, same as any other MTA. Reading
// the whole file in (rather than the plain link() this branch
// used to do) is unavoidable now that spamd may have rewritten
// the content the recipient actually needs to receive.
coreutils::File queuedFile(from, O_RDONLY);
queuedFile.read();
SpamAssassinFilter::Result scan = SpamAssassinFilter::scan(queuedFile.asString());
coreutils::File mailFile(path, O_CREAT | O_WRONLY, 0660);
mailFile.write(scan.scanned);
int rc = unlink(from.c_str());
coreutils::Log(coreutils::LOG_INFO) << "Message " << name[0] << " delivered to recipient " << name[1]
<< (scan.ok && scan.isSpam ? " (flagged as spam)" : "") << ".";
} else {
// Not a local mailbox - relay it out over SMTP. SendMail's
// own send() is a plain blocking call (see its doc comment
// for why) - queued delivery wants fire-and-forget, so this
// owns the heap-allocated SendMail itself and runs it on its
// own detached thread rather than blocking this EPoll
// worker thread for however long the remote host takes.
coreutils::MString sender(name[2]);
coreutils::MString recipient(name[1]);
coreutils::File queuedFile(from, O_RDONLY);
queuedFile.read();
coreutils::MString mailData(queuedFile.asString());
SendMail *outbound = new SendMail(hostName, mailFileSystem.getSendLogPath().str(),
name[0].str(), sender, recipient, mailData, dkimSigner);
std::thread([outbound]() {
outbound->send();
delete outbound;
}).detach();
}
}
}
void SMTPServer::processExisting() {
for (const auto & entry : std::filesystem::directory_iterator(mailFileSystem.getQueuePath().str())) {
std::string temp(entry.path().filename().string());
coreutils::ZString temp2(temp);
inCreate(temp2);
}
}
}