An SMTP client and server library for Zig implementing RFC 5321.
0

Configure Feed

Select the types of activity you want to include in your feed.

zig-smtp / src / protocol.zig
12 kB 310 lines
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 /// Unrecognized command verb; the payload is the full line. 116 unknown: []const u8, 117 118 pub const PathArgs = struct { 119 /// The mailbox, with angle brackets and any obsolete source route 120 /// stripped. 121 path: []const u8, 122 /// Raw ESMTP parameters that followed the path, e.g. "SIZE=1024". 123 params: []const u8 = "", 124 }; 125 126 pub const ParseError = error{Syntax}; 127 128 /// Parses one command line (without its line ending). Returned slices 129 /// point into `line`. 130 pub fn parse(line: []const u8) ParseError!Command { 131 const trimmed = std.mem.trim(u8, line, " \t"); 132 const verb_end = std.mem.indexOfAny(u8, trimmed, " \t") orelse trimmed.len; 133 const verb = trimmed[0..verb_end]; 134 const rest = std.mem.trimStart(u8, trimmed[verb_end..], " \t"); 135 136 if (ieql(verb, "HELO")) { 137 if (rest.len == 0) return error.Syntax; 138 return .{ .helo = rest }; 139 } 140 if (ieql(verb, "EHLO")) { 141 if (rest.len == 0) return error.Syntax; 142 return .{ .ehlo = rest }; 143 } 144 if (ieql(verb, "MAIL")) return .{ .mail = try parsePathArgs(rest, "FROM:") }; 145 if (ieql(verb, "RCPT")) return .{ .rcpt = try parsePathArgs(rest, "TO:") }; 146 if (ieql(verb, "DATA")) return .data; 147 if (ieql(verb, "RSET")) return .rset; 148 if (ieql(verb, "NOOP")) return .noop; 149 if (ieql(verb, "QUIT")) return .quit; 150 if (ieql(verb, "VRFY")) return .{ .vrfy = rest }; 151 if (ieql(verb, "HELP")) return .help; 152 return .{ .unknown = line }; 153 } 154 155 fn parsePathArgs(rest: []const u8, comptime keyword: []const u8) ParseError!PathArgs { 156 if (rest.len < keyword.len or !ieql(rest[0..keyword.len], keyword)) 157 return error.Syntax; 158 const after = std.mem.trimStart(u8, rest[keyword.len..], " \t"); 159 if (after.len == 0 or after[0] != '<') { 160 // Lenient: accept a bare address ending at whitespace. 161 const end = std.mem.indexOfAny(u8, after, " \t") orelse after.len; 162 if (end == 0) return error.Syntax; 163 return .{ 164 .path = after[0..end], 165 .params = std.mem.trimStart(u8, after[end..], " \t"), 166 }; 167 } 168 const close = std.mem.indexOfScalar(u8, after, '>') orelse return error.Syntax; 169 var path = after[1..close]; 170 // Strip an obsolete source route: <@relay1,@relay2:user@host>. 171 if (path.len > 0 and path[0] == '@') { 172 const colon = std.mem.indexOfScalar(u8, path, ':') orelse return error.Syntax; 173 path = path[colon + 1 ..]; 174 } 175 return .{ 176 .path = path, 177 .params = std.mem.trimStart(u8, after[close + 1 ..], " \t"), 178 }; 179 } 180 181 fn ieql(a: []const u8, b: []const u8) bool { 182 return std.ascii.eqlIgnoreCase(a, b); 183 } 184}; 185 186/// Writes `data` as SMTP message content: line endings are normalized to CRLF 187/// and lines beginning with '.' are dot-stuffed (RFC 5321 §4.5.2). Does not 188/// write the terminating ".\r\n". 189pub fn writeStuffed(writer: *Io.Writer, data: []const u8) Io.Writer.Error!void { 190 var rest = data; 191 while (rest.len > 0) { 192 var line: []const u8 = undefined; 193 if (std.mem.indexOfScalar(u8, rest, '\n')) |i| { 194 line = rest[0..i]; 195 rest = rest[i + 1 ..]; 196 } else { 197 line = rest; 198 rest = rest[rest.len..]; 199 } 200 if (line.len > 0 and line[line.len - 1] == '\r') line = line[0 .. line.len - 1]; 201 if (line.len > 0 and line[0] == '.') try writer.writeByte('.'); 202 try writer.writeAll(line); 203 try writer.writeAll(crlf); 204 } 205} 206 207test "readLine strips CRLF and LF" { 208 var reader: Io.Reader = .fixed("first\r\nsecond\nthird\r\n"); 209 try std.testing.expectEqualStrings("first", try readLine(&reader)); 210 try std.testing.expectEqualStrings("second", try readLine(&reader)); 211 try std.testing.expectEqualStrings("third", try readLine(&reader)); 212 try std.testing.expectError(error.EndOfStream, readLine(&reader)); 213} 214 215test "Reply.read single line" { 216 var reader: Io.Reader = .fixed("250 2.0.0 Ok\r\n"); 217 var buf: [128]u8 = undefined; 218 const reply = try Reply.read(&reader, &buf); 219 try std.testing.expectEqual(@as(u16, 250), reply.code); 220 try std.testing.expectEqualStrings("2.0.0 Ok", reply.text); 221 try std.testing.expect(reply.isPositiveCompletion()); 222} 223 224test "Reply.read multiline" { 225 var reader: Io.Reader = .fixed("250-mx.example.com\r\n250-PIPELINING\r\n250 SIZE 1000\r\n"); 226 var buf: [128]u8 = undefined; 227 const reply = try Reply.read(&reader, &buf); 228 try std.testing.expectEqual(@as(u16, 250), reply.code); 229 try std.testing.expectEqualStrings("mx.example.com\nPIPELINING\nSIZE 1000", reply.text); 230 var it = reply.lines(); 231 try std.testing.expectEqualStrings("mx.example.com", it.next().?); 232 try std.testing.expectEqualStrings("PIPELINING", it.next().?); 233 try std.testing.expectEqualStrings("SIZE 1000", it.next().?); 234 try std.testing.expectEqual(@as(?[]const u8, null), it.next()); 235} 236 237test "Reply.read rejects malformed replies" { 238 var buf: [128]u8 = undefined; 239 { 240 var reader: Io.Reader = .fixed("2x0 hello\r\n"); 241 try std.testing.expectError(error.InvalidReply, Reply.read(&reader, &buf)); 242 } 243 { 244 var reader: Io.Reader = .fixed("250-one\r\n251 two\r\n"); 245 try std.testing.expectError(error.InvalidReply, Reply.read(&reader, &buf)); 246 } 247 { 248 var reader: Io.Reader = .fixed("42\r\n"); 249 try std.testing.expectError(error.InvalidReply, Reply.read(&reader, &buf)); 250 } 251} 252 253test "Command.parse" { 254 { 255 const cmd = try Command.parse("EHLO client.example.com"); 256 try std.testing.expectEqualStrings("client.example.com", cmd.ehlo); 257 } 258 { 259 const cmd = try Command.parse("mail from:<alice@example.com> SIZE=1024"); 260 try std.testing.expectEqualStrings("alice@example.com", cmd.mail.path); 261 try std.testing.expectEqualStrings("SIZE=1024", cmd.mail.params); 262 } 263 { 264 // Null reverse-path and a space after the colon. 265 const cmd = try Command.parse("MAIL FROM: <>"); 266 try std.testing.expectEqualStrings("", cmd.mail.path); 267 } 268 { 269 // Obsolete source route is stripped. 270 const cmd = try Command.parse("RCPT TO:<@relay.example:bob@example.net>"); 271 try std.testing.expectEqualStrings("bob@example.net", cmd.rcpt.path); 272 } 273 { 274 const cmd = try Command.parse("QUIT"); 275 try std.testing.expectEqual(Command.quit, cmd); 276 } 277 { 278 const cmd = try Command.parse("MADE UP"); 279 try std.testing.expectEqualStrings("MADE UP", cmd.unknown); 280 } 281 try std.testing.expectError(error.Syntax, Command.parse("MAIL TO:<a@b>")); 282 try std.testing.expectError(error.Syntax, Command.parse("RCPT TO:")); 283 try std.testing.expectError(error.Syntax, Command.parse("HELO")); 284} 285 286test "writeStuffed" { 287 var buf: [256]u8 = undefined; 288 { 289 var w: Io.Writer = .fixed(&buf); 290 try writeStuffed(&w, "line one\r\n.starts with dot\r\n"); 291 try std.testing.expectEqualStrings("line one\r\n..starts with dot\r\n", w.buffered()); 292 } 293 { 294 // LF-only input is normalized, missing final newline is added. 295 var w: Io.Writer = .fixed(&buf); 296 try writeStuffed(&w, "a\nb"); 297 try std.testing.expectEqualStrings("a\r\nb\r\n", w.buffered()); 298 } 299 { 300 // A lone "." line must not become a terminator. 301 var w: Io.Writer = .fixed(&buf); 302 try writeStuffed(&w, ".\n"); 303 try std.testing.expectEqualStrings("..\r\n", w.buffered()); 304 } 305 { 306 var w: Io.Writer = .fixed(&buf); 307 try writeStuffed(&w, ""); 308 try std.testing.expectEqualStrings("", w.buffered()); 309 } 310}