summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/bin/main.zig85
-rw-r--r--src/bin/response.zig129
-rw-r--r--src/lib/commands.zig64
-rw-r--r--src/lib/dispatch.zig32
-rw-r--r--src/lib/parse.zig89
-rw-r--r--src/lib/parser.zig40
-rw-r--r--src/lib/reply.zig41
-rw-r--r--src/lib/response.zig117
-rw-r--r--src/lib/root.zig17
-rw-r--r--src/lib/smtp_parse.zig165
-rw-r--r--src/lib/tmp.zig50
11 files changed, 423 insertions, 406 deletions
diff --git a/src/bin/main.zig b/src/bin/main.zig
index 4c0adbb..634676d 100644
--- a/src/bin/main.zig
+++ b/src/bin/main.zig
@@ -1,7 +1,9 @@
const std = @import("std");
const Io = std.Io;
+const Response = @import("response.zig");
+const App = Response.App;
-const nvlope = @import("nvlope");
+const nv = @import("nvlope");
pub fn main(init: std.process.Init) !void {
const io = init.io;
@@ -17,55 +19,76 @@ pub fn main(init: std.process.Init) !void {
});
defer server.socket.close(io);
- // Async server
+ var group: Io.Group = .init;
+ defer group.cancel(io);
+
while (true) {
std.debug.print("Waiting for conn...\n", .{});
- _ = io.async(client, .{ alloc, io, &server });
+ const stream = try server.accept(io);
+ group.async(io, serve, .{ alloc, io, stream });
}
}
-fn client(alloc: std.mem.Allocator, io: Io, server: *Io.net.Server) !void {
- _ = alloc;
- var client_stream = try server.accept(io);
- defer client_stream.close(io);
+// Group tasks can't return errors, so catch and log at the boundary.
+fn serve(alloc: std.mem.Allocator, io: Io, stream: Io.net.Stream) void {
+ var s = stream;
+ defer s.close(io);
+ session(alloc, io, &s) catch |err|
+ std.debug.print("connection error: {s}\n", .{@errorName(err)});
+}
- var rbuf: [512]u8 = undefined;
- var reader = client_stream.reader(io, &rbuf);
+fn session(alloc: std.mem.Allocator, io: Io, stream: *Io.net.Stream) !void {
+ var rbuf: [1024]u8 = undefined;
+ var reader = stream.reader(io, &rbuf);
const r = &reader.interface;
- var wbuf: [512]u8 = undefined;
- var writer = client_stream.writer(io, &wbuf);
+ var wbuf: [1024]u8 = undefined;
+ var writer = stream.writer(io, &wbuf);
const w = &writer.interface;
- // Temporary outbuff for printing
- var outbuff: [128]u8 = undefined;
- var stdout: Io.File.Writer = .init(.stdout(), io, &outbuff);
- const sout = &stdout.interface;
+ // Per-connection state
+ var arena: std.heap.ArenaAllocator = .init(alloc);
+ defer arena.deinit();
+ var app: App = .{ .gpa = alloc };
- // Init response
- _ = try nvlope.Response.init(w, server);
+ // Greeting: the server speaks first
+ try nv.Reply.single(.ready, "localhost ESMTP ready").send(w);
+ try w.flush();
- try sout.print("New Connection: {}\n", .{client_stream.socket.address});
- try sout.flush();
+ var in_data = false;
- // Logic loop
while (true) {
- try w.flush();
const line = r.takeDelimiterInclusive('\n') catch |err| switch (err) {
- error.EndOfStream => break, // client closed the connection
- error.StreamTooLong => break,
+ error.EndOfStream => return, // client hung up
+ error.StreamTooLong => {
+ try nv.Reply.single(.bad_cmd, "Line too long").send(w);
+ try w.flush();
+ return;
+ },
else => |e| return e,
};
- const parsed = try nvlope.Parser.parse(line);
- const resp = try nvlope.Response.respond(w, parsed, server);
- try sout.print("{s}\n", .{resp.contents});
- try sout.flush();
+ _ = arena.reset(.retain_capacity);
- if (!std.mem.endsWith(u8, line, "\r\n")) {
- // DATA section
+ if (in_data) {
+ if (std.mem.eql(u8, line, ".\r\n")) {
+ in_data = false;
+ try nv.Reply.single(.ok, "Queued").send(w);
+ try w.flush();
+ } else {
+ const status = try app.appendBodyLine(line);
+ switch (status) {
+ .ok => continue,
+ .too_large => try nv.Reply.single(.exceeded, "Message too large").send(w),
+ }
+ try w.flush();
+ }
continue;
}
+
+ switch (try nv.handleLine(App, &app, arena.allocator(), line, w)) {
+ .cont => {},
+ .data => in_data = true,
+ .close => return,
+ }
}
- try sout.print("ERROR\n", .{});
- try sout.flush();
}
diff --git a/src/bin/response.zig b/src/bin/response.zig
new file mode 100644
index 0000000..72b8cbd
--- /dev/null
+++ b/src/bin/response.zig
@@ -0,0 +1,129 @@
+const std = @import("std");
+const nv = @import("nvlope");
+const Allocator = std.mem.Allocator;
+
+pub const App = struct {
+ mailbox: std.fs.path,
+ gpa: Allocator,
+ domain: []const u8 = "localhost",
+ sender: ?[]const u8 = null,
+ recipients: std.ArrayList([]const u8) = .empty,
+ body: std.ArrayList(u8) = .empty,
+ state: enum(u8) {
+ init = 0,
+ start, // post 220 send
+ ready = 2, // EHLO / RSET
+ mail, // MAIL
+ rcpt, // RCPT
+ } = .init,
+
+ const max_rcpt = 100;
+ const max_size = 512;
+ const max_body = 10 * 1024 * 1024;
+
+ pub fn appendBodyLine(self: *App, line: []const u8) !enum { ok, too_large } {
+ const l = if (std.mem.startsWith(u8, line, "..")) line[1..] else line;
+ if (self.body.items.len + l.len > max_body) return .too_large;
+ try self.body.appendSlice(self.gpa, l);
+ return .ok;
+ }
+
+ pub fn resetTransaction(self: *App) void {
+ if (@intFromEnum(self.state) <= 2) self.state = .ready else self.state = .start;
+ self.sender = null;
+ for (self.recipients.items) |r| self.gpa.free(r);
+ self.recipients.clearRetainingCapacity();
+ self.body.clearRetainingCapacity();
+ }
+
+ pub fn init(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply {
+ _ = id;
+ self.state = .start;
+ const line = "nvlope ready";
+ return .{ .code = .init, .lines = try arena.dupe([]const u8, &.{line}) };
+ }
+
+ pub fn ehlo(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply {
+ self.resetTransaction();
+ var tmp: [64]u8 = undefined;
+ const who = try id.toString(&tmp);
+ const lines = try arena.alloc([]const u8, 3);
+ lines[0] = try std.fmt.allocPrint(arena, "{s} greets {s}", .{ self.domain, who });
+ lines[1] = "8BITMIME";
+ lines[2] = "SIZE 35882577";
+ self.state = .ready;
+ return .{ .code = .ok, .lines = lines };
+ }
+
+ pub fn helo(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply {
+ self.resetTransaction();
+ _ = id;
+ const line = try std.fmt.allocPrint(arena, "{s}", .{self.domain});
+ self.state = .ready;
+ return .{ .code = .ok, .lines = try arena.dupe([]const u8, &.{line}) };
+ }
+
+ pub fn mail(self: *App, arena: Allocator, m: nv.MailFrom) !nv.Reply {
+ _ = arena;
+ if (@intFromEnum(self.state) < 2) return nv.Reply.single(.bad_sequence, "Need EHLO before MAIL");
+ var it = m.paramIterator();
+ while (it.next()) |p| {
+ if (std.ascii.eqlIgnoreCase(p.key, "SIZE")) {
+ const n = std.fmt.parseInt(usize, p.value orelse "", 10) catch
+ return nv.Reply.single(.bad_param, "Bad SIZE parameter");
+ if (n > max_size) return nv.Reply.single(.exceeded, "Message too large");
+ } else if (!std.ascii.eqlIgnoreCase(p.key, "BODY")) {
+ return nv.Reply.single(.param_not_impl, "Unrecognized parameter");
+ }
+ }
+ self.sender = m.path; // dupe it if it must outlive this line
+ self.state = .mail;
+ return nv.Reply.single(.ok, "OK");
+ }
+
+ pub fn rcpt(self: *App, arena: Allocator, r: nv.RcptTo) !nv.Reply {
+ _ = arena;
+ if (self.sender == null) return nv.Reply.single(.bad_sequence, "Need MAIL before RCPT");
+ if (self.recipients.items.len >= max_rcpt)
+ return nv.Reply.single(.too_many, "Too many recipients");
+
+ var it = r.paramIterator();
+ if (it.next() != null) // NOTIFY/ORCPT not supported
+ return nv.Reply.single(.param_unrecognized, "Unrecognized parameter");
+
+ const owned = try self.gpa.dupe(u8, r.path);
+ errdefer self.gpa.free(owned);
+ try self.recipients.append(self.gpa, owned);
+ return nv.Reply.single(.ok, "OK");
+ }
+
+ pub fn rset(self: *App, arena: Allocator, _: void) !nv.Reply {
+ _ = arena;
+ self.resetTransaction();
+ return nv.Reply.single(.ok, "OK");
+ }
+
+ pub fn noop(self: *App, arena: Allocator, _: void) !nv.Reply {
+ _ = self;
+ _ = arena;
+ return nv.Reply.single(.ok, "OK");
+ }
+
+ pub fn data(self: *App, arena: Allocator, _: void) !nv.Reply {
+ _ = self;
+ const line = "Start mail input; end with <CRLF>.<CRLF>";
+ return .{ .code = .start_data, .lines = try arena.dupe([]const u8, &.{line}), .action = .data };
+ }
+
+ pub fn vrfy(self: *App, arena: Allocator, who: []const u8) !nv.Reply {
+ _ = self;
+ _ = arena;
+ _ = who;
+ return nv.Reply.single(.cannot_verify, "Cannot VRFY user, but will accept message and attempt delivery");
+ }
+
+ pub fn quit(self: *App, arena: Allocator, _: void) !nv.Reply {
+ const line = try std.fmt.allocPrint(arena, "{s} Service closing transmission channel", .{self.domain});
+ return .{ .code = .closing, .lines = try arena.dupe([]const u8, &.{line}), .action = .close };
+ }
+};
diff --git a/src/lib/commands.zig b/src/lib/commands.zig
new file mode 100644
index 0000000..719e93f
--- /dev/null
+++ b/src/lib/commands.zig
@@ -0,0 +1,64 @@
+const IpAddress = @import("std").Io.net.IpAddress;
+const std = @import("std");
+
+pub const Identity = union(enum) {
+ domain: []const u8,
+ addr: IpAddress,
+
+ pub fn toString(self: Identity, buf: []u8) ![]const u8 {
+ return switch (self) {
+ .domain => self.domain,
+ .addr => blk: {
+ var fw: std.Io.Writer = .fixed(buf);
+ try self.addr.format(&fw);
+ const full = fw.buffered();
+ const host: []const u8 = if (std.mem.lastIndexOfScalar(u8, full, ':')) |i| full[0..i] else full;
+ break :blk host;
+ },
+ };
+ }
+};
+
+pub const Path = struct {
+ path: []const u8,
+ params: []const u8,
+
+ pub const Param = struct { key: []const u8, value: ?[]const u8 };
+
+ pub const ParamIterator = struct {
+ it: std.mem.TokenIterator(u8, .scalar),
+
+ pub fn next(self: *ParamIterator) ?Param {
+ const tok = self.it.next() orelse return null;
+ if (std.mem.indexOfScalar(u8, tok, '=')) |i|
+ return .{ .key = tok[0..i], .value = tok[i + 1 ..] };
+ return .{ .key = tok, .value = null };
+ }
+ };
+
+ pub fn paramIterator(self: Path) ParamIterator {
+ return .{ .it = std.mem.tokenizeScalar(u8, self.params, ' ') };
+ }
+};
+
+pub const MailFrom = Path;
+pub const RcptTo = Path;
+
+pub const User = struct {
+ name: []const u8, // local part; a quoted string keeps its quotes
+ host: ?Identity, // null only for <postmaster>
+};
+
+pub const Verb = enum { ehlo, helo, mail, rcpt, data, rset, noop, quit, vrfy };
+
+pub const Command = union(Verb) {
+ ehlo: Identity,
+ helo: Identity,
+ mail: MailFrom,
+ rcpt: RcptTo,
+ data: void,
+ rset: void,
+ noop: void,
+ quit: void,
+ vrfy: []const u8,
+};
diff --git a/src/lib/dispatch.zig b/src/lib/dispatch.zig
new file mode 100644
index 0000000..d4c83b8
--- /dev/null
+++ b/src/lib/dispatch.zig
@@ -0,0 +1,32 @@
+const std = @import("std");
+const nvcmd = @import("commands.zig");
+const nvparse = @import("parse.zig");
+const nvrply = @import("reply.zig");
+const Reply = nvrply.Reply;
+const Command = nvcmd.Command;
+const Allocator = std.mem.Allocator;
+const Io = std.Io;
+const Action = nvrply.Action;
+const parse = nvparse.parse;
+
+pub fn dispatch(comptime H: type, h: *H, arena: Allocator, cmd: Command) !Reply {
+ switch (cmd) {
+ inline else => |payload, tag| {
+ const name = @tagName(tag);
+ if (@hasDecl(H, name)) return @field(H, name)(h, arena, payload);
+ return Reply.single(.not_impl, "Command not implemented");
+ },
+ }
+}
+
+pub fn handleLine(comptime H: type, h: *H, arena: Allocator, line: []const u8, w: *Io.Writer) !Action {
+ const reply = if (parse(line)) |cmd|
+ try dispatch(H, h, arena, cmd)
+ else |err| switch (err) {
+ error.UnknownCommand => Reply.single(.bad_cmd, "Command not recognized"),
+ error.BadParam => Reply.single(.bad_param, "Syntax error in parameters"),
+ };
+ try reply.send(w);
+ try w.flush();
+ return reply.action;
+}
diff --git a/src/lib/parse.zig b/src/lib/parse.zig
new file mode 100644
index 0000000..334813e
--- /dev/null
+++ b/src/lib/parse.zig
@@ -0,0 +1,89 @@
+const std = @import("std");
+const net = std.Io.net;
+const Command = @import("commands.zig").Command;
+const Verb = @import("commands.zig").Verb;
+const Identity = @import("commands.zig").Identity;
+const User = @import("commands.zig").Path;
+
+pub const ParseError = error{ UnknownCommand, BadParam };
+
+pub fn parse(raw: []const u8) ParseError!Command {
+ const line = std.mem.trimEnd(u8, raw, "\r\n");
+ const sp = std.mem.indexOfScalar(u8, line, ' ');
+ const verb_str = line[0 .. sp orelse line.len];
+ const arg = if (sp) |i| std.mem.trimStart(u8, line[i + 1 ..], " ") else "";
+
+ if (verb_str.len != 4) return error.UnknownCommand;
+ var lower: [4]u8 = undefined;
+ _ = std.ascii.lowerString(&lower, verb_str);
+ const verb = std.meta.stringToEnum(Verb, &lower) orelse return error.UnknownCommand;
+
+ return switch (verb) {
+ .ehlo => .{ .ehlo = try identity(arg) },
+ .helo => .{ .helo = try identity(arg) },
+ .mail => .{ .mail = try path(arg, "FROM:", .{ .allow_null = true }) },
+ .rcpt => .{ .rcpt = try path(arg, "TO:", .{ .allow_postmaster = true }) },
+ .vrfy => blk: {
+ if (arg.len == 0) return error.BadParam;
+ break :blk .{ .vrfy = arg };
+ },
+ inline else => |v| @unionInit(Command, @tagName(v), {}),
+ };
+}
+
+const PathRules = struct {
+ allow_null: bool = false,
+ allow_postmaster: bool = false,
+};
+
+fn path(arg: []const u8, comptime prefix: []const u8, rules: PathRules) ParseError!User {
+ if (!std.ascii.startsWithIgnoreCase(arg, prefix)) return error.BadParam;
+
+ const rest = std.mem.trimStart(u8, arg[prefix.len..], " ");
+ if (rest.len == 0 or rest[0] != '<') return error.BadParam;
+
+ const close = std.mem.indexOfScalar(u8, rest, '>') orelse return error.BadParam;
+ var p = rest[1..close];
+
+ const tail = rest[close + 1 ..];
+ if (tail.len > 0 and tail[0] != ' ') return error.BadParam;
+ const params = std.mem.trim(u8, tail, " ");
+
+ if (p.len > 0 and p[0] == '@') {
+ const colon = std.mem.indexOfScalar(u8, p, ':') orelse return error.BadParam;
+ p = p[colon + 1 ..];
+ }
+
+ if (p.len == 0) {
+ if (!rules.allow_null) return error.BadParam;
+ } else if (rules.allow_postmaster and std.ascii.eqlIgnoreCase(p, "postmaster")) {} else {
+ try validateMailbox(p);
+ }
+ return .{ .path = p, .params = params };
+}
+
+fn validateMailbox(vpath: []const u8) ParseError!void {
+ if (vpath.len > 254) return error.BadParam;
+ const at = std.mem.lastIndexOfScalar(u8, vpath, '@') orelse return error.BadParam;
+ const local = vpath[0..at];
+ const domain = vpath[at + 1 ..];
+ if (local.len == 0 or local.len > 64) return error.BadParam;
+ if (domain.len == 0 or domain.len > 255) return error.BadParam;
+ for (vpath) |c| {
+ if (c < 0x20 or c == 0x7f) return error.BadParam;
+ }
+}
+
+fn identity(arg: []const u8) ParseError!Identity {
+ if (arg.len == 0) return error.BadParam;
+ if (arg[0] != '[') return .{ .domain = arg };
+
+ if (arg[arg.len - 1] != ']') return error.BadParam;
+ const inner = arg[1 .. arg.len - 1];
+ if (std.ascii.startsWithIgnoreCase(inner, "IPv6:")) {
+ const ip = net.Ip6Address.parse(inner[5..], 0) catch return error.BadParam;
+ return .{ .addr = .{ .ip6 = ip } };
+ }
+ const ip = net.Ip4Address.parse(inner, 0) catch return error.BadParam;
+ return .{ .addr = .{ .ip4 = ip } };
+}
diff --git a/src/lib/parser.zig b/src/lib/parser.zig
deleted file mode 100644
index f0cc8d9..0000000
--- a/src/lib/parser.zig
+++ /dev/null
@@ -1,40 +0,0 @@
-const std = @import("std");
-
-pub const ParserError = error{ Unexpected, EndOfString };
-
-str: []const u8,
-pos: u32 = 0,
-
-const Self = @This();
-
-pub fn peek(self: Self) ?u8 {
- if (self.pos >= self.str.len) return null;
- return self.str[self.pos];
-}
-
-pub fn consume(self: *Self, c: u8) ParserError!void {
- if (self.peek()) |pk| {
- if (pk == c) {
- self.pos += 1;
- return;
- }
- return ParserError.Unexpected;
- }
- return ParserError.EndOfString;
-}
-
-pub fn skip(self: *Self) void {
- self.pos += 1;
-}
-
-pub fn skipMany(self: *Self, n: usize) void {
- for (0..n) |_|
- self.skip();
-}
-
-pub fn takeUntil(self: *Self, c: u8) ParserError![]const u8 {
- const i = self.pos;
- while (self.peek() != null and self.peek().? != c) self.skip();
- self.skip();
- return self.str[i .. self.pos - 1];
-}
diff --git a/src/lib/reply.zig b/src/lib/reply.zig
new file mode 100644
index 0000000..61df971
--- /dev/null
+++ b/src/lib/reply.zig
@@ -0,0 +1,41 @@
+const std = @import("std");
+const Io = std.Io;
+
+pub const Code = enum(u16) {
+ ready = 220,
+ cannot_verify = 252,
+ closing = 221,
+ start_data = 354,
+ ok = 250,
+ not_avail = 421,
+ bad_cmd = 500,
+ bad_param = 501,
+ not_impl = 502,
+ bad_sequence = 503,
+ param_not_impl = 504,
+ rejected = 550,
+ too_many = 452,
+ exceeded = 552,
+ param_unrecognized = 555,
+ _, //@as(Code, @enumFromInt(user defined code))
+};
+
+pub const Action = enum { cont, data, close };
+
+pub const Reply = struct {
+ code: Code,
+ lines: []const []const u8,
+ action: Action = .cont,
+
+ pub fn single(code: Code, comptime text: []const u8) Reply {
+ return .{ .code = code, .lines = &.{text} };
+ }
+
+ pub fn send(self: Reply, w: *Io.Writer) !void {
+ const code = @intFromEnum(self.code);
+ for (self.lines, 0..) |line, i| {
+ const sep: u8 = if (i == self.lines.len - 1) ' ' else '-';
+ try w.print("{d}{c}{s}\r\n", .{ code, sep, line });
+ }
+ }
+};
diff --git a/src/lib/response.zig b/src/lib/response.zig
deleted file mode 100644
index 06458ff..0000000
--- a/src/lib/response.zig
+++ /dev/null
@@ -1,117 +0,0 @@
-const std = @import("std");
-
-pub const ResponseError = error{Unimplemented};
-
-pub const Identity = union(enum) {
- domain: []const u8,
- addr: std.Io.net.IpAddress,
-};
-
-pub const Message = struct {
- str: []const u8,
- cmd: Command,
- client: Identity,
-};
-
-pub const Command = enum {
- EHLO,
- HELO,
- MAIL,
- RCPT,
- DATA,
- RSET,
- NOOP,
- QUIT,
- VRFY,
-
- pub fn fromStr(msg: []const u8) ?Command {
- var MSG: [4]u8 = undefined;
- if (msg.len != 4) return null;
- _ = std.ascii.upperString(&MSG, msg);
- if (std.mem.eql(u8, &MSG, "EHLO")) return .EHLO;
- if (std.mem.eql(u8, &MSG, "HELO")) return .HELO;
- if (std.mem.eql(u8, &MSG, "MAIL")) return .MAIL;
- if (std.mem.eql(u8, &MSG, "RCPT")) return .RCPT;
- if (std.mem.eql(u8, &MSG, "DATA")) return .DATA;
- if (std.mem.eql(u8, &MSG, "RSET")) return .RSET;
- if (std.mem.eql(u8, &MSG, "NOOP")) return .NOOP;
- if (std.mem.eql(u8, &MSG, "QUIT")) return .QUIT;
- if (std.mem.eql(u8, &MSG, "VRFY")) return .VRFY;
- return null;
- }
-};
-
-const Code = enum(u32) {
- INIT = 220,
- OK = 250,
-};
-
-pub const Response = struct {
- code: Code,
- contents: []const u8,
-};
-
-pub fn init(w: *std.Io.Writer, server: *std.Io.net.Server) !Response {
- const resp: Response = .{ .code = .INIT, .contents = "nvlope ready" };
- try w.print("{d} ", .{resp.code});
- var buf: [64]u8 = undefined;
- const l = try strip_port(server.socket.address, &buf);
- const host = buf[0..l];
- try w.print("[{s}]", .{host});
- try w.print(" {s}\r\n", .{resp.contents});
- try w.flush();
- return resp;
-}
-
-pub fn respond(w: *std.Io.Writer, msg: Message, server: *std.Io.net.Server) !Response {
- return switch (msg.cmd) {
- .EHLO => try ehlo(w, msg, null, server),
- .HELO => try helo(w, msg, null, server),
- else => ResponseError.Unimplemented,
- };
-}
-
-pub fn helo(w: *std.Io.Writer, msg: Message, domain: ?[]const u8, server: *std.Io.net.Server) !Response {
- _ = msg;
- var resp: Response = .{ .code = .OK, .contents = undefined };
- if (domain) |d| {
- resp.contents = d;
- try w.print("{d} {s}\r\n", .{ resp.code, resp.contents });
- try w.flush();
- return resp;
- }
- try w.print("{d} ", .{resp.code});
- var buf: [64]u8 = undefined;
- const l = try strip_port(server.socket.address, &buf);
- const host: []const u8 = buf[0..l];
- try w.print("[{s}]\r\n", .{host});
- resp.contents = host;
- return resp;
-}
-
-pub fn ehlo(w: *std.Io.Writer, msg: Message, domain: ?[]const u8, server: *std.Io.net.Server) !Response {
- _ = msg;
- var resp: Response = .{ .code = .OK, .contents = undefined };
- if (domain) |d| {
- resp.contents = d;
- try w.print("{d} {s}\r\n", .{ resp.code, resp.contents });
- try w.flush();
- return resp;
- }
- try w.print("{d} ", .{resp.code});
- var buf: [64]u8 = undefined;
- const l = try strip_port(server.socket.address, &buf);
- const host: []const u8 = buf[0..l];
- try w.print("[{s}]\r\n", .{host});
- resp.contents = host;
- return resp;
-}
-
-fn strip_port(addr: std.Io.net.IpAddress, buf: []u8) !usize {
- var fw: std.Io.Writer = .fixed(buf);
- try addr.format(&fw);
- const full = fw.buffered();
- const host = if (std.mem.lastIndexOfScalar(u8, full, ':')) |i| full[0..i] else full;
- std.mem.copyForwards(u8, buf, host);
- return host.len;
-}
diff --git a/src/lib/root.zig b/src/lib/root.zig
index 3e8fcb2..7379fc7 100644
--- a/src/lib/root.zig
+++ b/src/lib/root.zig
@@ -1,7 +1,18 @@
-pub const Parser = @import("smtp_parse.zig");
-pub const Response = @import("response.zig");
+pub const Parser = @import("parse.zig");
+pub const Dispatch = @import("dispatch.zig");
+pub const Reply = @import("reply.zig").Reply;
+pub const Code = @import("reply.zig").Code;
+pub const Commands = @import("commands.zig");
+pub const Command = Commands.Command;
+pub const Identity = Commands.Identity;
+pub const MailFrom = Commands.MailFrom;
+pub const RcptTo = Commands.RcptTo;
+pub const handleLine = Dispatch.handleLine;
test "all" {
+ _ = Identity;
_ = Parser;
- _ = Response;
+ _ = Reply;
+ _ = Code;
+ _ = Command;
}
diff --git a/src/lib/smtp_parse.zig b/src/lib/smtp_parse.zig
deleted file mode 100644
index 44822ff..0000000
--- a/src/lib/smtp_parse.zig
+++ /dev/null
@@ -1,165 +0,0 @@
-const std = @import("std");
-const Parser = @import("parser.zig");
-const Identity = @import("response.zig").Identity;
-const Message = @import("response.zig").Message;
-const Command = @import("response.zig").Command;
-const net = std.Io.net;
-
-const ServerError = error{ InvalidCommand, Unimplemented, UnknownCommand };
-
-fn parse_crlf(parser: *Parser) Parser.ParserError![]const u8 {
- var result = try parser.takeUntil('\r');
- if (parser.peek()) |c| {
- if (c == '\n') return result;
- } else return Parser.ParserError.EndOfString;
-
- // parser.consume(' ') catch {
- // parser.skip();
- // result = try parse_crlf(parser);
- // };
- result = try parse_crlf(parser);
- return result;
-}
-
-pub fn parse(msg: []const u8) !Message {
- if (msg.len < 4) return ServerError.InvalidCommand;
- const cmd: ?Command = .fromStr(msg[0..4]);
- const client: ?Identity = if (cmd) |c|
- try switch (c) {
- .EHLO => try ehlo(msg[4..]),
- .HELO => try helo(msg[4..]),
- else => ServerError.Unimplemented,
- }
- else
- null;
- if (client == null) return ServerError.UnknownCommand;
- return .{
- .client = client.?,
- .cmd = cmd.?,
- .str = msg,
- };
-}
-
-// Expects a string in the format of "[ipaddr]" no \r\n
-fn address(msg: []const u8) !?net.IpAddress {
- const ip6 = net.Ip6Address.parse(msg[1 .. msg.len - 1], 0) catch null;
- const ip4 = net.Ip4Address.parse(msg[1 .. msg.len - 1], 0) catch null;
- return if (ip6) |ip|
- net.IpAddress{ .ip6 = ip }
- else if (ip4) |ip|
- net.IpAddress{ .ip4 = ip }
- else
- null;
-}
-
-fn ehlo(msg: []const u8) !Identity {
- var parser: Parser = .{ .str = msg };
- try parser.consume(' ');
- const ipaddr = try address(msg[1 .. msg.len - 3]);
-
- parser.skipMany(msg[1 .. msg.len - 2].len);
-
- if (ipaddr) |ip| {
- try parser.consume('\r');
- try parser.consume('\n');
- return .{ .addr = ip };
- }
- return .{ .domain = try parse_crlf(&parser) };
-}
-
-fn helo(msg: []const u8) !Identity {
- var parser: Parser = .{ .str = msg };
- try parser.consume(' ');
- parser.skip();
- return .{ .domain = try parse_crlf(&parser) };
-}
-
-const t = std.testing;
-
-test "Command.fromStr: known verbs, any case" {
- try t.expectEqual(Command.EHLO, Command.fromStr("EHLO").?);
- try t.expectEqual(Command.EHLO, Command.fromStr("ehlo").?);
- try t.expectEqual(Command.MAIL, Command.fromStr("MaIl").?);
- try t.expectEqual(Command.QUIT, Command.fromStr("quit").?);
-}
-
-test "Command.fromStr: unknown or wrong length" {
- try t.expectEqual(@as(?Command, null), Command.fromStr("XXXX"));
- try t.expectEqual(@as(?Command, null), Command.fromStr("EHL"));
- try t.expectEqual(@as(?Command, null), Command.fromStr("EHLOO"));
- try t.expectEqual(@as(?Command, null), Command.fromStr(""));
-}
-
-test "parse_crlf: strips terminator" {
- var p: Parser = .{ .str = "hello\r\n" };
- std.debug.print("{s}\n", .{try parse_crlf(&p)});
- var p2: Parser = .{ .str = "hello\r\n" };
- try t.expectEqualStrings("hello", try parse_crlf(&p2));
- try t.expectEqual(@as(usize, 0), p2.str.len - p2.pos - 1);
-}
-
-test "parse_crlf: rejects bare LF, missing terminator, trailing data" {
- var a: Parser = .{ .str = "hello\n" };
- try t.expectError(Parser.ParserError.EndOfString, parse_crlf(&a));
- var b: Parser = .{ .str = "hello" };
- try t.expectError(Parser.ParserError.EndOfString, parse_crlf(&b));
- var c: Parser = .{ .str = "hello\r\nextra" };
- try t.expectError(Parser.ParserError.EndOfString, parse_crlf(&c));
-}
-
-test "parse_crlf: lone CR inside the line is not a terminator" {
- var p: Parser = .{ .str = "a\rb\r\n" };
- try t.expectEqualStrings("a\rb", try parse_crlf(&p));
-}
-
-// test "ehlo: domain" {
-// const id = try ehlo(" mail.example.com\r\n");
-// try t.expectEqualStrings("mail.example.com", id.domain);
-// }
-
-test "ehlo: IPv4 address literal" {
- const id = try ehlo(" [192.0.2.1]\r\n");
- std.debug.print("{}\n", .{id.addr});
- try t.expect(id == Identity.addr);
-}
-
-test "ehlo: IPv6 address literal" {
- const id = try ehlo(" [IPv6:2001:db8::1]\r\n");
- try t.expect(id == .addr);
-}
-
-test "ehlo: errors" {
- try t.expectError(Parser.ParserError.Unexpected, ehlo("mail.example.com\r\n")); // no space
- try t.expectError(error.Unexpected, ehlo(" mail.example.com")); // no CRLF
- try t.expectError(error.InvalidDomain, ehlo(" \r\n")); // empty
- try t.expectError(error.InvalidDomain, ehlo(" bad_domain!\r\n"));
- try t.expectError(error.Unexpected, ehlo(" [1.2.3.4\r\n")); // unclosed
- try t.expectError(error.InvalidAddressLiteral, ehlo(" [not.an.ip]\r\n"));
-}
-
-test "helo: domain and errors" {
- const id = try helo(" example.org\r\n");
- try t.expectEqualStrings("example.org", id.domain);
- // try t.expectError(anyerror{}, helo(" [1.2.3.4]\r\n"));
- try t.expectError(Parser.ParserError.Unexpected, helo("example.org\r\n"));
-}
-
-// test "parse: dispatches EHLO/HELO case-insensitively" {
-// const a = try parse("ehlo client.example\r\n");
-// try t.expectEqualStrings("client.example", a.ehlo.domain);
-// const b = try parse("HELO client.example\r\n");
-// try t.expectEqualStrings("client.example", b.helo.domain);
-// }
-//
-// test "parse: argument-less commands" {
-// try t.expectEqual(Command.QUIT, (try parse("QUIT\r\n")).simple);
-// try t.expectEqual(Command.NOOP, (try parse("noop\r\n")).simple);
-// try t.expectError(error.Unexpected, parse("QUIT now\r\n"));
-// try t.expectError(error.Unexpected, parse("QUIT\n"));
-// }
-
-test "parse: bad input" {
- try t.expectError(ServerError.InvalidCommand, parse("EH"));
- try t.expectError(ServerError.UnknownCommand, parse("FOOO\r\n"));
- try t.expectError(ServerError.Unimplemented, parse("MAIL FROM:<a@b.c>\r\n"));
-}
diff --git a/src/lib/tmp.zig b/src/lib/tmp.zig
deleted file mode 100644
index 3777b31..0000000
--- a/src/lib/tmp.zig
+++ /dev/null
@@ -1,50 +0,0 @@
-const std = @import("std");
-
-const Code = enum(u16) {
- OK = 250,
- UNKNOWN = 404,
-};
-
-const Response = struct {
- code: Code,
- pass: bool,
- msg: []const u8,
-};
-
-const Message = struct {
- name: []const u8,
- pass: []const Code,
- fail: []const Code,
- handle: fn (*std.Io.Writer, *std.Io.net.Server, args: anytype) anyerror!Response,
-};
-
-const Messages = union(enum(u8)) {
- HELO = Message{
- .name = "HELO",
- .pass = .{.OK},
- .fail = .{.UNKNOWN},
- .handle = blk: {
- const f = struct {
- pub fn handle(w: *std.Io.Writer, s: *std.Io.net.Server, args: anytype) !Response {
- var resp: Response = .{ .code = .OK, .pass = true, .contents = undefined };
- if (args.domain) |d| {
- resp.contents = d;
- try w.print("{d} {s}\r\n", .{ resp.code, resp.contents });
- try w.flush();
- return resp;
- }
- try w.print("{d} ", .{resp.code});
- var buf: [64]u8 = undefined;
- var fw: std.Io.Writer = .fixed(&buf);
- try s.socket.address.format(&fw);
- const full = fw.buffered();
- const host = if (std.mem.lastIndexOfScalar(u8, full, ':')) |i| full[0..i] else full;
- try w.print("[{s}]\r\n", .{host});
- resp.contents = host;
- return resp;
- }
- };
- break :blk f.handle;
- },
- },
-};