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
|
const std = @import("std");
const Io = std.Io;
const Response = @import("response.zig");
const App = Response.App;
const nv = @import("nvlope");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const alloc = std.heap.smp_allocator;
// Initialize server on localhost at the specified port
const port = 8080;
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);
while (true) {
std.debug.print("Waiting for conn...\n", .{});
const stream = try server.accept(io);
group.async(io, serve, .{ alloc, io, stream });
}
}
// 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 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;
// Per-connection state
var arena: std.heap.ArenaAllocator = .init(alloc);
defer arena.deinit();
var app: App = .{ .gpa = alloc };
// Greeting: the server speaks first
try nv.Reply.single(.ready, "localhost ESMTP ready").send(w);
try w.flush();
var in_data = 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();
return;
},
else => |e| return e,
};
_ = arena.reset(.retain_capacity);
if (in_data) {
if (std.mem.eql(u8, line, ".\r\n")) {
in_data = false;
try nv.Reply.single(.ok, "Queued").send(w);
try w.flush();
} else {
const status = try app.appendBodyLine(line);
switch (status) {
.ok => continue,
.too_large => try nv.Reply.single(.exceeded, "Message too large").send(w),
}
try w.flush();
}
continue;
}
switch (try nv.handleLine(App, &app, arena.allocator(), line, w)) {
.cont => {},
.data => in_data = true,
.close => return,
}
}
}
|