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//! A single-connection SMTP server session. Like the client, it runs over
5//! any `Io.Reader`/`Io.Writer` pair; accept a TCP connection and hand its
6//! stream reader/writer to `run`. Accepting connections, concurrency, and
7//! message storage are left to the caller — the session just speaks the
8//! protocol and forwards decisions to a `Handler`.
9//!
10//! Typical use:
11//! ```
12//! var session: Server = .init(&stream_reader, &stream_writer, handler, .{
13//! .hostname = "mx.example.com",
14//! });
15//! try session.run(gpa);
16//! ```
17
18const Server = @This();
19
20const std = @import("std");
21const Io = std.Io;
22const tls = @import("tls");
23const protocol = @import("protocol.zig");
24
25reader: *Io.Reader,
26writer: *Io.Writer,
27handler: Handler,
28options: Options,
29/// True once a STARTTLS handshake has completed for this session.
30secured: bool = false,
31tls_connection: tls.Connection = undefined,
32tls_reader: tls.Connection.Reader = undefined,
33tls_writer: tls.Connection.Writer = undefined,
34tls_read_buffer: [4096]u8 = undefined,
35tls_write_buffer: [4096]u8 = undefined,
36
37pub const Options = struct {
38 /// Which protocol the session speaks. See `Protocol`.
39 protocol: Protocol = .smtp,
40 /// Hostname announced in the greeting and the EHLO response.
41 hostname: []const u8 = "localhost",
42 /// Advertised via the SIZE extension and enforced during DATA.
43 max_message_size: usize = 16 * 1024 * 1024,
44 max_recipients: usize = 100,
45 /// When set, the session speaks TLS (see `TlsOptions.mode`). The
46 /// underlying stream reader/writer handed to `init` must then have
47 /// buffers of at least `tls.input_buffer_len` and
48 /// `tls.output_buffer_len` bytes, since the handshake and TLS records
49 /// run over them.
50 tls: ?TlsOptions = null,
51 /// Reject MAIL with 530 until the client has authenticated. Requires a
52 /// handler with an `authenticate` callback.
53 require_auth: bool = false,
54};
55
56/// SMTP, or its local-delivery sibling LMTP
57/// ([RFC 2033](https://datatracker.ietf.org/doc/html/rfc2033)).
58pub const Protocol = enum {
59 smtp,
60 /// LMTP differs from SMTP in two ways that matter here: the greeting is
61 /// `LHLO` and `HELO`/`EHLO` are refused, and the end of a message is
62 /// answered with one reply per accepted recipient instead of one for
63 /// the message. It exists so that a delivery agent can report a
64 /// different outcome for each mailbox, which SMTP gives no way to say.
65 ///
66 /// RFC 2033 §5 forbids running it on TCP port 25 and advises against
67 /// wide-area use at all: it is for the hop between a queueing MTA and
68 /// the thing that writes to mailboxes.
69 lmtp,
70};
71
72pub const TlsOptions = struct {
73 io: Io,
74 /// Server certificate chain and private key presented to clients.
75 auth: *tls.config.CertKeyPair,
76 mode: Mode = .starttls,
77
78 pub const Mode = enum {
79 /// Advertise and accept the STARTTLS command
80 /// ([RFC 3207](https://datatracker.ietf.org/doc/html/rfc3207)).
81 starttls,
82 /// Perform the TLS handshake before the greeting (implicit TLS /
83 /// SMTPS, port 465 style; [RFC 8314](https://datatracker.ietf.org/doc/html/rfc8314)).
84 implicit,
85 };
86};
87
88/// A handler's verdict on an envelope step or a complete message.
89pub const Decision = union(enum) {
90 accept,
91 reject: Rejection,
92
93 pub const Rejection = struct {
94 /// Use 4xx for "try again later", 5xx for permanent rejection.
95 code: u16 = 550,
96 /// By convention prefixed with an enhanced status code
97 /// ([RFC 3463](https://datatracker.ietf.org/doc/html/rfc3463)).
98 text: []const u8 = "5.7.1 Rejected",
99 };
100};
101
102/// One accepted recipient, with whatever the client attached to it.
103pub const Recipient = struct {
104 /// The forward-path from RCPT TO.
105 address: []const u8,
106 /// Value of the RCPT `NOTIFY=` parameter
107 /// ([RFC 3461](https://datatracker.ietf.org/doc/html/rfc3461)), if the
108 /// client sent one. Absent means the client did not say, which RFC 3461
109 /// lets a reporting MTA read as either `FAILURE` or `FAILURE,DELAY`.
110 notify: ?protocol.Notify = null,
111 /// Value of the RCPT `ORCPT=` parameter, xtext-decoded: the address the
112 /// message was originally addressed to, before whatever aliasing led
113 /// here.
114 orcpt: ?protocol.Orcpt = null,
115};
116
117pub const Envelope = struct {
118 /// Empty for the null reverse-path (`MAIL FROM:<>`).
119 from: []const u8,
120 recipients: []const Recipient,
121 /// Value of the MAIL SIZE= parameter
122 /// ([RFC 1870](https://datatracker.ietf.org/doc/html/rfc1870)), if the client
123 /// declared one. Already validated against `Options.max_message_size`.
124 declared_size: ?u64 = null,
125 /// Value of the MAIL BODY= parameter
126 /// ([RFC 6152](https://datatracker.ietf.org/doc/html/rfc6152)).
127 body: Body = .unspecified,
128 /// True when the client requested the SMTPUTF8 extension
129 /// ([RFC 6531](https://datatracker.ietf.org/doc/html/rfc6531)); the
130 /// envelope addresses and message headers may then contain UTF-8.
131 smtputf8: bool = false,
132 /// Value of the MAIL `RET=` parameter
133 /// ([RFC 3461](https://datatracker.ietf.org/doc/html/rfc3461)): how much
134 /// of the message the sender wants carried back in a failure DSN.
135 /// Absent leaves the choice to whoever reports.
136 ret: ?protocol.Ret = null,
137 /// Value of the MAIL `ENVID=` parameter, xtext-decoded: an identifier
138 /// the sender wants quoted back in any DSN for this message.
139 envid: ?[]const u8 = null,
140
141 pub const Body = enum { unspecified, seven_bit, eight_bit_mime };
142};
143
144/// What a mail transaction accumulates between MAIL and the end of the
145/// message. Kept together so that resetting it cannot forget a field —
146/// RSET, a completed message and a new (L)HLO all discard the lot.
147const Transaction = struct {
148 from: ?[]const u8 = null,
149 recipients: std.ArrayList(Recipient) = .empty,
150 declared_size: ?u64 = null,
151 body: Envelope.Body = .unspecified,
152 smtputf8: bool = false,
153 ret: ?protocol.Ret = null,
154 envid: ?[]const u8 = null,
155
156 /// The memory all of this points into is the session arena, which the
157 /// caller resets alongside.
158 fn clear(t: *Transaction) void {
159 t.* = .{};
160 }
161
162 fn envelope(t: Transaction) Envelope {
163 return .{
164 .from = t.from.?,
165 .recipients = t.recipients.items,
166 .declared_size = t.declared_size,
167 .body = t.body,
168 .smtputf8 = t.smtputf8,
169 .ret = t.ret,
170 .envid = t.envid,
171 };
172 }
173};
174
175/// Callbacks invoked during a session. All slices passed to callbacks are
176/// only valid for the duration of the call.
177pub const Handler = struct {
178 context: ?*anyopaque = null,
179 vtable: *const VTable,
180
181 pub const VTable = struct {
182 /// Called for AUTH with the decoded credentials; return true to
183 /// accept. When set, AUTH PLAIN and AUTH LOGIN are advertised and
184 /// accepted ([RFC 4954](https://datatracker.ietf.org/doc/html/rfc4954)).
185 authenticate: ?*const fn (context: ?*anyopaque, username: []const u8, password: []const u8) bool = null,
186 /// Called for MAIL FROM. Null accepts every sender.
187 mailFrom: ?*const fn (context: ?*anyopaque, from: []const u8) Decision = null,
188 /// Called for each RCPT TO, with the address and any DSN
189 /// parameters that came with it. Null accepts every recipient.
190 rcptTo: ?*const fn (context: ?*anyopaque, recipient: Recipient) Decision = null,
191 /// Called once the complete message has been received. The data has
192 /// CRLF line endings and dot-stuffing already removed. Exactly one
193 /// of `message` and `messageReader` must be set.
194 message: ?*const fn (context: ?*anyopaque, envelope: Envelope, data: []const u8) Decision = null,
195 /// LMTP only: the verdict for one recipient of the message just
196 /// received, `envelope.recipients[index]`, called once per accepted
197 /// recipient after `message` or `messageReader` has returned
198 /// `.accept`. This is what LMTP exists for — one mailbox can be
199 /// full while another is fine — so a `.lmtp` session without it
200 /// answers every recipient identically and gains nothing over SMTP.
201 ///
202 /// Not called when the message itself was rejected: that verdict
203 /// applies to every recipient and is sent for each of them.
204 recipientResult: ?*const fn (context: ?*anyopaque, envelope: Envelope, index: usize) Decision = null,
205 /// Streaming alternative to `message`: called after DATA with a
206 /// reader that yields the message content (dot-stuffing removed,
207 /// line endings normalized to CRLF) until end of stream. Anything
208 /// the callback leaves unread is drained by the session, so
209 /// returning early is fine. `Options.max_message_size` is not
210 /// enforced in this mode; individual message lines must fit the
211 /// session's stream reader buffer.
212 messageReader: ?*const fn (context: ?*anyopaque, envelope: Envelope, message: *Io.Reader) Decision = null,
213 };
214};
215
216pub fn init(reader: *Io.Reader, writer: *Io.Writer, handler: Handler, options: Options) Server {
217 return .{ .reader = reader, .writer = writer, .handler = handler, .options = options };
218}
219
220pub const RunError = error{ WriteFailed, ReadFailed, OutOfMemory, TlsHandshakeFailed };
221
222/// Serves the session until the client sends QUIT or disconnects. `gpa`
223/// backs per-transaction storage (envelope and message data); everything is
224/// freed on return.
225pub fn run(s: *Server, gpa: std.mem.Allocator) RunError!void {
226 var arena_state: std.heap.ArenaAllocator = .init(gpa);
227 defer arena_state.deinit();
228 const arena = arena_state.allocator();
229
230 std.debug.assert(!s.options.require_auth or s.handler.vtable.authenticate != null);
231 std.debug.assert((s.handler.vtable.message == null) != (s.handler.vtable.messageReader == null));
232
233 if (s.options.tls) |config| {
234 if (config.mode == .implicit and !s.secured) try s.upgradeToTls(config);
235 }
236
237 var greeted = false;
238 var authenticated = false;
239 var transaction: Transaction = .{};
240
241 try s.writer.print("220 {s} ESMTP ready" ++ protocol.crlf, .{s.options.hostname});
242 try s.writer.flush();
243
244 while (true) {
245 const line = protocol.readLine(s.reader) catch |err| switch (err) {
246 error.EndOfStream => return, // Client disconnected.
247 error.ReadFailed => return error.ReadFailed,
248 error.LineTooLong => {
249 try s.discardLine();
250 try s.reply(500, "5.5.2 Line too long");
251 continue;
252 },
253 };
254 const command = protocol.Command.parse(line) catch {
255 try s.reply(501, "5.5.4 Syntax error in parameters");
256 continue;
257 };
258 switch (command) {
259 .helo => {
260 // RFC 2033 §4: an LMTP server must not answer HELO or EHLO
261 // with a positive completion, and 500 is what it suggests.
262 if (s.options.protocol == .lmtp) {
263 try s.reply(500, "5.5.1 This is LMTP, use LHLO");
264 continue;
265 }
266 greeted = true;
267 transaction.clear();
268 _ = arena_state.reset(.retain_capacity);
269 try s.reply(250, s.options.hostname);
270 },
271 .ehlo => {
272 if (s.options.protocol == .lmtp) {
273 try s.reply(500, "5.5.1 This is LMTP, use LHLO");
274 continue;
275 }
276 greeted = true;
277 transaction.clear();
278 _ = arena_state.reset(.retain_capacity);
279 try s.greetExtended(authenticated);
280 },
281 .lhlo => {
282 if (s.options.protocol == .smtp) {
283 try s.reply(500, "5.5.2 Command not recognized");
284 continue;
285 }
286 greeted = true;
287 transaction.clear();
288 _ = arena_state.reset(.retain_capacity);
289 try s.greetExtended(authenticated);
290 },
291 .mail => |args| {
292 if (!greeted) {
293 try s.reply(503, "5.5.1 Send EHLO first");
294 continue;
295 }
296 if (s.options.require_auth and !authenticated) {
297 try s.reply(530, "5.7.0 Authentication required");
298 continue;
299 }
300 if (transaction.from != null) {
301 try s.reply(503, "5.5.1 Nested MAIL command");
302 continue;
303 }
304 var mail_declared_size: ?u64 = null;
305 var mail_body: Envelope.Body = .unspecified;
306 var mail_smtputf8 = false;
307 var mail_ret: ?protocol.Ret = null;
308 var mail_envid: ?[]const u8 = null;
309 var params_ok = true;
310 var params = args.paramIterator();
311 while (params.next()) |param| {
312 if (std.ascii.eqlIgnoreCase(param.keyword, "SIZE")) {
313 const size = std.fmt.parseInt(u64, param.value, 10) catch {
314 try s.reply(501, "5.5.2 Invalid SIZE parameter");
315 params_ok = false;
316 break;
317 };
318 if (size > s.options.max_message_size) {
319 try s.reply(552, "5.3.4 Message size exceeds fixed maximum");
320 params_ok = false;
321 break;
322 }
323 mail_declared_size = size;
324 } else if (std.ascii.eqlIgnoreCase(param.keyword, "BODY")) {
325 if (std.ascii.eqlIgnoreCase(param.value, "7BIT")) {
326 mail_body = .seven_bit;
327 } else if (std.ascii.eqlIgnoreCase(param.value, "8BITMIME")) {
328 mail_body = .eight_bit_mime;
329 } else {
330 try s.reply(555, "5.5.4 Unsupported BODY value");
331 params_ok = false;
332 break;
333 }
334 } else if (std.ascii.eqlIgnoreCase(param.keyword, "SMTPUTF8")) {
335 if (param.value.len != 0) {
336 try s.reply(501, "5.5.4 SMTPUTF8 takes no value");
337 params_ok = false;
338 break;
339 }
340 mail_smtputf8 = true;
341 } else if (std.ascii.eqlIgnoreCase(param.keyword, "RET")) {
342 mail_ret = protocol.Ret.parse(param.value) catch {
343 try s.reply(501, "5.5.4 Invalid RET parameter");
344 params_ok = false;
345 break;
346 };
347 } else if (std.ascii.eqlIgnoreCase(param.keyword, "ENVID")) {
348 // The cap is on the encoded form, which is what
349 // arrived, so it is checked before decoding.
350 if (param.value.len == 0 or param.value.len > protocol.max_envid_len) {
351 try s.reply(501, "5.5.4 Invalid ENVID parameter");
352 params_ok = false;
353 break;
354 }
355 const decoded = arena.alloc(u8, param.value.len) catch return error.OutOfMemory;
356 mail_envid = protocol.xtextDecode(decoded, param.value) catch {
357 try s.reply(501, "5.5.4 Invalid ENVID parameter");
358 params_ok = false;
359 break;
360 };
361 } else {
362 try s.reply(555, "5.5.4 Unrecognized parameter");
363 params_ok = false;
364 break;
365 }
366 }
367 if (!params_ok) continue;
368 if (!try s.validateAddress(args.path, mail_smtputf8)) continue;
369 if (s.handler.vtable.mailFrom) |callback| {
370 switch (callback(s.handler.context, args.path)) {
371 .accept => {},
372 .reject => |r| {
373 try s.reply(r.code, r.text);
374 continue;
375 },
376 }
377 }
378 transaction.from = try arena.dupe(u8, args.path);
379 transaction.declared_size = mail_declared_size;
380 transaction.body = mail_body;
381 transaction.smtputf8 = mail_smtputf8;
382 transaction.ret = mail_ret;
383 transaction.envid = mail_envid;
384 try s.reply(250, "2.1.0 Ok");
385 },
386 .rcpt => |args| {
387 if (transaction.from == null) {
388 try s.reply(503, "5.5.1 Need MAIL command first");
389 continue;
390 }
391 var recipient: Recipient = .{ .address = args.path };
392 var params_ok = true;
393 var params = args.paramIterator();
394 while (params.next()) |param| {
395 if (std.ascii.eqlIgnoreCase(param.keyword, "NOTIFY")) {
396 recipient.notify = protocol.Notify.parse(param.value) catch {
397 try s.reply(501, "5.5.4 Invalid NOTIFY parameter");
398 params_ok = false;
399 break;
400 };
401 } else if (std.ascii.eqlIgnoreCase(param.keyword, "ORCPT")) {
402 if (param.value.len == 0 or param.value.len > protocol.Orcpt.max_len) {
403 try s.reply(501, "5.5.4 Invalid ORCPT parameter");
404 params_ok = false;
405 break;
406 }
407 const decoded = arena.alloc(u8, param.value.len) catch return error.OutOfMemory;
408 recipient.orcpt = protocol.Orcpt.parse(decoded, param.value) catch {
409 try s.reply(501, "5.5.4 Invalid ORCPT parameter");
410 params_ok = false;
411 break;
412 };
413 } else {
414 try s.reply(555, "5.5.4 Unrecognized parameter");
415 params_ok = false;
416 break;
417 }
418 }
419 if (!params_ok) continue;
420 if (!try s.validateAddress(args.path, transaction.smtputf8)) continue;
421 if (transaction.recipients.items.len >= s.options.max_recipients) {
422 try s.reply(452, "4.5.3 Too many recipients");
423 continue;
424 }
425 if (s.handler.vtable.rcptTo) |callback| {
426 switch (callback(s.handler.context, recipient)) {
427 .accept => {},
428 .reject => |r| {
429 try s.reply(r.code, r.text);
430 continue;
431 },
432 }
433 }
434 recipient.address = try arena.dupe(u8, args.path);
435 if (recipient.orcpt) |*orcpt| orcpt.addr_type = try arena.dupe(u8, orcpt.addr_type);
436 try transaction.recipients.append(arena, recipient);
437 try s.reply(250, "2.1.5 Ok");
438 },
439 .data => {
440 if (transaction.recipients.items.len == 0) {
441 try s.reply(503, "5.5.1 Need RCPT command first");
442 continue;
443 }
444 try s.receiveData(arena, transaction.envelope());
445 transaction.clear();
446 _ = arena_state.reset(.retain_capacity);
447 },
448 .bdat => |args| {
449 if (transaction.recipients.items.len == 0) {
450 // The chunk's octets follow regardless; consume them to
451 // keep the length-framed stream in sync.
452 s.reader.discardAll64(args.size) catch |err| switch (err) {
453 error.EndOfStream => return,
454 error.ReadFailed => return error.ReadFailed,
455 };
456 try s.reply(503, "5.5.1 Need RCPT command first");
457 continue;
458 }
459 const outcome = try s.receiveChunked(arena, transaction.envelope(), args);
460 transaction.clear();
461 _ = arena_state.reset(.retain_capacity);
462 switch (outcome) {
463 .done => {},
464 .end_session => return,
465 }
466 },
467 .rset => {
468 transaction.clear();
469 _ = arena_state.reset(.retain_capacity);
470 try s.reply(250, "2.0.0 Ok");
471 },
472 .noop => try s.reply(250, "2.0.0 Ok"),
473 .vrfy => try s.reply(252, "2.5.2 Cannot VRFY user"),
474 .help => try s.reply(214, "2.0.0 See RFC 5321"),
475 .starttls => {
476 const config = s.options.tls orelse {
477 try s.reply(502, "5.5.1 STARTTLS not supported");
478 continue;
479 };
480 if (config.mode != .starttls) {
481 try s.reply(502, "5.5.1 STARTTLS not supported");
482 continue;
483 }
484 if (s.secured) {
485 try s.reply(503, "5.5.1 TLS already active");
486 continue;
487 }
488 try s.reply(220, "2.0.0 Ready to start TLS");
489 try s.upgradeToTls(config);
490 // RFC 3207 §4.2: both sides return to their initial state;
491 // the client must EHLO again.
492 greeted = false;
493 authenticated = false;
494 transaction.clear();
495 _ = arena_state.reset(.retain_capacity);
496 },
497 .quit => {
498 try s.reply(221, "2.0.0 Bye");
499 if (s.secured) s.tls_connection.close() catch {};
500 return;
501 },
502 .auth => |args| {
503 if (s.handler.vtable.authenticate == null) {
504 try s.reply(503, "5.5.1 Authentication not enabled");
505 continue;
506 }
507 if (!greeted) {
508 try s.reply(503, "5.5.1 Send EHLO first");
509 continue;
510 }
511 if (authenticated) {
512 try s.reply(503, "5.5.1 Already authenticated");
513 continue;
514 }
515 if (transaction.from != null) {
516 try s.reply(503, "5.5.1 MAIL transaction in progress");
517 continue;
518 }
519 switch (try s.receiveAuth(args)) {
520 .authenticated => authenticated = true,
521 .rejected => {},
522 .disconnected => return,
523 }
524 },
525 .unknown => try s.reply(500, "5.5.2 Command not recognized"),
526 }
527 }
528}
529
530/// Writes the EHLO or LHLO response: the hostname, then one line per
531/// extension. The two are the same list — RFC 2033 gives LHLO the semantics
532/// of EHLO — and it requires PIPELINING and ENHANCEDSTATUSCODES of an LMTP
533/// server, both of which are here for every session anyway.
534fn greetExtended(s: *Server, authenticated: bool) error{WriteFailed}!void {
535 // Every reply carries an enhanced status code (RFC 3463), so the
536 // ENHANCEDSTATUSCODES extension (RFC 2034) is advertised.
537 try s.writer.print("250-{s}\r\n250-PIPELINING\r\n250-8BITMIME\r\n250-CHUNKING\r\n250-SMTPUTF8\r\n250-ENHANCEDSTATUSCODES\r\n250-DSN\r\n", .{s.options.hostname});
538 if (s.options.tls) |config| {
539 if (config.mode == .starttls and !s.secured)
540 try s.writer.writeAll("250-STARTTLS\r\n");
541 }
542 if (s.handler.vtable.authenticate != null and !authenticated)
543 try s.writer.writeAll("250-AUTH PLAIN LOGIN\r\n");
544 try s.writer.print("250 SIZE {d}\r\n", .{s.options.max_message_size});
545 try s.writer.flush();
546}
547
548/// Performs the server-side TLS handshake over the current transport and
549/// swaps the session onto the encrypted connection.
550fn upgradeToTls(s: *Server, config: TlsOptions) error{TlsHandshakeFailed}!void {
551 var rng_source: std.Random.IoSource = .{ .io = config.io };
552 s.tls_connection = tls.server(s.reader, s.writer, .{
553 .auth = config.auth,
554 .rng = rng_source.interface(),
555 .now = Io.Clock.real.now(config.io),
556 }) catch return error.TlsHandshakeFailed;
557 s.tls_reader = s.tls_connection.reader(&s.tls_read_buffer);
558 s.tls_writer = s.tls_connection.writer(&s.tls_write_buffer);
559 s.reader = &s.tls_reader.interface;
560 s.writer = &s.tls_writer.interface;
561 s.secured = true;
562}
563
564const AuthOutcome = enum { authenticated, rejected, disconnected };
565
566/// Runs the challenge/response exchange for AUTH PLAIN or AUTH LOGIN
567/// (RFC 4954) and consults the handler's `authenticate` callback. Every
568/// outcome except `disconnected` has already sent its reply.
569fn receiveAuth(s: *Server, args: protocol.Command.AuthArgs) RunError!AuthOutcome {
570 const callback = s.handler.vtable.authenticate.?;
571
572 if (std.ascii.eqlIgnoreCase(args.mechanism, "PLAIN")) {
573 var decoded_buf: [576]u8 = undefined;
574 var response: []const u8 = args.initial;
575 if (response.len == 0) {
576 try s.reply(334, "");
577 response = switch (try s.takeAuthLine()) {
578 .line => |line| line,
579 .cancelled => return .rejected,
580 .disconnected => return .disconnected,
581 };
582 }
583 const decoded = decodeBase64(&decoded_buf, response) orelse {
584 try s.reply(501, "5.5.2 Invalid base64");
585 return .rejected;
586 };
587 // authzid NUL authcid NUL password; the authzid is ignored.
588 const first_nul = std.mem.indexOfScalar(u8, decoded, 0) orelse {
589 try s.reply(501, "5.5.2 Malformed PLAIN response");
590 return .rejected;
591 };
592 const after_authzid = decoded[first_nul + 1 ..];
593 const second_nul = std.mem.indexOfScalar(u8, after_authzid, 0) orelse {
594 try s.reply(501, "5.5.2 Malformed PLAIN response");
595 return .rejected;
596 };
597 return s.finishAuth(callback, after_authzid[0..second_nul], after_authzid[second_nul + 1 ..]);
598 }
599
600 if (std.ascii.eqlIgnoreCase(args.mechanism, "LOGIN")) {
601 var user_buf: [192]u8 = undefined;
602 var pass_buf: [192]u8 = undefined;
603
604 var username: []const u8 = undefined;
605 if (args.initial.len > 0) {
606 // Some clients send the username as an initial response.
607 username = decodeBase64(&user_buf, args.initial) orelse {
608 try s.reply(501, "5.5.2 Invalid base64");
609 return .rejected;
610 };
611 } else {
612 try s.reply(334, "VXNlcm5hbWU6"); // base64("Username:")
613 const line = switch (try s.takeAuthLine()) {
614 .line => |line| line,
615 .cancelled => return .rejected,
616 .disconnected => return .disconnected,
617 };
618 username = decodeBase64(&user_buf, line) orelse {
619 try s.reply(501, "5.5.2 Invalid base64");
620 return .rejected;
621 };
622 }
623 try s.reply(334, "UGFzc3dvcmQ6"); // base64("Password:")
624 const line = switch (try s.takeAuthLine()) {
625 .line => |line| line,
626 .cancelled => return .rejected,
627 .disconnected => return .disconnected,
628 };
629 const password = decodeBase64(&pass_buf, line) orelse {
630 try s.reply(501, "5.5.2 Invalid base64");
631 return .rejected;
632 };
633 return s.finishAuth(callback, username, password);
634 }
635
636 try s.reply(504, "5.5.4 Unrecognized authentication type");
637 return .rejected;
638}
639
640fn finishAuth(
641 s: *Server,
642 callback: *const fn (?*anyopaque, []const u8, []const u8) bool,
643 username: []const u8,
644 password: []const u8,
645) RunError!AuthOutcome {
646 if (callback(s.handler.context, username, password)) {
647 try s.reply(235, "2.7.0 Authentication successful");
648 return .authenticated;
649 }
650 try s.reply(535, "5.7.8 Authentication credentials invalid");
651 return .rejected;
652}
653
654const AuthLine = union(enum) { line: []u8, cancelled, disconnected };
655
656/// Reads one continuation line of an AUTH exchange. `cancelled` covers both
657/// an explicit "*" and an overlong line; its reply has already been sent.
658fn takeAuthLine(s: *Server) RunError!AuthLine {
659 const line = protocol.readLine(s.reader) catch |err| switch (err) {
660 error.EndOfStream => return .disconnected,
661 error.ReadFailed => return error.ReadFailed,
662 error.LineTooLong => {
663 try s.discardLine();
664 try s.reply(501, "5.5.2 Response too long");
665 return .cancelled;
666 },
667 };
668 if (std.mem.eql(u8, line, "*")) {
669 try s.reply(501, "5.7.0 Authentication cancelled");
670 return .cancelled;
671 }
672 return .{ .line = line };
673}
674
675/// Decodes a base64 AUTH argument; "=" denotes an empty response.
676fn decodeBase64(out: []u8, encoded: []const u8) ?[]u8 {
677 if (std.mem.eql(u8, encoded, "=")) return out[0..0];
678 const len = std.base64.standard.Decoder.calcSizeForSlice(encoded) catch return null;
679 if (len > out.len) return null;
680 std.base64.standard.Decoder.decode(out[0..len], encoded) catch return null;
681 return out[0..len];
682}
683
684const ChunkOutcome = enum { done, end_session };
685
686/// Receives a message sent with BDAT chunks (RFC 3030 CHUNKING), starting
687/// from the already-parsed first chunk header. Chunk data is raw: no
688/// dot-stuffing and no line-ending normalization.
689fn receiveChunked(
690 s: *Server,
691 arena: std.mem.Allocator,
692 envelope: Envelope,
693 first: protocol.Command.BdatArgs,
694) RunError!ChunkOutcome {
695 if (s.handler.vtable.messageReader) |callback| {
696 var buffer: [1024]u8 = undefined;
697 var bdat_reader: BdatReader = .{
698 .server = s,
699 .remaining = first.size,
700 .last = first.last,
701 .interface = .{
702 .buffer = &buffer,
703 .vtable = &.{ .stream = BdatReader.stream },
704 .seek = 0,
705 .end = 0,
706 },
707 };
708 const decision = callback(s.handler.context, envelope, &bdat_reader.interface);
709 if (bdat_reader.abort == null and !bdat_reader.finished) {
710 // Consume whatever the callback left unread, through LAST.
711 var discard_buf: [256]u8 = undefined;
712 var discarding: Io.Writer.Discarding = .init(&discard_buf);
713 _ = bdat_reader.interface.streamRemaining(&discarding.writer) catch {};
714 }
715 if (bdat_reader.abort) |abort| switch (abort) {
716 .rset, .protocol => return .done, // Replies already sent.
717 .quit, .disconnected => return .end_session,
718 .transport_failure => return error.ReadFailed,
719 };
720 try s.replyMessage(envelope, decision);
721 return .done;
722 }
723
724 var data: std.ArrayList(u8) = .empty;
725 var oversize = false;
726 var size = first.size;
727 var last = first.last;
728 while (true) {
729 var left = size;
730 while (left > 0) {
731 const available = s.reader.peekGreedy(1) catch |err| switch (err) {
732 error.EndOfStream => return .end_session,
733 error.ReadFailed => return error.ReadFailed,
734 };
735 const n: usize = @intCast(@min(@as(u64, available.len), left));
736 if (!oversize) {
737 if (data.items.len + n > s.options.max_message_size) {
738 oversize = true;
739 } else {
740 try data.appendSlice(arena, available[0..n]);
741 }
742 }
743 s.reader.toss(n);
744 left -= n;
745 }
746 if (last) break;
747 try s.reply(250, "2.0.0 Chunk received");
748 const line = protocol.readLine(s.reader) catch |err| switch (err) {
749 error.EndOfStream => return .end_session,
750 error.ReadFailed => return error.ReadFailed,
751 error.LineTooLong => {
752 try s.discardLine();
753 try s.reply(500, "5.5.2 Line too long");
754 return .done; // Transaction aborted.
755 },
756 };
757 const command = protocol.Command.parse(line) catch {
758 try s.reply(501, "5.5.4 Syntax error in parameters");
759 return .done;
760 };
761 switch (command) {
762 .bdat => |b| {
763 size = b.size;
764 last = b.last;
765 },
766 .rset => {
767 try s.reply(250, "2.0.0 Ok");
768 return .done;
769 },
770 .quit => {
771 try s.reply(221, "2.0.0 Bye");
772 if (s.secured) s.tls_connection.close() catch {};
773 return .end_session;
774 },
775 else => {
776 try s.reply(503, "5.5.1 BDAT expected");
777 return .done;
778 },
779 }
780 }
781 if (oversize) {
782 try s.reply(552, "5.3.4 Message exceeds maximum size");
783 return .done;
784 }
785 try s.replyMessage(envelope, s.handler.vtable.message.?(s.handler.context, envelope, data.items));
786 return .done;
787}
788
789/// Adapts a BDAT chunk sequence into an `Io.Reader` of the raw message
790/// content for `Handler.VTable.messageReader`, replying 250 between chunks
791/// and following the chunk headers as they arrive.
792const BdatReader = struct {
793 server: *Server,
794 interface: Io.Reader,
795 remaining: u64,
796 last: bool,
797 finished: bool = false,
798 abort: ?Abort = null,
799
800 const Abort = enum { rset, quit, protocol, disconnected, transport_failure };
801
802 fn stream(io_r: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize {
803 const br: *BdatReader = @alignCast(@fieldParentPtr("interface", io_r));
804 const s = br.server;
805 while (br.remaining == 0) {
806 if (br.last) {
807 br.finished = true;
808 return error.EndOfStream;
809 }
810 s.reply(250, "2.0.0 Chunk received") catch {
811 br.abort = .transport_failure;
812 return error.ReadFailed;
813 };
814 const line = protocol.readLine(s.reader) catch |err| {
815 switch (err) {
816 error.EndOfStream => br.abort = .disconnected,
817 error.ReadFailed => br.abort = .transport_failure,
818 error.LineTooLong => {
819 s.discardLine() catch {};
820 s.reply(500, "5.5.2 Line too long") catch {};
821 br.abort = .protocol;
822 },
823 }
824 return error.ReadFailed;
825 };
826 const command = protocol.Command.parse(line) catch {
827 s.reply(501, "5.5.4 Syntax error in parameters") catch {};
828 br.abort = .protocol;
829 return error.ReadFailed;
830 };
831 switch (command) {
832 .bdat => |b| {
833 br.remaining = b.size;
834 br.last = b.last;
835 },
836 .rset => {
837 s.reply(250, "2.0.0 Ok") catch {};
838 br.abort = .rset;
839 return error.ReadFailed;
840 },
841 .quit => {
842 s.reply(221, "2.0.0 Bye") catch {};
843 if (s.secured) s.tls_connection.close() catch {};
844 br.abort = .quit;
845 return error.ReadFailed;
846 },
847 else => {
848 s.reply(503, "5.5.1 BDAT expected") catch {};
849 br.abort = .protocol;
850 return error.ReadFailed;
851 },
852 }
853 }
854 const available = s.reader.peekGreedy(1) catch |err| switch (err) {
855 error.EndOfStream => {
856 br.abort = .disconnected;
857 return error.ReadFailed;
858 },
859 error.ReadFailed => {
860 br.abort = .transport_failure;
861 return error.ReadFailed;
862 },
863 };
864 const dest = limit.slice(try w.writableSliceGreedy(1));
865 const n: usize = @intCast(@min(@min(@as(u64, available.len), @as(u64, dest.len)), br.remaining));
866 @memcpy(dest[0..n], available[0..n]);
867 s.reader.toss(n);
868 br.remaining -= n;
869 w.advance(n);
870 return n;
871 }
872};
873
874/// Reads message content after DATA up to the terminating ".\r\n",
875/// un-stuffing dots, then asks the handler to accept or reject.
876fn receiveData(s: *Server, arena: std.mem.Allocator, envelope: Envelope) RunError!void {
877 try s.reply(354, "End data with <CR><LF>.<CR><LF>");
878
879 if (s.handler.vtable.messageReader) |callback| {
880 var buffer: [1024]u8 = undefined;
881 var data_reader: DataReader = .{
882 .session_reader = s.reader,
883 .interface = .{
884 .buffer = &buffer,
885 .vtable = &.{ .stream = DataReader.stream },
886 .seek = 0,
887 .end = 0,
888 },
889 };
890 const decision = callback(s.handler.context, envelope, &data_reader.interface);
891 // Consume whatever the callback left unread, up to and including
892 // the terminating ".".
893 while (!data_reader.finished) {
894 const line = protocol.readLine(s.reader) catch |err| switch (err) {
895 error.EndOfStream => return, // Client disconnected mid-message.
896 error.ReadFailed => return error.ReadFailed,
897 error.LineTooLong => {
898 try s.discardLine();
899 continue;
900 },
901 };
902 if (std.mem.eql(u8, line, ".")) break;
903 }
904 try s.replyMessage(envelope, decision);
905 return;
906 }
907
908 var data: std.ArrayList(u8) = .empty;
909 var oversize = false;
910 while (true) {
911 const line = protocol.readLine(s.reader) catch |err| switch (err) {
912 error.EndOfStream => return, // Client disconnected mid-message.
913 error.ReadFailed => return error.ReadFailed,
914 error.LineTooLong => {
915 // Longer than our reader buffer; RFC 5321 caps text lines at
916 // 1000 octets, so treat it as oversize but keep scanning for
917 // the terminator.
918 try s.discardLine();
919 oversize = true;
920 continue;
921 },
922 };
923 if (std.mem.eql(u8, line, ".")) break;
924 const content = if (line.len > 0 and line[0] == '.') line[1..] else line;
925 if (oversize) continue;
926 if (data.items.len + content.len + protocol.crlf.len > s.options.max_message_size) {
927 oversize = true;
928 continue;
929 }
930 try data.appendSlice(arena, content);
931 try data.appendSlice(arena, protocol.crlf);
932 }
933 if (oversize) {
934 try s.reply(552, "5.3.4 Message exceeds maximum size");
935 return;
936 }
937 try s.replyMessage(envelope, s.handler.vtable.message.?(s.handler.context, envelope, data.items));
938}
939
940/// Adapts the session's line-based DATA phase into an `Io.Reader` of the
941/// unstuffed message content for `Handler.VTable.messageReader`.
942const DataReader = struct {
943 session_reader: *Io.Reader,
944 interface: Io.Reader,
945 /// Unread remainder of the current line (points into the session
946 /// reader's buffer, which only this reader touches during DATA).
947 line: []const u8 = &.{},
948 line_ending: []const u8 = &.{},
949 finished: bool = false,
950
951 fn stream(io_r: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize {
952 const dr: *DataReader = @alignCast(@fieldParentPtr("interface", io_r));
953 if (dr.line.len == 0 and dr.line_ending.len == 0) {
954 if (dr.finished) return error.EndOfStream;
955 const raw = protocol.readLine(dr.session_reader) catch return error.ReadFailed;
956 if (std.mem.eql(u8, raw, ".")) {
957 dr.finished = true;
958 return error.EndOfStream;
959 }
960 dr.line = if (raw.len > 0 and raw[0] == '.') raw[1..] else raw;
961 dr.line_ending = protocol.crlf;
962 }
963 const dest = limit.slice(try w.writableSliceGreedy(1));
964 const line_n = @min(dest.len, dr.line.len);
965 @memcpy(dest[0..line_n], dr.line[0..line_n]);
966 dr.line = dr.line[line_n..];
967 var n = line_n;
968 if (dr.line.len == 0) {
969 const ending_n = @min(dest.len - n, dr.line_ending.len);
970 @memcpy(dest[n..][0..ending_n], dr.line_ending[0..ending_n]);
971 dr.line_ending = dr.line_ending[ending_n..];
972 n += ending_n;
973 }
974 w.advance(n);
975 return n;
976 }
977};
978
979/// Enforces RFC 6531: a non-ASCII envelope address is only allowed when
980/// the transaction requested SMTPUTF8, and must be well-formed UTF-8.
981/// Replies and returns false on rejection.
982fn validateAddress(s: *Server, path: []const u8, smtputf8: bool) error{WriteFailed}!bool {
983 for (path) |byte| {
984 if (byte >= 0x80) {
985 if (!smtputf8) {
986 try s.reply(553, "5.6.7 Non-ASCII address requires SMTPUTF8");
987 return false;
988 }
989 if (!std.unicode.utf8ValidateSlice(path)) {
990 try s.reply(553, "5.6.7 Address is not valid UTF-8");
991 return false;
992 }
993 return true;
994 }
995 }
996 return true;
997}
998
999fn reply(s: *Server, code: u16, text: []const u8) error{WriteFailed}!void {
1000 try s.replyLine(code, text);
1001 try s.writer.flush();
1002}
1003
1004/// A reply without the flush, for when several are going out together.
1005fn replyLine(s: *Server, code: u16, text: []const u8) error{WriteFailed}!void {
1006 try s.writer.print("{d} {s}" ++ protocol.crlf, .{ code, text });
1007}
1008
1009/// Answers a completed message.
1010///
1011/// SMTP gets one reply. LMTP gets one for each previously successful RCPT,
1012/// in the order they were issued
1013/// ([RFC 2033 §4.2](https://datatracker.ietf.org/doc/html/rfc2033#section-4.2))
1014/// — including a repeat for a recipient named twice, which is why this
1015/// walks the accepted list rather than a set of addresses.
1016fn replyMessage(s: *Server, envelope: Envelope, decision: Decision) error{WriteFailed}!void {
1017 if (s.options.protocol == .smtp) {
1018 try s.writeVerdict(decision);
1019 try s.writer.flush();
1020 return;
1021 }
1022 for (envelope.recipients, 0..) |_, index| {
1023 // A rejected message is rejected for everybody; there is nothing
1024 // left to ask about an individual recipient.
1025 const verdict: Decision = switch (decision) {
1026 .reject => decision,
1027 .accept => if (s.handler.vtable.recipientResult) |callback|
1028 callback(s.handler.context, envelope, index)
1029 else
1030 .accept,
1031 };
1032 try s.writeVerdict(verdict);
1033 }
1034 try s.writer.flush();
1035}
1036
1037fn writeVerdict(s: *Server, decision: Decision) error{WriteFailed}!void {
1038 switch (decision) {
1039 .accept => try s.replyLine(250, "2.0.0 Ok, message accepted"),
1040 .reject => |r| try s.replyLine(r.code, r.text),
1041 }
1042}
1043
1044/// Discards input through the next newline after `error.LineTooLong`, which
1045/// leaves the reader positioned at the start of the oversized line.
1046fn discardLine(s: *Server) error{ReadFailed}!void {
1047 _ = s.reader.discardDelimiterInclusive('\n') catch |err| switch (err) {
1048 error.EndOfStream => {},
1049 error.ReadFailed => return error.ReadFailed,
1050 };
1051}
1052
1053const TestHandler = struct {
1054 from: std.ArrayList(u8) = .empty,
1055 recipients: std.ArrayList(u8) = .empty,
1056 data: std.ArrayList(u8) = .empty,
1057 messages_accepted: usize = 0,
1058 reject_recipient: ?[]const u8 = null,
1059 /// Accepted at RCPT time and then failed per-recipient at the end of
1060 /// the message, which only LMTP can express.
1061 fail_delivery: ?[]const u8 = null,
1062 /// Returned for the message as a whole, before any per-recipient
1063 /// verdict is asked for.
1064 reject_message: ?Decision.Rejection = null,
1065 declared_size: ?u64 = null,
1066 body: Envelope.Body = .unspecified,
1067 smtputf8: bool = false,
1068 /// DSN parameters, kept from the last RCPT and the last message. The
1069 /// strings are copied because everything a callback is handed lives
1070 /// only for the duration of the call.
1071 last_notify: ?protocol.Notify = null,
1072 last_orcpt: bool = false,
1073 last_orcpt_type: std.ArrayList(u8) = .empty,
1074 last_orcpt_address: std.ArrayList(u8) = .empty,
1075 ret: ?protocol.Ret = null,
1076 envid: std.ArrayList(u8) = .empty,
1077 /// When set, enables the authenticate callback accepting user "alice"
1078 /// with this password.
1079 password: ?[]const u8 = null,
1080
1081 fn deinit(h: *TestHandler) void {
1082 h.from.deinit(std.testing.allocator);
1083 h.recipients.deinit(std.testing.allocator);
1084 h.data.deinit(std.testing.allocator);
1085 h.envid.deinit(std.testing.allocator);
1086 h.last_orcpt_type.deinit(std.testing.allocator);
1087 h.last_orcpt_address.deinit(std.testing.allocator);
1088 }
1089
1090 fn handler(h: *TestHandler) Handler {
1091 return .{ .context = h, .vtable = if (h.password != null) &.{
1092 .authenticate = onAuthenticate,
1093 .rcptTo = onRcptTo,
1094 .message = onMessage,
1095 .recipientResult = onRecipientResult,
1096 } else &.{
1097 .rcptTo = onRcptTo,
1098 .message = onMessage,
1099 .recipientResult = onRecipientResult,
1100 } };
1101 }
1102
1103 /// LMTP's per-recipient verdict: everybody is fine except the one
1104 /// address `fail_delivery` names, which is the outcome that has no
1105 /// spelling in SMTP.
1106 fn onRecipientResult(context: ?*anyopaque, envelope: Envelope, index: usize) Decision {
1107 const h: *TestHandler = @ptrCast(@alignCast(context.?));
1108 const failing = h.fail_delivery orelse return .accept;
1109 if (std.mem.eql(u8, envelope.recipients[index].address, failing))
1110 return .{ .reject = .{ .code = 550, .text = "5.2.1 Mailbox disabled" } };
1111 return .accept;
1112 }
1113
1114 fn onAuthenticate(context: ?*anyopaque, username: []const u8, password: []const u8) bool {
1115 const h: *TestHandler = @ptrCast(@alignCast(context.?));
1116 return std.mem.eql(u8, username, "alice") and
1117 std.mem.eql(u8, password, h.password.?);
1118 }
1119
1120 fn onRcptTo(context: ?*anyopaque, recipient: Recipient) Decision {
1121 const h: *TestHandler = @ptrCast(@alignCast(context.?));
1122 h.last_notify = recipient.notify;
1123 if (recipient.orcpt) |orcpt| {
1124 const gpa = std.testing.allocator;
1125 h.last_orcpt = true;
1126 h.last_orcpt_type.appendSlice(gpa, orcpt.addr_type) catch return .{ .reject = .{} };
1127 h.last_orcpt_address.appendSlice(gpa, orcpt.address) catch return .{ .reject = .{} };
1128 }
1129 if (h.reject_recipient) |rejected| {
1130 if (std.mem.eql(u8, recipient.address, rejected)) return .{ .reject = .{
1131 .code = 550,
1132 .text = "5.1.1 No such user",
1133 } };
1134 }
1135 return .accept;
1136 }
1137
1138 fn onMessage(context: ?*anyopaque, envelope: Envelope, data: []const u8) Decision {
1139 const h: *TestHandler = @ptrCast(@alignCast(context.?));
1140 if (h.reject_message) |rejection| return .{ .reject = rejection };
1141 const gpa = std.testing.allocator;
1142 h.from.appendSlice(gpa, envelope.from) catch return .{ .reject = .{} };
1143 for (envelope.recipients) |recipient| {
1144 h.recipients.appendSlice(gpa, recipient.address) catch return .{ .reject = .{} };
1145 h.recipients.append(gpa, ';') catch return .{ .reject = .{} };
1146 }
1147 h.data.appendSlice(gpa, data) catch return .{ .reject = .{} };
1148 h.messages_accepted += 1;
1149 h.declared_size = envelope.declared_size;
1150 h.body = envelope.body;
1151 h.smtputf8 = envelope.smtputf8;
1152 h.ret = envelope.ret;
1153 if (envelope.envid) |envid| h.envid.appendSlice(gpa, envid) catch return .{ .reject = .{} };
1154 return .accept;
1155 }
1156};
1157
1158fn runScript(input: []const u8, out_buf: []u8, handler: Handler, options: Options) ![]const u8 {
1159 var reader: Io.Reader = .fixed(input);
1160 var writer: Io.Writer = .fixed(out_buf);
1161 var session: Server = .init(&reader, &writer, handler, options);
1162 try session.run(std.testing.allocator);
1163 return writer.buffered();
1164}
1165
1166test "LMTP answers once per accepted recipient" {
1167 var h: TestHandler = .{ .fail_delivery = "bad@example.net" };
1168 defer h.deinit();
1169
1170 var out_buf: [2048]u8 = undefined;
1171 const out = try runScript(
1172 "LHLO client.example.org\r\n" ++
1173 "MAIL FROM:<alice@example.com>\r\n" ++
1174 "RCPT TO:<good@example.net>\r\n" ++
1175 "RCPT TO:<bad@example.net>\r\n" ++
1176 // RFC 2033 §4.2 is explicit that a repeated forward-path still
1177 // gets a reply of its own.
1178 "RCPT TO:<good@example.net>\r\n" ++
1179 "DATA\r\nhi\r\n.\r\nQUIT\r\n",
1180 &out_buf,
1181 h.handler(),
1182 .{ .protocol = .lmtp, .hostname = "mx.test" },
1183 );
1184
1185 const tail = out[std.mem.indexOf(u8, out, "354").?..];
1186 try std.testing.expectEqualStrings(
1187 "354 End data with <CR><LF>.<CR><LF>\r\n" ++
1188 "250 2.0.0 Ok, message accepted\r\n" ++
1189 "550 5.2.1 Mailbox disabled\r\n" ++
1190 "250 2.0.0 Ok, message accepted\r\n" ++
1191 "221 2.0.0 Bye\r\n",
1192 tail,
1193 );
1194}
1195
1196test "a message rejected outright is rejected for every LMTP recipient" {
1197 var h: TestHandler = .{
1198 .reject_message = .{ .code = 452, .text = "4.3.1 Out of storage" },
1199 };
1200 defer h.deinit();
1201
1202 var out_buf: [2048]u8 = undefined;
1203 const out = try runScript(
1204 "LHLO client.example.org\r\n" ++
1205 "MAIL FROM:<alice@example.com>\r\n" ++
1206 "RCPT TO:<a@example.net>\r\n" ++
1207 "RCPT TO:<b@example.net>\r\n" ++
1208 "DATA\r\nhi\r\n.\r\nQUIT\r\n",
1209 &out_buf,
1210 h.handler(),
1211 .{ .protocol = .lmtp, .hostname = "mx.test" },
1212 );
1213
1214 const tail = out[std.mem.indexOf(u8, out, "354").?..];
1215 try std.testing.expectEqualStrings(
1216 "354 End data with <CR><LF>.<CR><LF>\r\n" ++
1217 "452 4.3.1 Out of storage\r\n" ++
1218 "452 4.3.1 Out of storage\r\n" ++
1219 "221 2.0.0 Bye\r\n",
1220 tail,
1221 );
1222}
1223
1224test "BDAT LAST also answers once per LMTP recipient" {
1225 var h: TestHandler = .{ .fail_delivery = "bad@example.net" };
1226 defer h.deinit();
1227
1228 var out_buf: [2048]u8 = undefined;
1229 const out = try runScript(
1230 "LHLO client.example.org\r\n" ++
1231 "MAIL FROM:<alice@example.com>\r\n" ++
1232 "RCPT TO:<good@example.net>\r\n" ++
1233 "RCPT TO:<bad@example.net>\r\n" ++
1234 "BDAT 4 LAST\r\nhi\r\nQUIT\r\n",
1235 &out_buf,
1236 h.handler(),
1237 .{ .protocol = .lmtp, .hostname = "mx.test" },
1238 );
1239
1240 const tail = out[std.mem.lastIndexOf(u8, out, "250 2.1.5 Ok\r\n").? + "250 2.1.5 Ok\r\n".len ..];
1241 try std.testing.expectEqualStrings(
1242 "250 2.0.0 Ok, message accepted\r\n" ++
1243 "550 5.2.1 Mailbox disabled\r\n" ++
1244 "221 2.0.0 Bye\r\n",
1245 tail,
1246 );
1247}
1248
1249test "each protocol refuses the other's greeting" {
1250 var h: TestHandler = .{};
1251 defer h.deinit();
1252
1253 var out_buf: [2048]u8 = undefined;
1254 // RFC 2033 §4: an LMTP server must not answer HELO or EHLO positively.
1255 const lmtp = try runScript(
1256 "EHLO client.example.org\r\nHELO client.example.org\r\nQUIT\r\n",
1257 &out_buf,
1258 h.handler(),
1259 .{ .protocol = .lmtp, .hostname = "mx.test" },
1260 );
1261 try std.testing.expectEqualStrings(
1262 "220 mx.test ESMTP ready\r\n" ++
1263 "500 5.5.1 This is LMTP, use LHLO\r\n" ++
1264 "500 5.5.1 This is LMTP, use LHLO\r\n" ++
1265 "221 2.0.0 Bye\r\n",
1266 lmtp,
1267 );
1268
1269 var smtp_buf: [2048]u8 = undefined;
1270 const smtp = try runScript(
1271 "LHLO client.example.org\r\nQUIT\r\n",
1272 &smtp_buf,
1273 h.handler(),
1274 .{ .hostname = "mx.test" },
1275 );
1276 try std.testing.expectEqualStrings(
1277 "220 mx.test ESMTP ready\r\n" ++
1278 "500 5.5.2 Command not recognized\r\n" ++
1279 "221 2.0.0 Bye\r\n",
1280 smtp,
1281 );
1282}
1283
1284test "LHLO advertises what LMTP requires" {
1285 var h: TestHandler = .{};
1286 defer h.deinit();
1287
1288 var out_buf: [2048]u8 = undefined;
1289 const out = try runScript(
1290 "LHLO client.example.org\r\nQUIT\r\n",
1291 &out_buf,
1292 h.handler(),
1293 .{ .protocol = .lmtp, .hostname = "mx.test" },
1294 );
1295 // RFC 2033 §5 requires both of these of an LMTP server.
1296 try std.testing.expect(std.mem.indexOf(u8, out, "250-PIPELINING\r\n") != null);
1297 try std.testing.expect(std.mem.indexOf(u8, out, "250-ENHANCEDSTATUSCODES\r\n") != null);
1298}
1299
1300test "DSN parameters reach the handler" {
1301 var h: TestHandler = .{};
1302 defer h.deinit();
1303
1304 var out_buf: [2048]u8 = undefined;
1305 const out = try runScript(
1306 "EHLO client.example.org\r\n" ++
1307 "MAIL FROM:<alice@example.com> RET=HDRS ENVID=batch+207\r\n" ++
1308 "RCPT TO:<bob@example.net> NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;team@example.net\r\n" ++
1309 "DATA\r\nhi\r\n.\r\nQUIT\r\n",
1310 &out_buf,
1311 h.handler(),
1312 .{ .hostname = "mx.test" },
1313 );
1314
1315 // Nothing in the session was refused.
1316 try std.testing.expect(std.mem.indexOf(u8, out, "\r\n5") == null);
1317 try std.testing.expectEqual(protocol.Ret.hdrs, h.ret.?);
1318 // The ENVID arrives xtext-decoded: "batch+207" carried a space.
1319 try std.testing.expectEqualStrings("batch 7", h.envid.items);
1320 const notify = h.last_notify.?;
1321 try std.testing.expect(notify.on.success and notify.on.failure and !notify.on.delay);
1322 try std.testing.expect(h.last_orcpt);
1323 try std.testing.expectEqualStrings("rfc822", h.last_orcpt_type.items);
1324 try std.testing.expectEqualStrings("team@example.net", h.last_orcpt_address.items);
1325}
1326
1327test "the DSN extension is advertised and its parameters are validated" {
1328 var h: TestHandler = .{};
1329 defer h.deinit();
1330
1331 var out_buf: [2048]u8 = undefined;
1332 const out = try runScript(
1333 "EHLO client.example.org\r\n" ++
1334 "MAIL FROM:<a@example.com> RET=PARTIAL\r\n" ++ // 501: not FULL or HDRS
1335 "MAIL FROM:<a@example.com> ENVID=bad+ZZ\r\n" ++ // 501: not xtext
1336 "MAIL FROM:<a@example.com> ENVID=" ++ ("x" ** 101) ++ "\r\n" ++ // 501: too long
1337 "MAIL FROM:<a@example.com>\r\n" ++
1338 "RCPT TO:<b@example.net> NOTIFY=NEVER,SUCCESS\r\n" ++ // 501: NEVER stands alone
1339 "RCPT TO:<b@example.net> NOTIFY=SOMETIMES\r\n" ++ // 501: not a keyword
1340 "RCPT TO:<b@example.net> ORCPT=team@example.net\r\n" ++ // 501: no addr-type
1341 "RCPT TO:<b@example.net> FROB=1\r\n" ++ // 555: still unrecognized
1342 "QUIT\r\n",
1343 &out_buf,
1344 h.handler(),
1345 .{ .hostname = "mx.test" },
1346 );
1347
1348 try std.testing.expect(std.mem.indexOf(u8, out, "250-DSN\r\n") != null);
1349 var replies = std.mem.splitSequence(u8, out, "\r\n");
1350 var codes: std.ArrayList([]const u8) = .empty;
1351 defer codes.deinit(std.testing.allocator);
1352 while (replies.next()) |line| {
1353 if (line.len >= 4 and line[3] == ' ') try codes.append(std.testing.allocator, line[0..3]);
1354 }
1355 // 220 greeting, 250 EHLO, then the parameter verdicts, then 221.
1356 try std.testing.expectEqualStrings("220", codes.items[0]);
1357 try std.testing.expectEqualStrings("250", codes.items[1]);
1358 try std.testing.expectEqualStrings("501", codes.items[2]);
1359 try std.testing.expectEqualStrings("501", codes.items[3]);
1360 try std.testing.expectEqualStrings("501", codes.items[4]);
1361 try std.testing.expectEqualStrings("250", codes.items[5]);
1362 try std.testing.expectEqualStrings("501", codes.items[6]);
1363 try std.testing.expectEqualStrings("501", codes.items[7]);
1364 try std.testing.expectEqualStrings("501", codes.items[8]);
1365 try std.testing.expectEqualStrings("555", codes.items[9]);
1366 try std.testing.expectEqualStrings("221", codes.items[10]);
1367}
1368
1369test run {
1370 var h: TestHandler = .{};
1371 defer h.deinit();
1372
1373 var reader: Io.Reader = .fixed("EHLO client.example.org\r\n" ++
1374 "MAIL FROM:<alice@example.com>\r\n" ++
1375 "RCPT TO:<bob@example.net>\r\n" ++
1376 "RCPT TO:<carol@example.net>\r\n" ++
1377 "DATA\r\n" ++
1378 "Subject: hi\r\n" ++
1379 "\r\n" ++
1380 "..stuffed line\r\n" ++
1381 "body\r\n" ++
1382 ".\r\n" ++
1383 "QUIT\r\n");
1384 var out_buf: [1024]u8 = undefined;
1385 var writer: Io.Writer = .fixed(&out_buf);
1386
1387 var session: Server = .init(&reader, &writer, h.handler(), .{ .hostname = "mx.test" });
1388 try session.run(std.testing.allocator);
1389 const output = writer.buffered();
1390
1391 try std.testing.expectEqualStrings("alice@example.com", h.from.items);
1392 try std.testing.expectEqualStrings("bob@example.net;carol@example.net;", h.recipients.items);
1393 try std.testing.expectEqualStrings("Subject: hi\r\n\r\n.stuffed line\r\nbody\r\n", h.data.items);
1394 try std.testing.expectEqual(@as(usize, 1), h.messages_accepted);
1395
1396 try std.testing.expectEqualStrings(
1397 "220 mx.test ESMTP ready\r\n" ++
1398 "250-mx.test\r\n250-PIPELINING\r\n250-8BITMIME\r\n250-CHUNKING\r\n250-SMTPUTF8\r\n250-ENHANCEDSTATUSCODES\r\n250-DSN\r\n250 SIZE 16777216\r\n" ++
1399 "250 2.1.0 Ok\r\n" ++
1400 "250 2.1.5 Ok\r\n" ++
1401 "250 2.1.5 Ok\r\n" ++
1402 "354 End data with <CR><LF>.<CR><LF>\r\n" ++
1403 "250 2.0.0 Ok, message accepted\r\n" ++
1404 "221 2.0.0 Bye\r\n",
1405 output,
1406 );
1407}
1408
1409test "command sequencing is enforced" {
1410 var h: TestHandler = .{};
1411 defer h.deinit();
1412
1413 var out_buf: [1024]u8 = undefined;
1414 const output = try runScript(
1415 "MAIL FROM:<early@example.com>\r\n" ++
1416 "EHLO client.example.org\r\n" ++
1417 "RCPT TO:<bob@example.net>\r\n" ++
1418 "DATA\r\n" ++
1419 "QUIT\r\n",
1420 &out_buf,
1421 h.handler(),
1422 .{},
1423 );
1424
1425 try std.testing.expectEqual(@as(usize, 0), h.messages_accepted);
1426 try std.testing.expect(std.mem.indexOf(u8, output, "503 5.5.1 Send EHLO first") != null);
1427 try std.testing.expect(std.mem.indexOf(u8, output, "503 5.5.1 Need MAIL command first") != null);
1428 try std.testing.expect(std.mem.indexOf(u8, output, "503 5.5.1 Need RCPT command first") != null);
1429}
1430
1431test "handler can reject a recipient" {
1432 var h: TestHandler = .{ .reject_recipient = "nobody@example.net" };
1433 defer h.deinit();
1434
1435 var out_buf: [1024]u8 = undefined;
1436 const output = try runScript(
1437 "EHLO client.example.org\r\n" ++
1438 "MAIL FROM:<alice@example.com>\r\n" ++
1439 "RCPT TO:<nobody@example.net>\r\n" ++
1440 "RCPT TO:<bob@example.net>\r\n" ++
1441 "DATA\r\n" ++
1442 "hello\r\n" ++
1443 ".\r\n" ++
1444 "QUIT\r\n",
1445 &out_buf,
1446 h.handler(),
1447 .{},
1448 );
1449
1450 try std.testing.expect(std.mem.indexOf(u8, output, "550 5.1.1 No such user") != null);
1451 try std.testing.expectEqualStrings("bob@example.net;", h.recipients.items);
1452 try std.testing.expectEqual(@as(usize, 1), h.messages_accepted);
1453}
1454
1455test "AUTH PLAIN with initial response" {
1456 var h: TestHandler = .{ .password = "secret" };
1457 defer h.deinit();
1458
1459 var out_buf: [1024]u8 = undefined;
1460 // base64("\x00alice\x00secret")
1461 const output = try runScript(
1462 "EHLO client.example.org\r\n" ++
1463 "AUTH PLAIN AGFsaWNlAHNlY3JldA==\r\n" ++
1464 "MAIL FROM:<alice@example.com>\r\n" ++
1465 "RCPT TO:<bob@example.net>\r\n" ++
1466 "DATA\r\nauthed mail\r\n.\r\n" ++
1467 "QUIT\r\n",
1468 &out_buf,
1469 h.handler(),
1470 .{ .require_auth = true },
1471 );
1472
1473 try std.testing.expect(std.mem.indexOf(u8, output, "250-AUTH PLAIN LOGIN\r\n") != null);
1474 try std.testing.expect(std.mem.indexOf(u8, output, "235 2.7.0") != null);
1475 try std.testing.expectEqual(@as(usize, 1), h.messages_accepted);
1476}
1477
1478test "AUTH LOGIN challenge exchange" {
1479 var h: TestHandler = .{ .password = "secret" };
1480 defer h.deinit();
1481
1482 var out_buf: [1024]u8 = undefined;
1483 // base64("alice"), base64("secret")
1484 const output = try runScript(
1485 "EHLO client.example.org\r\n" ++
1486 "AUTH LOGIN\r\n" ++
1487 "YWxpY2U=\r\n" ++
1488 "c2VjcmV0\r\n" ++
1489 "QUIT\r\n",
1490 &out_buf,
1491 h.handler(),
1492 .{},
1493 );
1494
1495 try std.testing.expect(std.mem.indexOf(u8, output, "334 VXNlcm5hbWU6\r\n") != null);
1496 try std.testing.expect(std.mem.indexOf(u8, output, "334 UGFzc3dvcmQ6\r\n") != null);
1497 try std.testing.expect(std.mem.indexOf(u8, output, "235 2.7.0") != null);
1498}
1499
1500test "AUTH failures and sequencing" {
1501 var h: TestHandler = .{ .password = "secret" };
1502 defer h.deinit();
1503
1504 var out_buf: [2048]u8 = undefined;
1505 const output = try runScript(
1506 "EHLO client.example.org\r\n" ++
1507 "MAIL FROM:<alice@example.com>\r\n" ++ // before auth: 530
1508 "AUTH PLAIN AGFsaWNlAHdyb25n\r\n" ++ // wrong password: 535
1509 "AUTH GSSAPI\r\n" ++ // unsupported: 504
1510 "AUTH PLAIN not!base64\r\n" ++ // 501
1511 "AUTH LOGIN\r\n" ++
1512 "*\r\n" ++ // cancelled: 501
1513 "AUTH PLAIN AGFsaWNlAHNlY3JldA==\r\n" ++ // correct: 235
1514 "AUTH PLAIN AGFsaWNlAHNlY3JldA==\r\n" ++ // again: 503
1515 "QUIT\r\n",
1516 &out_buf,
1517 h.handler(),
1518 .{ .require_auth = true },
1519 );
1520
1521 try std.testing.expect(std.mem.indexOf(u8, output, "530 5.7.0") != null);
1522 try std.testing.expect(std.mem.indexOf(u8, output, "535 5.7.8") != null);
1523 try std.testing.expect(std.mem.indexOf(u8, output, "504 5.5.4") != null);
1524 try std.testing.expect(std.mem.indexOf(u8, output, "501 5.5.2 Invalid base64") != null);
1525 try std.testing.expect(std.mem.indexOf(u8, output, "501 5.7.0 Authentication cancelled") != null);
1526 try std.testing.expect(std.mem.indexOf(u8, output, "235 2.7.0") != null);
1527 try std.testing.expect(std.mem.indexOf(u8, output, "503 5.5.1 Already authenticated") != null);
1528}
1529
1530test "AUTH without a handler is refused" {
1531 var h: TestHandler = .{};
1532 defer h.deinit();
1533
1534 var out_buf: [1024]u8 = undefined;
1535 const output = try runScript(
1536 "EHLO client.example.org\r\nAUTH PLAIN AGEAYg==\r\nQUIT\r\n",
1537 &out_buf,
1538 h.handler(),
1539 .{},
1540 );
1541
1542 try std.testing.expect(std.mem.indexOf(u8, output, "250-AUTH") == null);
1543 try std.testing.expect(std.mem.indexOf(u8, output, "503 5.5.1 Authentication not enabled") != null);
1544}
1545
1546test "oversize message is rejected but session continues" {
1547 var h: TestHandler = .{};
1548 defer h.deinit();
1549
1550 var out_buf: [1024]u8 = undefined;
1551 const output = try runScript(
1552 "EHLO client.example.org\r\n" ++
1553 "MAIL FROM:<alice@example.com>\r\n" ++
1554 "RCPT TO:<bob@example.net>\r\n" ++
1555 "DATA\r\n" ++
1556 "0123456789012345678901234567890123456789\r\n" ++
1557 ".\r\n" ++
1558 "NOOP\r\n" ++
1559 "QUIT\r\n",
1560 &out_buf,
1561 h.handler(),
1562 .{ .max_message_size = 16 },
1563 );
1564
1565 try std.testing.expectEqual(@as(usize, 0), h.messages_accepted);
1566 try std.testing.expect(std.mem.indexOf(u8, output, "552 5.3.4") != null);
1567 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok\r\n221") != null);
1568}
1569
1570const StreamTestHandler = struct {
1571 collected: std.ArrayList(u8) = .empty,
1572 take_only: ?usize = null,
1573
1574 fn handler(h: *StreamTestHandler) Handler {
1575 return .{ .context = h, .vtable = &.{
1576 .messageReader = onMessageReader,
1577 } };
1578 }
1579
1580 fn onMessageReader(context: ?*anyopaque, envelope: Envelope, message: *Io.Reader) Decision {
1581 const h: *StreamTestHandler = @ptrCast(@alignCast(context.?));
1582 _ = envelope;
1583 const gpa = std.testing.allocator;
1584 if (h.take_only) |n| {
1585 const bytes = message.take(n) catch return .{ .reject = .{} };
1586 h.collected.appendSlice(gpa, bytes) catch return .{ .reject = .{} };
1587 return .accept;
1588 }
1589 message.appendRemaining(gpa, &h.collected, .unlimited) catch return .{ .reject = .{} };
1590 return .accept;
1591 }
1592};
1593
1594test "streaming message handler receives unstuffed content" {
1595 var h: StreamTestHandler = .{};
1596 defer h.collected.deinit(std.testing.allocator);
1597
1598 var out_buf: [1024]u8 = undefined;
1599 const output = try runScript(
1600 "EHLO client.example.org\r\n" ++
1601 "MAIL FROM:<alice@example.com>\r\n" ++
1602 "RCPT TO:<bob@example.net>\r\n" ++
1603 "DATA\r\n" ++
1604 "Subject: streamed\r\n" ++
1605 "\r\n" ++
1606 "..dot line\r\n" ++
1607 "body\r\n" ++
1608 ".\r\n" ++
1609 "QUIT\r\n",
1610 &out_buf,
1611 h.handler(),
1612 .{},
1613 );
1614
1615 try std.testing.expectEqualStrings(
1616 "Subject: streamed\r\n\r\n.dot line\r\nbody\r\n",
1617 h.collected.items,
1618 );
1619 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok, message accepted") != null);
1620}
1621
1622test "session drains what a streaming handler leaves unread" {
1623 var h: StreamTestHandler = .{ .take_only = 7 };
1624 defer h.collected.deinit(std.testing.allocator);
1625
1626 var out_buf: [1024]u8 = undefined;
1627 const output = try runScript(
1628 "EHLO client.example.org\r\n" ++
1629 "MAIL FROM:<alice@example.com>\r\n" ++
1630 "RCPT TO:<bob@example.net>\r\n" ++
1631 "DATA\r\n" ++
1632 "Subject: mostly unread\r\n" ++
1633 "lots of body\r\n" ++
1634 ".\r\n" ++
1635 "NOOP\r\n" ++
1636 "QUIT\r\n",
1637 &out_buf,
1638 h.handler(),
1639 .{},
1640 );
1641
1642 try std.testing.expectEqualStrings("Subject", h.collected.items);
1643 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok, message accepted") != null);
1644 // The NOOP after DATA proves the terminator was consumed.
1645 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok\r\n221") != null);
1646}
1647
1648test "fuzz session with arbitrary client input" {
1649 try std.testing.fuzz({}, fuzzSession, .{});
1650}
1651
1652fn fuzzSession(context: void, smith: *std.testing.Smith) !void {
1653 _ = context;
1654 var input_buf: [2048]u8 = undefined;
1655 const input = input_buf[0..smith.value(u11)];
1656 smith.bytes(input);
1657
1658 var h: TestHandler = .{ .password = "secret" };
1659 defer h.deinit();
1660
1661 var reader: Io.Reader = .fixed(input);
1662 var discarding: Io.Writer.Discarding = .init(&.{});
1663 var session: Server = .init(&reader, &discarding.writer, h.handler(), .{
1664 .max_message_size = 512,
1665 .max_recipients = 4,
1666 });
1667 // Whatever the "client" sends, the session must fail cleanly, never crash.
1668 session.run(std.testing.allocator) catch {};
1669}
1670
1671test "fuzz collecting and streaming DATA agree" {
1672 try std.testing.fuzz({}, fuzzDataEquivalence, .{});
1673}
1674
1675fn fuzzDataEquivalence(context: void, smith: *std.testing.Smith) !void {
1676 _ = context;
1677 var body_buf: [1024]u8 = undefined;
1678 const body = body_buf[0..smith.value(u10)];
1679 smith.bytes(body);
1680
1681 var script_buf: [1200]u8 = undefined;
1682 const script = std.fmt.bufPrint(
1683 &script_buf,
1684 "EHLO fuzz.example.org\r\n" ++
1685 "MAIL FROM:<a@example.com>\r\n" ++
1686 "RCPT TO:<b@example.net>\r\n" ++
1687 "DATA\r\n{s}\r\n.\r\nQUIT\r\n",
1688 .{body},
1689 ) catch unreachable;
1690
1691 var collecting: TestHandler = .{};
1692 defer collecting.deinit();
1693 var out_buf: [4096]u8 = undefined;
1694 _ = runScript(script, &out_buf, collecting.handler(), .{}) catch {};
1695
1696 var streaming: StreamTestHandler = .{};
1697 defer streaming.collected.deinit(std.testing.allocator);
1698 _ = runScript(script, &out_buf, streaming.handler(), .{}) catch {};
1699
1700 try std.testing.expectEqualSlices(u8, collecting.data.items, streaming.collected.items);
1701}
1702
1703test "MAIL parameters SIZE and BODY are honored" {
1704 var h: TestHandler = .{};
1705 defer h.deinit();
1706
1707 var out_buf: [1024]u8 = undefined;
1708 const output = try runScript(
1709 "EHLO client.example.org\r\n" ++
1710 "MAIL FROM:<alice@example.com> SIZE=42 BODY=8BITMIME\r\n" ++
1711 "RCPT TO:<bob@example.net>\r\n" ++
1712 "DATA\r\nsized body\r\n.\r\n" ++
1713 "QUIT\r\n",
1714 &out_buf,
1715 h.handler(),
1716 .{ .max_message_size = 1024 },
1717 );
1718
1719 try std.testing.expectEqual(@as(usize, 1), h.messages_accepted);
1720 try std.testing.expectEqual(@as(?u64, 42), h.declared_size);
1721 try std.testing.expectEqual(Envelope.Body.eight_bit_mime, h.body);
1722 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.1.0 Ok") != null);
1723}
1724
1725test "invalid MAIL and RCPT parameters are rejected" {
1726 var h: TestHandler = .{};
1727 defer h.deinit();
1728
1729 var out_buf: [2048]u8 = undefined;
1730 const output = try runScript(
1731 "EHLO client.example.org\r\n" ++
1732 "MAIL FROM:<a@example.com> SIZE=9999\r\n" ++ // over the maximum: 552
1733 "RCPT TO:<b@example.net>\r\n" ++ // that MAIL never started: 503
1734 "MAIL FROM:<a@example.com> SIZE=banana\r\n" ++ // 501
1735 "MAIL FROM:<a@example.com> BODY=BINARYMIME\r\n" ++ // 555
1736 "MAIL FROM:<a@example.com> FUTURE=yes\r\n" ++ // 555
1737 "MAIL FROM:<a@example.com> BODY=7bit\r\n" ++ // ok
1738 "RCPT TO:<b@example.net> NOTIFY=SUCCESS\r\n" ++ // no RCPT params: 555
1739 "RCPT TO:<b@example.net>\r\n" ++
1740 "DATA\r\nbody\r\n.\r\nQUIT\r\n",
1741 &out_buf,
1742 h.handler(),
1743 .{ .max_message_size = 1024 },
1744 );
1745
1746 try std.testing.expect(std.mem.indexOf(u8, output, "552 5.3.4") != null);
1747 try std.testing.expect(std.mem.indexOf(u8, output, "503 5.5.1 Need MAIL command first") != null);
1748 try std.testing.expect(std.mem.indexOf(u8, output, "501 5.5.2 Invalid SIZE parameter") != null);
1749 try std.testing.expect(std.mem.indexOf(u8, output, "555 5.5.4 Unsupported BODY value") != null);
1750 try std.testing.expect(std.mem.indexOf(u8, output, "555 5.5.4 Unrecognized parameter") != null);
1751 try std.testing.expectEqual(@as(usize, 1), h.messages_accepted);
1752 try std.testing.expectEqual(Envelope.Body.seven_bit, h.body);
1753 try std.testing.expectEqual(@as(?u64, null), h.declared_size);
1754}
1755
1756test init {
1757 var reader: Io.Reader = .fixed("");
1758 var out_buf: [16]u8 = undefined;
1759 var writer: Io.Writer = .fixed(&out_buf);
1760 var h: TestHandler = .{};
1761 const session: Server = .init(&reader, &writer, h.handler(), .{ .hostname = "mx.test" });
1762 try std.testing.expectEqualStrings("mx.test", session.options.hostname);
1763 try std.testing.expect(!session.secured);
1764}
1765
1766test Options {
1767 const options: Options = .{};
1768 try std.testing.expectEqualStrings("localhost", options.hostname);
1769 try std.testing.expect(options.tls == null);
1770 try std.testing.expect(!options.require_auth);
1771}
1772
1773test Decision {
1774 const ok: Decision = .accept;
1775 try std.testing.expectEqual(Decision.accept, ok);
1776
1777 const no: Decision = .{ .reject = .{ .code = 451, .text = "4.3.0 Try again later" } };
1778 try std.testing.expectEqual(@as(u16, 451), no.reject.code);
1779}
1780
1781test Envelope {
1782 const envelope: Envelope = .{ .from = "", .recipients = &.{.{ .address = "a@example.com" }} };
1783 try std.testing.expectEqual(@as(usize, 1), envelope.recipients.len);
1784 try std.testing.expectEqual(@as(?u64, null), envelope.declared_size);
1785 try std.testing.expectEqual(Envelope.Body.unspecified, envelope.body);
1786}
1787
1788test Handler {
1789 const Callbacks = struct {
1790 fn onMessage(context: ?*anyopaque, envelope: Envelope, message_data: []const u8) Decision {
1791 _ = context;
1792 _ = envelope;
1793 _ = message_data;
1794 return .accept;
1795 }
1796 };
1797 const handler: Handler = .{ .vtable = &.{ .message = Callbacks.onMessage } };
1798 const envelope: Envelope = .{ .from = "", .recipients = &.{} };
1799 try std.testing.expectEqual(Decision.accept, handler.vtable.message.?(null, envelope, ""));
1800}
1801
1802// SPDX-SnippetBegin
1803// SPDX-SnippetCopyrightText: © The Exim Maintainers
1804// SPDX-SnippetCopyrightText: © University of Cambridge
1805// SPDX-SnippetCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>
1806// SPDX-License-Identifier: GPL-2.0-or-later
1807//
1808// The command dialogue and message lines below are adapted from exim's
1809// test suite (test/scripts/0000-Basic); the reply expectations are ours.
1810test "protocol gauntlet adapted from exim's test suite" {
1811 // Command sequences and dot-stuffing cases distilled from exim's
1812 // test/scripts/0000-Basic (notably 0019's SMTP syntax-error dialogue
1813 // and 0008/0100's dotted message lines), verified against this server
1814 // with exim's own scriptable test client.
1815 var h: TestHandler = .{};
1816 defer h.deinit();
1817
1818 var out_buf: [4096]u8 = undefined;
1819 const output = try runScript(
1820 "NOOP\r\n" ++
1821 "rhubarb\r\n" ++
1822 "mail from:<x@y>\r\n" ++
1823 "rcpt to:<a@b>\r\n" ++
1824 "ehlo test.client\r\n" ++
1825 "mail\r\n" ++
1826 "mail from:\r\n" ++
1827 "mail from:<>\r\n" ++
1828 "mail from:<x@y>\r\n" ++
1829 "rcpt to:\r\n" ++
1830 "data\r\n" ++
1831 "rset\r\n" ++
1832 "etrn abc\r\n" ++
1833 "vrfy userx\r\n" ++
1834 "help\r\n" ++
1835 "mail from:<ok@test1> SIZE=100 BODY=8BITMIME\r\n" ++
1836 "rcpt to:<userx@test.ex>\r\n" ++
1837 "rcpt to:<@relay.example:route@test.ex>\r\n" ++
1838 "data\r\n" ++
1839 "..that line started with a dot\r\n" ++
1840 ".. and one starting with two dots\r\n" ++
1841 "Message body\r\n" ++
1842 ".\r\n" ++
1843 "mail from:<a@b> SIZE=99999999\r\n" ++
1844 "mail from:<a@b> BODY=BINARYMIME\r\n" ++
1845 "mail from:<a@b> FOO=bar\r\n" ++
1846 "mail from:<a@b> SIZE=nan\r\n" ++
1847 "starttls\r\n" ++
1848 "mail from:<böb@test.ex>\r\n" ++
1849 "mail from:<a@b> SMTPUTF8=YES\r\n" ++
1850 "mail from:<böb@test.ex> SMTPUTF8\r\n" ++
1851 "rset\r\n" ++
1852 "BDAT 5\r\n" ++
1853 "abc\r\n" ++
1854 "mail from:<chunky@test.ex>\r\n" ++
1855 "rcpt to:<userx@test.ex>\r\n" ++
1856 "BDAT 7\r\n" ++
1857 "hello\r\n" ++
1858 "BDAT 23 LAST\r\n" ++
1859 "world of chunked mail\r\n" ++
1860 "quit\r\n",
1861 &out_buf,
1862 h.handler(),
1863 .{},
1864 );
1865
1866 try std.testing.expectEqualStrings(
1867 "220 localhost ESMTP ready\r\n" ++
1868 "250 2.0.0 Ok\r\n" ++
1869 "500 5.5.2 Command not recognized\r\n" ++
1870 "503 5.5.1 Send EHLO first\r\n" ++
1871 "503 5.5.1 Need MAIL command first\r\n" ++
1872 "250-localhost\r\n250-PIPELINING\r\n250-8BITMIME\r\n250-CHUNKING\r\n" ++
1873 "250-SMTPUTF8\r\n250-ENHANCEDSTATUSCODES\r\n250-DSN\r\n250 SIZE 16777216\r\n" ++
1874 "501 5.5.4 Syntax error in parameters\r\n" ++
1875 "501 5.5.4 Syntax error in parameters\r\n" ++
1876 "250 2.1.0 Ok\r\n" ++
1877 "503 5.5.1 Nested MAIL command\r\n" ++
1878 "501 5.5.4 Syntax error in parameters\r\n" ++
1879 "503 5.5.1 Need RCPT command first\r\n" ++
1880 "250 2.0.0 Ok\r\n" ++
1881 "500 5.5.2 Command not recognized\r\n" ++
1882 "252 2.5.2 Cannot VRFY user\r\n" ++
1883 "214 2.0.0 See RFC 5321\r\n" ++
1884 "250 2.1.0 Ok\r\n" ++
1885 "250 2.1.5 Ok\r\n" ++
1886 "250 2.1.5 Ok\r\n" ++
1887 "354 End data with <CR><LF>.<CR><LF>\r\n" ++
1888 "250 2.0.0 Ok, message accepted\r\n" ++
1889 "552 5.3.4 Message size exceeds fixed maximum\r\n" ++
1890 "555 5.5.4 Unsupported BODY value\r\n" ++
1891 "555 5.5.4 Unrecognized parameter\r\n" ++
1892 "501 5.5.2 Invalid SIZE parameter\r\n" ++
1893 "502 5.5.1 STARTTLS not supported\r\n" ++
1894 "553 5.6.7 Non-ASCII address requires SMTPUTF8\r\n" ++
1895 "501 5.5.4 SMTPUTF8 takes no value\r\n" ++
1896 "250 2.1.0 Ok\r\n" ++
1897 "250 2.0.0 Ok\r\n" ++
1898 "503 5.5.1 Need RCPT command first\r\n" ++
1899 "250 2.1.0 Ok\r\n" ++
1900 "250 2.1.5 Ok\r\n" ++
1901 "250 2.0.0 Chunk received\r\n" ++
1902 "250 2.0.0 Ok, message accepted\r\n" ++
1903 "221 2.0.0 Bye\r\n",
1904 output,
1905 );
1906 try std.testing.expectEqual(@as(usize, 2), h.messages_accepted);
1907 try std.testing.expectEqualStrings("ok@test1chunky@test.ex", h.from.items);
1908 try std.testing.expectEqualStrings(
1909 "userx@test.ex;route@test.ex;userx@test.ex;",
1910 h.recipients.items,
1911 );
1912 try std.testing.expectEqualStrings(
1913 ".that line started with a dot\r\n. and one starting with two dots\r\nMessage body\r\n" ++
1914 "hello\r\nworld of chunked mail\r\n",
1915 h.data.items,
1916 );
1917}
1918// SPDX-SnippetEnd
1919
1920test "BDAT chunks are reassembled without unstuffing" {
1921 var h: TestHandler = .{};
1922 defer h.deinit();
1923
1924 var out_buf: [1024]u8 = undefined;
1925 const output = try runScript(
1926 "EHLO client.example.org\r\n" ++
1927 "MAIL FROM:<alice@example.com>\r\n" ++
1928 "RCPT TO:<bob@example.net>\r\n" ++
1929 "BDAT 20\r\n" ++
1930 "Subject: chunked\r\n\r\n" ++ // exactly 20 raw octets
1931 "BDAT 18\r\n" ++
1932 ".dots stay\nas-is\r\n" ++ // 18 raw octets, no unstuffing
1933 "BDAT 0 LAST\r\n" ++
1934 "QUIT\r\n",
1935 &out_buf,
1936 h.handler(),
1937 .{},
1938 );
1939
1940 try std.testing.expectEqualStrings(
1941 "Subject: chunked\r\n\r\n.dots stay\nas-is\r\n",
1942 h.data.items,
1943 );
1944 try std.testing.expectEqual(@as(usize, 1), h.messages_accepted);
1945 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Chunk received") != null);
1946 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok, message accepted") != null);
1947}
1948
1949test "BDAT framing is length-based, not content-based" {
1950 var h: TestHandler = .{};
1951 defer h.deinit();
1952
1953 var out_buf: [1024]u8 = undefined;
1954 const output = try runScript(
1955 "EHLO client.example.org\r\n" ++
1956 // Without a transaction the chunk must still be consumed, or the
1957 // embedded commands would be executed.
1958 "BDAT 12\r\n" ++
1959 "QUIT\r\nRSET\r\n" ++
1960 "MAIL FROM:<alice@example.com>\r\n" ++
1961 "RCPT TO:<bob@example.net>\r\n" ++
1962 // A chunk whose payload looks like commands is still just data.
1963 "BDAT 23 LAST\r\n" ++
1964 "QUIT\r\nMAIL FROM:<x@y>\r\n" ++
1965 "QUIT\r\n",
1966 &out_buf,
1967 h.handler(),
1968 .{},
1969 );
1970
1971 try std.testing.expectEqualStrings("QUIT\r\nMAIL FROM:<x@y>\r\n", h.data.items);
1972 try std.testing.expect(std.mem.indexOf(u8, output, "503 5.5.1 Need RCPT command first") != null);
1973 try std.testing.expectEqual(@as(usize, 1), h.messages_accepted);
1974 try std.testing.expect(std.mem.indexOf(u8, output, "221 2.0.0 Bye") != null);
1975}
1976
1977test "RSET between BDAT chunks aborts the message" {
1978 var h: TestHandler = .{};
1979 defer h.deinit();
1980
1981 var out_buf: [1024]u8 = undefined;
1982 const output = try runScript(
1983 "EHLO client.example.org\r\n" ++
1984 "MAIL FROM:<alice@example.com>\r\n" ++
1985 "RCPT TO:<bob@example.net>\r\n" ++
1986 "BDAT 5\r\n" ++
1987 "abc\r\n" ++
1988 "RSET\r\n" ++
1989 "NOOP\r\n" ++
1990 "QUIT\r\n",
1991 &out_buf,
1992 h.handler(),
1993 .{},
1994 );
1995
1996 try std.testing.expectEqual(@as(usize, 0), h.messages_accepted);
1997 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Chunk received") != null);
1998 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok\r\n250 2.0.0 Ok\r\n221") != null);
1999}
2000
2001test "oversize BDAT message is rejected" {
2002 var h: TestHandler = .{};
2003 defer h.deinit();
2004
2005 var out_buf: [1024]u8 = undefined;
2006 const output = try runScript(
2007 "EHLO client.example.org\r\n" ++
2008 "MAIL FROM:<alice@example.com>\r\n" ++
2009 "RCPT TO:<bob@example.net>\r\n" ++
2010 "BDAT 40 LAST\r\n" ++
2011 "0123456789012345678901234567890123456789" ++
2012 "NOOP\r\n" ++
2013 "QUIT\r\n",
2014 &out_buf,
2015 h.handler(),
2016 .{ .max_message_size = 16 },
2017 );
2018
2019 try std.testing.expectEqual(@as(usize, 0), h.messages_accepted);
2020 try std.testing.expect(std.mem.indexOf(u8, output, "552 5.3.4") != null);
2021 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok\r\n221") != null);
2022}
2023
2024test "streaming handler receives BDAT chunks" {
2025 var h: StreamTestHandler = .{};
2026 defer h.collected.deinit(std.testing.allocator);
2027
2028 var out_buf: [1024]u8 = undefined;
2029 const output = try runScript(
2030 "EHLO client.example.org\r\n" ++
2031 "MAIL FROM:<alice@example.com>\r\n" ++
2032 "RCPT TO:<bob@example.net>\r\n" ++
2033 "BDAT 6\r\n" ++
2034 "part1\n" ++
2035 "BDAT 8 LAST\r\n" ++
2036 ".part2\r\n" ++
2037 "QUIT\r\n",
2038 &out_buf,
2039 h.handler(),
2040 .{},
2041 );
2042
2043 try std.testing.expectEqualStrings("part1\n.part2\r\n", h.collected.items);
2044 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok, message accepted") != null);
2045}
2046
2047test "session drains BDAT chunks a streaming handler leaves unread" {
2048 var h: StreamTestHandler = .{ .take_only = 4 };
2049 defer h.collected.deinit(std.testing.allocator);
2050
2051 var out_buf: [1024]u8 = undefined;
2052 const output = try runScript(
2053 "EHLO client.example.org\r\n" ++
2054 "MAIL FROM:<alice@example.com>\r\n" ++
2055 "RCPT TO:<bob@example.net>\r\n" ++
2056 "BDAT 10\r\n" ++
2057 "0123456789" ++
2058 "BDAT 10 LAST\r\n" ++
2059 "abcdefghij" ++
2060 "NOOP\r\n" ++
2061 "QUIT\r\n",
2062 &out_buf,
2063 h.handler(),
2064 .{},
2065 );
2066
2067 try std.testing.expectEqualStrings("0123", h.collected.items);
2068 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok, message accepted") != null);
2069 // The NOOP after the final chunk proves the stream stayed in sync.
2070 try std.testing.expect(std.mem.indexOf(u8, output, "250 2.0.0 Ok\r\n221") != null);
2071}
2072
2073test "SMTPUTF8 transactions and non-ASCII address enforcement" {
2074 var h: TestHandler = .{};
2075 defer h.deinit();
2076
2077 var out_buf: [2048]u8 = undefined;
2078 const output = try runScript(
2079 "EHLO client.example.org\r\n" ++
2080 // Non-ASCII without the parameter: rejected.
2081 "MAIL FROM:<böb@example.com>\r\n" ++
2082 "MAIL FROM:<alice@example.com>\r\n" ++
2083 "RCPT TO:<jürgen@example.net>\r\n" ++
2084 "RSET\r\n" ++
2085 // The parameter takes no value.
2086 "MAIL FROM:<a@example.com> SMTPUTF8=YES\r\n" ++
2087 // Invalid UTF-8 bytes even with the parameter: rejected.
2088 "MAIL FROM:<b\xff\xfeb@example.com> SMTPUTF8\r\n" ++
2089 // Proper internationalized transaction.
2090 "MAIL FROM:<böb@example.com> SMTPUTF8\r\n" ++
2091 "RCPT TO:<jürgen@example.net>\r\n" ++
2092 "DATA\r\nSubject: ünïcode\r\n\r\nhello\r\n.\r\n" ++
2093 "QUIT\r\n",
2094 &out_buf,
2095 h.handler(),
2096 .{},
2097 );
2098
2099 try std.testing.expectEqual(@as(usize, 1), h.messages_accepted);
2100 try std.testing.expect(h.smtputf8);
2101 try std.testing.expectEqualStrings("böb@example.com", h.from.items);
2102 try std.testing.expectEqualStrings("jürgen@example.net;", h.recipients.items);
2103 try std.testing.expect(std.mem.indexOf(u8, output, "250-SMTPUTF8\r\n") != null);
2104 try std.testing.expect(std.mem.indexOf(u8, output, "553 5.6.7 Non-ASCII address requires SMTPUTF8") != null);
2105 try std.testing.expect(std.mem.indexOf(u8, output, "501 5.5.4 SMTPUTF8 takes no value") != null);
2106 try std.testing.expect(std.mem.indexOf(u8, output, "553 5.6.7 Address is not valid UTF-8") != null);
2107}