From f9ad26b8a4eb91506b48c3f8275226a8983cd694 Mon Sep 17 00:00:00 2001 From: Nic Gaffney Date: Wed, 21 Oct 2026 04:00:42 -0500 Subject: Functioning local mailserver --- src/bin/app.zig | 82 +++++++++++++++++++++++++++++++++++++++++++++++-------- src/bin/main.zig | 18 ++++++++++-- src/bin/trace.zig | 46 +++++++++++++++++++++++++++++++ src/bin/util.zig | 8 ++++++ src/lib/reply.zig | 1 + 5 files changed, 141 insertions(+), 14 deletions(-) create mode 100644 src/bin/trace.zig (limited to 'src') diff --git a/src/bin/app.zig b/src/bin/app.zig index e3b76fd..474592e 100644 --- a/src/bin/app.zig +++ b/src/bin/app.zig @@ -3,6 +3,7 @@ const nv = @import("nvlope"); const Allocator = std.mem.Allocator; const normalizeUser = @import("util.zig").normalizeUser; const Store = @import("store.zig"); +const Trace = @import("trace.zig"); pub const App = @This(); @@ -20,27 +21,71 @@ state: enum(u8) { rcpt, // RCPT } = .init, store: *Store, +peer: []const u8, +helo_ident: ?[]u8 = null, +esmtp: bool = false, const max_rcpt = 100; const max_size = 512; const max_body = 10 * 1024 * 1024; +var next_id: std.atomic.Value(u64) = .init(0); + +fn makeId(buf: []u8, nanos: i96, host: []const u8) ![]const u8 { + const n = next_id.fetchAdd(1, .monotonic); + return std.fmt.bufPrint(buf, "{d}.{d}.{s}", .{ nanos, n, host }); +} + fn acceptLocal(self: *App, raw: []const u8) !nv.Reply { _ = self; _ = raw; return error.NotImplemented; } -pub fn queue(self: *App) void { +pub fn queue(self: *App) !void { for (self.recipients.items) |rc| { - const at = std.mem.lastIndexOfScalar(u8, rc, '@') orelse rc.len; - const local = rc.path[0..at]; - const domain = rc.path[at + 1 ..]; - if (std.ascii.eqlIgnoreCase(domain, self.domain) and self.store.exists(self.io, local)) { - var mailbox = try self.store.maildir.openDir(self.io, local, .{}); + const at = std.mem.lastIndexOfScalar(u8, rc, '@') orelse continue; + const local = rc[0..at]; + const domain = rc[at + 1 ..]; + if (std.ascii.eqlIgnoreCase(domain, self.domain) and try self.store.exists(self.io, local)) { + var maildir = try self.store.maildir.openDir(self.io, "mailboxes", .{}); + defer maildir.close(self.io); + var mailbox = try maildir.openDir(self.io, local, .{}); defer mailbox.close(self.io); - var tmp = try mailbox.openDir(self.io, "tmp"); - tmp.createFile(self.io, "MAAAIL", .{.lock}); + var tmp = try mailbox.openDir(self.io, "tmp", .{}); + defer tmp.close(self.io); + + const nano = std.Io.Timestamp.now(self.io, .real).nanoseconds; + var buf: [64]u8 = undefined; + const id = try makeId(&buf, nano, domain); + + const trace: Trace = .{ + .sender = self.sender.?, + .helo = self.helo_ident orelse "unknown", + .peer = self.peer, + .by = self.domain, + .esmtp = self.esmtp, + .id = id, + .rcpt = rc, + .secs = @divFloor(nano, std.time.ns_per_s), + }; + + var file = try tmp.createFile(self.io, id, .{ .exclusive = true }); + errdefer tmp.deleteFile(self.io, id) catch {}; + + var fbuf: [512]u8 = undefined; + var fwriter = file.writer(self.io, &fbuf); + const writer = &fwriter.interface; + try trace.writeTrace(writer); + try writer.writeAll(self.body.items); + try writer.flush(); + try file.sync(self.io); + file.close(self.io); + + const new = try mailbox.openDir(self.io, "new", .{}); + try tmp.rename(id, new, id, self.io); + } else { + // Relay / user not defined } } } @@ -63,21 +108,34 @@ pub fn resetTransaction(self: *App) void { pub fn ehlo(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply { self.resetTransaction(); - var tmp: [64]u8 = undefined; + var tmp: [255]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; + + var buf: [255]u8 = undefined; + const n = @min(who.len, buf.len); + for (who[0..n], buf[0..n]) |c, *o| o.* = if (c > 0x20 and c < 0x7f) c else '?'; + self.helo_ident = try arena.dupe(u8, buf[0..n]); + + self.esmtp = true; 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; + var tmp: [255]u8 = undefined; + const who = try id.toString(&tmp); + const line = try std.fmt.allocPrint(arena, "{s}", .{self.domain}); + + var buf: [255]u8 = undefined; + const n = @min(who.len, buf.len); + for (who[0..n], buf[0..n]) |c, *o| o.* = if (c > 0x20 and c < 0x7f) c else '?'; + self.helo_ident = try arena.dupe(u8, buf[0..n]); return .{ .code = .ok, .lines = try arena.dupe([]const u8, &.{line}) }; } @@ -141,7 +199,7 @@ pub fn noop(self: *App, arena: Allocator, _: void) !nv.Reply { } pub fn data(self: *App, arena: Allocator, _: void) !nv.Reply { - _ = self; + if (self.recipients.items.len == 0) return nv.Reply.single(.bad_sequence, "Need RCPT before DATA"); const line = "Start mail input; end with ."; return .{ .code = .start_data, .lines = try arena.dupe([]const u8, &.{line}), .action = .data }; } diff --git a/src/bin/main.zig b/src/bin/main.zig index 1a9243b..db41f36 100644 --- a/src/bin/main.zig +++ b/src/bin/main.zig @@ -63,11 +63,21 @@ fn session(alloc: std.mem.Allocator, io: Io, stream: *Io.net.Stream) !void { var writer = stream.writer(io, &wbuf); const w = &writer.interface; + var tmp: [255]u8 = undefined; + var buf: [255]u8 = undefined; + var fbuf: [255]u8 = undefined; + const id = nv.Identity{ .addr = stream.socket.address }; + const who = try id.toString(&tmp); + const n = @min(who.len, buf.len); + for (who[0..n], buf[0..n]) |c, *o| o.* = if (c > 0x20 and c < 0x7f) c else '?'; + var fw: std.Io.Writer = .fixed(&fbuf); + try util.literal(&fw, who); + // Per-connection state var arena: std.heap.ArenaAllocator = .init(alloc); defer arena.deinit(); var store: Store = try .init(io, MAILDIR); - var app: App = .{ .gpa = alloc, .store = &store, .io = io }; + var app: App = .{ .gpa = alloc, .store = &store, .io = io, .peer = fw.buffered() }; // Greeting: the server speaks first try nv.Reply.single(.ready, "nvlope ready").send(w); @@ -90,7 +100,11 @@ fn session(alloc: std.mem.Allocator, io: Io, stream: *Io.net.Stream) !void { if (in_data) { if (std.mem.eql(u8, line, ".\r\n")) { in_data = false; - app.queue(); + app.queue() catch { + try nv.Reply.single(.storage_error, "Internal storage error").send(w); + try w.flush(); + continue; + }; try nv.Reply.single(.ok, "Queued").send(w); try w.flush(); std.debug.print("App {{\n\t body: {s}\n\tsender: {s}\n\trecipients: {any}\n}}\n", .{ app.body.items, app.sender.?, app.recipients.items }); diff --git a/src/bin/trace.zig b/src/bin/trace.zig new file mode 100644 index 0000000..a2fb394 --- /dev/null +++ b/src/bin/trace.zig @@ -0,0 +1,46 @@ +const std = @import("std"); +const Io = std.Io; + +sender: []const u8, +helo: []const u8, +peer: []const u8, +by: []const u8, +esmtp: bool, +id: []const u8, +rcpt: []const u8, +secs: i96, + +const Self = @This(); +const Trace = @This(); + +pub fn writeTrace(t: Trace, w: *Io.Writer) !void { + try w.print("Return-Path: <{s}>\r\n", .{t.sender}); + try w.print( + "Received: from {s} ({s})\r\n\tby {s} with {s} id {s}\r\n\tfor <{s}>; ", + .{ t.helo, t.peer, t.by, if (t.esmtp) "ESMTP" else "SMTP", t.id, t.rcpt }, + ); + try writeDate(w, t.secs); + try w.writeAll("\r\n"); +} + +fn writeDate(w: *Io.Writer, secs: i96) !void { + const days = [_][]const u8{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; + const mons = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; + + const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(secs) }; + const ed = es.getEpochDay(); + const yd = ed.calculateYearDay(); + const md = yd.calculateMonthDay(); + const ds = es.getDaySeconds(); + const dow = (ed.day + 4) % 7; + + try w.print("{s}, {d} {s} {d} {d:0>2}:{d:0>2}:{d:0>2} +0000", .{ + days[dow], + md.day_index + 1, + mons[md.month.numeric() - 1], + yd.year, + ds.getHoursIntoDay(), + ds.getMinutesIntoHour(), + ds.getSecondsIntoMinute(), + }); +} diff --git a/src/bin/util.zig b/src/bin/util.zig index 756ed74..9fb2ce4 100644 --- a/src/bin/util.zig +++ b/src/bin/util.zig @@ -13,3 +13,11 @@ pub fn normalizeUser(user: []const u8, buf: *[64]u8) ![]const u8 { try validateUser(out); return out; } + +pub fn literal(w: *std.Io.Writer, host: []const u8) !void { + const bare = std.mem.trim(u8, host, "[]"); + if (std.mem.indexOfScalar(u8, bare, ':') != null) + try w.print("[IPv6:{s}]", .{bare}) + else + try w.print("[{s}]", .{bare}); +} diff --git a/src/lib/reply.zig b/src/lib/reply.zig index 5bb5c94..5b20b9c 100644 --- a/src/lib/reply.zig +++ b/src/lib/reply.zig @@ -18,6 +18,7 @@ pub const Code = enum(u16) { exceeded = 552, param_unrecognized = 555, relay_denied = 554, + storage_error = 451, _, //@as(Code, @enumFromInt(user defined code)) }; -- cgit v1.2.3