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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The client against a server, over a loopback socket.//!//! The unit tests in `src/Client.zig` drive the protocol against a fixed//! buffer, which covers what the RFCs say and nothing about the transport.//! These cover `Connection`: a socket that really has to be connected, read//! buffers that really have to be flushed in the right order, and a peer that//! answers only once it has seen a whole command line — or, for a literal,//! only once it has been told how long the literal is and said `+`. A client//! that forgets to flush passes every test in the first set and hangs in this//! one.//!//! The server here is a toy — two messages, one password, no state worth the//! name — written to be the other end of a conversation rather than an IMAP//! implementation. Anything about how a *real* server behaves belongs in a//! test against a real one.//!//! Each test runs the server in a task of its own, because the accept and the//! connect block on each other: whichever runs first waits for the other.
const std = @import("std");const Io = std.Io;const net = Io.net;const testing = std.testing;
const imap = @import("imap");
const messages = [_][]const u8{ "From: alice@example.com\r\n" ++ "Subject: first\r\n" ++ "\r\n" ++ "hello\r\n" ++ // A line beginning with a dot, which IMAP does not stuff and a // client that came from POP3 might expect to. ".signature\r\n", "From: bob@example.com\r\n" ++ "Subject: second\r\n" ++ "\r\n" ++ "goodbye\r\n",};
const uids = [_]u32{ 101, 102 };
/// A server on a loopback port with a client connected to it.////// Must not be moved once `start` has returned: the connection holds/// pointers into itself, and the server task holds one into this.const Fixture = struct { listener: net.Server, tasks: Io.Group, connection: *imap.Connection, client: imap.Client,
const gpa = testing.allocator;
fn start(f: *Fixture) !void { const io = testing.io; var address: net.IpAddress = .{ .ip4 = .loopback(0) }; f.listener = try net.IpAddress.listen(&address, io, .{ .reuse_address = true }); errdefer f.listener.deinit(io);
f.tasks = .init; // `concurrent` rather than `async`: the accept and the connect below // must both be able to make progress, and `async` may run its task // to completion first. f.tasks.concurrent(io, serve, .{ io, &f.listener }) catch return error.SkipZigTest; errdefer f.tasks.await(io) catch {};
// A listener bound to port 0 reports the port the kernel picked in // its own address, which is how this avoids choosing one that // something else may already have. const port = switch (f.listener.socket.address) { .ip4 => |ip4| ip4.port, .ip6 => |ip6| ip6.port, }; f.connection = try imap.Connection.connect(gpa, io, "127.0.0.1", .{ .port = port, .tls = .off, }); errdefer f.connection.destroy(); f.client = f.connection.client(); // The transport really is in the clear, so LOGIN has to be allowed // explicitly -- which is the whole point of the default. f.client.allow_cleartext_auth = true; }
fn stop(f: *Fixture) void { const io = testing.io; f.connection.destroy(); f.tasks.await(io) catch {}; f.listener.deinit(io); }};
/// Accepts one connection and serves it until it goes away.fn serve(io: Io, listener: *net.Server) void { const stream = listener.accept(io) catch return; defer stream.close(io); var read_buffer: [4096]u8 = undefined; var write_buffer: [4096]u8 = undefined; var stream_reader = stream.reader(io, &read_buffer); var stream_writer = stream.writer(io, &write_buffer); session(&stream_reader.interface, &stream_writer.interface) catch {};}
const Session = struct { input: *Io.Reader, output: *Io.Writer, deleted: [messages.len]bool = @splat(false), seen: [messages.len]bool = @splat(false), authenticated: bool = false, selected: bool = false, appended: usize = 0,
fn reply(s: *Session, comptime fmt: []const u8, args: anytype) !void { try s.output.print(fmt ++ "\r\n", args); try s.output.flush(); }
fn line(s: *Session) ![]const u8 { const raw = try s.input.takeDelimiterInclusive('\n'); var l = raw[0 .. raw.len - 1]; if (l.len > 0 and l[l.len - 1] == '\r') l = l[0 .. l.len - 1]; return l; }
/// The count of messages not expunged. fn exists(s: *const Session) u32 { var n: u32 = 0; for (s.deleted) |d| n += @intFromBool(!d); return n + @as(u32, @intCast(s.appended)); }};
fn session(input: *Io.Reader, output: *Io.Writer) !void { var s: Session = .{ .input = input, .output = output }; try s.reply("* OK [CAPABILITY IMAP4rev2 AUTH=PLAIN SASL-IR UIDPLUS IDLE MOVE] zig-imap test server", .{});
while (true) { const l = s.line() catch return; var it = std.mem.tokenizeScalar(u8, l, ' '); // Copied out of the read buffer, which a command that reads more -- // a literal, IDLE's DONE -- overwrites before the reply is written. var tag_buf: [32]u8 = undefined; const tag_text = it.next() orelse continue; if (tag_text.len > tag_buf.len) continue; @memcpy(tag_buf[0..tag_text.len], tag_text); const tag = tag_buf[0..tag_text.len]; const verb = it.next() orelse { try s.reply("{s} BAD empty command", .{tag}); continue; }; const rest = std.mem.trimStart(u8, it.rest(), " ");
if (eql(verb, "LOGOUT")) { try s.reply("* BYE signing off\r\n{s} OK LOGOUT completed", .{tag}); return; } else if (eql(verb, "CAPABILITY")) { try s.reply("* CAPABILITY IMAP4rev2 AUTH=PLAIN SASL-IR UIDPLUS IDLE MOVE\r\n{s} OK", .{tag}); } else if (eql(verb, "NOOP")) { try s.reply("{s} OK", .{tag}); } else if (eql(verb, "LOGIN")) { if (std.mem.eql(u8, rest, "\"alice\" \"s3cret\"")) { s.authenticated = true; try s.reply("{s} OK [CAPABILITY IMAP4rev2 UIDPLUS IDLE MOVE] logged in", .{tag}); } else { try s.reply("{s} NO [AUTHENTICATIONFAILED] bad credentials", .{tag}); } } else if (eql(verb, "AUTHENTICATE")) { // PLAIN with an initial response, the only shape offered. if (std.mem.eql(u8, rest, "PLAIN AGFsaWNlAHMzY3JldA==")) { s.authenticated = true; try s.reply("{s} OK [CAPABILITY IMAP4rev2 UIDPLUS IDLE MOVE] authenticated", .{tag}); } else { try s.reply("{s} NO [AUTHENTICATIONFAILED] bad credentials", .{tag}); } } else if (!s.authenticated) { try s.reply("{s} BAD not authenticated", .{tag}); } else if (eql(verb, "LIST")) { try s.reply("* LIST (\\HasNoChildren) \"/\" INBOX\r\n" ++ "* LIST (\\HasNoChildren) \"/\" Entw&APw-rfe\r\n{s} OK", .{tag}); } else if (eql(verb, "SELECT") or eql(verb, "EXAMINE")) { if (!std.mem.eql(u8, rest, "INBOX")) { try s.reply("{s} NO no such mailbox", .{tag}); continue; } s.selected = true; try s.reply("* {d} EXISTS\r\n* FLAGS (\\Seen \\Deleted)\r\n" ++ "* OK [UIDVALIDITY 42] ok\r\n* OK [UIDNEXT 103] ok\r\n" ++ "{s} OK [{s}] done", .{ s.exists(), tag, if (eql(verb, "SELECT")) "READ-WRITE" else "READ-ONLY" }); } else if (!s.selected) { try s.reply("{s} BAD no mailbox selected", .{tag}); } else if (eql(verb, "UID")) { try uidCommand(&s, tag, rest); } else if (eql(verb, "SEARCH")) { try s.output.writeAll("* SEARCH"); for (s.deleted, 0..) |d, i| if (!d) try s.output.print(" {d}", .{i + 1}); try s.reply("\r\n{s} OK", .{tag}); } else if (eql(verb, "EXPUNGE")) { // Highest first, so that each number is still right when sent. var i: usize = messages.len; while (i > 0) { i -= 1; if (s.deleted[i]) try s.output.print("* {d} EXPUNGE\r\n", .{i + 1}); } try s.reply("{s} OK", .{tag}); } else if (eql(verb, "APPEND")) { // `APPEND INBOX {n}`: agree, take the octets, then the CRLF that // ends the command. const open = std.mem.findScalar(u8, rest, '{') orelse { try s.reply("{s} BAD", .{tag}); continue; }; const n = try std.fmt.parseUnsigned(usize, rest[open + 1 .. rest.len - 1], 10); try s.reply("+ go ahead", .{}); var got: usize = 0; while (got < n) { const chunk = try s.input.peekGreedy(1); const take = @min(chunk.len, n - got); got += take; s.input.toss(take); } _ = try s.line(); s.appended += 1; try s.reply("* {d} EXISTS\r\n{s} OK [APPENDUID 42 {d}] appended", .{ s.exists(), tag, 200 + s.appended }); } else if (eql(verb, "IDLE")) { try s.reply("+ idling", .{}); // Something happens, then the client says DONE. try s.reply("* 1 RECENT", .{}); const done = try s.line(); if (!eql(done, "DONE")) return; try s.reply("{s} OK idle finished", .{tag}); } else if (eql(verb, "CLOSE")) { s.selected = false; try s.reply("{s} OK", .{tag}); } else { try s.reply("{s} BAD unknown command", .{tag}); } }}
fn uidCommand(s: *Session, tag: []const u8, rest: []const u8) !void { var it = std.mem.tokenizeScalar(u8, rest, ' '); const verb = it.next() orelse return s.reply("{s} BAD", .{tag}); const set = it.next() orelse return s.reply("{s} BAD", .{tag}); const args = std.mem.trimStart(u8, it.rest(), " "); if (eql(verb, "FETCH")) { for (uids, 0..) |uid, i| { if (s.deleted[i] or !inSet(set, uid)) continue; if (std.mem.indexOf(u8, args, "BODY.PEEK[]") != null or std.mem.indexOf(u8, args, "BODY[]") != null) { if (std.mem.indexOf(u8, args, "BODY[]") != null) s.seen[i] = true; try s.output.print("* {d} FETCH (UID {d} BODY[] {{{d}}}\r\n", .{ i + 1, uid, messages[i].len }); try s.output.writeAll(messages[i]); try s.output.writeAll(")\r\n"); } else if (std.mem.indexOf(u8, args, "BODY.PEEK[HEADER]") != null) { const header_end = std.mem.indexOf(u8, messages[i], "\r\n\r\n").? + 4; try s.output.print("* {d} FETCH (UID {d} BODY[HEADER] {{{d}}}\r\n{s})\r\n", .{ i + 1, uid, header_end, messages[i][0..header_end], }); } else { try s.output.print("* {d} FETCH (UID {d} FLAGS ({s}) RFC822.SIZE {d})\r\n", .{ i + 1, uid, if (s.seen[i]) "\\Seen" else "", messages[i].len, }); } } try s.reply("{s} OK fetch done", .{tag}); } else if (eql(verb, "STORE")) { for (uids, 0..) |uid, i| { if (!inSet(set, uid)) continue; if (std.mem.indexOf(u8, args, "\\Deleted") != null) s.deleted[i] = std.mem.startsWith(u8, args, "+"); if (std.mem.indexOf(u8, args, "\\Seen") != null) s.seen[i] = std.mem.startsWith(u8, args, "+"); } try s.reply("{s} OK store done", .{tag}); } else if (eql(verb, "SEARCH")) { try s.output.writeAll("* SEARCH"); for (uids, 0..) |uid, i| if (!s.deleted[i]) try s.output.print(" {d}", .{uid}); try s.reply("\r\n{s} OK", .{tag}); } else if (eql(verb, "COPY")) { try s.reply("{s} OK [COPYUID 42 {s} 300] copied", .{ tag, set }); } else { try s.reply("{s} BAD", .{tag}); }}
fn inSet(set: []const u8, uid: u32) bool { var numbers: imap.SequenceIterator = .init(set); while (numbers.next() catch return false) |n| if (n == uid) return true; return std.mem.eql(u8, set, "1:*");}
fn eql(a: []const u8, b: []const u8) bool { return std.ascii.eqlIgnoreCase(a, b);}
test "a session over a socket" { var f: Fixture = undefined; try f.start(); defer f.stop(); const client = &f.client;
const greeting = try client.readGreeting(); try testing.expectEqual(.ok, greeting.status); try testing.expect(client.capabilities.uidplus);
const mechanism = try client.authenticate("alice", "s3cret"); try testing.expectEqual(imap.Client.Mechanism.plain, mechanism); // The capabilities after login are the ones on its tagged OK. try testing.expect(!client.capabilities.auth.any());
var mailboxes = try client.listAlloc(Fixture.gpa, "", "*", .{}); defer mailboxes.deinit(Fixture.gpa); try testing.expectEqual(@as(usize, 2), mailboxes.entries.len); try testing.expectEqualStrings("Entw\xc3\xbcrfe", mailboxes.entries[1].name);
const mailbox = try client.select("INBOX"); try testing.expectEqual(@as(u32, 2), mailbox.exists); try testing.expectEqual(@as(?u32, 42), mailbox.uidvalidity); try testing.expect(!mailbox.read_only);
const found = try client.searchAlloc(Fixture.gpa, .uid, "ALL"); defer Fixture.gpa.free(found); try testing.expectEqualSlices(u32, &uids, found);
// The message comes back byte-for-byte: no stuffing in IMAP. var out: Io.Writer.Allocating = .init(Fixture.gpa); defer out.deinit(); const n = try client.fetchTo(&out.writer, .uid, uids[0], "", .{}); try testing.expectEqual(messages[0].len, n); try testing.expectEqualStrings(messages[0], out.written());
// Headers alone, and a summary collected into memory. out.clearRetainingCapacity(); _ = try client.fetchTo(&out.writer, .uid, uids[1], "HEADER", .{}); try testing.expectEqualStrings("From: bob@example.com\r\nSubject: second\r\n\r\n", out.written()); var summary = try client.fetchAlloc(Fixture.gpa, .uid, uids[1], "(FLAGS RFC822.SIZE)", .unlimited); defer summary.deinit(Fixture.gpa); var items = summary.items(); _ = (try items.next()).?; // UID const flags = (try items.next()).?; try testing.expectEqualStrings("()", flags.value.list); const size = (try items.next()).?; try testing.expectEqual(@as(?u64, messages[1].len), size.value.number());
// A store, then an expunge that the mailbox state reflects. try client.store(.uid, "101", .add, "\\Deleted", .{}); try client.expunge(); try testing.expectEqual(@as(u32, 1), client.mailbox.?.exists);
try client.logout(); try testing.expect(client.bye);}
test "appending a message waits for the go ahead" { var f: Fixture = undefined; try f.start(); defer f.stop(); const client = &f.client;
_ = try client.readGreeting(); try client.login("alice", "s3cret"); _ = try client.select("INBOX");
// No LITERAL+ here, so the octets go only after the server's `+`; a // client that sent them early would have them read as a command. const r = (try client.append("INBOX", .{ .flags = "\\Seen" }, messages[1])).?; try testing.expectEqual(@as(u32, 42), r.uidvalidity); try testing.expectEqualStrings("201", r.uids); try testing.expectEqual(@as(u32, 3), client.mailbox.?.exists);
try client.logout();}
test "idle" { var f: Fixture = undefined; try f.start(); defer f.stop(); const client = &f.client;
_ = try client.readGreeting(); try client.login("alice", "s3cret"); _ = try client.select("INBOX");
var idling = try client.idle(); const event = try idling.next(); try testing.expectEqual(@as(u32, 1), event.recent); try idling.done(); try testing.expectEqual(@as(u32, 1), client.mailbox.?.recent);
try client.logout();}
test "the connection reports a plaintext transport" { var f: Fixture = undefined; try f.start(); defer f.stop();
try testing.expectEqual(imap.Client.Security.plaintext, f.connection.security()); // A fresh client over this connection refuses to send the password, // because nothing about the socket protects it. var strict = f.connection.client(); _ = try strict.readGreeting(); try testing.expectError(error.InsecureTransport, strict.login("alice", "s3cret")); try testing.expectError(error.InsecureTransport, strict.authenticate("alice", "s3cret")); try strict.logout();}
test "a message too long for the limit leaves the session usable" { var f: Fixture = undefined; try f.start(); defer f.stop(); const client = &f.client;
_ = try client.readGreeting(); try client.login("alice", "s3cret"); _ = try client.select("INBOX");
var buf: [8]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError( error.MessageTooLong, client.fetchTo(&w, .uid, uids[0], "", .{ .limit = .limited(8) }), ); // The rest of the literal was drained rather than left on the socket, // so the next command's response is its own. try client.noop(); const copied = (try client.copy(.uid, "102", "Archive")).?; try testing.expectEqualStrings("300", copied.uids);
try client.logout();}