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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
|
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");
const Trace = @import("trace.zig");
pub const App = @This();
gpa: Allocator,
cfg: Config,
io: std.Io,
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,
store: *Store,
peer: []const u8,
helo_ident: ?[]u8 = null,
esmtp: bool = false,
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 {
for (self.recipients.items) |rc| {
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.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);
var mailbox = try maildir.openDir(self.io, local, .{});
defer mailbox.close(self.io);
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.cfg.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 file.close(self.io);
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, false);
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", .{});
defer new.close(self.io);
// errdefer maildir.close(self.io);
try tmp.rename(id, new, id, self.io);
// std.posix.sync();
} else {
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 > self.cfg.size) return .too_large;
try self.body.appendSlice(self.gpa, l);
return .ok;
}
pub fn resetTransaction(self: *App) void {
if (self.state != .init and self.state != .start) self.state = .ready;
if (self.sender) |s| self.gpa.free(s);
self.sender = null;
for (self.recipients.items) |r| self.gpa.free(r);
self.recipients.clearRetainingCapacity();
self.body.clearRetainingCapacity();
}
pub fn deinit(self: *App) void {
self.resetTransaction();
self.recipients.deinit(self.gpa);
self.body.deinit(self.gpa);
if (self.helo_ident) |h| self.gpa.free(h);
self.helo_ident = null;
}
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;
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.cfg.domain, who });
lines[1] = "8BITMIME";
lines[2] = "SIZE 35882577";
self.state = .ready;
try self.setHelo(who);
self.esmtp = true;
return .{ .code = .ok, .lines = lines };
}
pub fn helo(self: *App, arena: Allocator, id: nv.Identity) !nv.Reply {
self.resetTransaction();
self.state = .ready;
var tmp: [255]u8 = undefined;
const who = try id.toString(&tmp);
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}) };
}
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();
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 > 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");
}
}
self.state = .mail;
self.sender = try self.gpa.dupe(u8, m.path);
return nv.Reply.single(.ok, "Sender 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 >= self.cfg.max_rcpt)
return nv.Reply.single(.too_many, "Too many recipients");
var it = r.paramIterator();
if (it.next() != null)
return nv.Reply.single(.param_unrecognized, "Unrecognized parameter");
const at = std.mem.lastIndexOfScalar(u8, r.path, '@') orelse
return self.acceptLocal(std.mem.trim(u8, r.path, " "));
const local = r.path[0..at];
const domain = r.path[at + 1 ..];
if (domain.len < 1) return nv.Reply.single(.param_unrecognized, "Invalid 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 (!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);
for (self.recipients.items) |existing| {
if (std.ascii.eqlIgnoreCase(existing, owned)) {
self.gpa.free(owned);
return nv.Reply.single(.ok, "OK"); // already accepted; one copy only
}
}
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 {
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 <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.cfg.domain});
return .{ .code = .closing, .lines = try arena.dupe([]const u8, &.{line}), .action = .close };
}
|