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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The lexical layer of IMAP: atoms, numbers, quoted strings, literals and//! parenthesized lists, as they arrive in a response line.//!//! IMAP has a grammar rather than a line format. A single response can hold//! nested lists (an ENVELOPE, a BODYSTRUCTURE), strings in three spellings//! (an atom, a quoted string, a literal), and a literal is not even on the//! line — it is the *next* `n` octets of the stream, announced by `{n}` at//! the end of a line and followed by the rest of the line after them. This//! module scans one line at a time and says where the literals are; what to//! do about them is `Client`'s business.//!//! Every slice here borrows from its input.//!//! https://datatracker.ietf.org/doc/html/rfc9051#section-9
const std = @import("std");
pub const Error = error{InvalidSyntax};
/// One lexical item of a response.pub const Token = union(enum) { /// An atom: a flag, a keyword, a number, `NIL`, a mailbox name that /// needed no quoting. Numbers are atoms — `number()` reads one. atom: []const u8, /// A quoted string, without its quotes and with its `\` escapes still in /// place; see `String`. quoted: []const u8, /// A literal whose octets are in the buffer being scanned, which is the /// case for a response that was collected into memory. The bytes are /// exactly what the server sent. string: []const u8, /// A literal of this many octets that is *not* in the buffer: the line /// ended with `{n}`, and the octets follow it on the wire. Nothing else /// can be scanned until they have been read. literal: usize, open_paren, close_paren, open_bracket, close_bracket,
/// The atom as a number, or null if it is not one. pub fn number(t: Token) ?u64 { return switch (t) { .atom => |a| parseDigits(u64, a), else => null, }; }
/// Whether this is the atom `NIL`, the IMAP spelling of "no value". pub fn isNil(t: Token) bool { return switch (t) { .atom => |a| std.ascii.eqlIgnoreCase(a, "NIL"), else => false, }; }
/// The token as a string, if it is one of the three string spellings. pub fn asString(t: Token) ?String { return switch (t) { .atom => |a| .{ .raw = a, .escaped = false }, .quoted => |q| .{ .raw = q, .escaped = std.mem.findScalar(u8, q, '\\') != null }, .string => |s| .{ .raw = s, .escaped = false }, else => null, }; }};
/// A string as IMAP delivered it, which may still hold the `\"` and `\\`/// escapes of a quoted string. Most do not, and `plain` says so; the rest/// are unescaped into a buffer or a writer.pub const String = struct { raw: []const u8, escaped: bool,
/// The bytes as they are, when nothing in them needs unescaping — which /// is nearly always. Null means an escape is present and one of the /// other methods is needed. pub fn plain(s: String) ?[]const u8 { return if (s.escaped) null else s.raw; }
/// The length once unescaped. pub fn len(s: String) usize { if (!s.escaped) return s.raw.len; var n: usize = 0; var i: usize = 0; while (i < s.raw.len) : (i += 1) { if (s.raw[i] == '\\' and i + 1 < s.raw.len) i += 1; n += 1; } return n; }
/// Writes the string, escapes removed. pub fn write(s: String, w: *std.Io.Writer) std.Io.Writer.Error!void { if (!s.escaped) return w.writeAll(s.raw); var i: usize = 0; while (i < s.raw.len) : (i += 1) { if (s.raw[i] == '\\' and i + 1 < s.raw.len) i += 1; try w.writeByte(s.raw[i]); } }
/// The string, escapes removed, in `buf`. pub fn unescape(s: String, buf: []u8) error{NoSpaceLeft}![]u8 { var w: std.Io.Writer = .fixed(buf); s.write(&w) catch return error.NoSpaceLeft; return w.buffered(); }
/// The string, escapes removed, in memory the caller owns. pub fn dupe(s: String, gpa: std.mem.Allocator) error{OutOfMemory}![]u8 { const out = try gpa.alloc(u8, s.len()); _ = s.unescape(out) catch unreachable; return out; }
/// Whether the string equals `other`, escapes taken into account. pub fn eql(s: String, other: []const u8) bool { if (!s.escaped) return std.mem.eql(u8, s.raw, other); var i: usize = 0; var j: usize = 0; while (i < s.raw.len) : (i += 1) { if (s.raw[i] == '\\' and i + 1 < s.raw.len) i += 1; if (j == other.len or s.raw[i] != other[j]) return false; j += 1; } return j == other.len; }};
/// Scans one line of a response, token by token.pub const Scanner = struct { text: []const u8, pos: usize = 0,
pub fn init(text: []const u8) Scanner { return .{ .text = text }; }
/// What has not been scanned yet. pub fn rest(s: *const Scanner) []const u8 { return s.text[s.pos..]; }
pub fn atEnd(s: *Scanner) bool { s.skipSpaces(); return s.pos >= s.text.len; }
pub fn skipSpaces(s: *Scanner) void { while (s.pos < s.text.len and s.text[s.pos] == ' ') s.pos += 1; }
/// The next token, or null at the end of the line. pub fn next(s: *Scanner) Error!?Token { s.skipSpaces(); if (s.pos >= s.text.len) return null; const c = s.text[s.pos]; switch (c) { '(' => { s.pos += 1; return .open_paren; }, ')' => { s.pos += 1; return .close_paren; }, '[' => { s.pos += 1; return .open_bracket; }, ']' => { s.pos += 1; return .close_bracket; }, '"' => return .{ .quoted = try s.scanQuoted() }, '{' => return try s.scanLiteral(), else => return .{ .atom = try s.scanAtom() }, } }
/// The next token, which must be there. pub fn expect(s: *Scanner) Error!Token { return (try s.next()) orelse error.InvalidSyntax; }
/// The next token if it is `tag`, consumed; otherwise nothing is. pub fn accept(s: *Scanner, comptime tag: std.meta.Tag(Token)) Error!bool { const saved = s.pos; const t = (try s.next()) orelse return false; if (t == tag) return true; s.pos = saved; return false; }
/// The next token, which must be a number. pub fn expectNumber(s: *Scanner, comptime T: type) Error!T { const t = try s.expect(); const n = t.number() orelse return error.InvalidSyntax; return std.math.cast(T, n) orelse error.InvalidSyntax; }
/// The next token, which must be a string in some spelling, or NIL for /// null. pub fn expectNString(s: *Scanner) Error!?String { const t = try s.expect(); if (t.isNil()) return null; return t.asString() orelse error.InvalidSyntax; }
/// The next item as a whole, whatever it is: a token, or a balanced /// parenthesized list with everything in it, as the raw text. The /// returned slice starts at the item's first byte. /// /// A list cut short by a literal cannot be balanced on this line, and /// comes back as `error.LiteralInList`: the octets are on the wire, and /// what to do about them is the caller's decision. `Client` collects such /// a value into memory when asked to. pub fn item(s: *Scanner) (Error || error{LiteralInList})![]const u8 { s.skipSpaces(); const start = s.pos; const t = try s.expect(); if (t != .open_paren) return s.text[start..s.pos]; var depth: usize = 1; while (depth > 0) { const inner = (try s.next()) orelse return error.InvalidSyntax; switch (inner) { .open_paren => depth += 1, .close_paren => depth -= 1, .literal => return error.LiteralInList, else => {}, } } return s.text[start..s.pos]; }
fn scanAtom(s: *Scanner) Error![]const u8 { const start = s.pos; while (s.pos < s.text.len) : (s.pos += 1) { switch (s.text[s.pos]) { ' ', '(', ')', '{', '"', '[', ']' => break, 0...31, 127 => return error.InvalidSyntax, else => {}, } } if (s.pos == start) return error.InvalidSyntax; return s.text[start..s.pos]; }
fn scanQuoted(s: *Scanner) Error![]const u8 { std.debug.assert(s.text[s.pos] == '"'); s.pos += 1; const start = s.pos; while (s.pos < s.text.len) : (s.pos += 1) { switch (s.text[s.pos]) { '"' => { const inner = s.text[start..s.pos]; s.pos += 1; return inner; }, '\\' => { // Only a quote or a backslash may be escaped, and the // escape has to have something after it. if (s.pos + 1 >= s.text.len) return error.InvalidSyntax; switch (s.text[s.pos + 1]) { '"', '\\' => s.pos += 1, else => return error.InvalidSyntax, } }, '\r', '\n' => return error.InvalidSyntax, else => {}, } } return error.InvalidSyntax; }
fn scanLiteral(s: *Scanner) Error!Token { std.debug.assert(s.text[s.pos] == '{'); const close = std.mem.findScalarPos(u8, s.text, s.pos, '}') orelse return error.InvalidSyntax; var digits = s.text[s.pos + 1 .. close]; // A non-synchronizing literal, `{n+}`, is something a client sends; // a server never does. Accept the spelling anyway rather than fail a // session over it. if (digits.len > 0 and digits[digits.len - 1] == '+') digits = digits[0 .. digits.len - 1]; const n = parseDigits(usize, digits) orelse return error.InvalidSyntax; s.pos = close + 1; // Collected into memory: the octets are right here, after the CRLF // that ended the announcing line. if (s.pos + 2 + n <= s.text.len and s.text[s.pos] == '\r' and s.text[s.pos + 1] == '\n') { const start = s.pos + 2; s.pos = start + n; return .{ .string = s.text[start..s.pos] }; } // Otherwise the announcement has to be the last thing on the line: // the octets are on the wire. if (s.pos != s.text.len) return error.InvalidSyntax; return .{ .literal = n }; }};
/// A decimal number as IMAP writes one: digits and nothing else. This is/// not `std.fmt.parseUnsigned`, which accepts `_` between digits, so that/// `{1_2}` is not a literal of twelve octets.pub fn parseDigits(comptime T: type, text: []const u8) ?T { if (text.len == 0) return null; var n: T = 0; for (text) |c| { if (c < '0' or c > '9') return null; n = std.math.mul(T, n, 10) catch return null; n = std.math.add(T, n, @intCast(c - '0')) catch return null; } return n;}
/// The size of the literal a line announces at its end, if it does.////// A literal is the only thing in IMAP that reaches past the end of a line,/// so this is what a reader has to check after every line before it can/// know where the response ends.pub fn trailingLiteral(line: []const u8) ?usize { if (line.len < 3 or line[line.len - 1] != '}') return null; const open = std.mem.findScalarLast(u8, line, '{') orelse return null; var digits = line[open + 1 .. line.len - 1]; if (digits.len > 0 and digits[digits.len - 1] == '+') digits = digits[0 .. digits.len - 1]; return parseDigits(usize, digits);}
/// Whether a parenthesized list of atoms — a FLAGS list, a LIST attribute/// list — contains `name`, compared without regard to case as flags and/// attributes are. `list` may have its parentheses or not.pub fn listContains(list: []const u8, name: []const u8) bool { var it = listItems(list); while (it.next()) |entry| { if (std.ascii.eqlIgnoreCase(entry, name)) return true; } return false;}
/// The atoms of a parenthesized list, one at a time.pub fn listItems(list: []const u8) std.mem.TokenIterator(u8, .any) { return std.mem.tokenizeAny(u8, std.mem.trim(u8, list, "() "), " ");}
/// The bytes an atom may be made of on the way *out*: what can be sent bare/// as a command argument. Conservative — IMAP's atom is wider — because the/// alternative, quoting, is always correct.pub fn isAtomSafe(s: []const u8) bool { if (s.len == 0) return false; if (std.ascii.eqlIgnoreCase(s, "NIL")) return false; for (s) |c| switch (c) { 'A'...'Z', 'a'...'z', '0'...'9', '-', '_', '.', '/', '+', '=', '@', '#', '!', '$', '&', ':', ';', '<', '>', ',', '?', '^', '`', '|', '~', '\'' => {}, else => return false, }; return true;}
/// Whether `s` can be sent as a quoted string: 7-bit, with no CR, LF or NUL./// Anything else has to be a literal.pub fn isQuotable(s: []const u8) bool { for (s) |c| switch (c) { '\r', '\n', 0 => return false, else => if (c >= 0x80) return false, }; return true;}
/// Writes `s` as a quoted string, escaping what has to be.pub fn writeQuoted(w: *std.Io.Writer, s: []const u8) std.Io.Writer.Error!void { try w.writeByte('"'); for (s) |c| { if (c == '"' or c == '\\') try w.writeByte('\\'); try w.writeByte(c); } try w.writeByte('"');}
test "atoms, numbers and NIL" { var s: Scanner = .init("FLAGS 42 NIL \\Seen"); try std.testing.expectEqualStrings("FLAGS", (try s.expect()).atom); try std.testing.expectEqual(@as(?u64, 42), (try s.expect()).number()); try std.testing.expect((try s.expect()).isNil()); try std.testing.expectEqualStrings("\\Seen", (try s.expect()).atom); try std.testing.expectEqual(@as(?Token, null), try s.next());}
test "quoted strings and escapes" { var s: Scanner = .init("\"plain\" \"with \\\"quotes\\\" and \\\\\""); const plain = (try s.expect()).asString().?; try std.testing.expectEqualStrings("plain", plain.plain().?); const escaped = (try s.expect()).asString().?; try std.testing.expect(escaped.plain() == null); try std.testing.expectEqual(@as(usize, 19), escaped.len()); var buf: [64]u8 = undefined; try std.testing.expectEqualStrings("with \"quotes\" and \\", try escaped.unescape(&buf)); try std.testing.expect(escaped.eql("with \"quotes\" and \\")); try std.testing.expect(!escaped.eql("with \"quotes\" and")); const owned = try escaped.dupe(std.testing.allocator); defer std.testing.allocator.free(owned); try std.testing.expectEqualStrings("with \"quotes\" and \\", owned);
// An unterminated string, a bad escape, a raw newline: none of them parse. var bad: Scanner = .init("\"open"); try std.testing.expectError(error.InvalidSyntax, bad.next()); var bad2: Scanner = .init("\"esc\\n\""); try std.testing.expectError(error.InvalidSyntax, bad2.next()); var bad3: Scanner = .init("\"\n\""); try std.testing.expectError(error.InvalidSyntax, bad3.next());}
test "literals on the wire and in memory" { // At the end of a line the octets are elsewhere. var wire: Scanner = .init("BODY[] {12}"); try std.testing.expectEqualStrings("BODY", (try wire.expect()).atom); try std.testing.expectEqual(Token.open_bracket, try wire.expect()); try std.testing.expectEqual(Token.close_bracket, try wire.expect()); try std.testing.expectEqual(Token{ .literal = 12 }, try wire.expect()); try std.testing.expectEqual(@as(?usize, 12), trailingLiteral("BODY[] {12}")); try std.testing.expectEqual(@as(?usize, 12), trailingLiteral("BODY[] {12+}")); try std.testing.expectEqual(@as(?usize, null), trailingLiteral("BODY[] {12} more")); try std.testing.expectEqual(@as(?usize, null), trailingLiteral("{}")); try std.testing.expectEqual(@as(?usize, null), trailingLiteral("{x}")); // Not twelve: `std.fmt` would take the underscore, and the fuzzer found // the two readers disagreeing about it. try std.testing.expectEqual(@as(?usize, null), trailingLiteral("{1_2}")); var underscore: Scanner = .init("{1_2+}"); try std.testing.expectError(error.InvalidSyntax, underscore.next()); try std.testing.expectEqual(@as(?u32, null), parseDigits(u32, "4294967296")); try std.testing.expectEqual(@as(?u32, 4294967295), parseDigits(u32, "4294967295"));
// Collected into memory the octets follow the CRLF, and the scan carries // on after them. var mem: Scanner = .init("SUBJECT {5}\r\nhello UID 3"); try std.testing.expectEqualStrings("SUBJECT", (try mem.expect()).atom); try std.testing.expectEqualStrings("hello", (try mem.expect()).string); try std.testing.expectEqualStrings("UID", (try mem.expect()).atom); try std.testing.expectEqual(@as(?u64, 3), (try mem.expect()).number());
// A literal announced in the middle of a line with nothing following it // in memory is not a thing the server can have sent. var mid: Scanner = .init("{5} after"); try std.testing.expectError(error.InvalidSyntax, mid.next());}
test "items and lists" { var s: Scanner = .init("FLAGS (\\Seen (nested) \\Draft) UID 7 ENVELOPE (\"x\" {3}"); try std.testing.expectEqualStrings("FLAGS", try s.item()); try std.testing.expectEqualStrings("(\\Seen (nested) \\Draft)", try s.item()); try std.testing.expectEqualStrings("UID", try s.item()); try std.testing.expectEqualStrings("7", try s.item()); try std.testing.expectEqualStrings("ENVELOPE", try s.item()); try std.testing.expectError(error.LiteralInList, s.item());
var unbalanced: Scanner = .init("(a (b)"); try std.testing.expectError(error.InvalidSyntax, unbalanced.item());
try std.testing.expect(listContains("(\\Seen \\Flagged)", "\\seen")); try std.testing.expect(!listContains("(\\Seen \\Flagged)", "\\Deleted")); try std.testing.expect(listContains("\\Noselect \\HasChildren", "\\HasChildren"));}
test "accept and expect helpers" { var s: Scanner = .init("(1 \"two\" NIL)"); try std.testing.expect(try s.accept(.open_paren)); try std.testing.expect(!try s.accept(.open_paren)); try std.testing.expectEqual(@as(u32, 1), try s.expectNumber(u32)); try std.testing.expectEqualStrings("two", (try s.expectNString()).?.raw); try std.testing.expectEqual(@as(?String, null), try s.expectNString()); try std.testing.expect(try s.accept(.close_paren)); try std.testing.expectError(error.InvalidSyntax, s.expect());
var big: Scanner = .init("4294967296"); try std.testing.expectError(error.InvalidSyntax, big.expectNumber(u32));}
test "what goes out bare, quoted or as a literal" { try std.testing.expect(isAtomSafe("INBOX")); try std.testing.expect(isAtomSafe("Sent/2026")); try std.testing.expect(!isAtomSafe("")); try std.testing.expect(!isAtomSafe("NIL")); try std.testing.expect(!isAtomSafe("has space")); try std.testing.expect(!isAtomSafe("star*")); try std.testing.expect(!isAtomSafe("\\Seen")); try std.testing.expect(isQuotable("has space and \"quotes\"")); try std.testing.expect(!isQuotable("line\r\nbreak")); try std.testing.expect(!isQuotable("caf\xc3\xa9"));
var buf: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try writeQuoted(&w, "say \"hi\" \\ there"); try std.testing.expectEqualStrings("\"say \\\"hi\\\" \\\\ there\"", w.buffered());}