From 5066d11e25dece937b48b5b5d70f2618a4ca3c47 Mon Sep 17 00:00:00 2001 From: Nic Gaffney Date: Sat, 31 Oct 2026 03:03:58 -0500 Subject: Timeouts --- build.zig.zon | 2 +- src/bin/app.zig | 36 +++++++++++++++++----------- src/bin/main.zig | 69 +++++++++++++++++++++++++++++++++++++++++++---------- src/bin/timeout.zig | 47 ++++++++++++++++++++++++++++++++++++ src/lib/reply.zig | 2 +- 5 files changed, 127 insertions(+), 29 deletions(-) create mode 100644 src/bin/timeout.zig diff --git a/build.zig.zon b/build.zig.zon index 314e590..07b8b56 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,6 +1,6 @@ .{ .name = .nvlope, - .version = "1.0.0", + .version = "1.1.0", .fingerprint = 0xd532f2614d0039f7, .minimum_zig_version = "0.17.0", .dependencies = .{}, diff --git a/src/bin/app.zig b/src/bin/app.zig index 474592e..801a7bd 100644 --- a/src/bin/app.zig +++ b/src/bin/app.zig @@ -47,7 +47,9 @@ pub fn queue(self: *App) !void { const at = std.mem.lastIndexOfScalar(u8, rc, '@') orelse continue; 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)) { + std.debug.print("sending {s}\n", .{rc}); var maildir = try self.store.maildir.openDir(self.io, "mailboxes", .{}); defer maildir.close(self.io); var mailbox = try maildir.openDir(self.io, local, .{}); @@ -83,7 +85,9 @@ pub fn queue(self: *App) !void { file.close(self.io); const new = try mailbox.openDir(self.io, "new", .{}); + // errdefer maildir.close(self.io); try tmp.rename(id, new, id, self.io); + // std.posix.sync(); } else { // Relay / user not defined } @@ -98,7 +102,10 @@ pub fn appendBodyLine(self: *App, line: []const u8) !enum { ok, too_large } { } pub fn resetTransaction(self: *App) void { - if (@backingInt(self.state) <= 2) self.state = .ready else self.state = .start; + if (self.helo_ident) |h| { + self.gpa.free(h); + self.state = .ready; + } if (self.sender) |s| self.gpa.free(s); self.sender = null; for (self.recipients.items) |r| self.gpa.free(r); @@ -106,6 +113,15 @@ pub fn resetTransaction(self: *App) void { self.body.clearRetainingCapacity(); } +fn setHelo(self: *App, who: []const u8) !void { + 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 '?'; + const owned = try self.gpa.dupe(u8, buf[0..n]); + if (self.helo_ident) |old| self.gpa.free(old); + self.helo_ident = owned; +} + pub fn ehlo(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply { self.resetTransaction(); var tmp: [255]u8 = undefined; @@ -115,12 +131,7 @@ pub fn ehlo(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply { 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]); - + try self.setHelo(who); self.esmtp = true; return .{ .code = .ok, .lines = lines }; } @@ -131,15 +142,12 @@ pub fn helo(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply { 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]); + try self.setHelo(who); return .{ .code = .ok, .lines = try arena.dupe([]const u8, &.{line}) }; } pub fn mail(self: *App, arena: Allocator, m: nv.MailFrom) !nv.Reply { + if (self.sender) |_| return nv.Reply.single(.bad_sequence, "MAIL already recieved, need RSET to reset MAIL"); _ = arena; if (@backingInt(self.state) < 2) return nv.Reply.single(.bad_sequence, "Need EHLO before MAIL"); var it = m.paramIterator(); @@ -153,7 +161,6 @@ pub fn mail(self: *App, arena: Allocator, m: nv.MailFrom) !nv.Reply { } } self.state = .mail; - if (self.sender) |old| self.gpa.free(old); self.sender = try self.gpa.dupe(u8, m.path); return nv.Reply.single(.ok, "Sender OK"); } @@ -180,7 +187,7 @@ pub fn rcpt(self: *App, arena: Allocator, r: nv.RcptTo) !nv.Reply { if (!try self.store.exists(self.io, user)) return nv.Reply.single(.rejected, "No such user"); // 550 - const owned = try self.gpa.dupe(u8, r.path); + const owned = try std.mem.concat(self.gpa, u8, &[_][]const u8{ user, "@", domain }); errdefer self.gpa.free(owned); try self.recipients.append(self.gpa, owned); return nv.Reply.single(.ok, "OK"); @@ -199,6 +206,7 @@ pub fn noop(self: *App, arena: Allocator, _: void) !nv.Reply { } pub fn data(self: *App, arena: Allocator, _: void) !nv.Reply { + if (self.sender == null) return nv.Reply.single(.bad_sequence, "Need MAIL before DATA"); 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 76504ef..317885e 100644 --- a/src/bin/main.zig +++ b/src/bin/main.zig @@ -2,20 +2,30 @@ const std = @import("std"); const Io = std.Io; const App = @import("app.zig"); const Store = @import("store.zig"); +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; +const limits: Limits = .{}; + pub fn main(init: std.process.Init) !void { const io = init.io; - const alloc = std.heap.smp_allocator; + // const alloc = std.heap.smp_allocator; + var dbg: std.heap.DebugAllocator(.{}) = .init; + defer _ = dbg.deinit(); + const alloc = dbg.allocator(); var argiter = init.minimal.args.iterate(); - _ = argiter.skip(); + const program = argiter.next().?; if (argiter.next()) |arg| { if (std.ascii.eqlIgnoreCase(arg[0..arg.len], "--register")) { - const raw = argiter.next().?; + const raw = argiter.next() orelse { + std.debug.print("Usage: {s} --register \n", .{program}); + return; + }; var store = try Store.init(io, MAILDIR); defer store.maildir.close(io); try store.register(io, raw); @@ -36,13 +46,18 @@ pub fn main(init: std.process.Init) !void { defer group.cancel(io); // First time startup check - (try Store.init(io, MAILDIR)).maildir.close(io); + var store = try Store.init(io, MAILDIR); + store.maildir.close(io); // Async delivery worker here while (true) { const stream = try server.accept(io); - group.async(io, serve, .{ alloc, io, stream }); + group.concurrent(io, serve, .{ alloc, io, stream }) catch { + // ConcurrencyUnavailable: at capacity, refuse politely + var s = stream; + s.close(io); + }; } } @@ -55,6 +70,10 @@ fn serve(alloc: std.mem.Allocator, io: Io, stream: Io.net.Stream) void { } fn session(alloc: std.mem.Allocator, io: Io, stream: *Io.net.Stream) !void { + var wd: Watchdog = .init(io, limits.session_s); + var dog = try io.concurrent(Watchdog.run, .{ &wd, io, stream.* }); + defer dog.cancel(io); // blocks until the task exits, so it can't touch a closed fd + var rbuf: [1024]u8 = undefined; var reader = stream.reader(io, &rbuf); const r = &reader.interface; @@ -82,38 +101,62 @@ fn session(alloc: std.mem.Allocator, io: Io, stream: *Io.net.Stream) !void { // Greeting: the server speaks first try nv.Reply.single(.ready, "nvlope ready").send(w); try w.flush(); + app.state = .start; + app.resetTransaction(); var in_data = false; + var too_large = false; while (true) { - const line = r.takeDelimiterInclusive('\n') catch |err| switch (err) { - error.EndOfStream => return, // client hung up - error.StreamTooLong => { - try nv.Reply.single(.bad_cmd, "Line too long").send(w); - try w.flush(); + wd.arm(io, if (in_data) limits.data_s else if (app.state == .start) limits.greeting_s else limits.command_s); + const line = r.takeDelimiterInclusive('\n') catch |err| { + if (wd.fired.load(.acquire)) { + nv.Reply.single(.not_avail, "Connection Timed Out").send(w) catch {}; + w.flush() catch {}; return; - }, - else => |e| return e, + } + switch (err) { + // error.EndOfStream => return, // client hung up + error.StreamTooLong => { + try nv.Reply.single(.bad_cmd, "Line too long").send(w); + try w.flush(); + return; + }, + else => { + nv.Reply.single(.not_avail, "Client Disconnected").send(w) catch {}; + w.flush() catch {}; + return; + }, + // else => |e| return e, + } }; + wd.disarm(); _ = arena.reset(.retain_capacity); std.debug.print("C: {s}", .{line}); if (in_data) { if (std.mem.eql(u8, line, ".\r\n")) { in_data = false; + if (too_large) { + try nv.Reply.single(.exceeded, "Message too large").send(w); + app.resetTransaction(); + continue; + } app.queue() catch { try nv.Reply.single(.storage_error, "Internal storage error").send(w); try w.flush(); + app.resetTransaction(); continue; }; try nv.Reply.single(.ok, "Queued").send(w); + app.resetTransaction(); 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 }); } else { const status = try app.appendBodyLine(line); switch (status) { .ok => continue, - .too_large => try nv.Reply.single(.exceeded, "Message too large").send(w), + .too_large => too_large = true, } try w.flush(); } diff --git a/src/bin/timeout.zig b/src/bin/timeout.zig new file mode 100644 index 0000000..c811c1d --- /dev/null +++ b/src/bin/timeout.zig @@ -0,0 +1,47 @@ +const std = @import("std"); +const Io = std.Io; + +pub const Limits = struct { + greeting_s: i64 = 30, + command_s: i64 = 300, + data_s: i64 = 180, + session_s: i64 = 1800, +}; + +pub const Watchdog = struct { + deadline_ms: std.atomic.Value(i64), + session_end_ms: i64, + fired: std.atomic.Value(bool) = .init(false), + + pub fn init(io: Io, session_s: i64) Watchdog { + const end = nowMs(io) + session_s * 1000; + return .{ .session_end_ms = end, .deadline_ms = .init(end) }; + } + + pub fn nowMs(io: Io) i64 { + return @intCast(@divFloor(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms)); + } + + pub fn arm(self: *Watchdog, io: Io, secs: i64) void { + self.deadline_ms.store(@min(nowMs(io) + secs * 1000, self.session_end_ms), .release); + } + + /// Call as soon as a line arrives, so slow processing isn't mistaken for idleness. + pub fn disarm(self: *Watchdog) void { + self.deadline_ms.store(self.session_end_ms, .release); + } + + pub fn run(self: *Watchdog, io: Io, stream: Io.net.Stream) void { + const tick_ms = 500; + while (true) { + const now = nowMs(io); + const dl = self.deadline_ms.load(.acquire); + if (now >= dl) { + self.fired.store(true, .release); + stream.shutdown(io, .recv) catch {}; + return; + } + io.sleep(.fromMilliseconds(@min(dl - now, tick_ms)), .awake) catch return; + } + } +}; diff --git a/src/lib/reply.zig b/src/lib/reply.zig index 866f6b4..42da073 100644 --- a/src/lib/reply.zig +++ b/src/lib/reply.zig @@ -37,8 +37,8 @@ pub const Reply = struct { const code = @backingInt(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 }); std.debug.print("S: {d}{c}{s}\r\n", .{ code, sep, line }); + try w.print("{d}{c}{s}\r\n", .{ code, sep, line }); } } }; -- cgit v1.2.3