diff options
| author | Nic Gaffney <gaffney_nic@protonmail.com> | 2026-11-19 19:47:26 -0600 |
|---|---|---|
| committer | Nic Gaffney <gaffney_nic@protonmail.com> | 2026-11-19 19:47:26 -0600 |
| commit | c714d9459d08b3f07d36b275e627473f1c962c83 (patch) | |
| tree | 9c5274c8efd2695485572e94a573261814d5de4b /src/bin | |
| parent | c9b27e99a830caae4419018938e796f7c96aedae (diff) | |
| download | nvlope-c714d9459d08b3f07d36b275e627473f1c962c83.tar.gz | |
Diffstat (limited to 'src/bin')
| -rw-r--r-- | src/bin/app.zig | 85 | ||||
| -rw-r--r-- | src/bin/config.zig | 23 | ||||
| -rw-r--r-- | src/bin/main.zig | 26 | ||||
| -rw-r--r-- | src/bin/store.zig | 3 | ||||
| -rw-r--r-- | src/bin/trace.zig | 5 |
5 files changed, 116 insertions, 26 deletions
diff --git a/src/bin/app.zig b/src/bin/app.zig index d448734..c755d23 100644 --- a/src/bin/app.zig +++ b/src/bin/app.zig @@ -1,5 +1,6 @@ const std = @import("std"); const nv = @import("nvlope"); +const Config = @import("config.zig").Config; const Allocator = std.mem.Allocator; const normalizeUser = @import("util.zig").normalizeUser; const Store = @import("store.zig"); @@ -8,8 +9,8 @@ const Trace = @import("trace.zig"); pub const App = @This(); gpa: Allocator, +cfg: Config, io: std.Io, -domain: []const u8 = "localhost", sender: ?[]const u8 = null, recipients: std.ArrayList([]const u8) = .empty, body: std.ArrayList(u8) = .empty, @@ -25,9 +26,6 @@ peer: []const u8, helo_ident: ?[]u8 = null, esmtp: bool = false, -const max_rcpt = 100; -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 { @@ -47,7 +45,7 @@ pub fn queue(self: *App) !void { const local = rc[0..at]; const domain = rc[at + 1 ..]; // std.debug.print("{s} {any}\n", .{ rc, try self.store.exists(self.io, local) }); - if (std.ascii.eqlIgnoreCase(domain, self.domain) and try self.store.exists(self.io, local)) { + if (std.ascii.eqlIgnoreCase(domain, self.cfg.domain) and try self.store.exists(self.io, local)) { std.debug.print("sending {s}\n", .{rc}); var maildir = try self.store.maildir.openDir(self.io, "mailboxes", .{}); defer maildir.close(self.io); @@ -64,7 +62,7 @@ pub fn queue(self: *App) !void { .sender = self.sender.?, .helo = self.helo_ident orelse "unknown", .peer = self.peer, - .by = self.domain, + .by = self.cfg.domain, .esmtp = self.esmtp, .id = id, .rcpt = rc, @@ -78,7 +76,7 @@ pub fn queue(self: *App) !void { var fbuf: [512]u8 = undefined; var fwriter = file.writer(self.io, &fbuf); const writer = &fwriter.interface; - try trace.writeTrace(writer); + try trace.writeTrace(writer, false); try writer.writeAll(self.body.items); try writer.flush(); try file.sync(self.io); @@ -90,14 +88,64 @@ pub fn queue(self: *App) !void { try tmp.rename(id, new, id, self.io); // std.posix.sync(); } else { - // Relay / user not defined + var spool = try self.store.maildir.openDir(self.io, "spool", .{}); + defer spool.close(self.io); + var tmp = try spool.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.cfg.domain, + .esmtp = self.esmtp, + .id = id, + .rcpt = rc, + .secs = @divFloor(nano, std.time.ns_per_s), + }; + + errdefer spool.close(self.io); + errdefer tmp.close(self.io); + tmp.createDir(self.io, id, @fromBackingInt(@intCast(0o700))) catch |e| + switch (e) { + error.PathAlreadyExists => {}, + else => return e, + }; + var msgdir = try tmp.openDir(self.io, id, .{}); + defer msgdir.close(self.io); + var msgfile = try msgdir.createFile(self.io, "msg", .{ .truncate = false }); + errdefer msgfile.close(self.io); + if (try msgfile.length(self.io) == 0) { + var fbuf: [512]u8 = undefined; + var fwriter = msgfile.writer(self.io, &fbuf); + const writer = &fwriter.interface; + try trace.writeTrace(writer, true); + try writer.writeAll(self.body.items); + try writer.flush(); + try msgfile.sync(self.io); + } + msgfile.close(self.io); + var metafile = try msgdir.createFile(self.io, "meta.zon", .{ .truncate = false }); + errdefer msgfile.close(self.io); + if (try metafile.length(self.io) == 0) { + var fbuf: [16]u8 = undefined; + var fwriter = metafile.writer(self.io, &fbuf); + const writer = &fwriter.interface; + writer.write(".{}"); + } + metafile.close(self.io); + //TODO: bruh the dir is made per the RCPT addr not the from addr ts sucks. } } } 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; + if (self.body.items.len + l.len > self.cfg.size) return .too_large; try self.body.appendSlice(self.gpa, l); return .ok; } @@ -133,7 +181,7 @@ pub fn ehlo(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply { 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[0] = try std.fmt.allocPrint(arena, "{s} greets {s}", .{ self.cfg.domain, who }); lines[1] = "8BITMIME"; lines[2] = "SIZE 35882577"; self.state = .ready; @@ -147,7 +195,7 @@ pub fn helo(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply { self.state = .ready; var tmp: [255]u8 = undefined; const who = try id.toString(&tmp); - const line = try std.fmt.allocPrint(arena, "{s}", .{self.domain}); + const line = try std.fmt.allocPrint(arena, "{s}", .{self.cfg.domain}); try self.setHelo(who); return .{ .code = .ok, .lines = try arena.dupe([]const u8, &.{line}) }; } @@ -161,7 +209,7 @@ pub fn mail(self: *App, arena: Allocator, m: nv.MailFrom) !nv.Reply { 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_body) return nv.Reply.single(.exceeded, "Message too large"); + if (n > self.cfg.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"); } @@ -174,7 +222,7 @@ pub fn mail(self: *App, arena: Allocator, m: nv.MailFrom) !nv.Reply { 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) + if (self.recipients.items.len >= self.cfg.max_rcpt) return nv.Reply.single(.too_many, "Too many recipients"); var it = r.paramIterator(); @@ -186,12 +234,17 @@ pub fn rcpt(self: *App, arena: Allocator, r: nv.RcptTo) !nv.Reply { const local = r.path[0..at]; const domain = r.path[at + 1 ..]; if (domain.len < 1) return nv.Reply.single(.param_unrecognized, "Invalid domain"); - if (!std.ascii.eqlIgnoreCase(domain, self.domain)) + var trust = false; + for (self.cfg.trusted_domains) |trusted| { + if (std.ascii.eqlIgnoreCase(trusted, domain)) + trust = true; + } + if (!trust and !std.ascii.eqlIgnoreCase(domain, self.cfg.domain)) return nv.Reply.single(.relay_denied, "Relay access denied"); // 554 var buf: [64]u8 = undefined; const user = normalizeUser(local, &buf) catch return nv.Reply.single(.rejected, "No such user"); // 550 - if (!try self.store.exists(self.io, user)) + if (!trust and !try self.store.exists(self.io, user)) return nv.Reply.single(.rejected, "No such user"); // 550 var slices = [_][]const u8{ user, r.path[at..] }; const owned = try std.mem.concat(self.gpa, u8, &slices); @@ -233,6 +286,6 @@ pub fn vrfy(self: *App, arena: Allocator, who: []const u8) !nv.Reply { } pub fn quit(self: *App, arena: Allocator, _: void) !nv.Reply { - const line = try std.fmt.allocPrint(arena, "{s} Service closing transmission channel", .{self.domain}); + const line = try std.fmt.allocPrint(arena, "{s} Service closing transmission channel", .{self.cfg.domain}); return .{ .code = .closing, .lines = try arena.dupe([]const u8, &.{line}), .action = .close }; } diff --git a/src/bin/config.zig b/src/bin/config.zig new file mode 100644 index 0000000..2a7ba7a --- /dev/null +++ b/src/bin/config.zig @@ -0,0 +1,23 @@ +const std = @import("std"); +const zon = std.zon; + +pub const Config = struct { + addr: []const u8 = "127.0.0.1", + port: u16 = 25, + maildir: []const u8 = "/var/mail", + domain: []const u8 = "localhost", + size: usize = 10 * 1024 * 1024, + max_rcpt: usize = 100, + trusted_domains: []const []const u8 = &[_][]const u8{ + "mail.google.com", + "mail.ngaffney.dev", + }, +}; + +pub fn readConfig(io: std.Io, alloc: std.mem.Allocator, path: []const u8) !Config { + const cfg = try std.Io.Dir.cwd().readFileAllocOptions(io, path, alloc, .unlimited, .@"8", 0); + defer alloc.free(cfg); + var diag: zon.parse.Diagnostics = undefined; + const parsed = try zon.parse.fromSlice(Config, .{ .gpa = alloc, .arena = alloc, .source = cfg, .diagnostics = &diag }); + return parsed; +} diff --git a/src/bin/main.zig b/src/bin/main.zig index cdc9d3d..d1b6770 100644 --- a/src/bin/main.zig +++ b/src/bin/main.zig @@ -2,14 +2,14 @@ const std = @import("std"); const Io = std.Io; const App = @import("app.zig"); const Store = @import("store.zig"); +const Config = @import("config.zig").Config; +const readConfig = @import("config.zig").readConfig; const Watchdog = @import("timeout.zig").Watchdog; const Limits = @import("timeout.zig").Limits; const util = @import("util.zig"); const nv = @import("nvlope"); -const MAILDIR: []const u8 = "/var/mail/"; -const PORT = 2525; - +var cfg: Config = .{}; // Default values const limits: Limits = .{}; pub fn main(init: std.process.Init) !void { @@ -18,12 +18,22 @@ pub fn main(init: std.process.Init) !void { var argiter = init.minimal.args.iterate(); const program = argiter.next().?; if (argiter.next()) |arg| { + if (std.ascii.eqlIgnoreCase(arg[0..arg.len], "--config")) { + const raw = argiter.next() orelse { + std.debug.print("Usage: {s} --config <file.zon>\n", .{program}); + return; + }; + cfg = readConfig(io, alloc, raw) catch { + std.debug.print("Failed to read config file {s}\n", .{raw}); + return; + }; + } if (std.ascii.eqlIgnoreCase(arg[0..arg.len], "--register")) { const raw = argiter.next() orelse { std.debug.print("Usage: {s} --register <uname>\n", .{program}); return; }; - var store = try Store.init(io, MAILDIR); + var store = try Store.init(io, cfg.maildir); defer store.maildir.close(io); try store.register(io, raw); return; @@ -31,7 +41,7 @@ pub fn main(init: std.process.Init) !void { } // Initialize server on localhost at the specified port - const addr = try Io.net.IpAddress.parse("127.0.0.1", PORT); + const addr = try Io.net.IpAddress.parse(cfg.addr, cfg.port); var server = try addr.listen(io, .{ .mode = .stream, .protocol = .tcp, @@ -43,7 +53,7 @@ pub fn main(init: std.process.Init) !void { defer group.cancel(io); // First time startup check - var store = try Store.init(io, MAILDIR); + var store = try Store.init(io, cfg.maildir); store.maildir.close(io); // Async delivery worker here @@ -92,8 +102,8 @@ fn session(alloc: std.mem.Allocator, io: Io, stream: *Io.net.Stream) !void { // 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, .peer = fw.buffered() }; + var store: Store = try .init(io, cfg.maildir); + var app: App = .{ .cfg = cfg, .gpa = alloc, .store = &store, .io = io, .peer = fw.buffered() }; defer app.deinit(); // Greeting: the server speaks first diff --git a/src/bin/store.zig b/src/bin/store.zig index 8d93fec..7eee897 100644 --- a/src/bin/store.zig +++ b/src/bin/store.zig @@ -36,6 +36,9 @@ pub fn init(io: std.Io, dir: []const u8) !Self { pub fn register(self: *Self, io: std.Io, raw: []const u8) !void { var buf: [64]u8 = undefined; const user = try normalizeUser(raw, &buf); + if (try self.exists(io, user)) { + return error.UserExists; + } var mailbox = try self.maildir.openDir(io, "mailboxes", .{}); defer mailbox.close(io); try mailbox.createDir(io, user, @fromBackingInt(@intCast(0o700))); diff --git a/src/bin/trace.zig b/src/bin/trace.zig index a2fb394..9577789 100644 --- a/src/bin/trace.zig +++ b/src/bin/trace.zig @@ -13,8 +13,9 @@ 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}); +pub fn writeTrace(t: Trace, w: *Io.Writer, remote: bool) !void { + if (!remote) + 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 }, |
