An SMTP client and server library for Zig implementing RFC 5321.
1// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>
2// SPDX-License-Identifier: MIT
3
4//! Shared SMTP protocol primitives (RFC 5321): line reading, reply parsing,
5//! command parsing, and message data dot-stuffing. Used by both the client
6//! and server layers, and usable directly for custom protocol handling.
7
8const std = @import("std");
9const Io = std.Io;
10
11pub const crlf = "\r\n";
12
13pub const ReadLineError = error{
14 ReadFailed,
15 EndOfStream,
16 /// The line did not fit in the reader's buffer.
17 LineTooLong,
18};
19
20/// Reads one CRLF- (or bare LF-) terminated line, returning it without the
21/// line ending. The returned slice points into the reader's buffer and is
22/// invalidated by the next read.
23pub fn readLine(reader: *Io.Reader) ReadLineError![]u8 {
24 const line = reader.takeSentinel('\n') catch |err| switch (err) {
25 error.StreamTooLong => return error.LineTooLong,
26 error.ReadFailed, error.EndOfStream => |e| return e,
27 };
28 if (line.len > 0 and line[line.len - 1] == '\r') return line[0 .. line.len - 1];
29 return line;
30}
31
32/// A server reply: a 3-digit code and one or more lines of text.
33pub const Reply = struct {
34 code: u16,
35 /// Text of all reply lines joined with '\n', with codes and separators
36 /// stripped. Points into the buffer passed to `read`.
37 text: []const u8,
38
39 pub const ReadError = ReadLineError || error{
40 InvalidReply,
41 /// The reply text did not fit in the provided buffer.
42 ReplyTooLong,
43 };
44
45 /// Reads one (possibly multiline) reply. The text is copied into `buffer`
46 /// and the returned reply's `text` field points into it.
47 pub fn read(reader: *Io.Reader, buffer: []u8) ReadError!Reply {
48 var text: Io.Writer = .fixed(buffer);
49 var code: ?u16 = null;
50 var first = true;
51 while (true) {
52 const line = try readLine(reader);
53 if (line.len < 3) return error.InvalidReply;
54 const line_code = std.fmt.parseInt(u16, line[0..3], 10) catch
55 return error.InvalidReply;
56 if (line_code < 100 or line_code > 599) return error.InvalidReply;
57 if (code) |prev| {
58 // All lines of a multiline reply must carry the same code.
59 if (prev != line_code) return error.InvalidReply;
60 } else {
61 code = line_code;
62 }
63 var last = true;
64 var line_text: []const u8 = "";
65 if (line.len > 3) {
66 switch (line[3]) {
67 ' ' => {},
68 '-' => last = false,
69 else => return error.InvalidReply,
70 }
71 line_text = line[4..];
72 }
73 if (!first) text.writeByte('\n') catch return error.ReplyTooLong;
74 text.writeAll(line_text) catch return error.ReplyTooLong;
75 first = false;
76 if (last) break;
77 }
78 return .{ .code = code.?, .text = text.buffered() };
79 }
80
81 /// Iterates over the individual text lines of the reply.
82 pub fn lines(r: *const Reply) std.mem.SplitIterator(u8, .scalar) {
83 return std.mem.splitScalar(u8, r.text, '\n');
84 }
85
86 // Reply classes per RFC 5321 §4.2.1.
87 pub fn isPositiveCompletion(r: Reply) bool {
88 return r.code >= 200 and r.code < 300;
89 }
90 pub fn isPositiveIntermediate(r: Reply) bool {
91 return r.code >= 300 and r.code < 400;
92 }
93 pub fn isTransientFailure(r: Reply) bool {
94 return r.code >= 400 and r.code < 500;
95 }
96 pub fn isPermanentFailure(r: Reply) bool {
97 return r.code >= 500 and r.code < 600;
98 }
99};
100
101/// A parsed client command, as seen by a server.
102pub const Command = union(enum) {
103 helo: []const u8,
104 ehlo: []const u8,
105 /// MAIL FROM. An empty path is the null reverse-path (`MAIL FROM:<>`).
106 mail: PathArgs,
107 /// RCPT TO.
108 rcpt: PathArgs,
109 data,
110 rset,
111 noop,
112 quit,
113 vrfy: []const u8,
114 help,
115 starttls,
116 /// AUTH (RFC 4954).
117 auth: AuthArgs,
118 /// Unrecognized command verb; the payload is the full line.
119 unknown: []const u8,
120
121 pub const AuthArgs = struct {
122 mechanism: []const u8,
123 /// Raw base64 initial response, if the client sent one ("=" denotes
124 /// an empty initial response).
125 initial: []const u8 = "",
126 };
127
128 pub const PathArgs = struct {
129 /// The mailbox, with angle brackets and any obsolete source route
130 /// stripped.
131 path: []const u8,
132 /// Raw ESMTP parameters that followed the path, e.g. "SIZE=1024".
133 params: []const u8 = "",
134
135 pub fn paramIterator(args: PathArgs) ParamIterator {
136 return .init(args.params);
137 }
138 };
139
140 pub const ParseError = error{Syntax};
141
142 /// Parses one command line (without its line ending). Returned slices
143 /// point into `line`.
144 pub fn parse(line: []const u8) ParseError!Command {
145 const trimmed = std.mem.trim(u8, line, " \t");
146 const verb_end = std.mem.indexOfAny(u8, trimmed, " \t") orelse trimmed.len;
147 const verb = trimmed[0..verb_end];
148 const rest = std.mem.trimStart(u8, trimmed[verb_end..], " \t");
149
150 if (ieql(verb, "HELO")) {
151 if (rest.len == 0) return error.Syntax;
152 return .{ .helo = rest };
153 }
154 if (ieql(verb, "EHLO")) {
155 if (rest.len == 0) return error.Syntax;
156 return .{ .ehlo = rest };
157 }
158 if (ieql(verb, "MAIL")) return .{ .mail = try parsePathArgs(rest, "FROM:") };
159 if (ieql(verb, "RCPT")) return .{ .rcpt = try parsePathArgs(rest, "TO:") };
160 if (ieql(verb, "DATA")) return .data;
161 if (ieql(verb, "RSET")) return .rset;
162 if (ieql(verb, "NOOP")) return .noop;
163 if (ieql(verb, "QUIT")) return .quit;
164 if (ieql(verb, "VRFY")) return .{ .vrfy = rest };
165 if (ieql(verb, "HELP")) return .help;
166 if (ieql(verb, "STARTTLS")) return .starttls;
167 if (ieql(verb, "AUTH")) {
168 const mech_end = std.mem.indexOfAny(u8, rest, " \t") orelse rest.len;
169 if (mech_end == 0) return error.Syntax;
170 return .{ .auth = .{
171 .mechanism = rest[0..mech_end],
172 .initial = std.mem.trimStart(u8, rest[mech_end..], " \t"),
173 } };
174 }
175 return .{ .unknown = line };
176 }
177
178 fn parsePathArgs(rest: []const u8, comptime keyword: []const u8) ParseError!PathArgs {
179 if (rest.len < keyword.len or !ieql(rest[0..keyword.len], keyword))
180 return error.Syntax;
181 const after = std.mem.trimStart(u8, rest[keyword.len..], " \t");
182 if (after.len == 0 or after[0] != '<') {
183 // Lenient: accept a bare address ending at whitespace.
184 const end = std.mem.indexOfAny(u8, after, " \t") orelse after.len;
185 if (end == 0) return error.Syntax;
186 return .{
187 .path = after[0..end],
188 .params = std.mem.trimStart(u8, after[end..], " \t"),
189 };
190 }
191 const close = std.mem.indexOfScalar(u8, after, '>') orelse return error.Syntax;
192 var path = after[1..close];
193 // Strip an obsolete source route: <@relay1,@relay2:user@host>.
194 if (path.len > 0 and path[0] == '@') {
195 const colon = std.mem.indexOfScalar(u8, path, ':') orelse return error.Syntax;
196 path = path[colon + 1 ..];
197 }
198 return .{
199 .path = path,
200 .params = std.mem.trimStart(u8, after[close + 1 ..], " \t"),
201 };
202 }
203
204 fn ieql(a: []const u8, b: []const u8) bool {
205 return std.ascii.eqlIgnoreCase(a, b);
206 }
207};
208
209/// Iterates the ESMTP parameters of a MAIL or RCPT command
210/// (RFC 5321 §4.1.2), e.g. "SIZE=1024 BODY=8BITMIME".
211pub const ParamIterator = struct {
212 rest: []const u8,
213
214 pub const Param = struct {
215 keyword: []const u8,
216 /// Empty when the parameter carries no value.
217 value: []const u8 = "",
218 };
219
220 pub fn init(params: []const u8) ParamIterator {
221 return .{ .rest = params };
222 }
223
224 pub fn next(it: *ParamIterator) ?Param {
225 it.rest = std.mem.trimStart(u8, it.rest, " \t");
226 if (it.rest.len == 0) return null;
227 const end = std.mem.indexOfAny(u8, it.rest, " \t") orelse it.rest.len;
228 const token = it.rest[0..end];
229 it.rest = it.rest[end..];
230 if (std.mem.indexOfScalar(u8, token, '=')) |eq| {
231 return .{ .keyword = token[0..eq], .value = token[eq + 1 ..] };
232 }
233 return .{ .keyword = token };
234 }
235};
236
237/// Writes `data` as SMTP message content: line endings are normalized to CRLF
238/// and lines beginning with '.' are dot-stuffed (RFC 5321 §4.5.2). Does not
239/// write the terminating ".\r\n".
240pub fn writeStuffed(writer: *Io.Writer, data: []const u8) Io.Writer.Error!void {
241 var rest = data;
242 while (rest.len > 0) {
243 var line: []const u8 = undefined;
244 if (std.mem.indexOfScalar(u8, rest, '\n')) |i| {
245 line = rest[0..i];
246 rest = rest[i + 1 ..];
247 } else {
248 line = rest;
249 rest = rest[rest.len..];
250 }
251 if (line.len > 0 and line[line.len - 1] == '\r') line = line[0 .. line.len - 1];
252 if (line.len > 0 and line[0] == '.') try writer.writeByte('.');
253 try writer.writeAll(line);
254 try writer.writeAll(crlf);
255 }
256}
257
258test readLine {
259 var reader: Io.Reader = .fixed("first\r\nsecond\nthird\r\n");
260 try std.testing.expectEqualStrings("first", try readLine(&reader));
261 try std.testing.expectEqualStrings("second", try readLine(&reader));
262 try std.testing.expectEqualStrings("third", try readLine(&reader));
263 try std.testing.expectError(error.EndOfStream, readLine(&reader));
264}
265
266test Reply {
267 var reader: Io.Reader = .fixed("250 2.0.0 Ok\r\n");
268 var buf: [128]u8 = undefined;
269 const reply = try Reply.read(&reader, &buf);
270 try std.testing.expectEqual(@as(u16, 250), reply.code);
271 try std.testing.expectEqualStrings("2.0.0 Ok", reply.text);
272 try std.testing.expect(reply.isPositiveCompletion());
273}
274
275test "Reply.read multiline" {
276 var reader: Io.Reader = .fixed("250-mx.example.com\r\n250-PIPELINING\r\n250 SIZE 1000\r\n");
277 var buf: [128]u8 = undefined;
278 const reply = try Reply.read(&reader, &buf);
279 try std.testing.expectEqual(@as(u16, 250), reply.code);
280 try std.testing.expectEqualStrings("mx.example.com\nPIPELINING\nSIZE 1000", reply.text);
281 var it = reply.lines();
282 try std.testing.expectEqualStrings("mx.example.com", it.next().?);
283 try std.testing.expectEqualStrings("PIPELINING", it.next().?);
284 try std.testing.expectEqualStrings("SIZE 1000", it.next().?);
285 try std.testing.expectEqual(@as(?[]const u8, null), it.next());
286}
287
288test "Reply.read rejects malformed replies" {
289 var buf: [128]u8 = undefined;
290 {
291 var reader: Io.Reader = .fixed("2x0 hello\r\n");
292 try std.testing.expectError(error.InvalidReply, Reply.read(&reader, &buf));
293 }
294 {
295 var reader: Io.Reader = .fixed("250-one\r\n251 two\r\n");
296 try std.testing.expectError(error.InvalidReply, Reply.read(&reader, &buf));
297 }
298 {
299 var reader: Io.Reader = .fixed("42\r\n");
300 try std.testing.expectError(error.InvalidReply, Reply.read(&reader, &buf));
301 }
302}
303
304test Command {
305 {
306 const cmd = try Command.parse("EHLO client.example.com");
307 try std.testing.expectEqualStrings("client.example.com", cmd.ehlo);
308 }
309 {
310 const cmd = try Command.parse("mail from:<alice@example.com> SIZE=1024");
311 try std.testing.expectEqualStrings("alice@example.com", cmd.mail.path);
312 try std.testing.expectEqualStrings("SIZE=1024", cmd.mail.params);
313 }
314 {
315 // Null reverse-path and a space after the colon.
316 const cmd = try Command.parse("MAIL FROM: <>");
317 try std.testing.expectEqualStrings("", cmd.mail.path);
318 }
319 {
320 // Obsolete source route is stripped.
321 const cmd = try Command.parse("RCPT TO:<@relay.example:bob@example.net>");
322 try std.testing.expectEqualStrings("bob@example.net", cmd.rcpt.path);
323 }
324 {
325 const cmd = try Command.parse("QUIT");
326 try std.testing.expectEqual(Command.quit, cmd);
327 }
328 {
329 const cmd = try Command.parse("AUTH PLAIN AHVzZXIAcGFzcw==");
330 try std.testing.expectEqualStrings("PLAIN", cmd.auth.mechanism);
331 try std.testing.expectEqualStrings("AHVzZXIAcGFzcw==", cmd.auth.initial);
332 }
333 {
334 const cmd = try Command.parse("auth login");
335 try std.testing.expectEqualStrings("login", cmd.auth.mechanism);
336 try std.testing.expectEqualStrings("", cmd.auth.initial);
337 }
338 {
339 const cmd = try Command.parse("MADE UP");
340 try std.testing.expectEqualStrings("MADE UP", cmd.unknown);
341 }
342 try std.testing.expectError(error.Syntax, Command.parse("AUTH"));
343 try std.testing.expectError(error.Syntax, Command.parse("MAIL TO:<a@b>"));
344 try std.testing.expectError(error.Syntax, Command.parse("RCPT TO:"));
345 try std.testing.expectError(error.Syntax, Command.parse("HELO"));
346}
347
348test writeStuffed {
349 var buf: [256]u8 = undefined;
350 {
351 var w: Io.Writer = .fixed(&buf);
352 try writeStuffed(&w, "line one\r\n.starts with dot\r\n");
353 try std.testing.expectEqualStrings("line one\r\n..starts with dot\r\n", w.buffered());
354 }
355 {
356 // LF-only input is normalized, missing final newline is added.
357 var w: Io.Writer = .fixed(&buf);
358 try writeStuffed(&w, "a\nb");
359 try std.testing.expectEqualStrings("a\r\nb\r\n", w.buffered());
360 }
361 {
362 // A lone "." line must not become a terminator.
363 var w: Io.Writer = .fixed(&buf);
364 try writeStuffed(&w, ".\n");
365 try std.testing.expectEqualStrings("..\r\n", w.buffered());
366 }
367 {
368 var w: Io.Writer = .fixed(&buf);
369 try writeStuffed(&w, "");
370 try std.testing.expectEqualStrings("", w.buffered());
371 }
372}
373
374test "fuzz Command.parse" {
375 try std.testing.fuzz({}, fuzzCommandParse, .{});
376}
377
378fn fuzzCommandParse(context: void, smith: *std.testing.Smith) !void {
379 _ = context;
380 var line_buf: [512]u8 = undefined;
381 const line = line_buf[0..smith.value(u9)];
382 smith.bytes(line);
383
384 const command = Command.parse(line) catch return;
385 // Payload slices must always lie within the parsed line.
386 switch (command) {
387 .helo, .ehlo, .vrfy, .unknown => |payload| try std.testing.expect(payload.len <= line.len),
388 .mail, .rcpt => |args| {
389 try std.testing.expect(args.path.len <= line.len);
390 try std.testing.expect(args.params.len <= line.len);
391 },
392 .auth => |args| {
393 try std.testing.expect(args.mechanism.len <= line.len);
394 try std.testing.expect(args.initial.len <= line.len);
395 },
396 .data, .rset, .noop, .quit, .help, .starttls => {},
397 }
398}
399
400test "fuzz Reply.read" {
401 try std.testing.fuzz({}, fuzzReplyRead, .{});
402}
403
404fn fuzzReplyRead(context: void, smith: *std.testing.Smith) !void {
405 _ = context;
406 var input_buf: [1024]u8 = undefined;
407 const input = input_buf[0..smith.value(u10)];
408 smith.bytes(input);
409
410 var reader: Io.Reader = .fixed(input);
411 var text_buf: [128]u8 = undefined;
412 // Each successful read consumes at least one line, so this terminates.
413 while (true) {
414 const reply = Reply.read(&reader, &text_buf) catch break;
415 try std.testing.expect(reply.code >= 100 and reply.code <= 599);
416 }
417}
418
419test ParamIterator {
420 const command = try Command.parse("MAIL FROM:<a@example.com> SIZE=1024 BODY=8BITMIME FLAG");
421 var it = command.mail.paramIterator();
422
423 const size = it.next().?;
424 try std.testing.expectEqualStrings("SIZE", size.keyword);
425 try std.testing.expectEqualStrings("1024", size.value);
426
427 const body = it.next().?;
428 try std.testing.expectEqualStrings("BODY", body.keyword);
429 try std.testing.expectEqualStrings("8BITMIME", body.value);
430
431 const flag = it.next().?;
432 try std.testing.expectEqualStrings("FLAG", flag.keyword);
433 try std.testing.expectEqualStrings("", flag.value);
434
435 try std.testing.expectEqual(@as(?ParamIterator.Param, null), it.next());
436}