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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A heap-allocated IMAP connection owning the TCP stream, its buffers, and//! (optionally) a TLS session, exposing the `std.Io.Reader`/`std.Io.Writer`//! pair a `Client` runs over.//!//! ```zig//! const conn = try Connection.connect(gpa, io, "mail.example.com", .{ .tls = .on });//! defer conn.destroy();//! var client = conn.client();//! const greeting = try client.readGreeting();//! ```
const std = @import("std");const Client = @import("Client.zig");
const Connection = @This();
gpa: std.mem.Allocator,io: std.Io,stream: std.Io.net.Stream,stream_reader: std.Io.net.Stream.Reader,stream_writer: std.Io.net.Stream.Writer,tls: ?Tls,/// The writer handed to the IMAP client. A `tls.Client` flush only reaches/// the buffer below it, so this forwards writes to the top of the write/// stack and cascades flushes all the way to the socket.flush_writer: std.Io.Writer,buffers: []u8,read_buffer_size: usize,write_buffer_size: usize,
const Tls = struct { client: std.crypto.tls.Client, ca_bundle: std.crypto.Certificate.Bundle, ca_lock: std.Io.RwLock,};
/// The port IMAP has had since RFC 1176.pub const default_port = 143;/// IMAPS: implicit TLS, which/// [RFC 8314](https://datatracker.ietf.org/doc/html/rfc8314#section-3)/// prefers over upgrading a plaintext session with STARTTLS.pub const default_tls_port = 993;
pub const Options = struct { /// Defaults to 993 with TLS and 143 without. port: ?u16 = null, tls: TlsMode = .on, /// Buffer for lines read from the server. A message body arrives as a /// literal and is streamed, but an ENVELOPE or a long SEARCH result is a /// line, and one that does not fit is `error.StreamTooLong`. read_buffer_size: usize = 64 * 1024, /// Buffer for outgoing commands. A message being appended streams through /// it; only an OAuth token otherwise gets anywhere near it. write_buffer_size: usize = 8 * 1024,
pub const TlsMode = union(enum) { /// Plain TCP. The password and the mail are readable by the network, /// so `Client` will refuse LOGIN over it unless /// `allow_cleartext_auth` is set; `startTls` is the way up from here. off, /// TLS, verifying the server certificate against the system's root /// certificates. on, /// TLS without certificate verification. Vulnerable to /// man-in-the-middle attacks; use only for testing. insecure, };};
pub const ConnectError = std.Io.net.HostName.ValidateError || std.Io.net.HostName.ConnectError || std.crypto.tls.Client.InitError || std.crypto.Certificate.Bundle.RescanError || error{OutOfMemory};
/// Resolves `host`, connects, and (per `options.tls`) performs a TLS/// handshake. The result is heap-allocated because the reader/writer state/// must not move; free it with `destroy`.pub fn connect( gpa: std.mem.Allocator, io: std.Io, host: []const u8, options: Options,) ConnectError!*Connection { const host_name = try std.Io.net.HostName.init(host); const use_tls = options.tls != .off; const port = options.port orelse @as(u16, if (use_tls) default_tls_port else default_port);
const tls_record_len = std.crypto.tls.Client.min_buffer_len; // Plaintext connections read and write directly through the stream // buffers; TLS connections need ciphertext-sized stream buffers plus // separate plaintext buffers for the application data. const socket_read_len = if (use_tls) tls_record_len else options.read_buffer_size; const socket_write_len = if (use_tls) tls_record_len else options.write_buffer_size; const tls_read_len = if (use_tls) tls_record_len + options.read_buffer_size else 0; const tls_write_len = if (use_tls) options.write_buffer_size else 0;
const conn = try gpa.create(Connection); errdefer gpa.destroy(conn); const buffers = try gpa.alloc(u8, socket_read_len + socket_write_len + tls_read_len + tls_write_len); errdefer gpa.free(buffers); const socket_read_buffer = buffers[0..socket_read_len]; const socket_write_buffer = buffers[socket_read_len..][0..socket_write_len]; const tls_read_buffer = buffers[socket_read_len + socket_write_len ..][0..tls_read_len]; const tls_write_buffer = buffers[socket_read_len + socket_write_len + tls_read_len ..];
const stream = try host_name.connect(io, port, .{ .mode = .stream }); errdefer stream.close(io);
conn.* = .{ .gpa = gpa, .io = io, .stream = stream, .stream_reader = stream.reader(io, socket_read_buffer), .stream_writer = stream.writer(io, socket_write_buffer), .tls = null, .flush_writer = .{ .buffer = &.{}, .vtable = &.{ .drain = flushWriterDrain, .flush = flushWriterFlush }, }, .buffers = buffers, .read_buffer_size = options.read_buffer_size, .write_buffer_size = options.write_buffer_size, };
if (use_tls) { try conn.handshake(switch (options.tls) { .on => .{ .host = host, .verification = .on }, else => .{ .host = host, .verification = .insecure }, }, tls_read_buffer, tls_write_buffer); }
return conn;}
fn flushWriterDrain( w: *std.Io.Writer, data: []const []const u8, splat: usize,) std.Io.Writer.Error!usize { const conn: *Connection = @alignCast(@fieldParentPtr("flush_writer", w)); const top = conn.transportWriter(); var n: usize = 0; for (data[0 .. data.len - 1]) |bytes| { try top.writeAll(bytes); n += bytes.len; } const pattern = data[data.len - 1]; for (0..splat) |_| { try top.writeAll(pattern); n += pattern.len; } return n;}
fn flushWriterFlush(w: *std.Io.Writer) std.Io.Writer.Error!void { const conn: *Connection = @alignCast(@fieldParentPtr("flush_writer", w)); if (conn.tls) |*t| try t.client.writer.flush(); try conn.stream_writer.interface.flush();}
fn transportReader(conn: *Connection) *std.Io.Reader { return if (conn.tls) |*t| &t.client.reader else &conn.stream_reader.interface;}
fn transportWriter(conn: *Connection) *std.Io.Writer { return if (conn.tls) |*t| &t.client.writer else &conn.stream_writer.interface;}
/// The reader carrying IMAP protocol data: the plaintext side of TLS when/// TLS is in use, the socket otherwise.pub fn reader(conn: *Connection) *std.Io.Reader { return conn.transportReader();}
/// The writer carrying IMAP protocol data: a forwarding writer whose flush/// pushes data through every layer to the socket.pub fn writer(conn: *Connection) *std.Io.Writer { return &conn.flush_writer;}
/// Whether what is written to this connection is encrypted, which is what a/// `Client` needs to know before it will send a password.pub fn security(conn: *const Connection) Client.Security { return if (conn.tls != null) .encrypted else .plaintext;}
/// An IMAP client running over this connection. The connection must outlive/// the client.pub fn client(conn: *Connection) Client { return .init(conn.reader(), conn.writer(), conn.security());}
const HandshakeOptions = struct { /// The name to verify the certificate against: the name the caller /// believes it is talking to, never anything the server said. host: []const u8, verification: enum { on, insecure },};
fn handshake( conn: *Connection, options: HandshakeOptions, read_buffer: []u8, write_buffer: []u8,) (std.crypto.tls.Client.InitError || std.crypto.Certificate.Bundle.RescanError)!void { conn.tls = .{ .client = undefined, .ca_bundle = .empty, .ca_lock = .init, }; const tls_state = &conn.tls.?; errdefer { tls_state.ca_bundle.deinit(conn.gpa); conn.tls = null; } if (options.verification == .on) { try tls_state.ca_bundle.rescan( conn.gpa, conn.io, std.Io.Timestamp.now(conn.io, .real), ); } var entropy: [std.crypto.tls.Client.Options.entropy_len]u8 = undefined; conn.io.random(&entropy); tls_state.client = try std.crypto.tls.Client.init( &conn.stream_reader.interface, &conn.stream_writer.interface, .{ .host = switch (options.verification) { .on => .{ .explicit = options.host }, .insecure => .no_verification, }, .ca = switch (options.verification) { .on => .{ .bundle = .{ .gpa = conn.gpa, .io = conn.io, .lock = &tls_state.ca_lock, .bundle = &tls_state.ca_bundle, } }, .insecure => .no_verification, }, .read_buffer = read_buffer, .write_buffer = write_buffer, .entropy = &entropy, .realtime_now = .now(conn.io, .real), }, );}
pub const StartTlsError = Client.Error || std.crypto.tls.Client.InitError || std.crypto.Certificate.Bundle.RescanError || error{ TlsAlreadyActive, TlsNotAvailable, UnexpectedResponse, OutOfMemory };
pub const StartTlsOptions = struct { /// Host name to verify the certificate against. This is the name the /// caller believes it is talking to, not anything the server said. host: []const u8, /// Whether to verify that certificate. `.insecure` accepts anything, /// which gives up the point of the upgrade outside a test. verification: enum { on, insecure } = .on,};
/// STARTTLS ([RFC 9051](https://datatracker.ietf.org/doc/html/rfc9051#section-6.2.1)):/// upgrades this connection to TLS in place. `c` must be a client of this/// connection; its streams are re-pointed, and its `security` set to/// `.encrypted`, once the handshake completes.////// Implicit TLS on port 993 is preferred where it is offered, which/// `connect` does directly, so reach for this only against a server that/// has no such port. Two things are the caller's to handle afterwards: the/// capability list from before the handshake must be discarded and CAPA/// re-issued, because an attacker could have written the first one -- which/// `Client.starttls` does -- and the login has yet to happen.pub fn startTls(conn: *Connection, c: *Client, options: StartTlsOptions) StartTlsError!void { if (conn.tls != null) return error.TlsAlreadyActive;
try c.starttls();
// A plaintext connection's socket buffers are sized for IMAP lines, but // TLS needs them to hold a whole ciphertext record -- 16645 bytes, well // over the 8 KiB a plaintext write buffer defaults to. `connect` sizes // them for that up front when TLS is on; here they have to be replaced, // along with the plaintext buffers the TLS client layers on top. // Nothing may be in flight across the swap. The tagged OK has been read and // the handshake has not begun, so the client speaks next and the socket // reader should be empty; bail rather than silently drop anything. Both // checks come before the allocation, so that failing either leaves the // connection exactly as it was. conn.stream_writer.interface.flush() catch return error.WriteFailed; if (conn.stream_reader.interface.bufferedLen() != 0) return error.UnexpectedResponse;
const record_len = std.crypto.tls.Client.min_buffer_len; const socket_read_len = record_len; const socket_write_len = record_len; const tls_read_len = record_len + conn.read_buffer_size; const tls_write_len = conn.write_buffer_size; // No errdefer: past the assignments below this belongs to the // connection, and a failed handshake leaves a plaintext connection with // roomier buffers rather than a dangling `conn.buffers`. const bufs = try conn.gpa.alloc( u8, socket_read_len + socket_write_len + tls_read_len + tls_write_len, );
const old_buffers = conn.buffers; conn.stream_reader = conn.stream.reader(conn.io, bufs[0..socket_read_len]); conn.stream_writer = conn.stream.writer( conn.io, bufs[socket_read_len..][0..socket_write_len], ); conn.buffers = bufs; conn.gpa.free(old_buffers);
try conn.handshake( .{ .host = options.host, .verification = switch (options.verification) { .on => .on, .insecure => .insecure, } }, bufs[socket_read_len + socket_write_len ..][0..tls_read_len], bufs[socket_read_len + socket_write_len + tls_read_len ..], );
c.setTransport(conn.reader(), conn.writer(), .encrypted);}
/// Closes the socket and frees everything. Send `Client.logout` first: a/// server told is cleaner than one that finds out, and CLOSE -- not a/// dropped connection -- is what expunges a mailbox's deleted messages.pub fn destroy(conn: *Connection) void { const gpa = conn.gpa; if (conn.tls) |*t| { t.client.end() catch {}; conn.stream_writer.interface.flush() catch {}; t.ca_bundle.deinit(gpa); } conn.stream.close(conn.io); gpa.free(conn.buffers); gpa.destroy(conn);}
test { // The connection cannot be exercised without a server; this at least // keeps it compiling, and `tests/e2e.zig` drives it against one. std.testing.refAllDecls(@This());}