Something went wrong. Try again.
An IMAP client library for Zig 0.17, covering IMAP4rev2 and rev1 with STARTTLS, implicit TLS, SASL authentication and streamed literals. jeff.jcollie.page/zig-imap
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! IMAP responses, parsed one line at a time: the tagged status line that//! ends a command, the untagged data that precedes it, the continuation//! request, and the typed payloads carried by particular untagged responses.//!//! Every `[]const u8` here borrows from the reader's buffer and is//! invalidated by the next read on the connection; copy what you keep. The//! types with fixed storage — `Capabilities`, `Mailbox`, `FlagList` — are//! the exception, and exist so that session state survives the next read.//!//! * IMAP4rev2: https://datatracker.ietf.org/doc/html/rfc9051//! * IMAP4rev1: https://datatracker.ietf.org/doc/html/rfc3501
const std = @import("std");const parser = @import("parser.zig");
pub const Scanner = parser.Scanner;pub const Token = parser.Token;pub const String = parser.String;
pub const ParseError = error{InvalidResponse};
/// The condition of a status response. `ok`, `no` and `bad` end a command;/// `preauth` and `bye` only ever come untagged./// https://datatracker.ietf.org/doc/html/rfc9051#section-7.1pub const Status = enum { ok, /// The command failed for an operational reason: no such mailbox, a /// permission denied, a quota exceeded. no, /// The command was not understood, or not valid in this state: a /// protocol error, and usually a bug on one side or the other. bad, /// The greeting of a connection that needs no login. preauth, /// The server is closing the connection. bye,
fn parse(word: []const u8) ?Status { inline for (@typeInfo(Status).@"enum".field_names) |name| { if (std.ascii.eqlIgnoreCase(word, name)) return @field(Status, name); } return null; }};
/// A response code: the `[...]` that may lead the text of a status/// response, giving the reason in a form a program can act on./// https://datatracker.ietf.org/doc/html/rfc9051#section-7.1pub const Code = struct { /// The code's name, e.g. `UIDVALIDITY`, `PERMANENTFLAGS`, `ALERT`. name: []const u8, /// Whatever followed the name inside the brackets, e.g. `3857529045`, /// `(\Deleted \Seen \*)`, or nothing. args: []const u8,
/// The arguments as one number, for the codes that carry one. pub fn number(c: Code, comptime T: type) ?T { return parser.parseDigits(T, c.args) orelse null; }
pub fn is(c: Code, name: []const u8) bool { return std.ascii.eqlIgnoreCase(c.name, name); }};
/// A status response: the condition, the optional response code, and the/// text meant for a human.pub const StatusResponse = struct { status: Status, code: ?Code, /// The text after the response code, or the whole text when there is /// none. May be empty. text: []const u8,
/// Parses what follows the tag or the `*`: `OK [CODE args] text`. pub fn parse(rest: []const u8) ParseError!StatusResponse { const word_end = std.mem.findScalar(u8, rest, ' ') orelse rest.len; const status = Status.parse(rest[0..word_end]) orelse return error.InvalidResponse; var text = if (word_end < rest.len) rest[word_end + 1 ..] else ""; var code: ?Code = null; if (text.len > 0 and text[0] == '[') { // A code cannot hold a `]`, so the first one closes it. if (std.mem.findScalar(u8, text, ']')) |end| { const inside = text[1..end]; const name_end = std.mem.findScalar(u8, inside, ' ') orelse inside.len; if (name_end > 0) { code = .{ .name = inside[0..name_end], .args = if (name_end < inside.len) inside[name_end + 1 ..] else "", }; text = text[end + 1 ..]; if (text.len > 0 and text[0] == ' ') text = text[1..]; } } } return .{ .status = status, .code = code, .text = text }; }
pub fn isOk(r: StatusResponse) bool { return r.status == .ok; }
/// Whether the response carried the code `name`. pub fn hasCode(r: StatusResponse, name: []const u8) bool { const code = r.code orelse return false; return code.is(name); }
/// The code, if it is `name`. pub fn codeNamed(r: StatusResponse, name: []const u8) ?Code { const code = r.code orelse return null; return if (code.is(name)) code else null; }};
/// A `* LIST` or `* LSUB` line./// https://datatracker.ietf.org/doc/html/rfc9051#section-7.3.1pub const ListItem = struct { /// The name attributes, without their parentheses: `\Noselect /// \HasChildren`, or empty. attributes: []const u8, /// The hierarchy delimiter, or null when the server sent NIL — a flat /// namespace, or a name that is not part of one. delimiter: ?u8, /// The mailbox name as sent: an atom, a quoted string, or — when a /// literal — announced here and delivered on the wire after this line. name: Token,
/// Whether the name attributes include `name`, e.g. `\Noselect`. pub fn hasAttribute(l: ListItem, name: []const u8) bool { return parser.listContains(l.attributes, name); }
fn parse(s: *Scanner) ParseError!ListItem { var item: ListItem = undefined; if (!(s.accept(.open_paren) catch return error.InvalidResponse)) return error.InvalidResponse; const attrs_start = s.pos; while (true) { const t = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; switch (t) { .close_paren => break, .atom => {}, else => return error.InvalidResponse, } } item.attributes = std.mem.trim(u8, s.text[attrs_start .. s.pos - 1], " "); const delim = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; item.delimiter = if (delim.isNil()) null else if (delim.asString()) |str| blk: { var buf: [4]u8 = undefined; const d = str.unescape(&buf) catch return error.InvalidResponse; if (d.len != 1) return error.InvalidResponse; break :blk d[0]; } else return error.InvalidResponse; item.name = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; switch (item.name) { .atom, .quoted, .string, .literal => {}, else => return error.InvalidResponse, } return item; }};
/// A `* STATUS mailbox (...)` line./// https://datatracker.ietf.org/doc/html/rfc9051#section-7.3.4pub const StatusItem = struct { /// The mailbox name as sent. When it is a literal, the attribute list /// follows on the line after the literal rather than on this one. name: Token, /// The parenthesized attribute list, or null when it has yet to arrive /// because the name was a literal. attributes: ?[]const u8,
fn parse(s: *Scanner) ParseError!StatusItem { const name = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; switch (name) { .atom, .quoted, .string => {}, .literal => return .{ .name = name, .attributes = null }, else => return error.InvalidResponse, } const attrs = s.item() catch return error.InvalidResponse; return .{ .name = name, .attributes = attrs }; }};
/// What STATUS reports, parsed from its attribute list. Anything the server/// was not asked for, or does not know, is null.pub const MailboxStatus = struct { messages: ?u32 = null, recent: ?u32 = null, uidnext: ?u32 = null, uidvalidity: ?u32 = null, unseen: ?u32 = null, /// RFC 8438: the mailbox's size in octets. size: ?u64 = null, /// RFC 8474: the mailbox's identifier. highest_modseq: ?u64 = null, /// IMAP4rev2: how many messages are flagged `\Deleted`. deleted: ?u32 = null,
/// Parses `(MESSAGES 231 UIDNEXT 44292)`, parentheses optional. Pairs /// this does not know are skipped. pub fn parse(list: []const u8) ParseError!MailboxStatus { var status: MailboxStatus = .{}; var it = parser.listItems(list); while (it.next()) |key| { const value = it.next() orelse return error.InvalidResponse; inline for (.{ .{ "MESSAGES", "messages" }, .{ "RECENT", "recent" }, .{ "UIDNEXT", "uidnext" }, .{ "UIDVALIDITY", "uidvalidity" }, .{ "UNSEEN", "unseen" }, .{ "SIZE", "size" }, .{ "HIGHESTMODSEQ", "highest_modseq" }, .{ "DELETED", "deleted" }, }) |pair| { if (std.ascii.eqlIgnoreCase(key, pair[0])) { const Field = @TypeOf(@field(status, pair[1])); const T = @typeInfo(Field).optional.child; @field(status, pair[1]) = parser.parseDigits(T, value) orelse return error.InvalidResponse; } } } return status; }};
/// An untagged response: `* ...`./// https://datatracker.ietf.org/doc/html/rfc9051#section-7pub const Untagged = union(enum) { /// `* OK`, `* NO`, `* BAD`, `* PREAUTH` or `* BYE`, with its text and /// any response code — which is where `[ALERT]`, `[UIDVALIDITY n]` and /// `[PERMANENTFLAGS (...)]` arrive. status: StatusResponse, /// The capability list, space-separated, as the server sent it. capability: []const u8, list: ListItem, lsub: ListItem, status_item: StatusItem, /// The message numbers (or UIDs, after `UID SEARCH`), space-separated. search: []const u8, /// An ESEARCH result (RFC 4731, and IMAP4rev2's SEARCH), raw. esearch: []const u8, /// The flags defined in the selected mailbox, without parentheses. flags: []const u8, exists: u32, recent: u32, /// A message number that has been removed. Every message after it has /// just been renumbered one lower. expunge: u32, fetch: Fetch, /// The NAMESPACE response, raw: three lists or NILs. namespace: []const u8, /// The capabilities ENABLE turned on, space-separated. enabled: []const u8, /// The server's ID parameter list, raw, or NIL. id: []const u8, /// Anything this library does not name, with its keyword and the rest /// of the line. other: Other,
pub const Fetch = struct { number: u32, /// The attribute list, parentheses included, as far as this line /// goes: a literal at its end means the list continues after it. attributes: []const u8, };
pub const Other = struct { name: []const u8, rest: []const u8, };
fn parse(rest: []const u8) ParseError!Untagged { var s: Scanner = .init(rest); const first = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; const word = switch (first) { .atom => |a| a, else => return error.InvalidResponse, };
// `* 12 EXISTS`, `* 3 FETCH (...)`: a number, then the keyword. if (first.number()) |n| { const number = std.math.cast(u32, n) orelse return error.InvalidResponse; const keyword = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; const kw = switch (keyword) { .atom => |a| a, else => return error.InvalidResponse, }; if (ieql(kw, "EXISTS")) return .{ .exists = number }; if (ieql(kw, "RECENT")) return .{ .recent = number }; if (ieql(kw, "EXPUNGE")) return .{ .expunge = number }; if (ieql(kw, "FETCH")) { s.skipSpaces(); return .{ .fetch = .{ .number = number, .attributes = s.rest() } }; } return .{ .other = .{ .name = kw, .rest = std.mem.trimStart(u8, s.rest(), " ") } }; }
if (Status.parse(word) != null) return .{ .status = try StatusResponse.parse(rest) };
s.skipSpaces(); const tail = s.rest(); if (ieql(word, "CAPABILITY")) return .{ .capability = tail }; if (ieql(word, "LIST")) return .{ .list = try ListItem.parse(&s) }; if (ieql(word, "LSUB")) return .{ .lsub = try ListItem.parse(&s) }; if (ieql(word, "STATUS")) return .{ .status_item = try StatusItem.parse(&s) }; if (ieql(word, "SEARCH")) return .{ .search = tail }; if (ieql(word, "ESEARCH")) return .{ .esearch = tail }; if (ieql(word, "FLAGS")) { const list = s.item() catch return error.InvalidResponse; if (list.len < 2 or list[0] != '(') return error.InvalidResponse; return .{ .flags = std.mem.trim(u8, list[1 .. list.len - 1], " ") }; } if (ieql(word, "NAMESPACE")) return .{ .namespace = tail }; if (ieql(word, "ENABLED")) return .{ .enabled = tail }; if (ieql(word, "ID")) return .{ .id = tail }; return .{ .other = .{ .name = word, .rest = tail } }; }};
/// One line from the server, classified./// https://datatracker.ietf.org/doc/html/rfc9051#section-7pub const Response = union(enum) { /// The end of a command: its tag and how it went. tagged: Tagged, untagged: Untagged, /// A continuation request: the server is ready for the rest of a /// command — a literal's octets, or the answer to a SASL challenge, /// which is the text here, base64 encoded. continuation: []const u8,
pub const Tagged = struct { tag: []const u8, status: StatusResponse, };
/// Parses one line with its CRLF already removed. /// /// A line that announces a literal is parsed as far as it goes; the /// caller learns about the literal from `parser.trailingLiteral`. pub fn parse(line: []const u8) ParseError!Response { if (line.len == 0) return error.InvalidResponse; if (line[0] == '+') { if (line.len == 1) return .{ .continuation = "" }; if (line[1] != ' ') return error.InvalidResponse; return .{ .continuation = line[2..] }; } if (line[0] == '*') { if (line.len < 3 or line[1] != ' ') return error.InvalidResponse; return .{ .untagged = try Untagged.parse(line[2..]) }; } const tag_end = std.mem.findScalar(u8, line, ' ') orelse return error.InvalidResponse; const tag = line[0..tag_end]; if (tag.len == 0) return error.InvalidResponse; for (tag) |c| switch (c) { '(', ')', '{', '"', '\\', '%', '*', '+', 0...31, 127 => return error.InvalidResponse, else => {}, }; const status = try StatusResponse.parse(line[tag_end + 1 ..]); // Only the three that end a command may be tagged. switch (status.status) { .ok, .no, .bad => {}, .preauth, .bye => return error.InvalidResponse, } return .{ .tagged = .{ .tag = tag, .status = status } }; }};
/// A list of atoms — flags, or SASL mechanism names — copied into fixed/// storage so that it outlives the read buffer it came from.pub fn AtomList(comptime capacity: usize) type { return struct { buf: [capacity]u8 = undefined, len: usize = 0, /// The server sent more than would fit. What is kept is a prefix of /// whole names, so lookups still work for the ones kept. truncated: bool = false,
const Self = @This();
pub const max_len = capacity;
/// The names, space-separated. pub fn list(l: *const Self) []const u8 { return l.buf[0..l.len]; }
pub fn any(l: *const Self) bool { return l.len != 0; }
/// Whether `name` is in the list, compared without regard to case. pub fn has(l: *const Self, name: []const u8) bool { return parser.listContains(l.list(), name); }
pub fn iterator(l: *const Self) std.mem.TokenIterator(u8, .any) { return parser.listItems(l.list()); }
/// Appends one name. pub fn add(l: *Self, name: []const u8) void { if (l.truncated) return; const needed = name.len + @intFromBool(l.len != 0); if (l.len + needed > capacity) { l.truncated = true; return; } if (l.len != 0) { l.buf[l.len] = ' '; l.len += 1; } @memcpy(l.buf[l.len..][0..name.len], name); l.len += name.len; }
/// Replaces the contents with the atoms of `text`, parentheses and /// all optional. pub fn set(l: *Self, text: []const u8) void { l.* = .{}; var it = parser.listItems(text); while (it.next()) |name| l.add(name); } };}
/// The flags of a mailbox: FLAGS, or the PERMANENTFLAGS the server will/// keep across sessions.pub const FlagList = AtomList(512);
/// What the server said it can do.////// Every capability is kept in `raw`, so one this library does not name can/// still be asked about with `has`; the fields are the ones it acts on./// https://datatracker.ietf.org/doc/html/rfc9051#section-7.2.2pub const Capabilities = struct { /// Whether a capability list has been received at all. Until then every /// field is a default, not a fact. known: bool = false, imap4rev1: bool = false, imap4rev2: bool = false, /// STARTTLS may upgrade this connection. starttls: bool = false, /// The LOGIN command is refused, usually because the connection is not /// yet encrypted. logindisabled: bool = false, /// AUTHENTICATE accepts an initial response on the command line /// (RFC 4959), saving a round trip. sasl_ir: bool = false, /// `AUTH=` mechanisms, names only, for `sasl.Client.selectFromList`. auth: AtomList(256) = .{}, /// Non-synchronizing literals (RFC 7888): `{n+}` needs no continuation. literal_plus: bool = false, /// The same, for literals of at most 4096 octets. literal_minus: bool = false, idle: bool = false, /// UID EXPUNGE, and the APPENDUID/COPYUID response codes (RFC 4315). uidplus: bool = false, /// The MOVE command (RFC 6851). move: bool = false, namespace: bool = false, unselect: bool = false, enable: bool = false, id: bool = false, condstore: bool = false, qresync: bool = false, /// UTF-8 mailbox names and headers may be enabled (RFC 6855). utf8_accept: bool = false, children: bool = false, list_extended: bool = false, list_status: bool = false, special_use: bool = false, esearch: bool = false, quota: bool = false, status_size: bool = false, binary: bool = false, /// The largest message APPEND accepts, when the server says. appendlimit: ?u64 = null, /// Every capability as sent, space-separated. raw: AtomList(1024) = .{},
/// Whether the server advertised `name`, compared without regard to /// case. `has("AUTH=PLAIN")` works as well as `auth.has("PLAIN")`. pub fn has(caps: *const Capabilities, name: []const u8) bool { return caps.raw.has(name); }
/// Parses a capability list: the text of a `* CAPABILITY` response or /// a `[CAPABILITY ...]` code. pub fn parse(text: []const u8) Capabilities { var caps: Capabilities = .{ .known = true }; var it = std.mem.tokenizeScalar(u8, text, ' '); while (it.next()) |token| caps.addToken(token); return caps; }
/// Folds one capability in. pub fn addToken(caps: *Capabilities, token: []const u8) void { caps.known = true; caps.raw.add(token); if (std.ascii.startsWithIgnoreCase(token, "AUTH=")) { caps.auth.add(token[5..]); return; } if (std.ascii.startsWithIgnoreCase(token, "APPENDLIMIT=")) { caps.appendlimit = parser.parseDigits(u64, token[12..]) orelse null; return; } inline for (.{ .{ "IMAP4rev1", "imap4rev1" }, .{ "IMAP4rev2", "imap4rev2" }, .{ "STARTTLS", "starttls" }, .{ "LOGINDISABLED", "logindisabled" }, .{ "SASL-IR", "sasl_ir" }, .{ "LITERAL+", "literal_plus" }, .{ "LITERAL-", "literal_minus" }, .{ "IDLE", "idle" }, .{ "UIDPLUS", "uidplus" }, .{ "MOVE", "move" }, .{ "NAMESPACE", "namespace" }, .{ "UNSELECT", "unselect" }, .{ "ENABLE", "enable" }, .{ "ID", "id" }, .{ "CONDSTORE", "condstore" }, .{ "QRESYNC", "qresync" }, .{ "UTF8=ACCEPT", "utf8_accept" }, .{ "CHILDREN", "children" }, .{ "LIST-EXTENDED", "list_extended" }, .{ "LIST-STATUS", "list_status" }, .{ "SPECIAL-USE", "special_use" }, .{ "ESEARCH", "esearch" }, .{ "QUOTA", "quota" }, .{ "STATUS=SIZE", "status_size" }, .{ "BINARY", "binary" }, }) |pair| { if (std.ascii.eqlIgnoreCase(token, pair[0])) @field(caps, pair[1]) = true; } }};
/// The state of the selected mailbox, kept current from the untagged/// responses the server sends — at SELECT, and at any time afterwards./// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.2pub const Mailbox = struct { /// How many messages are in the mailbox right now. exists: u32 = 0, /// IMAP4rev1's count of messages new since the last session; rev2 has /// dropped it. recent: u32 = 0, /// The number of the first unseen message, when the server said. unseen: ?u32 = null, /// The mailbox's UIDVALIDITY: UIDs are only comparable across sessions /// while this is unchanged. uidvalidity: ?u32 = null, /// The UID the next message will get, predicted. uidnext: ?u32 = null, highest_modseq: ?u64 = null, /// EXAMINE, or a mailbox the server will not let this session change. read_only: bool = false, /// The flags in use in the mailbox. flags: FlagList = .{}, /// The flags a client may change permanently; the rest last for the /// session. `\*` in it means new keywords may be created. permanent_flags: FlagList = .{},
/// Whether the server accepts keywords it has not seen before. pub fn allowsNewKeywords(m: *const Mailbox) bool { return m.permanent_flags.has("\\*"); }};
/// The result of a COPY, MOVE or APPEND on a server with UIDPLUS: which/// UIDs the messages got in their new home./// https://datatracker.ietf.org/doc/html/rfc4315#section-3pub const UidResult = struct { uidvalidity: u32, /// For APPEND a single UID; for COPY and MOVE the set of new UIDs, in /// the order of `source`. uids: []const u8, /// For COPY and MOVE, the UIDs the messages had, in the same order. /// Empty for APPEND. source: []const u8,
/// Parses the arguments of an APPENDUID or COPYUID code. pub fn parse(args: []const u8, kind: enum { append, copy }) ParseError!UidResult { var it = std.mem.tokenizeScalar(u8, args, ' '); const validity = it.next() orelse return error.InvalidResponse; const first = it.next() orelse return error.InvalidResponse; var r: UidResult = .{ .uidvalidity = parser.parseDigits(u32, validity) orelse return error.InvalidResponse, .uids = first, .source = "", }; if (kind == .copy) { r.source = first; r.uids = it.next() orelse return error.InvalidResponse; } return r; }};
/// The numbers of a sequence set, expanded: `1:3,7` is 1, 2, 3, 7.////// `*` cannot be expanded without knowing the mailbox, and is an error;/// a server never sends one in a SEARCH or ESEARCH result.pub const SequenceIterator = struct { ranges: std.mem.TokenIterator(u8, .scalar), current: ?u32 = null, last: u32 = 0,
pub fn init(set: []const u8) SequenceIterator { return .{ .ranges = std.mem.tokenizeScalar(u8, set, ',') }; }
pub fn next(it: *SequenceIterator) ParseError!?u32 { if (it.current) |n| { if (n < it.last) { it.current = n + 1; } else { it.current = null; } return n; } const range = it.ranges.next() orelse return null; if (std.mem.findScalar(u8, range, ':')) |colon| { const a = parser.parseDigits(u32, range[0..colon]) orelse return error.InvalidResponse; const b = parser.parseDigits(u32, range[colon + 1 ..]) orelse return error.InvalidResponse; const lo = @min(a, b); const hi = @max(a, b); if (lo == 0) return error.InvalidResponse; it.last = hi; it.current = if (lo < hi) lo + 1 else null; return lo; } const n = parser.parseDigits(u32, range) orelse return error.InvalidResponse; if (n == 0) return error.InvalidResponse; return n; }};
/// One address of an ENVELOPE: `(name adl mailbox host)`./// https://datatracker.ietf.org/doc/html/rfc9051#section-7.5.2pub const Address = struct { /// The display name, if any. name: ?String, /// The source route, obsolete and almost always NIL. adl: ?String, /// The local part; NIL with a non-null `host` marks the end of a group. mailbox: ?String, /// The domain; NIL marks the start of a group, `mailbox` holding its name. host: ?String,
/// Whether this is a group's start or end marker rather than an address. pub fn isGroupMarker(a: Address) bool { return a.host == null; }};
/// The addresses of one ENVELOPE field.pub const AddressIterator = struct { scanner: Scanner, done: bool,
pub fn init(list: []const u8) AddressIterator { var it: AddressIterator = .{ .scanner = .init(list), .done = false }; // NIL, or an empty list, or a list to walk. if (std.ascii.eqlIgnoreCase(std.mem.trim(u8, list, " "), "NIL")) { it.done = true; } else if (!(it.scanner.accept(.open_paren) catch false)) { it.done = true; } return it; }
pub fn next(it: *AddressIterator) ParseError!?Address { if (it.done) return null; const s = &it.scanner; const t = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; switch (t) { .close_paren => { it.done = true; return null; }, .open_paren => {}, else => return error.InvalidResponse, } const a: Address = .{ .name = s.expectNString() catch return error.InvalidResponse, .adl = s.expectNString() catch return error.InvalidResponse, .mailbox = s.expectNString() catch return error.InvalidResponse, .host = s.expectNString() catch return error.InvalidResponse, }; if (!(s.accept(.close_paren) catch return error.InvalidResponse)) return error.InvalidResponse; return a; }};
/// A parsed ENVELOPE: the message's headers as the server read them./// https://datatracker.ietf.org/doc/html/rfc9051#section-7.5.2pub const Envelope = struct { date: ?String, subject: ?String, /// Address lists, raw: `(("Alice" NIL "alice" "example.com"))`, or /// NIL. `addresses` walks one. from: []const u8, sender: []const u8, reply_to: []const u8, to: []const u8, cc: []const u8, bcc: []const u8, in_reply_to: ?String, message_id: ?String,
/// Parses the ENVELOPE value: a list of ten items, parentheses and all. /// Strings that arrived as literals have to be in the buffer, which /// they are when `Client` collected the attribute. pub fn parse(list: []const u8) ParseError!Envelope { var s: Scanner = .init(list); if (!(s.accept(.open_paren) catch return error.InvalidResponse)) return error.InvalidResponse; const e: Envelope = .{ .date = s.expectNString() catch return error.InvalidResponse, .subject = s.expectNString() catch return error.InvalidResponse, .from = s.item() catch return error.InvalidResponse, .sender = s.item() catch return error.InvalidResponse, .reply_to = s.item() catch return error.InvalidResponse, .to = s.item() catch return error.InvalidResponse, .cc = s.item() catch return error.InvalidResponse, .bcc = s.item() catch return error.InvalidResponse, .in_reply_to = s.expectNString() catch return error.InvalidResponse, .message_id = s.expectNString() catch return error.InvalidResponse, }; if (!(s.accept(.close_paren) catch return error.InvalidResponse)) return error.InvalidResponse; return e; }
/// The addresses of one of the six address fields. pub fn addresses(list: []const u8) AddressIterator { return .init(list); }};
/// One attribute of a FETCH response: `FLAGS (\Seen)`, `UID 4827313`,/// `BODY[HEADER.FIELDS (FROM)] {42}...`, `ENVELOPE (...)`.pub const FetchItem = struct { /// The attribute's name: `FLAGS`, `UID`, `BODY`, `BINARY`, `RFC822.SIZE`. /// For a body the section is separate, so `BODY[TEXT]` has name `BODY`. name: []const u8, /// What was in the brackets of a `BODY[...]` or `BINARY[...]` value, /// without them, or null for an attribute that has no section. Empty /// for `BODY[]`, the whole message. section: ?[]const u8, /// The `<origin>` of a partial fetch, when the server sent one. origin: ?u32, value: Value,
pub const Value = union(enum) { /// A single token: a string in any spelling, a number, NIL. token: Token, /// A parenthesized list, parentheses included: the value of FLAGS, /// ENVELOPE, BODYSTRUCTURE. list: []const u8,
/// The value as a string, or null for a list or NIL. pub fn string(v: Value) ?String { return switch (v) { .token => |t| if (t.isNil()) null else t.asString(), .list => null, }; }
pub fn number(v: Value) ?u64 { return switch (v) { .token => |t| t.number(), .list => null, }; }
pub fn isNil(v: Value) bool { return switch (v) { .token => |t| t.isNil(), .list => false, }; } };
pub fn is(item: FetchItem, name: []const u8) bool { return ieql(item.name, name); }
/// Whether this is `BODY[section]` for that section, compared without /// regard to case. pub fn isBodySection(item: FetchItem, section: []const u8) bool { const s = item.section orelse return false; return (item.is("BODY") or item.is("BINARY")) and ieql(s, section); }};
/// Walks the attributes of a FETCH response's list, which must be complete/// in memory: every literal in it in the `{n}CRLF octets` form, as/// `Client.Command.collectFetch` delivers it.pub const FetchIterator = struct { scanner: Scanner, done: bool,
/// `list` is the parenthesized attribute list, parentheses included. pub fn init(list: []const u8) FetchIterator { var it: FetchIterator = .{ .scanner = .init(list), .done = false }; if (!(it.scanner.accept(.open_paren) catch false)) it.done = true; return it; }
pub fn next(it: *FetchIterator) ParseError!?FetchItem { if (it.done) return null; const s = &it.scanner; const t = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; const name = switch (t) { .close_paren => { it.done = true; return null; }, .atom => |a| a, else => return error.InvalidResponse, }; var item: FetchItem = .{ .name = name, .section = null, .origin = null, .value = undefined }; if (s.accept(.open_bracket) catch return error.InvalidResponse) { const start = s.pos; var depth: usize = 1; while (depth > 0) { const inner = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; switch (inner) { .open_bracket => depth += 1, .close_bracket => depth -= 1, .open_paren, .close_paren, .atom, .quoted => {}, else => return error.InvalidResponse, } } item.section = std.mem.trim(u8, s.text[start .. s.pos - 1], " "); // A partial fetch's origin: `<0>`, attached without a space. if (s.pos < s.text.len and s.text[s.pos] == '<') { const close = std.mem.findScalarPos(u8, s.text, s.pos, '>') orelse return error.InvalidResponse; item.origin = parser.parseDigits(u32, s.text[s.pos + 1 .. close]) orelse return error.InvalidResponse; s.pos = close + 1; } } s.skipSpaces(); if (s.pos < s.text.len and s.text[s.pos] == '(') { item.value = .{ .list = s.item() catch return error.InvalidResponse }; } else { const v = (s.next() catch return error.InvalidResponse) orelse return error.InvalidResponse; switch (v) { .atom, .quoted, .string => {}, else => return error.InvalidResponse, } item.value = .{ .token = v }; } return item; }};
fn ieql(a: []const u8, b: []const u8) bool { return std.ascii.eqlIgnoreCase(a, b);}
// -- Tests -------------------------------------------------------------------
test "FetchIterator" { var it: FetchIterator = .init("(FLAGS (\\Seen) UID 4827313 RFC822.SIZE 44827 " ++ "INTERNALDATE \"17-Jul-1996 02:44:25 -0700\" " ++ "BODY[HEADER.FIELDS (FROM TO)] {5}\r\nhello BODY[TEXT]<0> NIL BODY[] \"\")"); const flags = (try it.next()).?; try std.testing.expect(flags.is("flags")); try std.testing.expectEqualStrings("(\\Seen)", flags.value.list); const uid = (try it.next()).?; try std.testing.expectEqual(@as(?u64, 4827313), uid.value.number()); const size = (try it.next()).?; try std.testing.expectEqualStrings("RFC822.SIZE", size.name); const date = (try it.next()).?; try std.testing.expectEqualStrings("17-Jul-1996 02:44:25 -0700", date.value.string().?.raw); const header = (try it.next()).?; try std.testing.expect(header.is("BODY")); try std.testing.expectEqualStrings("HEADER.FIELDS (FROM TO)", header.section.?); try std.testing.expect(header.isBodySection("header.fields (from to)")); try std.testing.expectEqualStrings("hello", header.value.string().?.raw); const text = (try it.next()).?; try std.testing.expectEqualStrings("TEXT", text.section.?); try std.testing.expectEqual(@as(?u32, 0), text.origin); try std.testing.expect(text.value.isNil()); const whole = (try it.next()).?; try std.testing.expectEqualStrings("", whole.section.?); try std.testing.expectEqualStrings("", whole.value.string().?.raw); try std.testing.expectEqual(@as(?FetchItem, null), try it.next());
var bad: FetchIterator = .init("(UID)"); try std.testing.expectError(error.InvalidResponse, bad.next()); var not_list: FetchIterator = .init("UID 1"); try std.testing.expectEqual(@as(?FetchItem, null), try not_list.next());}
test "tagged responses" { const ok = try Response.parse("A001 OK LOGIN completed"); try std.testing.expectEqualStrings("A001", ok.tagged.tag); try std.testing.expectEqual(Status.ok, ok.tagged.status.status); try std.testing.expectEqualStrings("LOGIN completed", ok.tagged.status.text); try std.testing.expectEqual(@as(?Code, null), ok.tagged.status.code);
const no = try Response.parse("A002 NO [AUTHENTICATIONFAILED] Authentication failed."); try std.testing.expectEqual(Status.no, no.tagged.status.status); try std.testing.expect(no.tagged.status.hasCode("authenticationfailed")); try std.testing.expectEqualStrings("Authentication failed.", no.tagged.status.text);
const bad = try Response.parse("A003 BAD"); try std.testing.expectEqual(Status.bad, bad.tagged.status.status); try std.testing.expectEqualStrings("", bad.tagged.status.text);
// Only OK, NO and BAD may be tagged. try std.testing.expectError(error.InvalidResponse, Response.parse("A004 BYE")); try std.testing.expectError(error.InvalidResponse, Response.parse("A005 MAYBE")); try std.testing.expectError(error.InvalidResponse, Response.parse("A006")); try std.testing.expectError(error.InvalidResponse, Response.parse("")); try std.testing.expectError(error.InvalidResponse, Response.parse("(tag) OK")); // A leading space is not an empty tag; the fuzzer found this one. try std.testing.expectError(error.InvalidResponse, Response.parse(" OK"));}
test "response codes" { const r = (try Response.parse("* OK [UIDVALIDITY 3857529045] UIDs valid")).untagged.status; try std.testing.expectEqualStrings("UIDVALIDITY", r.code.?.name); try std.testing.expectEqual(@as(?u32, 3857529045), r.code.?.number(u32)); try std.testing.expectEqualStrings("UIDs valid", r.text);
const flags = (try Response.parse("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)] Limited")).untagged.status; try std.testing.expectEqualStrings("(\\Deleted \\Seen \\*)", flags.codeNamed("PERMANENTFLAGS").?.args);
const bare = (try Response.parse("* OK [READ-WRITE] Select completed")).untagged.status; try std.testing.expectEqualStrings("", bare.code.?.args); try std.testing.expect(bare.hasCode("READ-WRITE"));
// No code: brackets with nothing in them, or never closed, or absent. const empty = (try Response.parse("* OK [] text")).untagged.status; try std.testing.expectEqual(@as(?Code, null), empty.code); try std.testing.expectEqualStrings("[] text", empty.text); const open = (try Response.parse("* OK [unterminated")).untagged.status; try std.testing.expectEqual(@as(?Code, null), open.code); const none = (try Response.parse("* OK ready")).untagged.status; try std.testing.expect(!none.hasCode("ALERT"));
const alert = (try Response.parse("* OK [ALERT] Disk is nearly full")).untagged.status; try std.testing.expect(alert.hasCode("ALERT")); try std.testing.expectEqualStrings("Disk is nearly full", alert.text);}
test "continuation requests" { try std.testing.expectEqualStrings("", (try Response.parse("+")).continuation); try std.testing.expectEqualStrings("", (try Response.parse("+ ")).continuation); try std.testing.expectEqualStrings("Ready for literal", (try Response.parse("+ Ready for literal")).continuation); try std.testing.expectEqualStrings("PDE4OTY+", (try Response.parse("+ PDE4OTY+")).continuation); try std.testing.expectError(error.InvalidResponse, Response.parse("+x"));}
test "numbered untagged responses" { try std.testing.expectEqual(@as(u32, 172), (try Response.parse("* 172 EXISTS")).untagged.exists); try std.testing.expectEqual(@as(u32, 1), (try Response.parse("* 1 RECENT")).untagged.recent); try std.testing.expectEqual(@as(u32, 44), (try Response.parse("* 44 expunge")).untagged.expunge); const fetch = (try Response.parse("* 12 FETCH (FLAGS (\\Seen) UID 4827313)")).untagged.fetch; try std.testing.expectEqual(@as(u32, 12), fetch.number); try std.testing.expectEqualStrings("(FLAGS (\\Seen) UID 4827313)", fetch.attributes); try std.testing.expectError(error.InvalidResponse, Response.parse("* 12")); try std.testing.expectError(error.InvalidResponse, Response.parse("* 99999999999 EXISTS")); const other = (try Response.parse("* 5 VANISHED 3")).untagged.other; try std.testing.expectEqualStrings("VANISHED", other.name);}
test "keyword untagged responses" { const caps = (try Response.parse("* CAPABILITY IMAP4rev1 AUTH=PLAIN IDLE")).untagged.capability; try std.testing.expectEqualStrings("IMAP4rev1 AUTH=PLAIN IDLE", caps);
const flags = (try Response.parse("* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)")).untagged.flags; try std.testing.expectEqualStrings("\\Answered \\Flagged \\Deleted \\Seen \\Draft", flags); try std.testing.expectEqualStrings("", (try Response.parse("* FLAGS ()")).untagged.flags); try std.testing.expectError(error.InvalidResponse, Response.parse("* FLAGS \\Seen"));
try std.testing.expectEqualStrings("2 84 882", (try Response.parse("* SEARCH 2 84 882")).untagged.search); try std.testing.expectEqualStrings("", (try Response.parse("* SEARCH")).untagged.search); try std.testing.expectEqualStrings( "(TAG \"A282\") MIN 2 COUNT 3", (try Response.parse("* ESEARCH (TAG \"A282\") MIN 2 COUNT 3")).untagged.esearch, ); try std.testing.expectEqualStrings("IMAP4rev2", (try Response.parse("* ENABLED IMAP4rev2")).untagged.enabled); try std.testing.expectEqualStrings("((\"\" \"/\")) NIL NIL", (try Response.parse("* NAMESPACE ((\"\" \"/\")) NIL NIL")).untagged.namespace); try std.testing.expectEqualStrings("NIL", (try Response.parse("* ID NIL")).untagged.id);
const other = (try Response.parse("* QUOTAROOT INBOX \"\"")).untagged.other; try std.testing.expectEqualStrings("QUOTAROOT", other.name); try std.testing.expectEqualStrings("INBOX \"\"", other.rest);
try std.testing.expectEqual(Status.preauth, (try Response.parse("* PREAUTH ready")).untagged.status.status); try std.testing.expectEqual(Status.bye, (try Response.parse("* BYE going down")).untagged.status.status); try std.testing.expectError(error.InvalidResponse, Response.parse("*")); try std.testing.expectError(error.InvalidResponse, Response.parse("* ")); try std.testing.expectError(error.InvalidResponse, Response.parse("*x"));}
test "LIST responses" { const l = (try Response.parse("* LIST (\\Noselect \\HasChildren) \"/\" ~/Mail/foo")).untagged.list; try std.testing.expectEqualStrings("\\Noselect \\HasChildren", l.attributes); try std.testing.expect(l.hasAttribute("\\noselect")); try std.testing.expect(!l.hasAttribute("\\Marked")); try std.testing.expectEqual(@as(?u8, '/'), l.delimiter); try std.testing.expectEqualStrings("~/Mail/foo", l.name.atom);
const quoted = (try Response.parse("* LIST () \".\" \"Sent Items\"")).untagged.list; try std.testing.expectEqualStrings("", quoted.attributes); try std.testing.expectEqualStrings("Sent Items", quoted.name.quoted);
const nil = (try Response.parse("* LIST (\\Noinferiors) NIL INBOX")).untagged.list; try std.testing.expectEqual(@as(?u8, null), nil.delimiter);
// A delimiter that had to be escaped. const backslash = (try Response.parse("* LIST () \"\\\\\" INBOX")).untagged.list; try std.testing.expectEqual(@as(?u8, '\\'), backslash.delimiter);
// A name too awkward for a quoted string comes as a literal, after // this line. const literal = (try Response.parse("* LSUB () \"/\" {12}")).untagged.lsub; try std.testing.expectEqual(@as(usize, 12), literal.name.literal);
try std.testing.expectError(error.InvalidResponse, Response.parse("* LIST \"/\" INBOX")); try std.testing.expectError(error.InvalidResponse, Response.parse("* LIST () \"//\" INBOX")); try std.testing.expectError(error.InvalidResponse, Response.parse("* LIST () \"/\""));}
test "STATUS responses" { const s = (try Response.parse("* STATUS blurdybloop (MESSAGES 231 UIDNEXT 44292)")).untagged.status_item; try std.testing.expectEqualStrings("blurdybloop", s.name.atom); const values = try MailboxStatus.parse(s.attributes.?); try std.testing.expectEqual(@as(?u32, 231), values.messages); try std.testing.expectEqual(@as(?u32, 44292), values.uidnext); try std.testing.expectEqual(@as(?u32, null), values.unseen);
const lit = (try Response.parse("* STATUS {5}")).untagged.status_item; try std.testing.expectEqual(@as(usize, 5), lit.name.literal); try std.testing.expectEqual(@as(?[]const u8, null), lit.attributes);
const all = try MailboxStatus.parse("(MESSAGES 1 RECENT 2 UIDNEXT 3 UIDVALIDITY 4 UNSEEN 5 SIZE 6 HIGHESTMODSEQ 7 DELETED 8 X-UNKNOWN 9)"); try std.testing.expectEqual(@as(?u32, 2), all.recent); try std.testing.expectEqual(@as(?u64, 6), all.size); try std.testing.expectEqual(@as(?u64, 7), all.highest_modseq); try std.testing.expectEqual(@as(?u32, 8), all.deleted); try std.testing.expectError(error.InvalidResponse, MailboxStatus.parse("(MESSAGES)")); try std.testing.expectError(error.InvalidResponse, MailboxStatus.parse("(MESSAGES many)"));}
test "capabilities" { const caps = Capabilities.parse("IMAP4rev1 IMAP4rev2 STARTTLS AUTH=PLAIN AUTH=LOGIN auth=cram-md5 SASL-IR " ++ "LITERAL+ IDLE UIDPLUS MOVE NAMESPACE ENABLE UTF8=ACCEPT APPENDLIMIT=35651584 X-GM-EXT-1"); try std.testing.expect(caps.known); try std.testing.expect(caps.imap4rev1 and caps.imap4rev2); try std.testing.expect(caps.starttls); try std.testing.expect(!caps.logindisabled); try std.testing.expect(caps.sasl_ir); try std.testing.expect(caps.literal_plus and !caps.literal_minus); try std.testing.expect(caps.idle and caps.uidplus and caps.move and caps.namespace and caps.enable); try std.testing.expect(caps.utf8_accept); try std.testing.expectEqual(@as(?u64, 35651584), caps.appendlimit); try std.testing.expectEqualStrings("PLAIN LOGIN cram-md5", caps.auth.list()); try std.testing.expect(caps.auth.has("CRAM-MD5")); try std.testing.expect(caps.has("X-GM-EXT-1")); try std.testing.expect(caps.has("auth=plain")); try std.testing.expect(!caps.has("QUOTA"));
const none: Capabilities = .{}; try std.testing.expect(!none.known); try std.testing.expect(!none.auth.any());}
test "an atom list is copied and bounded" { var l: AtomList(16) = .{}; l.set("(\\Seen \\Draft)"); try std.testing.expectEqualStrings("\\Seen \\Draft", l.list()); try std.testing.expect(l.has("\\seen")); l.add("\\Answered"); try std.testing.expect(l.truncated); try std.testing.expectEqualStrings("\\Seen \\Draft", l.list()); var it = l.iterator(); try std.testing.expectEqualStrings("\\Seen", it.next().?); try std.testing.expectEqualStrings("\\Draft", it.next().?); try std.testing.expectEqual(@as(?[]const u8, null), it.next());}
test "UidResult" { const appended = try UidResult.parse("38505 3955", .append); try std.testing.expectEqual(@as(u32, 38505), appended.uidvalidity); try std.testing.expectEqualStrings("3955", appended.uids); try std.testing.expectEqualStrings("", appended.source);
const copied = try UidResult.parse("38505 304,319:320 3956:3958", .copy); try std.testing.expectEqualStrings("304,319:320", copied.source); try std.testing.expectEqualStrings("3956:3958", copied.uids); try std.testing.expectError(error.InvalidResponse, UidResult.parse("38505 304", .copy)); try std.testing.expectError(error.InvalidResponse, UidResult.parse("x 1", .append));}
test "SequenceIterator" { var it: SequenceIterator = .init("1:3,7,10:9"); const expected = [_]u32{ 1, 2, 3, 7, 9, 10 }; for (expected) |n| try std.testing.expectEqual(@as(?u32, n), try it.next()); try std.testing.expectEqual(@as(?u32, null), try it.next());
var single: SequenceIterator = .init("5:5"); try std.testing.expectEqual(@as(?u32, 5), try single.next()); try std.testing.expectEqual(@as(?u32, null), try single.next());
var star: SequenceIterator = .init("1:*"); try std.testing.expectError(error.InvalidResponse, star.next()); var zero: SequenceIterator = .init("0"); try std.testing.expectError(error.InvalidResponse, zero.next()); var empty: SequenceIterator = .init(""); try std.testing.expectEqual(@as(?u32, null), try empty.next());}
test "Envelope" { const e = try Envelope.parse("(\"Wed, 17 Jul 1996 02:23:25 -0700 (PDT)\" " ++ "\"IMAP4rev2 WG mtg summary and minutes\" " ++ "((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\")) " ++ "((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\")) " ++ "((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\")) " ++ "((NIL NIL \"imap\" \"cac.washington.edu\")) " ++ "((NIL NIL \"minutes\" \"CNRI.Reston.VA.US\") (\"John Klensin\" NIL \"KLENSIN\" \"MIT.EDU\")) " ++ "NIL NIL \"<B27397-0100000@cac.washington.edu>\")"); try std.testing.expectEqualStrings("IMAP4rev2 WG mtg summary and minutes", e.subject.?.plain().?); try std.testing.expectEqualStrings("<B27397-0100000@cac.washington.edu>", e.message_id.?.raw); try std.testing.expectEqual(@as(?String, null), e.in_reply_to); try std.testing.expectEqualStrings("NIL", e.bcc);
var cc = Envelope.addresses(e.cc); const first = (try cc.next()).?; try std.testing.expectEqual(@as(?String, null), first.name); try std.testing.expectEqualStrings("minutes", first.mailbox.?.raw); try std.testing.expectEqualStrings("CNRI.Reston.VA.US", first.host.?.raw); const second = (try cc.next()).?; try std.testing.expectEqualStrings("John Klensin", second.name.?.raw); try std.testing.expectEqual(@as(?Address, null), try cc.next());
var none = Envelope.addresses(e.bcc); try std.testing.expectEqual(@as(?Address, null), try none.next());
// A subject that came as a literal, collected into the buffer. const lit = try Envelope.parse("(NIL {6}\r\nh\xc3\xa9llo NIL NIL NIL NIL NIL NIL NIL NIL)"); try std.testing.expectEqualStrings("h\xc3\xa9llo", lit.subject.?.plain().?); try std.testing.expectEqual(@as(?String, null), lit.date);
try std.testing.expectError(error.InvalidResponse, Envelope.parse("(NIL NIL)")); try std.testing.expectError(error.InvalidResponse, Envelope.parse("NIL"));}