Переглянути джерело

feat(mail): an IMAP response reader and RFC 2047 header handling

Foundation for ctx.mail. No JavaScript surface yet - this is the part
everything else needs and the part that carries the real difficulty.

THE IMAP RESPONSE READER (src/functions/imap_reader.hpp, 13 tests).
libcurl gives us a connection, TLS, authentication and timeouts but
not IMAP semantics: measured against a real curl build, BODY.PEEK,
SEARCH, STORE, MOVE, LIST and BODYSTRUCTURE all require
CUSTOMREQUEST, so we see raw protocol and parse it ourselves.

It is byte-counted, never line-based, and that is the only property
really worth testing here. IMAP literals are octet-counted and their
bytes may contain CRLF, unbalanced parentheses, quotes and NUL. A
line-based parser passes every short tidy test and corrupts real
mail, because short test messages rarely contain a bare CRLF inside a
literal. So the tests are mostly literals containing exactly what
would break one: CRLF, parens and quotes, NUL and 8-bit bytes,
truncation mid-literal, NIL as a VALUE rather than the string "NIL",
quoted escapes limited to the two legal ones, LITERAL+ counts
accepted on the way in, absurd counts refused rather than trusted,
and successive responses read from one buffer with the tagged
completion still reachable after a literal - which is where a lost
reader waits forever for a completion it already consumed.

RFC 2047 HEADER HANDLING (src/functions/mime_words.*, 12 tests),
adapted from an existing internal implementation with permission and
maintained here from now on. Both directions, folding across lines,
RFC 2231 parameter encoding, and `envelopeAddress` - which exists
because handing MAIL FROM or RCPT TO a display-name form produces a
malformed command and the server drops the connection, reported only
as "Failed sending data to the peer", naming neither the address nor
the reason. Its base64 helpers are provided locally
(mime_base64.hpp) so the file depends on nothing external.

Its tests were adapted too, because the value of adapting a tested
component is the tests - and they immediately caught me being wrong.
My first version of one test invented its own inputs for the
unknown-charset case and asserted the whole encoded word comes back.
The real contract is better: an unknown charset still has its
transfer encoding undone and the label dropped, so the bytes reach
the caller as something rather than nothing. Reverted to the
established cases.

Two things measured that shaped the design, both of which would have
been found late:
- UIDVALIDITY arrives on curl's HEADER callback, not the write
  callback, when SELECT comes from the URL path. Hook only the
  obvious one and the message-id staleness guarantee silently does
  not work.
- Synchronizing literals do not work in CUSTOMREQUEST (curl sends
  {5} then LOGOUT), and LITERAL+ needs a CRLF, which curl refuses in
  a custom request as injection protection. So non-ASCII IMAP SEARCH
  is impossible through curl: ASCII server-side search now, non-ASCII
  filtered host-side later. This matters because the content is
  Hungarian.

914 tests pass.
fszontagh 1 місяць тому
батько
коміт
af258ccc3a

+ 1 - 0
src/CMakeLists.txt

@@ -2,6 +2,7 @@ add_library(vectorapi_core STATIC
     config.cpp
     errors.cpp
     db_errors.cpp
+    functions/mime_words.cpp
     json_http.cpp
     filters.cpp
     vector_search.cpp

+ 183 - 0
src/functions/imap_reader.hpp

@@ -0,0 +1,183 @@
+#pragma once
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+/// Reading IMAP server responses.
+///
+/// This exists because libcurl gives us a connection, TLS, authentication and
+/// timeouts, but NOT IMAP semantics: anything beyond a plain whole-message
+/// fetch has to go through CURLOPT_CUSTOMREQUEST, so we see raw protocol and
+/// parse it ourselves. Measured against a real curl build - BODY.PEEK, SEARCH,
+/// STORE, MOVE, LIST and BODYSTRUCTURE all require a custom request.
+///
+/// ⚠ THE LITERAL IS THE WHOLE PROBLEM. IMAP sends octet-counted literals:
+///
+///     * 1 FETCH (UID 7 BODY[TEXT] {14}
+///     hello\r\nworld!
+///      FLAGS (\Seen))
+///
+/// Those 14 bytes are DATA and may contain CRLF, unbalanced parentheses,
+/// quotes, NUL - anything. A line-based parser splits that into nonsense, and
+/// it does so only on real mail: every small test passes, because short test
+/// messages rarely contain a bare CRLF inside a literal. So the tokenizer is
+/// byte-counted, never line-based, and that is the single property most worth
+/// testing here.
+///
+/// Pure and allocation-light: feed it bytes, get tokens. No sockets, no curl,
+/// so the awkward cases can be tested exhaustively without a mail server.
+namespace svapi::functions {
+
+/// One IMAP token. A LITERAL and a QUOTED string are distinguished because
+/// only a literal may contain arbitrary bytes, and a caller that treats them
+/// alike will eventually mis-handle a quoted string containing a backslash
+/// escape.
+struct ImapToken {
+    enum class Kind { Atom, Quoted, Literal, ListOpen, ListClose, Nil };
+    Kind kind = Kind::Atom;
+    std::string text;          ///< decoded content; escapes already resolved
+};
+
+/// Why a parse stopped.
+enum class ImapParse {
+    Ok,            ///< a complete response was read
+    NeedMore,      ///< valid so far, but truncated - read more bytes and retry
+    Malformed,     ///< cannot be valid IMAP however many bytes arrive
+};
+
+/// A byte-counted IMAP response reader.
+///
+/// Deliberately NOT a streaming push parser: a response is read from a buffer
+/// that already holds it, and `NeedMore` tells the caller to read again. That
+/// keeps the awkward state - "we are 9 bytes into a 14-byte literal" - out of
+/// this class entirely, because that state is where a half-read response
+/// corrupts the next one. A handle whose read failed mid-literal has unknown
+/// stream position and must be destroyed rather than reused.
+class ImapReader {
+public:
+    explicit ImapReader(std::string_view buffer) : buf_(buffer) {}
+
+    /// Tokenize one response line (plus any literals it carries).
+    ///
+    /// Returns NeedMore when the buffer ends inside a literal or before the
+    /// terminating CRLF - which is the case a line-based reader gets wrong,
+    /// because the bytes it is missing may themselves contain CRLF.
+    ImapParse readLine(std::vector<ImapToken>& out) {
+        out.clear();
+        if (at_ >= buf_.size()) return ImapParse::NeedMore;
+        for (;;) {
+            if (at_ >= buf_.size()) return ImapParse::NeedMore;
+            const char c = buf_[at_];
+            if (c == '\r') {
+                if (at_ + 1 >= buf_.size()) return ImapParse::NeedMore;
+                if (buf_[at_ + 1] != '\n') return ImapParse::Malformed;
+                at_ += 2;
+                return ImapParse::Ok;
+            }
+            if (c == '\n') { ++at_; return ImapParse::Ok; }   // tolerated: some servers
+            if (c == ' ') { ++at_; continue; }
+            if (c == '(') { out.push_back({ImapToken::Kind::ListOpen, "("}); ++at_; continue; }
+            if (c == ')') { out.push_back({ImapToken::Kind::ListClose, ")"}); ++at_; continue; }
+            if (c == '"') {
+                std::string s;
+                const ImapParse r = readQuoted(s);
+                if (r != ImapParse::Ok) return r;
+                out.push_back({ImapToken::Kind::Quoted, std::move(s)});
+                continue;
+            }
+            if (c == '{') {
+                std::string s;
+                const ImapParse r = readLiteral(s);
+                if (r != ImapParse::Ok) return r;
+                out.push_back({ImapToken::Kind::Literal, std::move(s)});
+                continue;
+            }
+            // An atom: everything up to a delimiter. NIL is called out because
+            // it is a VALUE meaning absent, and a caller that sees the atom
+            // "NIL" as the three-letter string will store it as data - which
+            // is how a message ends up with a sender literally named NIL.
+            const size_t start = at_;
+            while (at_ < buf_.size() && !isDelim(buf_[at_])) ++at_;
+            std::string atom(buf_.substr(start, at_ - start));
+            const bool nil = atom.size() == 3 && (atom[0] == 'N' || atom[0] == 'n') &&
+                             (atom[1] == 'I' || atom[1] == 'i') && (atom[2] == 'L' || atom[2] == 'l');
+            out.push_back({nil ? ImapToken::Kind::Nil : ImapToken::Kind::Atom, std::move(atom)});
+        }
+    }
+
+    /// How many bytes have been consumed - the caller's resume point.
+    size_t consumed() const { return at_; }
+
+private:
+    static bool isDelim(char c) {
+        return c == ' ' || c == '(' || c == ')' || c == '\r' || c == '\n' || c == '"' || c == '{';
+    }
+
+    ImapParse readQuoted(std::string& out) {
+        ++at_;                                  // the opening quote
+        for (;;) {
+            if (at_ >= buf_.size()) return ImapParse::NeedMore;
+            const char c = buf_[at_];
+            if (c == '\\') {
+                // Only " and \ may be escaped. A quoted string may not contain
+                // CR or LF at all - that is what literals are for - so a bare
+                // one here is malformed rather than something to pass through.
+                if (at_ + 1 >= buf_.size()) return ImapParse::NeedMore;
+                const char n = buf_[at_ + 1];
+                if (n != '"' && n != '\\') return ImapParse::Malformed;
+                out += n;
+                at_ += 2;
+                continue;
+            }
+            if (c == '"') { ++at_; return ImapParse::Ok; }
+            if (c == '\r' || c == '\n') return ImapParse::Malformed;
+            out += c;
+            ++at_;
+        }
+    }
+
+    /// `{N}` CRLF then exactly N octets. The count is authoritative; the bytes
+    /// are opaque.
+    ImapParse readLiteral(std::string& out) {
+        const size_t brace = at_;
+        ++at_;                                   // '{'
+        uint64_t n = 0;
+        bool any = false;
+        while (at_ < buf_.size() && buf_[at_] >= '0' && buf_[at_] <= '9') {
+            // Bounded so a hostile or corrupt count cannot overflow into a
+            // small number and make us read the wrong span as data.
+            if (n > (kMaxLiteral / 10)) return ImapParse::Malformed;
+            n = n * 10 + static_cast<uint64_t>(buf_[at_] - '0');
+            ++at_;
+            any = true;
+        }
+        if (!any) { at_ = brace; return ImapParse::Malformed; }
+        // LITERAL+ writes `{N+}`; accept the marker on the way in, since a
+        // server may use it even though we cannot SEND one through curl.
+        if (at_ < buf_.size() && buf_[at_] == '+') ++at_;
+        if (at_ >= buf_.size()) return ImapParse::NeedMore;
+        if (buf_[at_] != '}') return ImapParse::Malformed;
+        ++at_;
+        if (at_ + 1 >= buf_.size()) return ImapParse::NeedMore;
+        if (buf_[at_] != '\r' || buf_[at_ + 1] != '\n') return ImapParse::Malformed;
+        at_ += 2;
+        if (n > kMaxLiteral) return ImapParse::Malformed;
+        if (buf_.size() - at_ < n) return ImapParse::NeedMore;
+        out.assign(buf_.substr(at_, static_cast<size_t>(n)));
+        at_ += static_cast<size_t>(n);
+        return ImapParse::Ok;
+    }
+
+    /// A ceiling on one literal, so a malformed or hostile count cannot make
+    /// us try to address a span larger than any mail we would accept. The
+    /// per-run caps live above this; this one only stops arithmetic nonsense.
+    static constexpr uint64_t kMaxLiteral = 256ull * 1024 * 1024;
+
+    std::string_view buf_;
+    size_t at_ = 0;
+};
+
+} // namespace svapi::functions

+ 60 - 0
src/functions/mime_base64.hpp

@@ -0,0 +1,60 @@
+#pragma once
+#include <string>
+
+/// base64 for the MIME layer, provided locally so mime_words.cpp needs nothing
+/// else from the project it was lifted from.
+///
+/// Deliberately a separate small header rather than a reach into the sibling
+/// project's string utilities: taking one file is a copy, taking its
+/// dependencies too is a fork.
+namespace svapi::functions {
+
+inline std::string mimeBase64Encode(const std::string& in) {
+    static const char* t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    std::string out;
+    out.reserve((in.size() + 2) / 3 * 4);
+    const auto* p = reinterpret_cast<const unsigned char*>(in.data());
+    for (std::size_t i = 0; i < in.size(); i += 3) {
+        const unsigned a = p[i];
+        const unsigned b = (i + 1 < in.size()) ? p[i + 1] : 0;
+        const unsigned c = (i + 2 < in.size()) ? p[i + 2] : 0;
+        const unsigned v = (a << 16) | (b << 8) | c;
+        out += t[(v >> 18) & 0x3F];
+        out += t[(v >> 12) & 0x3F];
+        out += (i + 1 < in.size()) ? t[(v >> 6) & 0x3F] : '=';
+        out += (i + 2 < in.size()) ? t[v & 0x3F] : '=';
+    }
+    return out;
+}
+
+/// Decodes, skipping whitespace - encoded words arrive folded across lines, so
+/// a decoder that refused embedded CRLF would reject ordinary mail. Invalid
+/// characters end the decode rather than being silently dropped, because a
+/// truncated value a caller can see beats a corrupted one it cannot.
+inline std::string mimeBase64Decode(const std::string& in) {
+    auto val = [](unsigned char c) -> int {
+        if (c >= 'A' && c <= 'Z') return c - 'A';
+        if (c >= 'a' && c <= 'z') return c - 'a' + 26;
+        if (c >= '0' && c <= '9') return c - '0' + 52;
+        if (c == '+') return 62;
+        if (c == '/') return 63;
+        return -1;
+    };
+    std::string out;
+    int buf = 0, bits = 0;
+    for (const unsigned char c : in) {
+        if (c == '=' ) break;
+        if (c == '\r' || c == '\n' || c == ' ' || c == '\t') continue;
+        const int v = val(c);
+        if (v < 0) break;
+        buf = (buf << 6) | v;
+        bits += 6;
+        if (bits >= 8) {
+            bits -= 8;
+            out += static_cast<char>((buf >> bits) & 0xFF);
+        }
+    }
+    return out;
+}
+
+} // namespace svapi::functions

+ 305 - 0
src/functions/mime_words.cpp

@@ -0,0 +1,305 @@
+// ============================================================================
+// ADAPTED FROM AN EXISTING INTERNAL IMPLEMENTATION, AND NOW OURS TO MAINTAIN.
+//
+// Brought in 2026-10-08 with permission, from another of our own codebases.
+// That codebase is deliberately not identified here and this file carries no
+// reference to it: it ships inside our .deb packages and lives in a repository
+// with a remote, so naming it would disclose something that is not ours to
+// disclose.
+//
+// TREAT THIS COPY AS OURS. The two cannot be kept in sync for reasons outside
+// engineering, so there is no upstream to defer to and no fix that will arrive
+// on its own. Develop it forward here, test it here, and do not assume a bug
+// found here has been fixed anywhere else. If the two are ever allowed to
+// converge, that will be a deliberate exercise rather than a merge.
+//
+// Why it was worth adapting rather than writing from scratch: it already
+// handles both directions of RFC 2047, folding across lines, RFC 2231
+// parameter encoding, and - the one that would have cost a day to learn -
+// `envelopeAddress`, which exists because handing MAIL FROM or RCPT TO a
+// display-name form produces a malformed command and the server drops the
+// connection, reported only as "Failed sending data to the peer", naming
+// neither the address nor the reason.
+//
+// Adapted on the way in: the namespace, and its two base64 helpers are now
+// provided locally (mime_base64.hpp) so this file depends on nothing external.
+// Its tests came with it - see tests/test_mime_words.cpp - because the value
+// of adapting a tested component is the tests.
+// ============================================================================
+
+#include "functions/mime_words.hpp"
+
+#include "functions/mime_base64.hpp"
+
+#include <algorithm>
+#include <cctype>
+#include <sstream>
+
+namespace svapi::functions {
+
+namespace {
+
+int hexValue(char c) {
+    if (c >= '0' && c <= '9') return c - '0';
+    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
+    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
+    return -1;
+}
+
+std::string upper(std::string text) {
+    std::transform(text.begin(), text.end(), text.begin(),
+                   [](unsigned char c) { return std::toupper(c); });
+    return text;
+}
+
+// ISO-8859-1 and -2 are still what a good deal of European mail says it is.
+// Only 8859-1 maps trivially - each byte is the code point - so that is the one
+// converted; anything else is left as it arrived rather than guessed at.
+std::string latin1ToUtf8(const std::string& input) {
+    std::string out;
+    out.reserve(input.size() * 2);
+    for (unsigned char c : input) {
+        if (c < 0x80) {
+            out.push_back(static_cast<char>(c));
+        } else {
+            out.push_back(static_cast<char>(0xC0 | (c >> 6)));
+            out.push_back(static_cast<char>(0x80 | (c & 0x3F)));
+        }
+    }
+    return out;
+}
+
+std::string decodeQ(const std::string& payload) {
+    std::string out;
+    out.reserve(payload.size());
+    for (size_t i = 0; i < payload.size(); ++i) {
+        const char c = payload[i];
+        if (c == '_') {
+            // In an encoded word an underscore is a space, not an underscore.
+            out.push_back(' ');
+        } else if (c == '=' && i + 2 < payload.size()) {
+            const int hi = hexValue(payload[i + 1]);
+            const int lo = hexValue(payload[i + 2]);
+            if (hi >= 0 && lo >= 0) {
+                out.push_back(static_cast<char>((hi << 4) | lo));
+                i += 2;
+            } else {
+                out.push_back(c);
+            }
+        } else {
+            out.push_back(c);
+        }
+    }
+    return out;
+}
+
+std::string toUtf8(const std::string& charset, const std::string& bytes) {
+    const std::string cs = upper(charset);
+    if (cs == "UTF-8" || cs == "UTF8" || cs == "US-ASCII" || cs == "ASCII") {
+        return bytes;
+    }
+    if (cs == "ISO-8859-1" || cs == "LATIN1" || cs == "ISO8859-1" || cs == "WINDOWS-1252") {
+        return latin1ToUtf8(bytes);
+    }
+    // An unknown charset is passed through. It may render oddly; it will not
+    // disappear, and the caller can still see what arrived.
+    return bytes;
+}
+
+} // namespace
+
+bool MimeWords::isAscii(const std::string& value) {
+    return std::all_of(value.begin(), value.end(),
+                       [](unsigned char c) { return c < 0x80; });
+}
+
+std::string MimeWords::decode(const std::string& value) {
+    if (value.find("=?") == std::string::npos) {
+        return value;
+    }
+
+    std::string out;
+    out.reserve(value.size());
+
+    size_t pos = 0;
+    bool previous_was_word = false;
+    while (pos < value.size()) {
+        const size_t start = value.find("=?", pos);
+        if (start == std::string::npos) {
+            out.append(value, pos, std::string::npos);
+            break;
+        }
+
+        // Whitespace between two encoded words is separator, not content, and
+        // is dropped - that is how a value too long for one word is rejoined.
+        std::string between = value.substr(pos, start - pos);
+        const bool only_space = !between.empty() &&
+            std::all_of(between.begin(), between.end(),
+                        [](unsigned char c) { return std::isspace(c); });
+        if (!(previous_was_word && only_space)) {
+            out += between;
+        }
+
+        const size_t charset_end = value.find('?', start + 2);
+        if (charset_end == std::string::npos) { out += value.substr(start); break; }
+        const size_t encoding_end = value.find('?', charset_end + 1);
+        if (encoding_end == std::string::npos) { out += value.substr(start); break; }
+        const size_t word_end = value.find("?=", encoding_end + 1);
+        if (word_end == std::string::npos) { out += value.substr(start); break; }
+
+        const std::string charset = value.substr(start + 2, charset_end - start - 2);
+        const std::string encoding = value.substr(charset_end + 1, encoding_end - charset_end - 1);
+        const std::string payload = value.substr(encoding_end + 1, word_end - encoding_end - 1);
+
+        std::string bytes;
+        if (encoding == "B" || encoding == "b") {
+            bytes = mimeBase64Decode(payload);
+        } else if (encoding == "Q" || encoding == "q") {
+            bytes = decodeQ(payload);
+        } else {
+            // Not an encoding we know - keep the word as written.
+            out += value.substr(start, word_end + 2 - start);
+            pos = word_end + 2;
+            previous_was_word = false;
+            continue;
+        }
+
+        out += toUtf8(charset, bytes);
+        pos = word_end + 2;
+        previous_was_word = true;
+    }
+
+    return out;
+}
+
+std::string MimeWords::encode(const std::string& value) {
+    if (isAscii(value)) {
+        return value;
+    }
+
+    // Base64 rather than Q: the values that need encoding here are mostly
+    // non-ASCII throughout, where Q would escape nearly every character.
+    //
+    // A word may be 75 characters including the `=?UTF-8?B?` and `?=` around
+    // it, so the payload is capped at 45 bytes - a multiple of 3, so no word
+    // ends mid-base64-group and each decodes on its own. Splitting is done on
+    // UTF-8 character boundaries so a multi-byte character is never cut in two.
+    constexpr size_t kMaxBytes = 45;
+    std::string out;
+    size_t pos = 0;
+    while (pos < value.size()) {
+        size_t take = std::min(kMaxBytes, value.size() - pos);
+        // Do not split inside a UTF-8 sequence: back off while the next byte is
+        // a continuation byte.
+        while (take > 0 && pos + take < value.size() &&
+               (static_cast<unsigned char>(value[pos + take]) & 0xC0) == 0x80) {
+            --take;
+        }
+        if (take == 0) take = std::min(kMaxBytes, value.size() - pos);
+
+        if (!out.empty()) out += "\r\n ";  // fold, as a long header must
+        out += "=?UTF-8?B?" + mimeBase64Encode(value.substr(pos, take)) + "?=";
+        pos += take;
+    }
+    return out;
+}
+
+std::string MimeWords::encodeAddress(const std::string& address) {
+    // `Display Name <local@domain>`. Only the display name may be touched; the
+    // address inside the angle brackets must go out exactly as it came.
+    const size_t open = address.rfind('<');
+    const size_t close = address.rfind('>');
+    if (open == std::string::npos || close == std::string::npos || close < open) {
+        // A bare address, or something we cannot split with confidence.
+        // Encoding the whole of it would corrupt the address itself, so it is
+        // left alone even when it is not ASCII.
+        return address;
+    }
+
+    std::string name = address.substr(0, open);
+    const std::string addr = address.substr(open, close - open + 1);
+
+    while (!name.empty() && std::isspace(static_cast<unsigned char>(name.back()))) {
+        name.pop_back();
+    }
+    // Often already quoted; the quotes must not end up inside the encoded word
+    // or doubled.
+    if (name.size() >= 2 && name.front() == '"' && name.back() == '"') {
+        name = name.substr(1, name.size() - 2);
+    }
+    if (name.empty()) {
+        return addr;
+    }
+
+    if (!isAscii(name)) {
+        // An encoded word is its own token and must NOT be wrapped in quotes -
+        // a quoted encoded word is treated as literal text by a conforming
+        // reader, which is how a name arrives looking like =?UTF-8?B?...?=.
+        return encode(name) + " " + addr;
+    }
+
+    // ASCII, but a display name carrying any of the specials RFC 5322 reserves
+    // has to be quoted or it breaks the address list it sits in - a comma in
+    // "Doe, John" otherwise reads as the end of one address and the start of
+    // another.
+    const std::string specials = "()<>[]:;@\\,.\"";
+    if (name.find_first_of(specials) != std::string::npos) {
+        std::string escaped;
+        escaped.reserve(name.size() + 2);
+        for (char c : name) {
+            if (c == '"' || c == '\\') escaped.push_back('\\');
+            escaped.push_back(c);
+        }
+        return "\"" + escaped + "\" " + addr;
+    }
+
+    return name + " " + addr;
+}
+
+std::string MimeWords::envelopeAddress(const std::string& address) {
+    const size_t open = address.rfind('<');
+    const size_t close = address.rfind('>');
+    if (open != std::string::npos && close != std::string::npos && close > open) {
+        return address.substr(open + 1, close - open - 1);
+    }
+    std::string trimmed = address;
+    while (!trimmed.empty() && std::isspace(static_cast<unsigned char>(trimmed.front()))) {
+        trimmed.erase(trimmed.begin());
+    }
+    while (!trimmed.empty() && std::isspace(static_cast<unsigned char>(trimmed.back()))) {
+        trimmed.pop_back();
+    }
+    return trimmed;
+}
+
+std::string MimeWords::encodeParameter(const std::string& name, const std::string& value) {
+    if (isAscii(value)) {
+        return name + "=\"" + value + "\"";
+    }
+
+    // RFC 2231. An ASCII-only fallback is emitted alongside for readers that do
+    // not implement it; a reader that does prefers the starred form.
+    std::string ascii;
+    ascii.reserve(value.size());
+    for (unsigned char c : value) {
+        ascii.push_back(c < 0x80 ? static_cast<char>(c) : '_');
+    }
+
+    std::ostringstream percent;
+    percent << std::hex;
+    for (unsigned char c : value) {
+        const bool safe = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+                          (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_';
+        if (safe) {
+            percent << static_cast<char>(c);
+        } else {
+            percent << '%' << (c < 16 ? "0" : "")
+                    << upper(std::string(1, "0123456789abcdef"[c >> 4]))
+                    << upper(std::string(1, "0123456789abcdef"[c & 0x0F]));
+        }
+    }
+
+    return name + "=\"" + ascii + "\"; " + name + "*=UTF-8''" + percent.str();
+}
+
+} // namespace svapi::functions

+ 80 - 0
src/functions/mime_words.hpp

@@ -0,0 +1,80 @@
+#pragma once
+// ============================================================================
+// ADAPTED FROM AN EXISTING INTERNAL IMPLEMENTATION, AND NOW OURS TO MAINTAIN.
+//
+// Brought in 2026-10-08 with permission, from another of our own codebases.
+// That codebase is deliberately not identified here and this file carries no
+// reference to it: it ships inside our .deb packages and lives in a repository
+// with a remote, so naming it would disclose something that is not ours to
+// disclose.
+//
+// TREAT THIS COPY AS OURS. The two cannot be kept in sync for reasons outside
+// engineering, so there is no upstream to defer to and no fix that will arrive
+// on its own. Develop it forward here, test it here, and do not assume a bug
+// found here has been fixed anywhere else. If the two are ever allowed to
+// converge, that will be a deliberate exercise rather than a merge.
+//
+// Why it was worth adapting rather than writing from scratch: it already
+// handles both directions of RFC 2047, folding across lines, RFC 2231
+// parameter encoding, and - the one that would have cost a day to learn -
+// `envelopeAddress`, which exists because handing MAIL FROM or RCPT TO a
+// display-name form produces a malformed command and the server drops the
+// connection, reported only as "Failed sending data to the peer", naming
+// neither the address nor the reason.
+//
+// Adapted on the way in: the namespace, and its two base64 helpers are now
+// provided locally (mime_base64.hpp) so this file depends on nothing external.
+// Its tests came with it - see tests/test_mime_words.cpp - because the value
+// of adapting a tested component is the tests.
+// ============================================================================
+
+
+#include <string>
+
+namespace svapi::functions {
+
+// RFC 2047 encoded words, both directions.
+//
+// A mail header is defined to be ASCII. Anything else - an accented name, a
+// subject in Hungarian, a filename with a Sárkány in it - travels as an encoded
+// word, `=?UTF-8?Q?...?=`, and long values are split into several of them and
+// folded across lines. Neither direction was handled here: inbound values were
+// passed on still encoded, and outbound values were written raw, which is not
+// valid and is mangled by the servers that do not quietly tolerate it.
+class MimeWords {
+public:
+    // Decode any encoded words in a header value, leaving the rest alone.
+    // Unknown charsets and malformed words are returned untouched rather than
+    // dropped - a name that survives as gibberish is better than one that
+    // vanishes.
+    static std::string decode(const std::string& value);
+
+    // Encode a header value if it needs it, as one or more `=?UTF-8?B?...?=`
+    // words no longer than RFC 2047 allows. Pure ASCII is returned unchanged,
+    // so ordinary headers stay readable in a raw message.
+    static std::string encode(const std::string& value);
+
+    // Encode the display name of an address, keeping the address itself
+    // untouched: `Szontágh Ferenc <a@b>` becomes `=?UTF-8?B?...?= <a@b>`.
+    // An address with no display name is returned as it came.
+    static std::string encodeAddress(const std::string& address);
+
+    // A MIME parameter such as a filename. Emits the RFC 2231 form
+    // (`filename*=UTF-8''...`) when the value is not ASCII, which is what
+    // modern clients read, and only the plain form when it is.
+    //
+    // `name` is the parameter name, e.g. "filename" or "name".
+    static std::string encodeParameter(const std::string& name, const std::string& value);
+
+    // The bare address for an SMTP envelope: `Name <a@b.com>` becomes
+    // `a@b.com`. MAIL FROM and RCPT TO take an address and nothing else -
+    // handing them the display-name form produces a malformed command and the
+    // server drops the connection, reported only as "Failed sending data to
+    // the peer".
+    static std::string envelopeAddress(const std::string& address);
+
+    // Whether a string is plain ASCII, and so needs none of the above.
+    static bool isAscii(const std::string& value);
+};
+
+} // namespace svapi::functions

+ 16 - 0
tests/CMakeLists.txt

@@ -233,6 +233,22 @@ target_include_directories(test_db_await PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_db_await PRIVATE GTest::gtest_main)
 gtest_discover_tests(test_db_await)
 
+# Pure: no curl, no sockets, no mail server. The awkward cases - a literal
+# containing CRLF, parens, NUL - are exactly the ones a real server produces
+# and a line-based parser gets wrong.
+add_executable(test_imap_reader test_imap_reader.cpp)
+target_include_directories(test_imap_reader PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_imap_reader PRIVATE GTest::gtest_main)
+gtest_discover_tests(test_imap_reader)
+
+# RFC 2047, lifted with the code from the sibling project and ported from its
+# hand-rolled main() to gtest. Every case the original covered is kept: the
+# value of taking a tested component is the tests.
+add_executable(test_mime_words test_mime_words.cpp)
+target_include_directories(test_mime_words PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_mime_words PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_mime_words)
+
 add_executable(test_file_name test_file_name.cpp)
 target_include_directories(test_file_name PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_file_name PRIVATE vectorapi_core GTest::gtest_main)

+ 198 - 0
tests/test_imap_reader.cpp

@@ -0,0 +1,198 @@
+#include "functions/imap_reader.hpp"
+#include <gtest/gtest.h>
+
+// The IMAP response reader. These tests are aimed at ONE property: the
+// tokenizer is byte-counted, never line-based. A line-based parser passes
+// every short, tidy test and corrupts real mail, because a literal's bytes may
+// contain CRLF, unbalanced parentheses and quotes - and short test messages
+// rarely do. So most of what follows is literals containing exactly the things
+// that would break a split-on-CRLF reader.
+namespace {
+
+using svapi::functions::ImapReader;
+using svapi::functions::ImapParse;
+using svapi::functions::ImapToken;
+using Kind = ImapToken::Kind;
+
+std::vector<ImapToken> parseOne(const std::string& in, ImapParse expect = ImapParse::Ok) {
+    ImapReader r(in);
+    std::vector<ImapToken> t;
+    EXPECT_EQ(r.readLine(t), expect);
+    return t;
+}
+
+TEST(ImapReader, AnOrdinaryUntaggedLine) {
+    const auto t = parseOne("* 1 EXISTS\r\n");
+    ASSERT_EQ(t.size(), 3u);
+    EXPECT_EQ(t[0].text, "*");
+    EXPECT_EQ(t[1].text, "1");
+    EXPECT_EQ(t[2].text, "EXISTS");
+}
+
+TEST(ImapReader, ALiteralContainingCRLFIsONEToken) {
+    // THE TEST THAT MATTERS. Split this on CRLF and you get three lines, two
+    // of them nonsense. The {12} is authoritative: those bytes are data.
+    //
+    // Searched by KIND rather than by index. The first version asserted on
+    // t[3] and t[4] and failed - not because the parser was wrong but because
+    // I had miscounted the tokens, forgetting the '(' - and it also declared
+    // {13} for a 12-byte literal. A positional assertion silently encodes an
+    // assumption about how many tokens there are, which is not the property
+    // under test.
+    const auto t = parseOne("* 1 FETCH (BODY[TEXT] {12}\r\nhello\r\nworld\r\n");
+    const ImapToken* lit = nullptr;
+    const ImapToken* field = nullptr;
+    for (const auto& tok : t) {
+        if (tok.kind == Kind::Literal) lit = &tok;
+        if (tok.kind == Kind::Atom && tok.text == "BODY[TEXT]") field = &tok;
+    }
+    ASSERT_NE(field, nullptr) << "the fetch item name must survive as one atom";
+    ASSERT_NE(lit, nullptr);
+    EXPECT_EQ(lit->text, "hello\r\nworld") << "the literal must survive its own CRLF intact";
+    EXPECT_EQ(lit->text.size(), 12u);
+}
+
+TEST(ImapReader, ALiteralContainingParensAndQuotesDoesNotDisturbTheStructure) {
+    // A real message body routinely contains these. A reader that scanned for
+    // the closing paren would end the FETCH in the middle of the mail.
+    const std::string body = "Dear \"Bob\",\r\n(see attached) )))\r\n";
+    const std::string in = "* 7 FETCH (UID 7 BODY[TEXT] {" + std::to_string(body.size()) +
+                           "}\r\n" + body + " FLAGS (\\Seen))\r\n";
+    const auto t = parseOne(in);
+    bool found = false;
+    for (const auto& tok : t)
+        if (tok.kind == Kind::Literal) { EXPECT_EQ(tok.text, body); found = true; }
+    ASSERT_TRUE(found);
+    // The structure after the literal must still parse: the FLAGS list and the
+    // closing paren of the FETCH.
+    ASSERT_GE(t.size(), 8u);
+    EXPECT_EQ(t.back().kind, Kind::ListClose);
+}
+
+TEST(ImapReader, ALiteralMayContainNulAndHighBytes) {
+    // 8-bit and NUL are legal in a literal. A reader using C-string semantics
+    // truncates here, which loses mail silently.
+    std::string body("a\0b\xc3\xa9", 5);
+    const std::string in = "* 1 FETCH (BODY[] {5}\r\n" + body + "\r\n";
+    const auto t = parseOne(in);
+    bool found = false;
+    for (const auto& tok : t)
+        if (tok.kind == Kind::Literal) {
+            EXPECT_EQ(tok.text.size(), 5u);
+            EXPECT_EQ(tok.text, body);
+            found = true;
+        }
+    ASSERT_TRUE(found);
+}
+
+TEST(ImapReader, ATruncatedLiteralAsksForMoreRatherThanGuessing) {
+    // The buffer promises 20 bytes and holds 5. Returning what is there would
+    // hand the caller a short body that looks complete.
+    (void)parseOne("* 1 FETCH (BODY[] {20}\r\nshort", ImapParse::NeedMore);
+}
+
+TEST(ImapReader, ALineTruncatedBeforeItsCRLFAsksForMore) {
+    (void)parseOne("* 1 EXI", ImapParse::NeedMore);
+    // And a lone CR, which must not be mistaken for a terminator.
+    (void)parseOne("* 1 EXISTS\r", ImapParse::NeedMore);
+}
+
+TEST(ImapReader, NILIsAValueMeaningAbsentNotTheStringNIL) {
+    // ENVELOPE and BODYSTRUCTURE are full of NIL. A caller that stores the
+    // atom would end up with a message whose sender is literally named NIL.
+    const auto t = parseOne("* 1 FETCH (ENVELOPE (NIL \"Subject\" nil))\r\n");
+    int nils = 0, quoted = 0;
+    for (const auto& tok : t) {
+        if (tok.kind == Kind::Nil) ++nils;
+        if (tok.kind == Kind::Quoted) ++quoted;
+    }
+    EXPECT_EQ(nils, 2) << "both spellings of NIL are the absent value";
+    EXPECT_EQ(quoted, 1);
+}
+
+TEST(ImapReader, QuotedEscapesAreResolvedAndOnlyTheTwoLegalOnesAccepted) {
+    const auto t = parseOne("* OK \"say \\\"hi\\\" and a \\\\ slash\"\r\n");
+    bool found = false;
+    for (const auto& tok : t)
+        if (tok.kind == Kind::Quoted) { EXPECT_EQ(tok.text, "say \"hi\" and a \\ slash"); found = true; }
+    ASSERT_TRUE(found);
+    // \n is not a legal escape in an IMAP quoted string.
+    (void)parseOne("* OK \"bad \\n escape\"\r\n", ImapParse::Malformed);
+}
+
+TEST(ImapReader, AQuotedStringMayNotContainABareCRLF) {
+    // That is what literals exist for. Accepting it would let a malformed
+    // response swallow the rest of the stream as string content.
+    (void)parseOne("* OK \"line\r\nbreak\"\r\n", ImapParse::Malformed);
+}
+
+TEST(ImapReader, AnAbsurdLiteralCountIsRefusedRatherThanTrusted) {
+    // A corrupt or hostile count must not make us address a span we would
+    // never accept, and must not overflow into a small number on the way.
+    (void)parseOne("* 1 FETCH (BODY[] {99999999999999999999}\r\nx\r\n", ImapParse::Malformed);
+    (void)parseOne("* 1 FETCH (BODY[] {}\r\nx\r\n", ImapParse::Malformed);
+}
+
+TEST(ImapReader, ALiteralPlusCountIsAccepted) {
+    // We cannot SEND a LITERAL+ through curl, but a server may use one, and
+    // refusing to read it would break against those servers for no reason.
+    const auto t = parseOne("* 1 FETCH (BODY[] {5+}\r\nhello\r\n");
+    bool found = false;
+    for (const auto& tok : t)
+        if (tok.kind == Kind::Literal) { EXPECT_EQ(tok.text, "hello"); found = true; }
+    ASSERT_TRUE(found);
+}
+
+TEST(ImapReader, SuccessiveResponsesAreReadFromOneBufferWithoutLosingPosition) {
+    // A real read returns several responses at once, and the second one begins
+    // immediately after the first literal's bytes - which is exactly where a
+    // line-based reader has already lost its place.
+    const std::string in =
+        "* 1 FETCH (UID 1 BODY[] {7}\r\na\r\nb\r\nc"      // literal holds two CRLFs
+        ")\r\n"
+        "* 2 FETCH (UID 2 FLAGS (\\Seen))\r\n"
+        "A004 OK FETCH completed\r\n";
+    ImapReader r(in);
+    std::vector<ImapToken> t;
+    ASSERT_EQ(r.readLine(t), ImapParse::Ok);
+    bool sawLiteral = false;
+    for (const auto& tok : t) if (tok.kind == Kind::Literal) { EXPECT_EQ(tok.text, "a\r\nb\r\nc"); sawLiteral = true; }
+    ASSERT_TRUE(sawLiteral);
+
+    // The second response, found by content rather than by position - same
+    // reason as above.
+    ASSERT_EQ(r.readLine(t), ImapParse::Ok);
+    bool sawUid = false, sawSeen = false;
+    for (const auto& tok : t) {
+        if (tok.text == "UID") sawUid = true;
+        if (tok.text == "\\Seen") sawSeen = true;
+    }
+    EXPECT_TRUE(sawUid) << "the second FETCH must parse after the first literal";
+    EXPECT_TRUE(sawSeen);
+
+    // And the TAGGED completion, which is how a caller knows the command
+    // finished. Losing it is the failure that matters: a reader that is lost
+    // after a literal waits forever for a completion it already consumed.
+    ASSERT_EQ(r.readLine(t), ImapParse::Ok);
+    ASSERT_GE(t.size(), 2u);
+    EXPECT_EQ(t[0].text, "A004");
+    EXPECT_EQ(t[1].text, "OK") << "the tagged completion must still be reachable";
+}
+
+TEST(ImapReader, TheUidvalidityResponseCodeIsReadable) {
+    // The whole id-staleness guarantee rests on seeing this. Measured
+    // separately: curl delivers it on the HEADER callback when SELECT comes
+    // from the URL path, so whatever reads it must be fed that stream too.
+    const auto t = parseOne("* OK [UIDVALIDITY 42] uidvalidity\r\n");
+    bool sawCode = false;
+    for (size_t i = 0; i + 1 < t.size(); ++i)
+        if (t[i].text == "[UIDVALIDITY" || t[i].text == "[UIDVALIDITY]") sawCode = true;
+    // The bracketed code arrives as atoms; what matters is that 42 survives as
+    // a token the caller can find rather than being swallowed.
+    bool saw42 = false;
+    for (const auto& tok : t) if (tok.text.find("42") != std::string::npos) saw42 = true;
+    EXPECT_TRUE(saw42) << "UIDVALIDITY's value must be reachable";
+    (void)sawCode;
+}
+
+} // namespace

+ 130 - 0
tests/test_mime_words.cpp

@@ -0,0 +1,130 @@
+#include "functions/mime_words.hpp"
+#include <gtest/gtest.h>
+
+// RFC 2047 encoded words, both directions.
+//
+// Adapted with the code (see the note in mime_words.hpp) and ported to
+// GoogleTest so ctest runs it alongside everything else. Every case the
+// original covered is here; nothing was dropped for convenience, because the
+// value of adapting a tested component is the tests. There is no upstream to
+// re-sync from, so these are now the only tests this code has.
+//
+// Pure logic, no I/O, no mail server. The Hungarian cases are not decoration -
+// this product's content is Hungarian, so an accented display name is the
+// ordinary case rather than the exotic one.
+namespace {
+
+using svapi::functions::MimeWords;
+
+// --- decoding: what arrives from a mail server ------------------------------
+
+TEST(MimeWords, DecodesANameInFrontOfAnAddressLeavingTheAddressAlone) {
+    // The shape that started it: only the display name is encoded, and the
+    // address must come through untouched.
+    EXPECT_EQ(MimeWords::decode("=?UTF-8?Q?Szont=C3=A1gh_Ferenc?= <ferenc.szontagh@smartbotics.ai>"),
+              "Szontágh Ferenc <ferenc.szontagh@smartbotics.ai>");
+}
+
+TEST(MimeWords, RejoinsTwoWordsWithoutTheFoldSpace) {
+    // A value too long for one word is split, and the whitespace BETWEEN the
+    // words is a separator - it must not survive into the decoded text.
+    EXPECT_EQ(MimeWords::decode("=?UTF-8?Q?a=C3=A1?= =?UTF-8?Q?b=C3=A9?="), "aábé");
+}
+
+TEST(MimeWords, DecodesBothEncodings) {
+    EXPECT_EQ(MimeWords::decode("=?UTF-8?B?w6FydsOtenTFsQ==?="), "árvíztű");
+    EXPECT_EQ(MimeWords::decode("=?UTF-8?Q?a_b?="), "a b") << "underscore is a space in Q";
+}
+
+TEST(MimeWords, LeavesAloneWhatItCannotOrShouldNotTouch) {
+    EXPECT_EQ(MimeWords::decode("Hello there"), "Hello there");
+
+    // THE ORIGINAL'S CASES, VERBATIM. My first port invented its own inputs
+    // and got the semantics wrong in two ways at once: it used B encoding (so
+    // "abcd" base64-decoded to binary) and expected the whole encoded word
+    // back. The actual contract is subtler and better:
+    //
+    // An UNKNOWN CHARSET still has its transfer encoding undone and the label
+    // dropped, so the bytes reach the caller as something rather than nothing -
+    // "gibberish is better than nothing", which is also why `decode` is
+    // documented as never dropping a value.
+    EXPECT_EQ(MimeWords::decode("=?SHIFT_JIS?Q?abc?="), "abc");
+
+    // A MALFORMED WORD - no closing `?=` - is returned exactly as it arrived,
+    // because there is nothing to decode and a truncated guess would be worse
+    // than the raw text.
+    EXPECT_EQ(MimeWords::decode("=?UTF-8?Q?unterminated"), "=?UTF-8?Q?unterminated");
+}
+
+// --- encoding: what we put on the wire --------------------------------------
+
+TEST(MimeWords, AsciiIsLeftReadable) {
+    // So an ordinary header stays legible in a raw message.
+    EXPECT_EQ(MimeWords::encode("Plain subject"), "Plain subject");
+    EXPECT_EQ(MimeWords::encodeAddress("a@b.com"), "a@b.com");
+    EXPECT_EQ(MimeWords::encodeAddress("John <a@b.com>"), "John <a@b.com>");
+}
+
+TEST(MimeWords, ACommaInADisplayNameForcesQuoting) {
+    // Unquoted, a comma makes one address look like two.
+    const std::string got = MimeWords::encodeAddress("Doe, John <a@b.com>");
+    EXPECT_NE(got.find('"'), std::string::npos) << got;
+    EXPECT_NE(got.find("a@b.com"), std::string::npos) << got;
+}
+
+TEST(MimeWords, ExistingQuotesAreNotDoubled) {
+    const std::string got = MimeWords::encodeAddress("\"Doe, John\" <a@b.com>");
+    EXPECT_EQ(got.find("\"\""), std::string::npos) << got;
+}
+
+TEST(MimeWords, RoundTripsWhateverWeSend) {
+    // The property that matters most: whatever we send, a conforming reader
+    // gets back what we meant.
+    for (const std::string& original : {std::string("Szontágh Ferenc"),
+                                        std::string("Sárkányok párzási és étkezési szokásaik"),
+                                        std::string("árvíztűrő tükörfúrógép"),
+                                        std::string("plain ascii")})
+        EXPECT_EQ(MimeWords::decode(MimeWords::encode(original)), original) << original;
+
+    EXPECT_EQ(MimeWords::decode(MimeWords::encodeAddress("Szontágh Ferenc <a@b.com>")),
+              "Szontágh Ferenc <a@b.com>");
+}
+
+// --- the header/envelope distinction, which is where a send breaks ----------
+
+TEST(MimeWords, TheEnvelopeTakesAnAddressAndNothingElse) {
+    // A display name in RCPT TO is a malformed command, and the server answers
+    // by dropping the connection - reported as "Failed sending data to the
+    // peer", which names neither the address nor the reason. That is why this
+    // function exists rather than being a caller's responsibility.
+    EXPECT_EQ(MimeWords::envelopeAddress("Szontágh Ferenc <a@b.com>"), "a@b.com");
+    EXPECT_EQ(MimeWords::envelopeAddress("a@b.com"), "a@b.com");
+    EXPECT_EQ(MimeWords::envelopeAddress("  a@b.com  "), "a@b.com");
+    EXPECT_EQ(MimeWords::envelopeAddress("\"Doe, John\" <a@b.com>"), "a@b.com");
+}
+
+TEST(MimeWords, OneAddressYieldsTwoDifferentThings) {
+    // The pair, from a single address: the HEADER keeps the display name
+    // (RFC 5322 name-addr, which is what the recipient's client shows) and the
+    // ENVELOPE drops it (RFC 5321 takes an address only). They are two
+    // different "To"s, and feeding one to the other is what broke a send.
+    const std::string address = "Szontágh Ferenc <ferenc.szontagh@smartbotics.ai>";
+    const std::string header = MimeWords::encodeAddress(address);
+    EXPECT_EQ(MimeWords::decode(header), address) << "the header round-trips to what was meant";
+    EXPECT_NE(header.find("ferenc.szontagh@smartbotics.ai"), std::string::npos)
+        << "and keeps the address untouched: " << header;
+    EXPECT_EQ(MimeWords::envelopeAddress(address), "ferenc.szontagh@smartbotics.ai");
+}
+
+TEST(MimeWords, AFilenameUsesRfc2231WhenItNeedsTo) {
+    EXPECT_EQ(MimeWords::encodeParameter("filename", "report.pdf"), "filename=\"report.pdf\"");
+    const std::string param = MimeWords::encodeParameter("filename", "Sárkányok.pdf");
+    EXPECT_NE(param.find("filename*=UTF-8''"), std::string::npos) << param;
+}
+
+TEST(MimeWords, IsAsciiAnswersWhatItSays) {
+    EXPECT_TRUE(MimeWords::isAscii("plain"));
+    EXPECT_FALSE(MimeWords::isAscii("Sárkány"));
+}
+
+} // namespace