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