// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! An IMAP client over any pair of `std.Io.Reader` and `std.Io.Writer` //! streams. The transport — plain TCP, TLS, or a fixed buffer in tests — is //! the caller's to supply; see `Connection` for a wrapper that owns a socket //! and can do TLS for you. //! //! Internet Message Access Protocol (IMAP) - Version 4rev2: //! https://datatracker.ietf.org/doc/html/rfc9051 //! //! ## How a command runs //! //! Every command is tagged, and the server answers it with any number of //! untagged responses followed by one tagged status line. `send` writes the //! command and hands back a `Command`, whose `next` yields the untagged //! responses one at a time and whose `finish` reads to the tagged line. The //! typed wrappers — `select`, `fetchTo`, `searchAlloc` — are all built on //! that and are what a caller normally wants; `send` is for the rest. //! //! Untagged responses are applied to the session as they pass — the message //! count, the flags, the capability list — whoever is iterating, so a client //! that ignores what `next` returns still has an up-to-date `mailbox`. //! //! ## Zero-copy, and literals //! //! Every slice handed back borrows the reader's buffer and is invalidated by //! the next read; copy what you keep, or use the `*Alloc` variants. A //! *literal* — `{n}` at the end of a line, then `n` octets — is not in that //! buffer at all: it is on the wire, and a `Command` that has one pending //! says so. Stream it, allocate it, or ignore it and `next` discards it. //! //! ## Lines //! //! The reader's buffer must hold the longest *line* the server may send. A //! message body arrives as a literal and is streamed, so it needs no room; //! but an ENVELOPE, a BODYSTRUCTURE, or a long SEARCH result is a line, and //! one that does not fit is `error.StreamTooLong`. const std = @import("std"); const sasl = @import("sasl"); const parser = @import("parser.zig"); const response = @import("response.zig"); const utf7 = @import("utf7.zig"); const Client = @This(); pub const Response = response.Response; pub const Untagged = response.Untagged; pub const Status = response.Status; pub const StatusResponse = response.StatusResponse; pub const Code = response.Code; pub const Capabilities = response.Capabilities; pub const Mailbox = response.Mailbox; pub const MailboxStatus = response.MailboxStatus; pub const ListItem = response.ListItem; pub const UidResult = response.UidResult; pub const FetchIterator = response.FetchIterator; pub const FetchItem = response.FetchItem; pub const SequenceIterator = response.SequenceIterator; pub const Envelope = response.Envelope; input: *std.Io.Reader, output: *std.Io.Writer, /// Whether the transport protects what is written to it. This is what /// decides whether a mechanism that transmits the password is allowed; only /// the caller knows, so only the caller can set it. security: Security, /// Permits a mechanism that puts the password on the wire in the clear over /// a transport that is not encrypted. Set this when the connection is /// protected by something this library cannot see — a VPN, a unix socket, an /// SSH tunnel — or when talking to a server on a network you are willing to /// trust. allow_cleartext_auth: bool = false, /// What the server has said it can do, kept current from every CAPABILITY /// response and `[CAPABILITY]` code. `capabilities.known` says whether it /// has said anything yet. capabilities: Capabilities = .{}, /// The selected mailbox, kept current from the untagged responses the /// server sends, or null when none is selected. mailbox: ?Mailbox = null, state: State = .not_authenticated, /// Whether `ENABLE UTF8=ACCEPT` has been agreed, after which mailbox names /// go on the wire as UTF-8 rather than modified UTF-7. utf8: bool = false, /// The server has sent BYE: the connection is closing, and nothing further /// will be answered. bye: bool = false, /// The status line that ended the most recent command, or the BYE that /// ended the session — the server's own wording and any response code, for /// the detail behind an error. Like every other borrowed slice here it /// points into the reader's buffer, so read it before issuing the next /// command. last_status: ?StatusResponse = null, tag_counter: u32 = 0, tag_buf: [12]u8 = undefined, tag_len: u8 = 0, /// Octets of a literal announced by the last line read and not yet /// consumed. pending_literal: usize = 0, /// The last line read ended with a literal, so once its octets are consumed /// the rest of that line is still to be read. line_continues: bool = false, /// Whether the transport encrypts. IMAP has no way to find this out — a /// server cannot tell you whether you are behind TLS — so it is declared by /// whoever built the streams. pub const Security = enum { /// Anything written can be read by the network. plaintext, /// TLS (or something equivalent) is in place. encrypted, }; /// Where the session is in IMAP's state machine, as far as this client has /// seen. A command sent in the wrong state is answered BAD by the server; /// nothing here prevents sending it. /// https://datatracker.ietf.org/doc/html/rfc9051#section-3 pub const State = enum { not_authenticated, authenticated, selected, logout, }; pub const ReadError = error{ ReadFailed, /// The connection closed mid-response. EndOfStream, /// A line did not fit in the reader's buffer. StreamTooLong, /// The server sent something that is not an IMAP response. InvalidResponse, }; pub const WriteError = error{ WriteFailed, /// A command argument contained CR, LF, or NUL, any of which would let /// it smuggle a second command onto the wire — or a mailbox name that is /// not UTF-8. InvalidArgument, }; pub const Error = ReadError || WriteError; /// The server answered NO or BAD. `last_status` says why. pub const CommandError = Error || error{ /// NO: the command could not be carried out — no such mailbox, no /// permission, a quota exceeded. CommandFailed, /// BAD: the command was not understood, or not valid in this state. BadCommand, }; pub fn init(input: *std.Io.Reader, output: *std.Io.Writer, security: Security) Client { return .{ .input = input, .output = output, .security = security }; } /// Points the client at a new transport, typically the TLS streams set up /// after `starttls`, and records whether that transport is encrypted. pub fn setTransport( c: *Client, input: *std.Io.Reader, output: *std.Io.Writer, security: Security, ) void { c.input = input; c.output = output; c.security = security; } // -- Reading ----------------------------------------------------------------- /// Reads one CRLF-terminated line, consuming the terminator but returning /// the line without it. fn takeLine(input: *std.Io.Reader) ReadError![]const u8 { const raw = input.takeDelimiterInclusive('\n') catch |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.EndOfStream => return error.EndOfStream, error.StreamTooLong => return error.StreamTooLong, }; const line = raw[0 .. raw.len - 1]; return if (line.len > 0 and line[line.len - 1] == '\r') line[0 .. line.len - 1] else line; } /// Discards whatever is left of the last response: an unconsumed literal, /// and the rest of the line after it, however many literals that takes. fn skipPending(c: *Client) ReadError!void { while (c.line_continues) { if (c.pending_literal > 0) { c.input.discardAll(c.pending_literal) catch |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.EndOfStream => return error.EndOfStream, }; c.pending_literal = 0; } _ = try c.readContinuation(); } } /// Reads the rest of a line after a literal, noting a further literal. fn readContinuation(c: *Client) ReadError![]const u8 { std.debug.assert(c.pending_literal == 0); const rest = try takeLine(c.input); if (parser.trailingLiteral(rest)) |n| { c.pending_literal = n; } else { c.line_continues = false; } return rest; } /// Reads and parses one response line, applying it to the session, and /// noting a literal announced at its end. pub fn readResponse(c: *Client) ReadError!Response { try c.skipPending(); const line = try takeLine(c.input); const r = Response.parse(line) catch return error.InvalidResponse; if (parser.trailingLiteral(line)) |n| { c.pending_literal = n; c.line_continues = true; } switch (r) { .untagged => |u| c.applyUntagged(u), .tagged => |t| { c.last_status = t.status; if (t.status.code) |code| c.applyCode(code); }, .continuation => {}, } return r; } /// Folds an untagged response into the session's state. fn applyUntagged(c: *Client, u: Untagged) void { switch (u) { .capability => |text| c.capabilities = Capabilities.parse(text), .exists => |n| if (c.mailbox) |*m| { m.exists = n; }, .recent => |n| if (c.mailbox) |*m| { m.recent = n; }, .expunge => if (c.mailbox) |*m| { m.exists -|= 1; }, .flags => |flags| if (c.mailbox) |*m| m.flags.set(flags), .enabled => |enabled| { if (parser.listContains(enabled, "UTF8=ACCEPT")) c.utf8 = true; }, .status => |s| { if (s.status == .bye) { c.bye = true; c.last_status = s; c.state = .logout; } if (s.code) |code| c.applyCode(code); }, else => {}, } } /// Folds a response code into the session's state, wherever it arrived. fn applyCode(c: *Client, code: Code) void { if (code.is("CAPABILITY")) { c.capabilities = Capabilities.parse(code.args); return; } const m = &(c.mailbox orelse return); if (code.is("UIDVALIDITY")) { m.uidvalidity = code.number(u32); } else if (code.is("UIDNEXT")) { m.uidnext = code.number(u32); } else if (code.is("UNSEEN")) { m.unseen = code.number(u32); } else if (code.is("HIGHESTMODSEQ")) { m.highest_modseq = code.number(u64); } else if (code.is("PERMANENTFLAGS")) { m.permanent_flags.set(code.args); } else if (code.is("READ-ONLY")) { m.read_only = true; } else if (code.is("READ-WRITE")) { m.read_only = false; } } // -- Writing ----------------------------------------------------------------- /// Rejects strings that would break out of a single command line. pub fn checkArgument(arg: []const u8) error{InvalidArgument}!void { for (arg) |b| switch (b) { '\r', '\n', 0 => return error.InvalidArgument, else => {}, }; } /// `checkArgument` over every string in a format's argument tuple. fn checkArguments(args: anytype) error{InvalidArgument}!void { inline for (args) |arg| { const info = @typeInfo(@TypeOf(arg)); if (info == .pointer) { const is_bytes = switch (info.pointer.size) { .slice => info.pointer.child == u8, .one => switch (@typeInfo(info.pointer.child)) { .array => |a| a.child == u8, else => false, }, else => false, }; if (is_bytes) try checkArgument(arg); } } } /// Writes the tag that begins a command. Every command goes through here, /// which is how the tags stay unique within the session. fn beginCommand(c: *Client) WriteError!void { c.tag_counter += 1; const text = std.fmt.bufPrint(&c.tag_buf, "A{d:0>4}", .{c.tag_counter}) catch unreachable; c.tag_len = @intCast(text.len); c.output.writeAll(text) catch return error.WriteFailed; c.output.writeByte(' ') catch return error.WriteFailed; } fn tag(c: *const Client) []const u8 { return c.tag_buf[0..c.tag_len]; } /// Ends the command line, flushes it, and returns the reader of its /// responses. fn endCommand(c: *Client) WriteError!Command { c.output.writeAll("\r\n") catch return error.WriteFailed; c.output.flush() catch return error.WriteFailed; return .{ .client = c }; } fn write(c: *Client, bytes: []const u8) WriteError!void { c.output.writeAll(bytes) catch return error.WriteFailed; } fn print(c: *Client, comptime fmt: []const u8, args: anytype) WriteError!void { c.output.print(fmt, args) catch return error.WriteFailed; } /// Sends one tagged command — the tag is supplied, `fmt`/`args` follow /// `std.fmt` — and returns the reader of its responses. Every string in /// `args` is checked for the CRLF that would smuggle a second command onto /// the wire. /// /// This is the escape hatch for a command with no wrapper here: /// ```zig /// var cmd = try client.send("GETQUOTAROOT {s}", .{"INBOX"}); /// while (try cmd.next()) |u| switch (u) { /// .other => |o| std.debug.print("{s} {s}\n", .{ o.name, o.rest }), /// else => {}, /// }; /// _ = try cmd.expectOk(); /// ``` pub fn send(c: *Client, comptime fmt: []const u8, args: anytype) WriteError!Command { try checkArguments(args); try c.beginCommand(); try c.print(fmt, args); return c.endCommand(); } /// `send`, then reads every response to the end, and returns the tagged /// status if it was OK. NO is `error.CommandFailed`, BAD is /// `error.BadCommand`, and `last_status` holds the reason for either. pub fn run(c: *Client, comptime fmt: []const u8, args: anytype) CommandError!StatusResponse { var cmd = try c.send(fmt, args); return cmd.expectOk(); } /// Writes a string argument the way IMAP wants it: quoted when it can be, /// as a literal when it cannot — which means waiting for the server's go /// ahead in the middle of the command, unless it has LITERAL+. /// https://datatracker.ietf.org/doc/html/rfc9051#section-4.3 fn writeString(c: *Client, s: []const u8) CommandError!void { if (parser.isQuotable(s)) { parser.writeQuoted(c.output, s) catch return error.WriteFailed; } else { try c.writeLiteral(s); } } /// Writes a literal argument: the announcement, the wait for `+` unless the /// server has said it needs none, and the octets. Leaves the command open. fn writeLiteral(c: *Client, bytes: []const u8) CommandError!void { try c.announceLiteral(bytes.len); try c.write(bytes); } /// Announces a literal of `len` octets and, if the server needs to agree, /// waits for it to. Untagged responses arriving in the meantime are applied /// and dropped. A tagged response instead is the server refusing — too /// large, usually — and ends the command. /// https://datatracker.ietf.org/doc/html/rfc7888 fn announceLiteral(c: *Client, len: usize) CommandError!void { const caps = c.capabilities; if (caps.literal_plus or (caps.literal_minus and len <= 4096)) { try c.print("{{{d}+}}\r\n", .{len}); return; } try c.print("{{{d}}}\r\n", .{len}); c.output.flush() catch return error.WriteFailed; while (true) { switch (try c.readResponse()) { .continuation => return, .untagged => {}, .tagged => |t| return switch (t.status.status) { .ok => error.InvalidResponse, .no => error.CommandFailed, .bad => error.BadCommand, else => unreachable, }, } } } /// Writes a mailbox name, encoded as the session requires: UTF-8 once /// `UTF8=ACCEPT` is enabled, modified UTF-7 otherwise. Bare when it can be, /// quoted when it needs to be, a literal when nothing else will do. /// https://datatracker.ietf.org/doc/html/rfc9051#section-5.1 fn writeMailbox(c: *Client, name: []const u8) CommandError!void { if (c.utf8) { if (parser.isAtomSafe(name)) return c.write(name); return c.writeString(name); } var buf: [max_mailbox_name]u8 = undefined; const encoded = utf7.encodeBuf(&buf, name) catch |err| switch (err) { error.InvalidUtf8 => return error.InvalidArgument, error.NoSpaceLeft => return error.InvalidArgument, }; if (parser.isAtomSafe(encoded)) return c.write(encoded); // Modified UTF-7 is 7-bit and has no CRLF, so this never becomes a // literal. parser.writeQuoted(c.output, encoded) catch return error.WriteFailed; } /// The longest mailbox name this client will send, after encoding. pub const max_mailbox_name = 4096; /// Rejects a mailbox name that `writeMailbox` could not send, *before* any /// of the command has been written: a command abandoned halfway through /// would sit in the write buffer and go out in front of the next one. fn checkMailboxName(c: *const Client, name: []const u8) error{InvalidArgument}!void { try checkArgument(name); if (!std.unicode.utf8ValidateSlice(name)) return error.InvalidArgument; // Modified UTF-7 is at most about three times the size of UTF-8, and // needs the room. if (!c.utf8 and name.len * 3 + 3 > max_mailbox_name) return error.InvalidArgument; } // -- Command responses ------------------------------------------------------- /// The responses to one command, read as they arrive. /// /// `next` yields the untagged responses; `finish` reads to the tagged line /// and returns it; `expectOk` does the same and turns NO and BAD into /// errors. Each borrowed slice is invalidated by the next call to any of /// them. /// /// When the line just read ended with a literal, `literalLen` says so, and /// the octets are on the wire: `streamLiteral`, `readLiteralAlloc` or /// `discardLiteral` consume them, `continuation` reads the rest of the line /// after them, and `next` does both for a caller that does not care. pub const Command = struct { client: *Client, status: ?StatusResponse = null, /// The next untagged response, or null once the tagged line has been /// read — after which `status` holds it. pub fn next(it: *Command) ReadError!?Untagged { if (it.status != null) return null; const c = it.client; while (true) { switch (try c.readResponse()) { .untagged => |u| return u, .tagged => |t| { // Only one command is ever outstanding, so any other tag // is the server having lost the thread. if (!std.mem.eql(u8, t.tag, c.tag())) return error.InvalidResponse; it.status = t.status; return null; }, // Nothing here asked for one. .continuation => return error.InvalidResponse, } } } /// Reads to the tagged line and returns it. pub fn finish(it: *Command) ReadError!StatusResponse { while (try it.next()) |_| {} return it.status.?; } /// Reads to the tagged line and returns it if it was OK. pub fn expectOk(it: *Command) CommandError!StatusResponse { const s = try it.finish(); return switch (s.status) { .ok => s, .no => error.CommandFailed, .bad => error.BadCommand, else => unreachable, }; } /// The size of the literal the last line announced, if it did and the /// octets have not been consumed. pub fn literalLen(it: *const Command) ?usize { return if (it.client.line_continues and it.client.pending_literal > 0) it.client.pending_literal else null; } /// Copies the pending literal to `w` and returns how many octets that /// was. Does not flush `w`. pub fn streamLiteral(it: *Command, w: *std.Io.Writer) (ReadError || error{WriteFailed})!usize { const c = it.client; const n = it.literalLen() orelse return 0; c.input.streamExact(w, n) catch |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.EndOfStream => return error.EndOfStream, error.WriteFailed => return error.WriteFailed, }; c.pending_literal = 0; return n; } /// The pending literal in memory the caller owns, or /// `error.MessageTooLong` — the literal then discarded — if it is /// larger than `limit`. pub fn readLiteralAlloc( it: *Command, gpa: std.mem.Allocator, limit: std.Io.Limit, ) (ReadError || error{ OutOfMemory, MessageTooLong })![]u8 { const n = it.literalLen() orelse return try gpa.alloc(u8, 0); if (limit.toInt()) |max| if (n > max) { try it.discardLiteral(); return error.MessageTooLong; }; const out = try gpa.alloc(u8, n); errdefer gpa.free(out); var w: std.Io.Writer = .fixed(out); _ = it.streamLiteral(&w) catch |err| switch (err) { error.WriteFailed => unreachable, // sized to fit else => |e| return e, }; return out; } /// Reads and drops the pending literal. pub fn discardLiteral(it: *Command) ReadError!void { const c = it.client; const n = it.literalLen() orelse return; c.input.discardAll(n) catch |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.EndOfStream => return error.EndOfStream, }; c.pending_literal = 0; } /// The rest of the line after a literal that has been consumed. It may /// itself end with another literal, in which case `literalLen` says so /// again. Empty, and nothing read, when no line is pending. pub fn continuation(it: *Command) ReadError![]const u8 { const c = it.client; if (!c.line_continues) return ""; if (c.pending_literal > 0) try it.discardLiteral(); return c.readContinuation(); } /// Gathers the rest of a response that ran past its first line into /// memory: `head` is what has been read of it so far, and every literal /// still to come is appended in the `{n}CRLF octets` form `Scanner` /// reads, followed by the rest of its line. The caller owns the result. /// /// `error.MessageTooLong` when the whole would exceed `limit`, the rest /// of the response then discarded. pub fn collect( it: *Command, gpa: std.mem.Allocator, head: []const u8, limit: std.Io.Limit, ) CollectError![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); out.writer.writeAll(head) catch return error.OutOfMemory; while (it.client.line_continues) { const n = it.client.pending_literal; if (limit.toInt()) |max| if (out.written().len + n > max) { try it.client.skipPending(); return error.MessageTooLong; }; out.writer.writeAll("\r\n") catch return error.OutOfMemory; _ = it.streamLiteral(&out.writer) catch |err| switch (err) { error.WriteFailed => return error.OutOfMemory, else => |e| return e, }; const rest = try it.continuation(); out.writer.writeAll(rest) catch return error.OutOfMemory; } return out.toOwnedSlice() catch return error.OutOfMemory; } /// A FETCH response as a whole, literals included, in memory the caller /// owns. `f` is what `next` just returned. Walk the result with /// `FetchIterator`. pub fn collectFetch( it: *Command, gpa: std.mem.Allocator, f: Untagged.Fetch, limit: std.Io.Limit, ) CollectError!OwnedFetch { return .{ .number = f.number, .attributes = try it.collect(gpa, f.attributes, limit), }; } }; pub const CollectError = ReadError || error{ OutOfMemory, MessageTooLong }; /// A FETCH response held in memory. pub const OwnedFetch = struct { number: u32, /// The attribute list, parentheses included, every literal in the form /// `FetchIterator` reads. attributes: []u8, pub fn items(f: OwnedFetch) FetchIterator { return .init(f.attributes); } pub fn deinit(f: *OwnedFetch, gpa: std.mem.Allocator) void { gpa.free(f.attributes); f.* = undefined; } }; // -- Any state --------------------------------------------------------------- /// The server's greeting, read once immediately after connecting. pub const Greeting = struct { /// Whether the connection needs a login. PREAUTH means it does not — /// the transport already said who this is — and the session is in /// authenticated state from the start. status: enum { ok, preauth }, text: []const u8, }; /// Reads the server's greeting. Call once, before anything else. /// /// A BYE greeting is a server refusing the connection outright and comes /// back as `error.CommandFailed`, with its reason in `last_status`. A /// greeting often carries the capability list in a `[CAPABILITY]` code, /// in which case `capabilities.known` is already true afterwards. /// https://datatracker.ietf.org/doc/html/rfc9051#section-7.1 pub fn readGreeting(c: *Client) CommandError!Greeting { const r = try c.readResponse(); const s = switch (r) { .untagged => |u| switch (u) { .status => |s| s, else => return error.InvalidResponse, }, else => return error.InvalidResponse, }; switch (s.status) { .ok => { c.state = .not_authenticated; return .{ .status = .ok, .text = s.text }; }, .preauth => { c.state = .authenticated; return .{ .status = .preauth, .text = s.text }; }, .bye => return error.CommandFailed, .no, .bad => return error.InvalidResponse, } } /// CAPABILITY: asks, and returns what `capabilities` now holds. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.1.1 pub fn capability(c: *Client) CommandError!Capabilities { _ = try c.run("CAPABILITY", .{}); return c.capabilities; } /// NOOP: does nothing, and gives the server a chance to say what has /// changed in the selected mailbox — new mail arrives as `* n EXISTS` /// here — which is applied to `mailbox` as it passes. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.1.2 pub fn noop(c: *Client) CommandError!void { _ = try c.run("NOOP", .{}); } /// LOGOUT: ends the session. The server says BYE and then OK, and closes. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.1.3 pub fn logout(c: *Client) CommandError!void { _ = try c.run("LOGOUT", .{}); c.state = .logout; c.mailbox = null; } /// ID: tells the server what this client is, and hears what it is /// ([RFC 2971](https://datatracker.ietf.org/doc/html/rfc2971)). `params` /// are name/value pairs, e.g. `&.{ .{ "name", "myclient" }, .{ "version", /// "1.0" } }`; empty sends NIL. The server's answer is the `.id` untagged /// response, raw. pub fn id(c: *Client, params: []const [2][]const u8) CommandError!Command { for (params) |pair| { try checkArgument(pair[0]); try checkArgument(pair[1]); } try c.beginCommand(); try c.write("ID "); if (params.len == 0) { try c.write("NIL"); } else { try c.write("("); for (params, 0..) |pair, i| { if (i != 0) try c.write(" "); try c.writeString(pair[0]); try c.write(" "); try c.writeString(pair[1]); } try c.write(")"); } return c.endCommand(); } // -- Not authenticated state ------------------------------------------------- /// STARTTLS: asks the server to begin a TLS handshake on this connection. /// On OK the handshake starts immediately after the response, so nothing /// may be sent until it completes and the client's streams are re-pointed /// at the TLS ones — `Connection.startTls` does the whole sequence. /// /// Implicit TLS on port 993 is preferred where the server offers it /// ([RFC 8314](https://datatracker.ietf.org/doc/html/rfc8314#section-3)), /// which `Connection.connect` does directly. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.2.1 pub fn starttls(c: *Client) (Error || error{TlsNotAvailable})!void { var cmd = try c.send("STARTTLS", .{}); const s = try cmd.finish(); if (s.status != .ok) return error.TlsNotAvailable; // Whatever was advertised before the handshake could have been written // by an attacker; RFC 9051 requires it be forgotten. c.capabilities = .{}; } pub const AuthError = Error || error{ /// The server rejected the credentials, or the exchange. AuthenticationFailed, /// The server has said LOGINDISABLED, and will refuse LOGIN — nearly /// always because the connection is not yet encrypted. LoginDisabled, /// The mechanism would have put the password on the wire in the clear /// over a transport that is not encrypted. Upgrade the session, or set /// `allow_cleartext_auth` if the connection is protected by something /// this library cannot see. InsecureTransport, /// The server's challenge was not valid base64. InvalidChallenge, /// The credentials do not fit the fixed buffers used to encode them. CredentialsTooLong, /// The server advertised no mechanism `authenticate` knows how to drive. NoSupportedMechanism, /// The server accepted the exchange but the mechanism had not finished /// proving what it set out to prove. /// /// For a one-way mechanism this cannot happen. For SCRAM it means the /// server reported success without producing its own signature, which is /// what something in the middle holding no verifier would do. ServerNotAuthenticated, /// The server answered BAD: it did not understand the command. BadCommand, /// A mechanism needed memory it could not get. This client allocates /// nothing itself; a mechanism may — SCRAM does — and it is the caller /// that gave it its allocator. OutOfMemory, }; /// Refuses a mechanism that would transmit the password unprotected. fn requireConfidentiality(c: *const Client) error{InsecureTransport}!void { if (c.security == .encrypted or c.allow_cleartext_auth) return; return error.InsecureTransport; } /// Turns a NO or BAD to an authentication command into the most specific /// error its response code allows. fn authFailure(s: StatusResponse) AuthError { if (s.hasCode("PRIVACYREQUIRED")) return error.InsecureTransport; return switch (s.status) { .bad => error.BadCommand, else => error.AuthenticationFailed, }; } /// LOGIN: the username and password in the clear. Refused without an /// encrypted transport unless `allow_cleartext_auth` is set, and refused /// outright when the server has said LOGINDISABLED. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.2.3 pub fn login(c: *Client, username: []const u8, password: []const u8) AuthError!void { if (c.capabilities.logindisabled) return error.LoginDisabled; try c.requireConfidentiality(); try c.beginCommand(); try c.write("LOGIN "); c.writeString(username) catch |err| return loginWriteError(err); try c.write(" "); c.writeString(password) catch |err| return loginWriteError(err); var cmd = try c.endCommand(); const s = try cmd.finish(); if (s.status != .ok) return authFailure(s); c.state = .authenticated; } fn loginWriteError(err: CommandError) AuthError { return switch (err) { error.CommandFailed => error.AuthenticationFailed, else => |e| e, }; } /// Runs a SASL exchange with `mechanism` through AUTHENTICATE. /// /// The mechanisms come from /// [zig-sasl](https://git.jcollie.dev/jeff/zig-sasl) — `sasl.Plain`, /// `sasl.CramMd5`, `sasl.XOAuth2` and the rest, with SCRAM in zig-scram — /// since nothing about them is specific to IMAP. What is specific to IMAP /// is what this drives them with: `AUTHENTICATE`, the `+ ` challenges, the /// `*` that cancels, and the initial response on the command line when the /// server has SASL-IR. /// /// ```zig /// var plain: imap.sasl.Plain = .init("user", "password"); /// const mechanism = imap.sasl.Client.selectFromList( /// &.{plain.client()}, /// client.capabilities.auth.list(), /// client.security == .encrypted, /// ) orelse return error.NoSupportedMechanism; /// try client.authenticateSasl(mechanism); /// ``` /// /// A mechanism that would put a reusable credential on an unencrypted /// transport is refused before anything is sent. One that fails partway /// cancels the exchange with `*` rather than abandoning it, so the session /// stays usable. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.2.2 pub fn authenticateSasl(c: *Client, mechanism: sasl.Client) AuthError!void { if (mechanism.cleartext()) try c.requireConfidentiality(); try checkArgument(mechanism.name()); var message_buf: [max_sasl_message]u8 = undefined; var message: std.Io.Writer = .fixed(&message_buf); var initial: ?[]const u8 = switch (try c.saslStep(mechanism.initial(&message))) { .none => null, .written => message.buffered(), }; try c.beginCommand(); try c.print("AUTHENTICATE {s}", .{mechanism.name()}); // With SASL-IR the initial response rides on the command line; without // it the server sends an empty challenge first and the same bytes // answer that instead, costing a round trip and nothing else. if (initial != null and c.capabilities.sasl_ir) { try c.write(" "); try c.writeBase64Line(initial.?, true); initial = null; } _ = try c.endCommand(); while (true) { const r = try c.readResponse(); switch (r) { .continuation => |encoded| { var challenge_buf: [max_sasl_message]u8 = undefined; const challenge = c.decodeChallenge(encoded, &challenge_buf) catch |err| { c.cancelAuth() catch {}; return err; }; if (initial != null) { // The empty first challenge stands in for SASL-IR: the // initial response is still in `message`, and goes now. initial = null; } else { message = .fixed(&message_buf); try c.saslStep(mechanism.respond(challenge, &message)); } try c.writeBase64Line(message.buffered(), false); try c.write("\r\n"); c.output.flush() catch return error.WriteFailed; }, .untagged => {}, .tagged => |t| { if (t.status.status != .ok) return authFailure(t.status); // The server is content. Whether that proves anything is the // mechanism's to say: for SCRAM it does not until the server // has signed too. if (!mechanism.satisfied()) return error.ServerNotAuthenticated; c.state = .authenticated; return; }, } } } /// The largest SASL message before base64. An OAuth token needs the room. pub const max_sasl_message = 8192; /// Writes `bytes` base64 encoded. An empty initial response is a single /// `=`, since an empty argument would be indistinguishable from none; an /// empty later response is an empty line. fn writeBase64Line(c: *Client, bytes: []const u8, is_initial: bool) AuthError!void { if (bytes.len == 0) { if (is_initial) try c.write("="); return; } var encoded_buf: [std.base64.standard.Encoder.calcSize(max_sasl_message)]u8 = undefined; if (std.base64.standard.Encoder.calcSize(bytes.len) > encoded_buf.len) return error.CredentialsTooLong; try c.write(std.base64.standard.Encoder.encode(&encoded_buf, bytes)); } fn decodeChallenge(c: *Client, encoded: []const u8, buf: []u8) AuthError![]const u8 { _ = c; const len = std.base64.standard.Decoder.calcSizeForSlice(encoded) catch return error.InvalidChallenge; if (len > buf.len) return error.InvalidChallenge; std.base64.standard.Decoder.decode(buf[0..len], encoded) catch return error.InvalidChallenge; return buf[0..len]; } /// Cancels an AUTHENTICATE in progress with the `*` reserved for it, and /// reads the tagged BAD the server answers with. fn cancelAuth(c: *Client) Error!void { try c.write("*\r\n"); c.output.flush() catch return error.WriteFailed; var cmd: Command = .{ .client = c }; _ = try cmd.finish(); } /// Cancels the exchange on a mechanism error and turns it into ours. /// /// A mechanism that has failed produces no further message, so the server /// would be left waiting for a line that is not coming. fn saslStep(c: *Client, result: anytype) AuthError!@typeInfo(@TypeOf(result)).error_union.payload { return result catch |err| { c.cancelAuth() catch {}; return switch (err) { error.WriteFailed => error.WriteFailed, error.OutOfMemory => error.OutOfMemory, error.BadCredential => error.CredentialsTooLong, error.BadChallenge => error.InvalidChallenge, error.BadServerProof, error.Rejected => error.AuthenticationFailed, }; }; } /// Which mechanism `authenticate` used. pub const Mechanism = enum { login, plain, sasl_login, cram_md5 }; /// Authenticates with the best mechanism available, and says which one it /// used. /// /// Over an encrypted transport the network cannot read any of them, so the /// order is by what the standard prefers: AUTHENTICATE PLAIN, which every /// IMAP4rev2 server has, then LOGIN unless the server has disabled it, then /// SASL LOGIN and CRAM-MD5. Over a plaintext one only CRAM-MD5 keeps the /// password off the wire, so that is tried and the rest are refused with /// `error.InsecureTransport` — unless `allow_cleartext_auth` says otherwise. /// /// A rejection stops the search: trying the next mechanism with credentials /// the server has already refused earns a lockout, not a login. /// /// For anything outside this — XOAUTH2, OAUTHBEARER, EXTERNAL, SCRAM — build /// the mechanism and hand it to `authenticateSasl`, which is what this does /// underneath. pub fn authenticate(c: *Client, username: []const u8, password: []const u8) AuthError!Mechanism { const advertised = c.capabilities.auth.list(); var plain: sasl.Plain = .init(username, password); var login_sasl: sasl.Login = .init(username, password); var cram_md5: sasl.CramMd5 = .init(username, password); const encrypted = c.security == .encrypted or c.allow_cleartext_auth; if (!encrypted) { const offered: []const sasl.Client = &.{cram_md5.client()}; if (sasl.Client.selectFromList(offered, advertised, false)) |mechanism| { try c.authenticateSasl(mechanism); return .cram_md5; } return error.InsecureTransport; } if (c.capabilities.auth.has("PLAIN")) { try c.authenticateSasl(plain.client()); return .plain; } if (!c.capabilities.logindisabled) { try c.login(username, password); return .login; } const offered: []const sasl.Client = &.{ login_sasl.client(), cram_md5.client() }; if (sasl.Client.selectFromList(offered, advertised, true)) |mechanism| { try c.authenticateSasl(mechanism); return if (mechanism.context == @as(*anyopaque, @ptrCast(&login_sasl))) .sasl_login else .cram_md5; } return error.NoSupportedMechanism; } // -- Authenticated state ----------------------------------------------------- /// ENABLE: asks for extensions that change the protocol — `UTF8=ACCEPT`, /// `CONDSTORE`, `QRESYNC` — and returns whether *every* one asked for was /// enabled. What was is applied as it passes: after `UTF8=ACCEPT`, mailbox /// names go out as UTF-8. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.1 pub fn enable(c: *Client, extensions: []const u8) CommandError!bool { var cmd = try c.send("ENABLE {s}", .{extensions}); var all = true; while (try cmd.next()) |u| switch (u) { .enabled => |enabled| { var wanted = std.mem.tokenizeScalar(u8, extensions, ' '); while (wanted.next()) |name| { if (!parser.listContains(enabled, name)) all = false; } }, else => {}, }; _ = try cmd.expectOk(); return all; } /// SELECT: opens a mailbox for reading and writing, and returns its state /// as the server described it — which `mailbox` then tracks. A failed /// SELECT leaves no mailbox selected, as the protocol requires. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.2 pub fn select(c: *Client, name: []const u8) CommandError!Mailbox { return c.open("SELECT", name); } /// EXAMINE: SELECT, read-only. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.3 pub fn examine(c: *Client, name: []const u8) CommandError!Mailbox { return c.open("EXAMINE", name); } fn open(c: *Client, verb: []const u8, name: []const u8) CommandError!Mailbox { try c.checkMailboxName(name); c.mailbox = .{ .read_only = std.mem.eql(u8, verb, "EXAMINE") }; if (c.state == .selected) c.state = .authenticated; errdefer c.mailbox = null; try c.beginCommand(); try c.write(verb); try c.write(" "); try c.writeMailbox(name); var cmd = try c.endCommand(); _ = try cmd.expectOk(); c.state = .selected; return c.mailbox.?; } /// A command whose only argument is a mailbox name. fn mailboxCommand(c: *Client, verb: []const u8, name: []const u8) CommandError!void { try c.checkMailboxName(name); try c.beginCommand(); try c.write(verb); try c.write(" "); try c.writeMailbox(name); var cmd = try c.endCommand(); _ = try cmd.expectOk(); } /// CREATE: makes a mailbox. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.4 pub fn create(c: *Client, name: []const u8) CommandError!void { return c.mailboxCommand("CREATE", name); } /// DELETE: removes a mailbox and every message in it. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.5 pub fn delete(c: *Client, name: []const u8) CommandError!void { return c.mailboxCommand("DELETE", name); } /// RENAME. Renaming INBOX moves its messages to the new name and leaves an /// empty INBOX behind. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.6 pub fn rename(c: *Client, from: []const u8, to: []const u8) CommandError!void { try c.checkMailboxName(from); try c.checkMailboxName(to); try c.beginCommand(); try c.write("RENAME "); try c.writeMailbox(from); try c.write(" "); try c.writeMailbox(to); var cmd = try c.endCommand(); _ = try cmd.expectOk(); } /// SUBSCRIBE: adds a mailbox to the subscribed set that `LIST (SUBSCRIBED)` /// and `LSUB` report. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.7 pub fn subscribe(c: *Client, name: []const u8) CommandError!void { return c.mailboxCommand("SUBSCRIBE", name); } /// UNSUBSCRIBE. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.8 pub fn unsubscribe(c: *Client, name: []const u8) CommandError!void { return c.mailboxCommand("UNSUBSCRIBE", name); } /// LIST: the mailboxes matching `pattern` under `reference`, one `.list` /// untagged response each. `*` matches anything, `%` anything but the /// hierarchy delimiter; `LIST "" ""` reports the delimiter alone. /// `options` is what goes in the parentheses before the pattern, if /// anything — `SUBSCRIBED`, `REMOTE`, `SPECIAL-USE` — and `return_options` /// what follows `RETURN`, for a server with LIST-EXTENDED. /// /// A name the server had to send as a literal arrives after the line, as /// `Command` explains; `listAlloc` handles that and the character set. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.9 pub fn list(c: *Client, reference: []const u8, pattern: []const u8, options: ListOptions) CommandError!Command { try c.checkMailboxName(reference); try c.checkMailboxName(pattern); try checkArgument(options.selection); try checkArgument(options.@"return"); try c.beginCommand(); try c.write("LIST "); if (options.selection.len > 0) try c.print("({s}) ", .{options.selection}); try c.writeListArg(reference); try c.write(" "); try c.writeListArg(pattern); if (options.@"return".len > 0) try c.print(" RETURN ({s})", .{options.@"return"}); return c.endCommand(); } /// A LIST reference or pattern: a mailbox name that may also hold the `*` /// and `%` wildcards, which have to go bare -- inside a quoted string they /// are wildcards as well, but not every server agrees. fn writeListArg(c: *Client, arg: []const u8) CommandError!void { if (arg.len > 0) { const bare = for (arg) |ch| { if (ch != '*' and ch != '%' and !parser.isAtomSafe(&.{ch})) break false; } else true; if (bare) return c.write(arg); } return c.writeMailbox(arg); } pub const ListOptions = struct { /// Selection options: `SUBSCRIBED`, `REMOTE`, `RECURSIVEMATCH`, /// `SPECIAL-USE`, space-separated. selection: []const u8 = "", /// Return options: `SUBSCRIBED`, `CHILDREN`, `STATUS (MESSAGES UNSEEN)`. @"return": []const u8 = "", }; /// One mailbox from a LIST, in memory the caller owns. pub const MailboxEntry = struct { /// The name, in UTF-8: decoded from modified UTF-7 unless the session /// has enabled UTF-8. A name that is not valid UTF-7 is kept as sent. name: []u8, delimiter: ?u8, /// The name attributes, space-separated, without parentheses. attributes: []u8, pub fn hasAttribute(e: MailboxEntry, name: []const u8) bool { return parser.listContains(e.attributes, name); } }; pub const MailboxList = struct { entries: []MailboxEntry, pub fn deinit(l: *MailboxList, gpa: std.mem.Allocator) void { for (l.entries) |e| { gpa.free(e.name); gpa.free(e.attributes); } gpa.free(l.entries); l.* = undefined; } }; /// LIST, collected: every mailbox with its name decoded to UTF-8. pub fn listAlloc( c: *Client, gpa: std.mem.Allocator, reference: []const u8, pattern: []const u8, options: ListOptions, ) (CommandError || error{OutOfMemory})!MailboxList { var cmd = try c.list(reference, pattern, options); var entries: std.ArrayList(MailboxEntry) = .empty; defer { for (entries.items) |e| { gpa.free(e.name); gpa.free(e.attributes); } entries.deinit(gpa); } while (try cmd.next()) |u| { const item = switch (u) { .list, .lsub => |l| l, else => continue, }; const attributes = try gpa.dupe(u8, item.attributes); errdefer gpa.free(attributes); const name = try c.mailboxNameAlloc(gpa, &cmd, item.name); errdefer gpa.free(name); try entries.append(gpa, .{ .name = name, .delimiter = item.delimiter, .attributes = attributes, }); } _ = try cmd.expectOk(); return .{ .entries = try entries.toOwnedSlice(gpa) }; } /// A mailbox name as the server sent it — an atom, a quoted string, or a /// literal still on the wire — decoded into memory the caller owns. fn mailboxNameAlloc( c: *Client, gpa: std.mem.Allocator, cmd: *Command, name: parser.Token, ) (ReadError || error{OutOfMemory})![]u8 { const raw: []u8 = switch (name) { .literal => cmd.readLiteralAlloc(gpa, .unlimited) catch |err| switch (err) { error.MessageTooLong => unreachable, else => |e| return e, }, else => try name.asString().?.dupe(gpa), }; if (c.utf8) return raw; defer gpa.free(raw); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); utf7.decode(&out.writer, raw) catch |err| switch (err) { error.WriteFailed => return error.OutOfMemory, // Not modified UTF-7 — a server already speaking UTF-8, or a name // that was never encoded. As sent is the best available. error.InvalidEncoding => return gpa.dupe(u8, raw), }; return out.toOwnedSlice() catch return error.OutOfMemory; } /// STATUS: asks about a mailbox without selecting it. `items` is what to /// ask for: `MESSAGES UNSEEN UIDNEXT UIDVALIDITY`, and `SIZE` or `DELETED` /// where the server has them. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.11 pub fn status(c: *Client, name: []const u8, items: []const u8) CommandError!MailboxStatus { try c.checkMailboxName(name); try checkArgument(items); try c.beginCommand(); try c.write("STATUS "); try c.writeMailbox(name); try c.print(" ({s})", .{items}); var cmd = try c.endCommand(); var result: ?MailboxStatus = null; while (try cmd.next()) |u| switch (u) { .status_item => |item| { const attrs = item.attributes orelse blk: { // The name came as a literal, so the list is on the line // after it. try cmd.discardLiteral(); break :blk try cmd.continuation(); }; result = MailboxStatus.parse(attrs) catch return error.InvalidResponse; }, else => {}, }; _ = try cmd.expectOk(); return result orelse error.InvalidResponse; } pub const AppendOptions = struct { /// Flags to set on the message, space-separated: `\Seen \Draft`. flags: []const u8 = "", /// The internal date to give it, in IMAP's own format: /// `17-Jul-1996 02:44:25 -0700`. The server's clock otherwise. date: []const u8 = "", }; /// APPEND: adds `message` — an RFC 5322 message, CRLF line endings — to a /// mailbox. On a server with UIDPLUS the result says which UID it got. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.12 pub fn append( c: *Client, mailbox: []const u8, options: AppendOptions, message: []const u8, ) CommandError!?UidResult { try c.beginAppend(mailbox, options, message.len); try c.write(message); return c.finishAppend(); } /// APPEND from a reader: `len` octets of it, streamed rather than held. pub fn appendFrom( c: *Client, mailbox: []const u8, options: AppendOptions, message: *std.Io.Reader, len: usize, ) (CommandError || error{MessageTruncated})!?UidResult { try c.beginAppend(mailbox, options, len); message.streamExact(c.output, len) catch |err| switch (err) { error.WriteFailed => return error.WriteFailed, // The message ran out before its announced length; the server is // owed the rest, and there is nothing to send. The command cannot // be completed, so neither can the session. error.ReadFailed, error.EndOfStream => return error.MessageTruncated, }; return c.finishAppend(); } fn beginAppend(c: *Client, mailbox: []const u8, options: AppendOptions, len: usize) CommandError!void { try c.checkMailboxName(mailbox); try checkArgument(options.flags); try checkArgument(options.date); try c.beginCommand(); try c.write("APPEND "); try c.writeMailbox(mailbox); if (options.flags.len > 0) try c.print(" ({s})", .{options.flags}); if (options.date.len > 0) { try c.write(" "); parser.writeQuoted(c.output, options.date) catch return error.WriteFailed; } try c.write(" "); try c.announceLiteral(len); } fn finishAppend(c: *Client) CommandError!?UidResult { var cmd = try c.endCommand(); const s = try cmd.expectOk(); const code = s.codeNamed("APPENDUID") orelse return null; return UidResult.parse(code.args, .append) catch error.InvalidResponse; } /// IDLE: waits for the server to say what changed. /// /// The server sends untagged responses — EXISTS for new mail, EXPUNGE, /// FETCH for a flag change — as they happen, and `Idle.next` returns each /// one, blocking until then. `Idle.done` ends it. The wait has no timeout /// of its own; RFC 9051 says a server may drop an IDLE after 30 minutes, /// so a client that waits longer than that in one go should expect to be /// disconnected, and anything shorter is the transport's `Io` to enforce. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.13 pub fn idle(c: *Client) CommandError!Idle { if (!c.capabilities.idle and c.capabilities.known) return error.BadCommand; _ = try c.send("IDLE", .{}); while (true) { switch (try c.readResponse()) { .continuation => return .{ .client = c }, .untagged => {}, .tagged => |t| return switch (t.status.status) { .no => error.CommandFailed, .bad => error.BadCommand, else => error.InvalidResponse, }, } } } pub const Idle = struct { client: *Client, /// The next thing the server says, applied to `mailbox` as it passes. pub fn next(it: *Idle) ReadError!Untagged { return switch (try it.client.readResponse()) { .untagged => |u| u, else => error.InvalidResponse, }; } /// Ends the IDLE and reads its tagged OK. pub fn done(it: *Idle) CommandError!void { const c = it.client; try c.write("DONE\r\n"); c.output.flush() catch return error.WriteFailed; var cmd: Command = .{ .client = c }; _ = try cmd.expectOk(); } }; // -- Selected state ---------------------------------------------------------- /// CLOSE: expunges what is flagged `\Deleted` and deselects the mailbox. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.2 pub fn close(c: *Client) CommandError!void { _ = try c.run("CLOSE", .{}); c.deselected(); } /// UNSELECT: deselects the mailbox without expunging anything. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.3 pub fn unselect(c: *Client) CommandError!void { _ = try c.run("UNSELECT", .{}); c.deselected(); } fn deselected(c: *Client) void { c.mailbox = null; c.state = .authenticated; } /// EXPUNGE: removes every message flagged `\Deleted`. Each removal arrives /// as an untagged EXPUNGE, and `mailbox.exists` has counted them by the /// time this returns. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.4 pub fn expunge(c: *Client) CommandError!void { _ = try c.run("EXPUNGE", .{}); } /// UID EXPUNGE: the same, for the messages in `uid_set` alone /// ([RFC 4315](https://datatracker.ietf.org/doc/html/rfc4315#section-2.1)). pub fn uidExpunge(c: *Client, uid_set: []const u8) CommandError!void { _ = try c.run("UID EXPUNGE {s}", .{uid_set}); } /// Whether a set names messages by UID or by sequence number. pub const Numbering = enum { /// Sequence numbers: positions in the mailbox, which change whenever a /// message is expunged. sequence, /// Unique identifiers, stable within a UIDVALIDITY. uid, fn prefix(n: Numbering) []const u8 { return switch (n) { .sequence => "", .uid => "UID ", }; } }; /// SEARCH: the messages matching `criteria`, into memory the caller owns. /// /// `criteria` is passed through as written: `ALL`, `UNSEEN`, `FROM "alice" /// SINCE 1-Feb-2026`, `OR FLAGGED SUBJECT "urgent"`. Strings in it must be /// quoted, with `parser.writeQuoted` if they come from anywhere untrusted; /// text that is not ASCII needs `CHARSET UTF-8` and a server that accepts /// it. With `.uid` the result holds UIDs. /// /// Both the SEARCH and the ESEARCH forms of the result are read. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.4 pub fn searchAlloc( c: *Client, gpa: std.mem.Allocator, numbering: Numbering, criteria: []const u8, ) (CommandError || error{OutOfMemory})![]u32 { var cmd = try c.send("{s}SEARCH {s}", .{ numbering.prefix(), criteria }); var found: std.ArrayList(u32) = .empty; defer found.deinit(gpa); while (try cmd.next()) |u| switch (u) { .search => |numbers| { var it = std.mem.tokenizeScalar(u8, numbers, ' '); while (it.next()) |n| { try found.append(gpa, parser.parseDigits(u32, n) orelse return error.InvalidResponse); } }, .esearch => |text| { // `(TAG "A1") UID ALL 2,10:12`: the set follows ALL. var it = std.mem.tokenizeScalar(u8, text, ' '); while (it.next()) |word| { if (!std.ascii.eqlIgnoreCase(word, "ALL")) continue; const set = it.next() orelse return error.InvalidResponse; var numbers: SequenceIterator = .init(set); while (numbers.next() catch return error.InvalidResponse) |n| try found.append(gpa, n); } }, else => {}, }; _ = try cmd.expectOk(); return found.toOwnedSlice(gpa); } /// FETCH: asks for `items` — `FLAGS`, `UID`, `ENVELOPE`, `BODY.PEEK[]`, /// `(FLAGS UID RFC822.SIZE)` — of the messages in `set`, and returns the /// reader of what comes back: one `.fetch` per message, each of which may /// have a literal pending. `Command.collectFetch` takes a whole one into /// memory; `fetchTo` streams a body without doing that. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.5 pub fn fetch(c: *Client, numbering: Numbering, set: []const u8, items: []const u8) CommandError!Command { return c.send("{s}FETCH {s} {s}", .{ numbering.prefix(), set, items }); } pub const FetchOptions = struct { /// `BODY.PEEK` rather than `BODY`, so that fetching does not set /// `\Seen`. peek: bool = true, /// Cap on the size of the body, after which it is discarded and /// `error.MessageTooLong` returned. limit: std.Io.Limit = .unlimited, }; pub const FetchError = CommandError || error{ WriteFailed, MessageTooLong, /// The server answered OK but sent no such message: a UID that does /// not exist, or one expunged since. NoSuchMessage, }; /// FETCH a body section — `""` for the whole message, `HEADER`, `TEXT`, /// `1.2` for a MIME part, `HEADER.FIELDS (FROM SUBJECT)` — of one message, /// straight to a writer, without holding it in memory. Returns the number /// of octets written; does not flush `w`. /// /// What is written is exactly what the server sent: an RFC 5322 message /// with CRLF line endings, when the section is the whole thing. pub fn fetchTo( c: *Client, w: *std.Io.Writer, numbering: Numbering, number: u32, section: []const u8, options: FetchOptions, ) FetchError!u64 { try checkArgument(section); var cmd = try c.send("{s}FETCH {d} (BODY{s}[{s}])", .{ numbering.prefix(), number, if (options.peek) ".PEEK" else "", section, }); var written: ?u64 = null; while (try cmd.next()) |u| { const f = switch (u) { .fetch => |f| f, else => continue, }; if (written != null) continue; if (cmd.literalLen()) |n| { if (options.limit.toInt()) |max| if (n > max) { try cmd.discardLiteral(); _ = try cmd.finish(); return error.MessageTooLong; }; written = try cmd.streamLiteral(w); } else { // Short enough to come as a quoted string, or NIL for a section // that does not exist. var items = FetchIterator.init(f.attributes); while (items.next() catch return error.InvalidResponse) |item| { if (!item.isBodySection(section)) continue; const s = item.value.string() orelse { written = 0; break; }; s.write(w) catch return error.WriteFailed; written = s.len(); } } } _ = try cmd.expectOk(); return written orelse error.NoSuchMessage; } /// FETCH one message's attributes into memory the caller owns, literals /// and all: what to use for an ENVELOPE, a BODYSTRUCTURE, a set of header /// fields. pub fn fetchAlloc( c: *Client, gpa: std.mem.Allocator, numbering: Numbering, number: u32, items: []const u8, limit: std.Io.Limit, ) (FetchError || error{OutOfMemory})!OwnedFetch { var cmd = try c.send("{s}FETCH {d} {s}", .{ numbering.prefix(), number, items }); var result: ?OwnedFetch = null; errdefer if (result) |*r| r.deinit(gpa); while (try cmd.next()) |u| switch (u) { .fetch => |f| { // An unsolicited FETCH for another message — a flag change — // can arrive here too; with UIDs the number would not match, so // the first one with an answer to the question is taken. if (result != null) continue; result = cmd.collectFetch(gpa, f, limit) catch |err| switch (err) { // The rest of the message has been discarded; the command // still has to be read to its end or the next one would be // answered with this one's status. error.MessageTooLong => { _ = try cmd.finish(); return error.MessageTooLong; }, else => |e| return e, }; }, else => {}, }; _ = try cmd.expectOk(); return result orelse error.NoSuchMessage; } pub const StoreAction = enum { /// Replace the flags with these. set, /// Add these to the flags. add, /// Remove these from the flags. remove, fn verb(a: StoreAction) []const u8 { return switch (a) { .set => "FLAGS", .add => "+FLAGS", .remove => "-FLAGS", }; } }; pub const StoreOptions = struct { /// `.SILENT`: the server does not report the new flags. Without it each /// message's new flags come back as an untagged FETCH, applied to /// nothing here and discarded; use `send` to read them. silent: bool = true, }; /// STORE: changes the flags of the messages in `set`. `flags` are /// space-separated: `\Seen \Flagged $Important`. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.6 pub fn store( c: *Client, numbering: Numbering, set: []const u8, action: StoreAction, flags: []const u8, options: StoreOptions, ) CommandError!void { _ = try c.run("{s}STORE {s} {s}{s} ({s})", .{ numbering.prefix(), set, action.verb(), if (options.silent) ".SILENT" else "", flags, }); } /// COPY: copies the messages in `set` to another mailbox. On a server with /// UIDPLUS the result says which UIDs the copies got. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.7 pub fn copy(c: *Client, numbering: Numbering, set: []const u8, mailbox: []const u8) CommandError!?UidResult { return c.transfer("COPY", numbering, set, mailbox); } /// MOVE: COPY, then the originals are expunged /// ([RFC 6851](https://datatracker.ietf.org/doc/html/rfc6851)). The /// expunges arrive as untagged EXPUNGE responses, applied as they pass. /// https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.8 pub fn move(c: *Client, numbering: Numbering, set: []const u8, mailbox: []const u8) CommandError!?UidResult { return c.transfer("MOVE", numbering, set, mailbox); } fn transfer(c: *Client, verb: []const u8, numbering: Numbering, set: []const u8, mailbox: []const u8) CommandError!?UidResult { try checkArgument(set); try c.checkMailboxName(mailbox); try c.beginCommand(); try c.print("{s}{s} {s} ", .{ numbering.prefix(), verb, set }); try c.writeMailbox(mailbox); var cmd = try c.endCommand(); var result: ?UidResult = null; while (try cmd.next()) |u| switch (u) { // MOVE reports COPYUID in an untagged OK before the expunges. .status => |s| if (s.codeNamed("COPYUID")) |code| { result = UidResult.parse(code.args, .copy) catch return error.InvalidResponse; }, else => {}, }; const s = try cmd.expectOk(); if (s.codeNamed("COPYUID")) |code| { result = UidResult.parse(code.args, .copy) catch return error.InvalidResponse; } return result; } // -- Tests ------------------------------------------------------------------- const TestPeer = struct { reader: std.Io.Reader, writer: std.Io.Writer, write_buffer: [8192]u8 = undefined, /// A client talking to a fixed script of server output. `.encrypted`, /// because the transport a test uses is not a network and demanding /// `allow_cleartext_auth` everywhere would only test that flag. fn init(peer: *TestPeer, server_data: []const u8) Client { return peer.initSecurity(server_data, .encrypted); } fn initSecurity(peer: *TestPeer, server_data: []const u8, security: Security) Client { peer.reader = .fixed(server_data); peer.writer = .fixed(&peer.write_buffer); return .init(&peer.reader, &peer.writer, security); } fn sent(peer: *const TestPeer) []const u8 { return peer.writer.buffered(); } }; const testing = std.testing; test "greeting with capabilities" { var peer: TestPeer = undefined; var c = peer.init("* OK [CAPABILITY IMAP4rev2 STARTTLS AUTH=PLAIN LOGINDISABLED] Dovecot ready.\r\n"); const g = try c.readGreeting(); try testing.expectEqual(.ok, g.status); try testing.expectEqualStrings("Dovecot ready.", g.text); try testing.expect(c.capabilities.known); try testing.expect(c.capabilities.imap4rev2); try testing.expect(c.capabilities.logindisabled); try testing.expectEqual(State.not_authenticated, c.state); } test "greeting variants" { var peer: TestPeer = undefined; var c = peer.init("* PREAUTH ready\r\n"); try testing.expectEqual(.preauth, (try c.readGreeting()).status); try testing.expectEqual(State.authenticated, c.state); try testing.expect(!c.capabilities.known); var peer2: TestPeer = undefined; var c2 = peer2.init("* BYE too many connections\r\n"); try testing.expectError(error.CommandFailed, c2.readGreeting()); try testing.expect(c2.bye); try testing.expectEqualStrings("too many connections", c2.last_status.?.text); var peer3: TestPeer = undefined; var c3 = peer3.init("220 smtp.example.com ESMTP\r\n"); try testing.expectError(error.InvalidResponse, c3.readGreeting()); } test "capability" { var peer: TestPeer = undefined; var c = peer.init("* CAPABILITY IMAP4rev1 IDLE UIDPLUS AUTH=PLAIN AUTH=LOGIN\r\nA0001 OK done\r\n"); const caps = try c.capability(); try testing.expect(caps.idle and caps.uidplus); try testing.expectEqualStrings("PLAIN LOGIN", caps.auth.list()); try testing.expectEqualStrings("A0001 CAPABILITY\r\n", peer.sent()); try testing.expectEqualStrings("done", c.last_status.?.text); } test "tags increment and must match" { var peer: TestPeer = undefined; var c = peer.init("A0001 OK\r\nA0002 OK\r\nA0009 OK\r\n"); try c.noop(); try c.noop(); try testing.expectError(error.InvalidResponse, c.noop()); try testing.expectEqualStrings("A0001 NOOP\r\nA0002 NOOP\r\nA0003 NOOP\r\n", peer.sent()); } test "NO and BAD" { var peer: TestPeer = undefined; var c = peer.init("A0001 NO [TRYCREATE] no such mailbox\r\nA0002 BAD parse error\r\n"); try testing.expectError(error.CommandFailed, c.run("SELECT nothing", .{})); try testing.expect(c.last_status.?.hasCode("TRYCREATE")); try testing.expectError(error.BadCommand, c.run("SELEKT", .{})); try testing.expectEqualStrings("parse error", c.last_status.?.text); } test "login" { var peer: TestPeer = undefined; var c = peer.init("A0001 OK [CAPABILITY IMAP4rev2 IDLE] Logged in\r\n"); try c.login("alice", "s3cret"); try testing.expectEqualStrings("A0001 LOGIN \"alice\" \"s3cret\"\r\n", peer.sent()); try testing.expectEqual(State.authenticated, c.state); // The capabilities on the tagged OK are picked up. try testing.expect(c.capabilities.idle); } test "login quotes what needs quoting and sends the rest as a literal" { var peer: TestPeer = undefined; var c = peer.init("+ go ahead\r\nA0001 OK\r\n"); try c.login("al \"ice\"", "p\xc3\xa4ss"); try testing.expectEqualStrings( "A0001 LOGIN \"al \\\"ice\\\"\" {5}\r\np\xc3\xa4ss\r\n", peer.sent(), ); // With LITERAL+ no permission is needed. var peer2: TestPeer = undefined; var c2 = peer2.init("A0001 OK\r\n"); c2.capabilities.literal_plus = true; try c2.login("alice", "p\xc3\xa4ss"); try testing.expectEqualStrings("A0001 LOGIN \"alice\" {5+}\r\np\xc3\xa4ss\r\n", peer2.sent()); } test "a refused literal ends the command" { var peer: TestPeer = undefined; var c = peer.init("A0001 NO too long\r\n"); try testing.expectError(error.AuthenticationFailed, c.login("alice", "p\xc3\xa4ss")); } test "login refused" { var peer: TestPeer = undefined; var c = peer.init("A0001 NO [AUTHENTICATIONFAILED] Authentication failed.\r\n"); try testing.expectError(error.AuthenticationFailed, c.login("alice", "wrong")); try testing.expect(c.last_status.?.hasCode("AUTHENTICATIONFAILED")); try testing.expectEqual(State.not_authenticated, c.state); } test "login is refused when disabled, or in the clear" { var peer: TestPeer = undefined; var c = peer.init(""); c.capabilities.logindisabled = true; try testing.expectError(error.LoginDisabled, c.login("alice", "s3cret")); var peer2: TestPeer = undefined; var c2 = peer2.initSecurity("", .plaintext); try testing.expectError(error.InsecureTransport, c2.login("alice", "s3cret")); try testing.expectEqualStrings("", peer2.sent()); var peer3: TestPeer = undefined; var c3 = peer3.initSecurity("A0001 OK\r\n", .plaintext); c3.allow_cleartext_auth = true; try c3.login("alice", "s3cret"); } test "authenticate PLAIN with SASL-IR" { var peer: TestPeer = undefined; var c = peer.init("A0001 OK authenticated\r\n"); c.capabilities.sasl_ir = true; var plain: sasl.Plain = .init("tim", "tanstaaftanstaaf"); try c.authenticateSasl(plain.client()); try testing.expectEqualStrings( "A0001 AUTHENTICATE PLAIN AHRpbQB0YW5zdGFhZnRhbnN0YWFm\r\n", peer.sent(), ); try testing.expectEqual(State.authenticated, c.state); } test "authenticate PLAIN without SASL-IR" { var peer: TestPeer = undefined; var c = peer.init("+ \r\nA0001 OK authenticated\r\n"); var plain: sasl.Plain = .init("tim", "tanstaaftanstaaf"); try c.authenticateSasl(plain.client()); try testing.expectEqualStrings( "A0001 AUTHENTICATE PLAIN\r\nAHRpbQB0YW5zdGFhZnRhbnN0YWFm\r\n", peer.sent(), ); } test "a challenge-response mechanism runs through the continuations" { var peer: TestPeer = undefined; var c = peer.initSecurity( "+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2UucmVzdG9uLm1jaS5uZXQ+\r\n" ++ "A0001 OK authenticated\r\n", .plaintext, ); var cram: sasl.CramMd5 = .init("tim", "tanstaaftanstaaf"); try c.authenticateSasl(cram.client()); try testing.expectEqualStrings( "A0001 AUTHENTICATE CRAM-MD5\r\n" ++ "dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw\r\n", peer.sent(), ); } test "a mechanism that sends a credential in the clear is refused first" { var peer: TestPeer = undefined; var c = peer.initSecurity("", .plaintext); var plain: sasl.Plain = .init("tim", "tanstaaftanstaaf"); try testing.expectError(error.InsecureTransport, c.authenticateSasl(plain.client())); try testing.expectEqualStrings("", peer.sent()); } test "a challenge that is not base64 cancels the exchange" { var peer: TestPeer = undefined; var c = peer.init("+ not!base64\r\nA0001 BAD cancelled\r\n"); var cram: sasl.CramMd5 = .init("tim", "tanstaaftanstaaf"); try testing.expectError(error.InvalidChallenge, c.authenticateSasl(cram.client())); try testing.expect(std.mem.endsWith(u8, peer.sent(), "*\r\n")); } test "an empty initial response is an equals sign" { var peer: TestPeer = undefined; var c = peer.init("A0001 OK\r\n"); c.capabilities.sasl_ir = true; var ext: sasl.External = .init(""); try c.authenticateSasl(ext.client()); try testing.expectEqualStrings("A0001 AUTHENTICATE EXTERNAL =\r\n", peer.sent()); } test "an XOAUTH2 failure report is acknowledged before the error is read" { var peer: TestPeer = undefined; var c = peer.init("+ eyJzdGF0dXMiOiI0MDEifQ==\r\nA0001 NO [AUTHENTICATIONFAILED] Invalid credentials\r\n"); c.capabilities.sasl_ir = true; var oauth: sasl.XOAuth2 = .init("user@example.com", "expired"); try testing.expectError(error.AuthenticationFailed, c.authenticateSasl(oauth.client())); // An empty line, not a cancellation, is what gets the real error out. try testing.expect(std.mem.endsWith(u8, peer.sent(), "\r\n\r\n")); try testing.expectEqualStrings("{\"status\":\"401\"}", oauth.report()); } test "authenticate chooses" { // Encrypted, PLAIN advertised: AUTHENTICATE PLAIN. var peer: TestPeer = undefined; var c = peer.init("+ \r\nA0001 OK\r\n"); c.capabilities = Capabilities.parse("IMAP4rev2 AUTH=PLAIN"); try testing.expectEqual(Mechanism.plain, try c.authenticate("alice", "s3cret")); // Encrypted, nothing advertised: LOGIN. var peer2: TestPeer = undefined; var c2 = peer2.init("A0001 OK\r\n"); try testing.expectEqual(Mechanism.login, try c2.authenticate("alice", "s3cret")); try testing.expectEqualStrings("A0001 LOGIN \"alice\" \"s3cret\"\r\n", peer2.sent()); // Plaintext: CRAM-MD5 or nothing. var peer3: TestPeer = undefined; var c3 = peer3.initSecurity("+ PDE+\r\nA0001 OK\r\n", .plaintext); c3.capabilities = Capabilities.parse("IMAP4rev1 AUTH=PLAIN AUTH=CRAM-MD5"); try testing.expectEqual(Mechanism.cram_md5, try c3.authenticate("alice", "s3cret")); var peer4: TestPeer = undefined; var c4 = peer4.initSecurity("", .plaintext); c4.capabilities = Capabilities.parse("IMAP4rev1 AUTH=PLAIN"); try testing.expectError(error.InsecureTransport, c4.authenticate("alice", "s3cret")); try testing.expectEqualStrings("", peer4.sent()); // LOGIN disabled and only something this cannot drive: nothing. var peer5: TestPeer = undefined; var c5 = peer5.init(""); c5.capabilities = Capabilities.parse("IMAP4rev1 LOGINDISABLED AUTH=GSSAPI"); try testing.expectError(error.NoSupportedMechanism, c5.authenticate("alice", "s3cret")); } test "starttls" { var peer: TestPeer = undefined; var c = peer.init("A0001 OK Begin TLS negotiation now.\r\nA0002 BAD Unknown command\r\n"); c.capabilities = Capabilities.parse("IMAP4rev2 STARTTLS"); try c.starttls(); // Forgotten, as RFC 9051 requires. try testing.expect(!c.capabilities.known); try testing.expectError(error.TlsNotAvailable, c.starttls()); } test "select" { var peer: TestPeer = undefined; var c = peer.init("* 172 EXISTS\r\n" ++ "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n" ++ "* OK [UIDNEXT 4392] Predicted next UID\r\n" ++ "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n" ++ "* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)] Limited\r\n" ++ "* OK [UNSEEN 12] Message 12 is first unseen\r\n" ++ "* LIST () \"/\" INBOX\r\n" ++ "A0001 OK [READ-WRITE] SELECT completed\r\n"); const m = try c.select("INBOX"); try testing.expectEqualStrings("A0001 SELECT INBOX\r\n", peer.sent()); try testing.expectEqual(@as(u32, 172), m.exists); try testing.expectEqual(@as(?u32, 3857529045), m.uidvalidity); try testing.expectEqual(@as(?u32, 4392), m.uidnext); try testing.expectEqual(@as(?u32, 12), m.unseen); try testing.expect(m.flags.has("\\Draft")); try testing.expect(m.permanent_flags.has("\\Seen")); try testing.expect(m.allowsNewKeywords()); try testing.expect(!m.read_only); try testing.expectEqual(State.selected, c.state); try testing.expectEqual(m, c.mailbox.?); } test "examine, and a failed select deselects" { var peer: TestPeer = undefined; var c = peer.init("* 3 EXISTS\r\nA0001 OK [READ-ONLY] done\r\n" ++ "A0002 NO no such mailbox\r\n"); const m = try c.examine("Sent"); try testing.expect(m.read_only); try testing.expectEqualStrings("A0001 EXAMINE Sent\r\n", peer.sent()); try testing.expectError(error.CommandFailed, c.select("Nope")); try testing.expectEqual(@as(?Mailbox, null), c.mailbox); try testing.expectEqual(State.authenticated, c.state); } test "the mailbox tracks what the server says" { var peer: TestPeer = undefined; var c = peer.init("* 3 EXISTS\r\nA0001 OK done\r\n" ++ "* 4 EXISTS\r\n* 1 RECENT\r\nA0002 OK\r\n" ++ "* 2 EXPUNGE\r\n* 2 EXPUNGE\r\nA0003 OK\r\n"); _ = try c.select("INBOX"); try c.noop(); try testing.expectEqual(@as(u32, 4), c.mailbox.?.exists); try testing.expectEqual(@as(u32, 1), c.mailbox.?.recent); try c.expunge(); try testing.expectEqual(@as(u32, 2), c.mailbox.?.exists); } test "mailbox names are encoded" { var peer: TestPeer = undefined; var c = peer.init("A0001 OK\r\nA0002 OK\r\nA0003 OK\r\nA0004 OK\r\n"); try c.create("Entw\xc3\xbcrfe"); try c.create("Sent Items"); try c.create("Fish & Chips"); try c.rename("a", "b"); try testing.expectEqualStrings( "A0001 CREATE Entw&APw-rfe\r\n" ++ "A0002 CREATE \"Sent Items\"\r\n" ++ "A0003 CREATE \"Fish &- Chips\"\r\n" ++ "A0004 RENAME a b\r\n", peer.sent(), ); try testing.expectError(error.InvalidArgument, c.create("\xff")); // Once UTF-8 is enabled, names go as they are. var peer2: TestPeer = undefined; var c2 = peer2.init("* ENABLED UTF8=ACCEPT\r\nA0001 OK\r\n+ go\r\nA0002 OK\r\n"); try testing.expect(try c2.enable("UTF8=ACCEPT")); try testing.expect(c2.utf8); try c2.delete("Entw\xc3\xbcrfe"); try testing.expectEqualStrings( "A0001 ENABLE UTF8=ACCEPT\r\nA0002 DELETE {9}\r\nEntw\xc3\xbcrfe\r\n", peer2.sent(), ); } test "enable reports what was not enabled" { var peer: TestPeer = undefined; var c = peer.init("* ENABLED CONDSTORE\r\nA0001 OK\r\n"); try testing.expect(!try c.enable("CONDSTORE QRESYNC")); } test "list" { var peer: TestPeer = undefined; var c = peer.init("* LIST (\\HasNoChildren) \"/\" INBOX\r\n" ++ "* LIST (\\Noselect \\HasChildren) \"/\" Entw&APw-rfe\r\n" ++ "* LIST () \"/\" {9}\r\nodd\"name\"\r\n" ++ "* LIST () \"/\" \"Sent Items\"\r\n" ++ "A0001 OK done\r\n"); var mailboxes = try c.listAlloc(testing.allocator, "", "*", .{}); defer mailboxes.deinit(testing.allocator); try testing.expectEqualStrings("A0001 LIST \"\" *\r\n", peer.sent()); try testing.expectEqual(@as(usize, 4), mailboxes.entries.len); try testing.expectEqualStrings("INBOX", mailboxes.entries[0].name); try testing.expect(mailboxes.entries[0].hasAttribute("\\HasNoChildren")); try testing.expectEqual(@as(?u8, '/'), mailboxes.entries[0].delimiter); // Decoded from modified UTF-7. try testing.expectEqualStrings("Entw\xc3\xbcrfe", mailboxes.entries[1].name); try testing.expect(mailboxes.entries[1].hasAttribute("\\Noselect")); // A literal name, read from the wire. try testing.expectEqualStrings("odd\"name\"", mailboxes.entries[2].name); try testing.expectEqualStrings("Sent Items", mailboxes.entries[3].name); } test "list with options" { var peer: TestPeer = undefined; var c = peer.init("A0001 OK\r\n"); var cmd = try c.list("", "%", .{ .selection = "SUBSCRIBED", .@"return" = "CHILDREN" }); _ = try cmd.expectOk(); try testing.expectEqualStrings("A0001 LIST (SUBSCRIBED) \"\" % RETURN (CHILDREN)\r\n", peer.sent()); } test "status" { var peer: TestPeer = undefined; var c = peer.init("* STATUS blurdybloop (MESSAGES 231 UIDNEXT 44292)\r\nA0001 OK\r\n" ++ "* STATUS {5}\r\nhello (UNSEEN 3)\r\nA0002 OK\r\n"); const s = try c.status("blurdybloop", "MESSAGES UIDNEXT"); try testing.expectEqual(@as(?u32, 231), s.messages); try testing.expectEqual(@as(?u32, 44292), s.uidnext); try testing.expectEqualStrings("A0001 STATUS blurdybloop (MESSAGES UIDNEXT)\r\n", peer.sent()); // The name as a literal puts the list on the line after it. const lit = try c.status("hello", "UNSEEN"); try testing.expectEqual(@as(?u32, 3), lit.unseen); } test "an unconsumed literal is skipped" { var peer: TestPeer = undefined; var c = peer.init("* 1 FETCH (BODY[] {5}\r\nhello UID 7)\r\n* 2 FETCH (UID 8)\r\nA0001 OK\r\n"); var cmd = try c.fetch(.sequence, "1:2", "(BODY[] UID)"); const first = (try cmd.next()).?; try testing.expectEqual(@as(u32, 1), first.fetch.number); try testing.expectEqual(@as(?usize, 5), cmd.literalLen()); // Not read: `next` drops it and the rest of its line. const second = (try cmd.next()).?; try testing.expectEqual(@as(u32, 2), second.fetch.number); try testing.expectEqual(@as(?usize, null), cmd.literalLen()); try testing.expectEqual(@as(?Untagged, null), try cmd.next()); try testing.expect(cmd.status.?.isOk()); } test "fetchTo streams a literal" { var peer: TestPeer = undefined; var c = peer.init("* 1 FETCH (UID 7 BODY[] {22}\r\nSubject: hi\r\n\r\nhello\r\n FLAGS (\\Seen))\r\nA0001 OK\r\n"); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const n = try c.fetchTo(&out.writer, .uid, 7, "", .{}); try testing.expectEqual(@as(u64, 22), n); try testing.expectEqualStrings("Subject: hi\r\n\r\nhello\r\n", out.written()); try testing.expectEqualStrings("A0001 UID FETCH 7 (BODY.PEEK[])\r\n", peer.sent()); } test "fetchTo with a quoted body, a missing section, and no message" { var peer: TestPeer = undefined; var c = peer.init("* 3 FETCH (BODY[TEXT] \"short\")\r\nA0001 OK\r\n" ++ "* 3 FETCH (BODY[2] NIL)\r\nA0002 OK\r\n" ++ "A0003 OK nothing matched\r\n"); var buf: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try testing.expectEqual(@as(u64, 5), try c.fetchTo(&w, .sequence, 3, "TEXT", .{ .peek = false })); try testing.expectEqualStrings("short", w.buffered()); try testing.expectEqual(@as(u64, 0), try c.fetchTo(&w, .sequence, 3, "2", .{})); try testing.expectError(error.NoSuchMessage, c.fetchTo(&w, .uid, 99, "", .{})); try testing.expect(std.mem.startsWith(u8, peer.sent(), "A0001 FETCH 3 (BODY[TEXT])\r\n")); } test "fetchTo respects its limit and leaves the session usable" { var peer: TestPeer = undefined; var c = peer.init("* 1 FETCH (BODY[] {5}\r\nhello)\r\nA0001 OK\r\nA0002 OK\r\n"); var buf: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try testing.expectError(error.MessageTooLong, c.fetchTo(&w, .sequence, 1, "", .{ .limit = .limited(4) })); try c.noop(); } test "fetchAlloc collects literals into memory" { var peer: TestPeer = undefined; var c = peer.init("* 4 FETCH (FLAGS (\\Seen) UID 12 BODY[HEADER.FIELDS (SUBJECT)] {13}\r\nSubject: hi\r\n ENVELOPE (\"date\" {2}\r\nhi NIL NIL NIL NIL NIL NIL NIL NIL))\r\nA0001 OK\r\n"); var f = try c.fetchAlloc(testing.allocator, .uid, 12, "(FLAGS BODY.PEEK[HEADER.FIELDS (SUBJECT)] ENVELOPE)", .unlimited); defer f.deinit(testing.allocator); try testing.expectEqual(@as(u32, 4), f.number); var items = f.items(); const flags = (try items.next()).?; try testing.expect(parser.listContains(flags.value.list, "\\Seen")); const uid = (try items.next()).?; try testing.expectEqual(@as(?u64, 12), uid.value.number()); const header = (try items.next()).?; try testing.expect(header.isBodySection("HEADER.FIELDS (SUBJECT)")); try testing.expectEqualStrings("Subject: hi\r\n", header.value.string().?.raw); const envelope = (try items.next()).?; const e = try Envelope.parse(envelope.value.list); try testing.expectEqualStrings("hi", e.subject.?.raw); try testing.expectEqual(@as(?FetchItem, null), try items.next()); // Over the limit: discarded, and the session carries on. var peer2: TestPeer = undefined; var c2 = peer2.init("* 1 FETCH (BODY[] {5}\r\nhello)\r\nA0001 OK\r\nA0002 OK\r\n"); try testing.expectError( error.MessageTooLong, c2.fetchAlloc(testing.allocator, .sequence, 1, "(BODY[])", .limited(8)), ); try c2.noop(); } test "search" { var peer: TestPeer = undefined; var c = peer.init("* SEARCH 2 84 882\r\nA0001 OK\r\n" ++ "* ESEARCH (TAG \"A0002\") UID ALL 2,10:12\r\nA0002 OK\r\n" ++ "* SEARCH\r\nA0003 OK\r\n"); const found = try c.searchAlloc(testing.allocator, .sequence, "FLAGGED SINCE 1-Feb-1994"); defer testing.allocator.free(found); try testing.expectEqualSlices(u32, &.{ 2, 84, 882 }, found); const uids = try c.searchAlloc(testing.allocator, .uid, "ALL"); defer testing.allocator.free(uids); try testing.expectEqualSlices(u32, &.{ 2, 10, 11, 12 }, uids); const none = try c.searchAlloc(testing.allocator, .sequence, "UNSEEN"); defer testing.allocator.free(none); try testing.expectEqual(@as(usize, 0), none.len); try testing.expectEqualStrings( "A0001 SEARCH FLAGGED SINCE 1-Feb-1994\r\nA0002 UID SEARCH ALL\r\nA0003 SEARCH UNSEEN\r\n", peer.sent(), ); } test "store" { var peer: TestPeer = undefined; var c = peer.init("A0001 OK\r\n* 2 FETCH (FLAGS (\\Deleted \\Seen))\r\nA0002 OK\r\n"); try c.store(.uid, "12,14", .add, "\\Seen", .{}); try c.store(.sequence, "2", .set, "\\Deleted \\Seen", .{ .silent = false }); try testing.expectEqualStrings( "A0001 UID STORE 12,14 +FLAGS.SILENT (\\Seen)\r\nA0002 STORE 2 FLAGS (\\Deleted \\Seen)\r\n", peer.sent(), ); } test "copy and move" { var peer: TestPeer = undefined; var c = peer.init("A0001 OK [COPYUID 38505 304,319:320 3956:3958] done\r\n" ++ "* OK [COPYUID 38505 12 100]\r\n* 3 EXPUNGE\r\nA0002 OK moved\r\n" ++ "A0003 OK copied\r\n"); const copied = (try c.copy(.uid, "304,319:320", "Archive")).?; try testing.expectEqualStrings("3956:3958", copied.uids); const moved = (try c.move(.sequence, "3", "Trash")).?; try testing.expectEqualStrings("100", moved.uids); try testing.expectEqual(@as(?UidResult, null), try c.copy(.sequence, "1", "Old")); try testing.expectEqualStrings( "A0001 UID COPY 304,319:320 Archive\r\nA0002 MOVE 3 Trash\r\nA0003 COPY 1 Old\r\n", peer.sent(), ); } test "append" { var peer: TestPeer = undefined; var c = peer.init("+ Ready for literal data\r\nA0001 OK [APPENDUID 38505 3955] done\r\n"); const message = "Subject: hi\r\n\r\nhello\r\n"; const r = (try c.append("Saved", .{ .flags = "\\Seen", .date = "17-Jul-1996 02:44:25 -0700" }, message)).?; try testing.expectEqual(@as(u32, 38505), r.uidvalidity); try testing.expectEqualStrings("3955", r.uids); try testing.expectEqualStrings( "A0001 APPEND Saved (\\Seen) \"17-Jul-1996 02:44:25 -0700\" {22}\r\n" ++ message ++ "\r\n", peer.sent(), ); // From a reader, with LITERAL+. var peer2: TestPeer = undefined; var c2 = peer2.init("A0001 OK\r\n"); c2.capabilities.literal_plus = true; var source: std.Io.Reader = .fixed(message); try testing.expectEqual(@as(?UidResult, null), try c2.appendFrom("Saved", .{}, &source, message.len)); try testing.expectEqualStrings("A0001 APPEND Saved {22+}\r\n" ++ message ++ "\r\n", peer2.sent()); // A reader that runs short. var peer3: TestPeer = undefined; var c3 = peer3.init(""); c3.capabilities.literal_plus = true; var short: std.Io.Reader = .fixed("abc"); try testing.expectError(error.MessageTruncated, c3.appendFrom("Saved", .{}, &short, 10)); } test "idle" { var peer: TestPeer = undefined; var c = peer.init("+ idling\r\n* 5 EXISTS\r\n* 1 RECENT\r\nA0001 OK Idle completed\r\n"); c.capabilities = Capabilities.parse("IMAP4rev1 IDLE"); c.mailbox = .{}; var idling = try c.idle(); try testing.expectEqual(@as(u32, 5), (try idling.next()).exists); try testing.expectEqual(@as(u32, 1), (try idling.next()).recent); try idling.done(); try testing.expectEqualStrings("A0001 IDLE\r\nDONE\r\n", peer.sent()); try testing.expectEqual(@as(u32, 5), c.mailbox.?.exists); var peer2: TestPeer = undefined; var c2 = peer2.init(""); c2.capabilities = Capabilities.parse("IMAP4rev1"); try testing.expectError(error.BadCommand, c2.idle()); } test "close, unselect, logout" { var peer: TestPeer = undefined; var c = peer.init("* 1 EXISTS\r\nA0001 OK\r\nA0002 OK\r\n* 1 EXISTS\r\nA0003 OK\r\nA0004 OK\r\n" ++ "* BYE Logging out\r\nA0005 OK Logout completed\r\n"); _ = try c.select("INBOX"); try c.close(); try testing.expectEqual(@as(?Mailbox, null), c.mailbox); try testing.expectEqual(State.authenticated, c.state); _ = try c.select("INBOX"); try c.unselect(); try testing.expectEqual(@as(?Mailbox, null), c.mailbox); try c.logout(); try testing.expect(c.bye); try testing.expectEqual(State.logout, c.state); } test "id" { var peer: TestPeer = undefined; var c = peer.init("* ID (\"name\" \"Dovecot\")\r\nA0001 OK\r\nA0002 OK\r\n"); var cmd = try c.id(&.{ .{ "name", "zig-imap" }, .{ "version", "0.0.0" } }); try testing.expectEqualStrings("(\"name\" \"Dovecot\")", (try cmd.next()).?.id); _ = try cmd.expectOk(); var nil = try c.id(&.{}); _ = try nil.expectOk(); try testing.expectEqualStrings( "A0001 ID (\"name\" \"zig-imap\" \"version\" \"0.0.0\")\r\nA0002 ID NIL\r\n", peer.sent(), ); } test "command injection is rejected" { var peer: TestPeer = undefined; var c = peer.init(""); try testing.expectError(error.InvalidArgument, c.run("SELECT {s}", .{"INBOX\r\nDELETE INBOX"})); try testing.expectError(error.InvalidArgument, c.store(.uid, "1\r\nEXPUNGE", .add, "\\Seen", .{})); try testing.expectError(error.InvalidArgument, c.searchAlloc(testing.allocator, .uid, "ALL\r\n")); try testing.expectError(error.InvalidArgument, c.create("a\rb")); try testing.expectError(error.InvalidArgument, c.status("INBOX", "MESSAGES\r\n")); try testing.expectError(error.InvalidArgument, c.rename("ok", "\xff")); try testing.expectError(error.InvalidArgument, c.copy(.uid, "1", "a\nb")); try testing.expectError(error.InvalidArgument, c.list("", "*\r\n", .{})); try testing.expectError(error.InvalidArgument, c.append("x\n", .{}, "m")); // A password with a CRLF is sent as a literal, which cannot break out. try testing.expectEqualStrings("", peer.sent()); } test "the escape hatch" { var peer: TestPeer = undefined; var c = peer.init("* QUOTAROOT INBOX \"\"\r\n* QUOTA \"\" (STORAGE 10 512)\r\nA0001 OK\r\n"); var cmd = try c.send("GETQUOTAROOT {s}", .{"INBOX"}); const root = (try cmd.next()).?.other; try testing.expectEqualStrings("QUOTAROOT", root.name); const quota = (try cmd.next()).?.other; try testing.expectEqualStrings("\"\" (STORAGE 10 512)", quota.rest); _ = try cmd.expectOk(); } test "a response that ends early" { var peer: TestPeer = undefined; var c = peer.init("* 1 FETCH (BODY[] {100}\r\nnot enough"); var cmd = try c.fetch(.sequence, "1", "BODY[]"); _ = try cmd.next(); try testing.expectError(error.EndOfStream, cmd.next()); } test "an unexpected continuation" { var peer: TestPeer = undefined; var c = peer.init("+ what\r\n"); try testing.expectError(error.InvalidResponse, c.noop()); } test "setTransport" { var peer: TestPeer = undefined; var c = peer.initSecurity("A0001 OK begin TLS\r\n", .plaintext); try c.starttls(); var tls_reader: std.Io.Reader = .fixed("A0002 OK\r\n"); var tls_write_buf: [128]u8 = undefined; var tls_writer: std.Io.Writer = .fixed(&tls_write_buf); c.setTransport(&tls_reader, &tls_writer, .encrypted); try c.login("alice", "s3cret"); try testing.expectEqualStrings("A0002 LOGIN \"alice\" \"s3cret\"\r\n", tls_writer.buffered()); } test "a whole session" { var peer: TestPeer = undefined; var c = peer.init("* OK [CAPABILITY IMAP4rev2 AUTH=PLAIN SASL-IR UIDPLUS] ready\r\n" ++ "A0001 OK [CAPABILITY IMAP4rev2 UIDPLUS IDLE] authenticated\r\n" ++ "* 2 EXISTS\r\n* FLAGS (\\Seen)\r\n* OK [UIDVALIDITY 1] ok\r\nA0002 OK [READ-WRITE] selected\r\n" ++ "* SEARCH 1 2\r\nA0003 OK\r\n" ++ "* 1 FETCH (UID 10 BODY[] {14}\r\nSubject: a\r\n\r\n)\r\nA0004 OK\r\n" ++ "A0005 OK\r\n" ++ "* 1 EXPUNGE\r\nA0006 OK\r\n" ++ "* BYE\r\nA0007 OK\r\n"); _ = try c.readGreeting(); try testing.expectEqual(Mechanism.plain, try c.authenticate("alice", "s3cret")); const m = try c.select("INBOX"); try testing.expectEqual(@as(u32, 2), m.exists); const unseen = try c.searchAlloc(testing.allocator, .uid, "UNSEEN"); defer testing.allocator.free(unseen); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); _ = try c.fetchTo(&out.writer, .uid, unseen[0], "", .{}); try testing.expectEqualStrings("Subject: a\r\n\r\n", out.written()); try c.store(.uid, "10", .add, "\\Deleted", .{}); try c.expunge(); try testing.expectEqual(@as(u32, 1), c.mailbox.?.exists); try c.logout(); }