# zig-imap An IMAP client library for Zig. Requires Zig 0.17.0; the `zig-0.16` branch and the `v0.1.0` tag build with Zig 0.16.0. **[API documentation](https://jeff.jcollie.page/zig-imap/)** — generated from the doc comments in the source, and published from `main` on every push. ## Supported standards | Standard | Title | Support in zig-imap | | --- | --- | --- | | [RFC 9051](https://datatracker.ietf.org/doc/html/rfc9051) | IMAP4rev2 | The session: greeting, CAPABILITY, NOOP, LOGOUT; LOGIN and AUTHENTICATE; ENABLE, SELECT, EXAMINE, CREATE, DELETE, RENAME, SUBSCRIBE, UNSUBSCRIBE, LIST, STATUS, APPEND, IDLE; CLOSE, UNSELECT, EXPUNGE, SEARCH, FETCH, STORE, COPY, MOVE, and the UID forms | | [RFC 3501](https://datatracker.ietf.org/doc/html/rfc3501) | IMAP4rev1 | The same commands against a rev1 server, LSUB responses, and mailbox names in modified UTF-7, encoded on the way out and decoded on the way back | | [RFC 4959](https://datatracker.ietf.org/doc/html/rfc4959) | SASL-IR | The initial response on the AUTHENTICATE line when the server allows it, and as the answer to an empty first challenge when it does not | | [RFC 7888](https://datatracker.ietf.org/doc/html/rfc7888) | LITERAL+ and LITERAL- | Non-synchronizing literals where advertised; otherwise the wait for `+` in the middle of a command | | [RFC 4315](https://datatracker.ietf.org/doc/html/rfc4315) | UIDPLUS | UID EXPUNGE, and the APPENDUID and COPYUID codes as a typed result | | [RFC 6851](https://datatracker.ietf.org/doc/html/rfc6851) | MOVE | MOVE and UID MOVE | | [RFC 2177](https://datatracker.ietf.org/doc/html/rfc2177) | IDLE | IDLE, with each untagged response handed back as it arrives | | [RFC 5161](https://datatracker.ietf.org/doc/html/rfc5161), [RFC 6855](https://datatracker.ietf.org/doc/html/rfc6855) | ENABLE, UTF8=ACCEPT | ENABLE, after which mailbox names go out as UTF-8 | | [RFC 4731](https://datatracker.ietf.org/doc/html/rfc4731) | ESEARCH | Both the SEARCH and the ESEARCH forms of a search result | | [RFC 2971](https://datatracker.ietf.org/doc/html/rfc2971) | ID | ID | | [RFC 8314](https://datatracker.ietf.org/doc/html/rfc8314) | Cleartext Considered Obsolete | Implicit TLS (IMAPS on port 993) with system-root certificate verification, which the RFC prefers over STARTTLS; STARTTLS for servers that only offer that | | [RFC 2195](https://datatracker.ietf.org/doc/html/rfc2195) | IMAP/POP AUTHorize Extension | CRAM-MD5 (from zig-sasl), the one mechanism here that keeps the password off the wire | ## Design - **`imap.Client`** implements the protocol over any `std.Io.Reader`/`std.Io.Writer` pair. Transport is the caller's business — plain TCP, TLS, a proxy, or fixed buffers in tests. - **`imap.Connection`** is the batteries-included transport: TCP or TLS (IMAPS on port 993) with system-root certificate verification, built on `std.Io`, and `startTls` for servers that only offer STARTTLS. - **A command is an iterator.** Every IMAP command is answered by untagged responses and then one tagged status line, so `send` returns a `Command` whose `next` yields the untagged responses and whose `finish` reads to the tagged one. The typed wrappers — `select`, `fetchTo`, `searchAlloc` — are built on that. Whoever is iterating, what passes is applied to the session: `client.mailbox` has the current message count, `capabilities` the current capability list. - **Zero-copy reads, and literals streamed.** Each line borrows the reader's buffer and is invalidated by the next read; copy what you keep, or use the `*Alloc` variants. A message body arrives as a *literal*, which is not in that buffer at all: `fetchTo` streams it to a writer without holding it, and a `Command` with a literal pending lets you stream, allocate, or skip it. A body never has to fit in memory; a line does. - **The SASL mechanisms are not here.** PLAIN, LOGIN, CRAM-MD5, EXTERNAL, XOAUTH2, OAUTHBEARER and SCRAM come from [zig-sasl](https://git.jcollie.dev/jeff/zig-sasl), re-exported as `imap.sasl`, because nothing about them is specific to IMAP — the SMTP and POP3 clients want the same ones, and one implementation of each beats three. What is here is the IMAP half: `AUTHENTICATE`, the `+ ` challenges, the `*` that cancels, and SASL-IR. `authenticateSasl` drives any mechanism; `authenticate` weighs them against LOGIN, which is IMAP's own and not SASL at all. - **It will not hand your password to the network.** A client over a transport it was told is `.plaintext` refuses LOGIN and any mechanism that would put a reusable credential on the wire, with `error.InsecureTransport`; CRAM-MD5, which sends a digest rather than the secret, is allowed. The mechanism decides which it is, so the rule needs no list of names. A server that says `LOGINDISABLED` is believed too. Set `client.allow_cleartext_auth = true` if the connection is protected by something the library cannot see — a VPN, an SSH tunnel — or if you are talking to a server on a network you trust. - **Mailbox names are UTF-8 at the API** and whatever the session needs on the wire: modified UTF-7 against a rev1 server, UTF-8 once `UTF8=ACCEPT` is enabled, quoted or as a literal as the characters require. Names coming back are decoded the same way, so "Entwürfe" is "Entwürfe" at both ends. - Every argument is checked for the CRLF that would smuggle a second command onto the wire, and checked *before* anything is written, so a rejected command leaves nothing in the buffer for the next one to carry. ## Usage ```zig const std = @import("std"); const imap = @import("imap"); pub fn main() !void { var gpa_state: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); var threaded: std.Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io(); // IMAPS on port 993, verified against the system's root certificates. const conn = try imap.Connection.connect(gpa, io, "mail.example.com", .{ .tls = .on, }); defer conn.destroy(); var client = conn.client(); const greeting = try client.readGreeting(); std.debug.print("{s}\n", .{greeting.text}); // The greeting usually carries the capabilities; if not, ask. if (!client.capabilities.known) _ = try client.capability(); _ = try client.authenticate("alice", "s3cret"); const mailbox = try client.select("INBOX"); std.debug.print("{d} messages, UIDVALIDITY {?d}\n", .{ mailbox.exists, mailbox.uidvalidity }); // UIDs survive the session (while UIDVALIDITY does), so they are what to // remember about a message you have already seen. const unseen = try client.searchAlloc(gpa, .uid, "UNSEEN"); defer gpa.free(unseen); for (unseen) |uid| { // A summary into memory: the flags, the size, the envelope. var summary = try client.fetchAlloc(gpa, .uid, uid, "(FLAGS RFC822.SIZE ENVELOPE)", .limited(64 << 10)); defer summary.deinit(gpa); var items = summary.items(); while (try items.next()) |item| { if (item.is("ENVELOPE")) { const envelope = try imap.Envelope.parse(item.value.list); if (envelope.subject) |subject| std.debug.print("{d}: {s}\n", .{ uid, subject.raw }); } } } try client.logout(); } ``` ### Messages too large to hold `fetchTo` copies a body section straight to a writer — a file, a pipe, a parser — without it ever being in memory all at once: ```zig var file = try std.Io.Dir.cwd().createFile(io, "message.eml", .{}); defer file.close(io); var buffer: [64 * 1024]u8 = undefined; var file_writer = file.writer(io, &buffer); // "" is the whole message; "HEADER", "TEXT", or "1.2" for a MIME part. _ = try client.fetchTo(&file_writer.interface, .uid, uid, "", .{}); try file_writer.interface.flush(); ``` It uses `BODY.PEEK` unless told otherwise, so reading a message does not mark it seen. `appendFrom` is the same idea in the other direction. ### Flags, copies, and deletion ```zig try client.store(.uid, "12,14", .add, "\\Seen", .{}); const copied = try client.copy(.uid, "12", "Archive"); // COPYUID, on UIDPLUS servers try client.store(.uid, "12", .add, "\\Deleted", .{}); try client.expunge(); // or, on a server with MOVE: _ = try client.move(.uid, "14", "Trash"); ``` ### Waiting for mail ```zig var idling = try client.idle(); const event = try idling.next(); // blocks until the server says something switch (event) { .exists => |n| std.debug.print("now {d} messages\n", .{n}), else => {}, } try idling.done(); ``` ### Upgrading a plaintext session ```zig const conn = try imap.Connection.connect(gpa, io, host, .{ .tls = .off }); defer conn.destroy(); var client = conn.client(); _ = try client.readGreeting(); if (client.capabilities.starttls) { try conn.startTls(&client, .{ .host = host }); // Everything the server said before the handshake could have been // written by an attacker, so it is forgotten and asked again. _ = try client.capability(); } ``` ### Commands with no wrapper Anything this library does not wrap goes through `send`, which returns the same iterator everything else is built on: ```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(); ``` ### Telling one failure from another ```zig _ = client.authenticate(user, password) catch |err| switch (err) { // The server said LOGINDISABLED: upgrade with STARTTLS first. error.LoginDisabled => return upgradeFirst(), // Nothing on offer is safe on this transport. error.InsecureTransport => return upgradeFirst(), error.AuthenticationFailed => return askForNewPassword(), else => |e| return e, }; ``` `client.last_status` holds the server's own wording and response code for any NO or BAD, until the next command overwrites it. ## Demo CLI ```console $ zig build run -- mail.example.com --user alice --search UNSEEN --headers 4711 ``` Prints the greeting, the capabilities, the mailboxes, the selected mailbox's state, a summary of every message matching `--search`, and whatever `--headers` or `--fetch` ask for. The password comes from `IMAP_PASSWORD` rather than the command line, so it stays out of the shell history and out of `ps`. `--starttls` starts in the clear on port 143 and upgrades; `--no-tls` stays there, and sending a password over that takes `--allow-cleartext` as well. ## Testing ```console $ zig build test ``` Three layers, none of which needs the network: - the protocol against fixed buffers, one test per command, in `src/Client.zig`, with the scanner, the response parsers and modified UTF-7 tested beside their code; - `tests/e2e.zig`, which drives `Connection` over a loopback socket against a toy server — the only way to cover the socket, the buffering, the flushes, and a literal that is not sent until the server says `+`; - `tests/fuzz.zig`, which states the parsers' properties rather than their examples: every borrowed slice points into its input, a response ends, a status line survives being written back out and read again, and a mailbox name survives modified UTF-7 in both directions. And a fourth that does, against a server nobody here wrote: ```console $ nix build .#checks.x86_64-linux.dovecot -L ``` Two NixOS guests — Dovecot on one, `tests/integration.zig` on the other — because the interesting behaviour only exists between machines: Dovecot refuses a cleartext password from anywhere but localhost, so the client sees `LOGINDISABLED`, upgrades the same connection with STARTTLS, and then connects again over implicit TLS on 993 with the certificate verified against a root the guest was given. It asserts the things only a real server can settle — that the octet count RFC822.SIZE promised is the octet count BODY[] delivers, that a message appended comes back byte for byte, that a mailbox created under a non-ASCII name is listed under that name, that BODY.PEEK leaves a message unseen, and that STORE marks while EXPUNGE is what removes — as well as what Dovecot *does not* offer, such as AUTH=PLAIN before TLS, since a check that stops being true is the one worth having. Those properties are also fuzz targets, run either by Zig's own coverage-guided fuzzer or by a standalone loop that mutates their seeds: ```console $ zig build test --fuzz # until interrupted, with a web interface $ zig build test --fuzz=1M # a bounded run, then a report $ zig build fuzz -- --seconds 300 $ zig build fuzz -- --target responses --iterations 100000 ``` The test binaries are compiled with LLVM even in Debug, because the self-hosted backend emits no coverage instrumentation and `--fuzz` (and kcov) would have nothing to go on. The bounded report names one target per test binary, but every fuzz test in that binary ran. The standalone loop has earned its keep already: an empty tag, a literal length with an underscore in it, and a non-canonical UTF-7 spelling were all its findings, and each is now a seed. ## Documentation ```console $ zig build docs # into zig-out/docs $ zig build docs-serve # and read it at http://127.0.0.1:8000/ ``` The viewer fetches `sources.tar` and `main.wasm` at runtime, which a browser refuses to do from a `file://` page, so the documentation has to be served rather than opened. `-Ddocs-port=N` picks a different port. ## Where this lives The canonical repository is on Forgejo, mirrored to Tangled, and seeded on the Radicle network: - - - `rad:z2rN2dG97cX6jfKLyi7osjPYRs8uG` ```console git clone https://git.jcollie.dev/jeff/zig-imap.git rad clone rad:z2rN2dG97cX6jfKLyi7osjPYRs8uG ``` The Radicle repository is findable only by that identifier, which is why it is written out in full above: `rad clone` fetches it from any node seeding it, and there is no name to look it up by. ## License MIT, and the repository follows [REUSE](https://reuse.software/): ```console $ nix develop -c reuse lint ```