1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
|
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;
var argiter = init.minimal.args.iterate();
const program = argiter.next().?;
if (argiter.next()) |arg| {
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);
defer store.maildir.close(io);
try store.register(io, raw);
return;
}
}
// Initialize server on localhost at the specified port
const addr = try Io.net.IpAddress.parse("127.0.0.1", PORT);
var server = try addr.listen(io, .{
.mode = .stream,
.protocol = .tcp,
.reuse_address = true,
});
defer server.socket.close(io);
var group: Io.Group = .init;
defer group.cancel(io);
// First time startup check
var store = try Store.init(io, MAILDIR);
store.maildir.close(io);
// Async delivery worker here
while (true) {
const stream = try server.accept(io);
group.concurrent(io, serve, .{ alloc, io, stream }) catch {
// ConcurrencyUnavailable: at capacity, refuse politely
var s = stream;
s.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)});
}
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;
var wbuf: [1024]u8 = undefined;
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, .peer = fw.buffered() };
// 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) {
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;
}
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 => too_large = true,
}
try w.flush();
}
continue;
}
switch (try nv.handleLine(App, &app, arena.allocator(), line, w)) {
.cont => {},
.data => in_data = true,
.close => return,
}
}
}
|