diff options
Diffstat (limited to 'src/lib')
| -rw-r--r-- | src/lib/commands.zig | 64 | ||||
| -rw-r--r-- | src/lib/dispatch.zig | 32 | ||||
| -rw-r--r-- | src/lib/parse.zig | 89 | ||||
| -rw-r--r-- | src/lib/parser.zig | 40 | ||||
| -rw-r--r-- | src/lib/reply.zig | 41 | ||||
| -rw-r--r-- | src/lib/response.zig | 117 | ||||
| -rw-r--r-- | src/lib/root.zig | 17 | ||||
| -rw-r--r-- | src/lib/smtp_parse.zig | 165 | ||||
| -rw-r--r-- | src/lib/tmp.zig | 50 |
9 files changed, 240 insertions, 375 deletions
diff --git a/src/lib/commands.zig b/src/lib/commands.zig new file mode 100644 index 0000000..719e93f --- /dev/null +++ b/src/lib/commands.zig @@ -0,0 +1,64 @@ +const IpAddress = @import("std").Io.net.IpAddress; +const std = @import("std"); + +pub const Identity = union(enum) { + domain: []const u8, + addr: IpAddress, + + pub fn toString(self: Identity, buf: []u8) ![]const u8 { + return switch (self) { + .domain => self.domain, + .addr => blk: { + var fw: std.Io.Writer = .fixed(buf); + try self.addr.format(&fw); + const full = fw.buffered(); + const host: []const u8 = if (std.mem.lastIndexOfScalar(u8, full, ':')) |i| full[0..i] else full; + break :blk host; + }, + }; + } +}; + +pub const Path = struct { + path: []const u8, + params: []const u8, + + pub const Param = struct { key: []const u8, value: ?[]const u8 }; + + pub const ParamIterator = struct { + it: std.mem.TokenIterator(u8, .scalar), + + pub fn next(self: *ParamIterator) ?Param { + const tok = self.it.next() orelse return null; + if (std.mem.indexOfScalar(u8, tok, '=')) |i| + return .{ .key = tok[0..i], .value = tok[i + 1 ..] }; + return .{ .key = tok, .value = null }; + } + }; + + pub fn paramIterator(self: Path) ParamIterator { + return .{ .it = std.mem.tokenizeScalar(u8, self.params, ' ') }; + } +}; + +pub const MailFrom = Path; +pub const RcptTo = Path; + +pub const User = struct { + name: []const u8, // local part; a quoted string keeps its quotes + host: ?Identity, // null only for <postmaster> +}; + +pub const Verb = enum { ehlo, helo, mail, rcpt, data, rset, noop, quit, vrfy }; + +pub const Command = union(Verb) { + ehlo: Identity, + helo: Identity, + mail: MailFrom, + rcpt: RcptTo, + data: void, + rset: void, + noop: void, + quit: void, + vrfy: []const u8, +}; diff --git a/src/lib/dispatch.zig b/src/lib/dispatch.zig new file mode 100644 index 0000000..d4c83b8 --- /dev/null +++ b/src/lib/dispatch.zig @@ -0,0 +1,32 @@ +const std = @import("std"); +const nvcmd = @import("commands.zig"); +const nvparse = @import("parse.zig"); +const nvrply = @import("reply.zig"); +const Reply = nvrply.Reply; +const Command = nvcmd.Command; +const Allocator = std.mem.Allocator; +const Io = std.Io; +const Action = nvrply.Action; +const parse = nvparse.parse; + +pub fn dispatch(comptime H: type, h: *H, arena: Allocator, cmd: Command) !Reply { + switch (cmd) { + inline else => |payload, tag| { + const name = @tagName(tag); + if (@hasDecl(H, name)) return @field(H, name)(h, arena, payload); + return Reply.single(.not_impl, "Command not implemented"); + }, + } +} + +pub fn handleLine(comptime H: type, h: *H, arena: Allocator, line: []const u8, w: *Io.Writer) !Action { + const reply = if (parse(line)) |cmd| + try dispatch(H, h, arena, cmd) + else |err| switch (err) { + error.UnknownCommand => Reply.single(.bad_cmd, "Command not recognized"), + error.BadParam => Reply.single(.bad_param, "Syntax error in parameters"), + }; + try reply.send(w); + try w.flush(); + return reply.action; +} diff --git a/src/lib/parse.zig b/src/lib/parse.zig new file mode 100644 index 0000000..334813e --- /dev/null +++ b/src/lib/parse.zig @@ -0,0 +1,89 @@ +const std = @import("std"); +const net = std.Io.net; +const Command = @import("commands.zig").Command; +const Verb = @import("commands.zig").Verb; +const Identity = @import("commands.zig").Identity; +const User = @import("commands.zig").Path; + +pub const ParseError = error{ UnknownCommand, BadParam }; + +pub fn parse(raw: []const u8) ParseError!Command { + const line = std.mem.trimEnd(u8, raw, "\r\n"); + const sp = std.mem.indexOfScalar(u8, line, ' '); + const verb_str = line[0 .. sp orelse line.len]; + const arg = if (sp) |i| std.mem.trimStart(u8, line[i + 1 ..], " ") else ""; + + if (verb_str.len != 4) return error.UnknownCommand; + var lower: [4]u8 = undefined; + _ = std.ascii.lowerString(&lower, verb_str); + const verb = std.meta.stringToEnum(Verb, &lower) orelse return error.UnknownCommand; + + return switch (verb) { + .ehlo => .{ .ehlo = try identity(arg) }, + .helo => .{ .helo = try identity(arg) }, + .mail => .{ .mail = try path(arg, "FROM:", .{ .allow_null = true }) }, + .rcpt => .{ .rcpt = try path(arg, "TO:", .{ .allow_postmaster = true }) }, + .vrfy => blk: { + if (arg.len == 0) return error.BadParam; + break :blk .{ .vrfy = arg }; + }, + inline else => |v| @unionInit(Command, @tagName(v), {}), + }; +} + +const PathRules = struct { + allow_null: bool = false, + allow_postmaster: bool = false, +}; + +fn path(arg: []const u8, comptime prefix: []const u8, rules: PathRules) ParseError!User { + if (!std.ascii.startsWithIgnoreCase(arg, prefix)) return error.BadParam; + + const rest = std.mem.trimStart(u8, arg[prefix.len..], " "); + if (rest.len == 0 or rest[0] != '<') return error.BadParam; + + const close = std.mem.indexOfScalar(u8, rest, '>') orelse return error.BadParam; + var p = rest[1..close]; + + const tail = rest[close + 1 ..]; + if (tail.len > 0 and tail[0] != ' ') return error.BadParam; + const params = std.mem.trim(u8, tail, " "); + + if (p.len > 0 and p[0] == '@') { + const colon = std.mem.indexOfScalar(u8, p, ':') orelse return error.BadParam; + p = p[colon + 1 ..]; + } + + if (p.len == 0) { + if (!rules.allow_null) return error.BadParam; + } else if (rules.allow_postmaster and std.ascii.eqlIgnoreCase(p, "postmaster")) {} else { + try validateMailbox(p); + } + return .{ .path = p, .params = params }; +} + +fn validateMailbox(vpath: []const u8) ParseError!void { + if (vpath.len > 254) return error.BadParam; + const at = std.mem.lastIndexOfScalar(u8, vpath, '@') orelse return error.BadParam; + const local = vpath[0..at]; + const domain = vpath[at + 1 ..]; + if (local.len == 0 or local.len > 64) return error.BadParam; + if (domain.len == 0 or domain.len > 255) return error.BadParam; + for (vpath) |c| { + if (c < 0x20 or c == 0x7f) return error.BadParam; + } +} + +fn identity(arg: []const u8) ParseError!Identity { + if (arg.len == 0) return error.BadParam; + if (arg[0] != '[') return .{ .domain = arg }; + + if (arg[arg.len - 1] != ']') return error.BadParam; + const inner = arg[1 .. arg.len - 1]; + if (std.ascii.startsWithIgnoreCase(inner, "IPv6:")) { + const ip = net.Ip6Address.parse(inner[5..], 0) catch return error.BadParam; + return .{ .addr = .{ .ip6 = ip } }; + } + const ip = net.Ip4Address.parse(inner, 0) catch return error.BadParam; + return .{ .addr = .{ .ip4 = ip } }; +} diff --git a/src/lib/parser.zig b/src/lib/parser.zig deleted file mode 100644 index f0cc8d9..0000000 --- a/src/lib/parser.zig +++ /dev/null @@ -1,40 +0,0 @@ -const std = @import("std"); - -pub const ParserError = error{ Unexpected, EndOfString }; - -str: []const u8, -pos: u32 = 0, - -const Self = @This(); - -pub fn peek(self: Self) ?u8 { - if (self.pos >= self.str.len) return null; - return self.str[self.pos]; -} - -pub fn consume(self: *Self, c: u8) ParserError!void { - if (self.peek()) |pk| { - if (pk == c) { - self.pos += 1; - return; - } - return ParserError.Unexpected; - } - return ParserError.EndOfString; -} - -pub fn skip(self: *Self) void { - self.pos += 1; -} - -pub fn skipMany(self: *Self, n: usize) void { - for (0..n) |_| - self.skip(); -} - -pub fn takeUntil(self: *Self, c: u8) ParserError![]const u8 { - const i = self.pos; - while (self.peek() != null and self.peek().? != c) self.skip(); - self.skip(); - return self.str[i .. self.pos - 1]; -} diff --git a/src/lib/reply.zig b/src/lib/reply.zig new file mode 100644 index 0000000..61df971 --- /dev/null +++ b/src/lib/reply.zig @@ -0,0 +1,41 @@ +const std = @import("std"); +const Io = std.Io; + +pub const Code = enum(u16) { + ready = 220, + cannot_verify = 252, + closing = 221, + start_data = 354, + ok = 250, + not_avail = 421, + bad_cmd = 500, + bad_param = 501, + not_impl = 502, + bad_sequence = 503, + param_not_impl = 504, + rejected = 550, + too_many = 452, + exceeded = 552, + param_unrecognized = 555, + _, //@as(Code, @enumFromInt(user defined code)) +}; + +pub const Action = enum { cont, data, close }; + +pub const Reply = struct { + code: Code, + lines: []const []const u8, + action: Action = .cont, + + pub fn single(code: Code, comptime text: []const u8) Reply { + return .{ .code = code, .lines = &.{text} }; + } + + pub fn send(self: Reply, w: *Io.Writer) !void { + const code = @intFromEnum(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 }); + } + } +}; diff --git a/src/lib/response.zig b/src/lib/response.zig deleted file mode 100644 index 06458ff..0000000 --- a/src/lib/response.zig +++ /dev/null @@ -1,117 +0,0 @@ -const std = @import("std"); - -pub const ResponseError = error{Unimplemented}; - -pub const Identity = union(enum) { - domain: []const u8, - addr: std.Io.net.IpAddress, -}; - -pub const Message = struct { - str: []const u8, - cmd: Command, - client: Identity, -}; - -pub const Command = enum { - EHLO, - HELO, - MAIL, - RCPT, - DATA, - RSET, - NOOP, - QUIT, - VRFY, - - pub fn fromStr(msg: []const u8) ?Command { - var MSG: [4]u8 = undefined; - if (msg.len != 4) return null; - _ = std.ascii.upperString(&MSG, msg); - if (std.mem.eql(u8, &MSG, "EHLO")) return .EHLO; - if (std.mem.eql(u8, &MSG, "HELO")) return .HELO; - if (std.mem.eql(u8, &MSG, "MAIL")) return .MAIL; - if (std.mem.eql(u8, &MSG, "RCPT")) return .RCPT; - if (std.mem.eql(u8, &MSG, "DATA")) return .DATA; - if (std.mem.eql(u8, &MSG, "RSET")) return .RSET; - if (std.mem.eql(u8, &MSG, "NOOP")) return .NOOP; - if (std.mem.eql(u8, &MSG, "QUIT")) return .QUIT; - if (std.mem.eql(u8, &MSG, "VRFY")) return .VRFY; - return null; - } -}; - -const Code = enum(u32) { - INIT = 220, - OK = 250, -}; - -pub const Response = struct { - code: Code, - contents: []const u8, -}; - -pub fn init(w: *std.Io.Writer, server: *std.Io.net.Server) !Response { - const resp: Response = .{ .code = .INIT, .contents = "nvlope ready" }; - try w.print("{d} ", .{resp.code}); - var buf: [64]u8 = undefined; - const l = try strip_port(server.socket.address, &buf); - const host = buf[0..l]; - try w.print("[{s}]", .{host}); - try w.print(" {s}\r\n", .{resp.contents}); - try w.flush(); - return resp; -} - -pub fn respond(w: *std.Io.Writer, msg: Message, server: *std.Io.net.Server) !Response { - return switch (msg.cmd) { - .EHLO => try ehlo(w, msg, null, server), - .HELO => try helo(w, msg, null, server), - else => ResponseError.Unimplemented, - }; -} - -pub fn helo(w: *std.Io.Writer, msg: Message, domain: ?[]const u8, server: *std.Io.net.Server) !Response { - _ = msg; - var resp: Response = .{ .code = .OK, .contents = undefined }; - if (domain) |d| { - resp.contents = d; - try w.print("{d} {s}\r\n", .{ resp.code, resp.contents }); - try w.flush(); - return resp; - } - try w.print("{d} ", .{resp.code}); - var buf: [64]u8 = undefined; - const l = try strip_port(server.socket.address, &buf); - const host: []const u8 = buf[0..l]; - try w.print("[{s}]\r\n", .{host}); - resp.contents = host; - return resp; -} - -pub fn ehlo(w: *std.Io.Writer, msg: Message, domain: ?[]const u8, server: *std.Io.net.Server) !Response { - _ = msg; - var resp: Response = .{ .code = .OK, .contents = undefined }; - if (domain) |d| { - resp.contents = d; - try w.print("{d} {s}\r\n", .{ resp.code, resp.contents }); - try w.flush(); - return resp; - } - try w.print("{d} ", .{resp.code}); - var buf: [64]u8 = undefined; - const l = try strip_port(server.socket.address, &buf); - const host: []const u8 = buf[0..l]; - try w.print("[{s}]\r\n", .{host}); - resp.contents = host; - return resp; -} - -fn strip_port(addr: std.Io.net.IpAddress, buf: []u8) !usize { - var fw: std.Io.Writer = .fixed(buf); - try addr.format(&fw); - const full = fw.buffered(); - const host = if (std.mem.lastIndexOfScalar(u8, full, ':')) |i| full[0..i] else full; - std.mem.copyForwards(u8, buf, host); - return host.len; -} diff --git a/src/lib/root.zig b/src/lib/root.zig index 3e8fcb2..7379fc7 100644 --- a/src/lib/root.zig +++ b/src/lib/root.zig @@ -1,7 +1,18 @@ -pub const Parser = @import("smtp_parse.zig"); -pub const Response = @import("response.zig"); +pub const Parser = @import("parse.zig"); +pub const Dispatch = @import("dispatch.zig"); +pub const Reply = @import("reply.zig").Reply; +pub const Code = @import("reply.zig").Code; +pub const Commands = @import("commands.zig"); +pub const Command = Commands.Command; +pub const Identity = Commands.Identity; +pub const MailFrom = Commands.MailFrom; +pub const RcptTo = Commands.RcptTo; +pub const handleLine = Dispatch.handleLine; test "all" { + _ = Identity; _ = Parser; - _ = Response; + _ = Reply; + _ = Code; + _ = Command; } diff --git a/src/lib/smtp_parse.zig b/src/lib/smtp_parse.zig deleted file mode 100644 index 44822ff..0000000 --- a/src/lib/smtp_parse.zig +++ /dev/null @@ -1,165 +0,0 @@ -const std = @import("std"); -const Parser = @import("parser.zig"); -const Identity = @import("response.zig").Identity; -const Message = @import("response.zig").Message; -const Command = @import("response.zig").Command; -const net = std.Io.net; - -const ServerError = error{ InvalidCommand, Unimplemented, UnknownCommand }; - -fn parse_crlf(parser: *Parser) Parser.ParserError![]const u8 { - var result = try parser.takeUntil('\r'); - if (parser.peek()) |c| { - if (c == '\n') return result; - } else return Parser.ParserError.EndOfString; - - // parser.consume(' ') catch { - // parser.skip(); - // result = try parse_crlf(parser); - // }; - result = try parse_crlf(parser); - return result; -} - -pub fn parse(msg: []const u8) !Message { - if (msg.len < 4) return ServerError.InvalidCommand; - const cmd: ?Command = .fromStr(msg[0..4]); - const client: ?Identity = if (cmd) |c| - try switch (c) { - .EHLO => try ehlo(msg[4..]), - .HELO => try helo(msg[4..]), - else => ServerError.Unimplemented, - } - else - null; - if (client == null) return ServerError.UnknownCommand; - return .{ - .client = client.?, - .cmd = cmd.?, - .str = msg, - }; -} - -// Expects a string in the format of "[ipaddr]" no \r\n -fn address(msg: []const u8) !?net.IpAddress { - const ip6 = net.Ip6Address.parse(msg[1 .. msg.len - 1], 0) catch null; - const ip4 = net.Ip4Address.parse(msg[1 .. msg.len - 1], 0) catch null; - return if (ip6) |ip| - net.IpAddress{ .ip6 = ip } - else if (ip4) |ip| - net.IpAddress{ .ip4 = ip } - else - null; -} - -fn ehlo(msg: []const u8) !Identity { - var parser: Parser = .{ .str = msg }; - try parser.consume(' '); - const ipaddr = try address(msg[1 .. msg.len - 3]); - - parser.skipMany(msg[1 .. msg.len - 2].len); - - if (ipaddr) |ip| { - try parser.consume('\r'); - try parser.consume('\n'); - return .{ .addr = ip }; - } - return .{ .domain = try parse_crlf(&parser) }; -} - -fn helo(msg: []const u8) !Identity { - var parser: Parser = .{ .str = msg }; - try parser.consume(' '); - parser.skip(); - return .{ .domain = try parse_crlf(&parser) }; -} - -const t = std.testing; - -test "Command.fromStr: known verbs, any case" { - try t.expectEqual(Command.EHLO, Command.fromStr("EHLO").?); - try t.expectEqual(Command.EHLO, Command.fromStr("ehlo").?); - try t.expectEqual(Command.MAIL, Command.fromStr("MaIl").?); - try t.expectEqual(Command.QUIT, Command.fromStr("quit").?); -} - -test "Command.fromStr: unknown or wrong length" { - try t.expectEqual(@as(?Command, null), Command.fromStr("XXXX")); - try t.expectEqual(@as(?Command, null), Command.fromStr("EHL")); - try t.expectEqual(@as(?Command, null), Command.fromStr("EHLOO")); - try t.expectEqual(@as(?Command, null), Command.fromStr("")); -} - -test "parse_crlf: strips terminator" { - var p: Parser = .{ .str = "hello\r\n" }; - std.debug.print("{s}\n", .{try parse_crlf(&p)}); - var p2: Parser = .{ .str = "hello\r\n" }; - try t.expectEqualStrings("hello", try parse_crlf(&p2)); - try t.expectEqual(@as(usize, 0), p2.str.len - p2.pos - 1); -} - -test "parse_crlf: rejects bare LF, missing terminator, trailing data" { - var a: Parser = .{ .str = "hello\n" }; - try t.expectError(Parser.ParserError.EndOfString, parse_crlf(&a)); - var b: Parser = .{ .str = "hello" }; - try t.expectError(Parser.ParserError.EndOfString, parse_crlf(&b)); - var c: Parser = .{ .str = "hello\r\nextra" }; - try t.expectError(Parser.ParserError.EndOfString, parse_crlf(&c)); -} - -test "parse_crlf: lone CR inside the line is not a terminator" { - var p: Parser = .{ .str = "a\rb\r\n" }; - try t.expectEqualStrings("a\rb", try parse_crlf(&p)); -} - -// test "ehlo: domain" { -// const id = try ehlo(" mail.example.com\r\n"); -// try t.expectEqualStrings("mail.example.com", id.domain); -// } - -test "ehlo: IPv4 address literal" { - const id = try ehlo(" [192.0.2.1]\r\n"); - std.debug.print("{}\n", .{id.addr}); - try t.expect(id == Identity.addr); -} - -test "ehlo: IPv6 address literal" { - const id = try ehlo(" [IPv6:2001:db8::1]\r\n"); - try t.expect(id == .addr); -} - -test "ehlo: errors" { - try t.expectError(Parser.ParserError.Unexpected, ehlo("mail.example.com\r\n")); // no space - try t.expectError(error.Unexpected, ehlo(" mail.example.com")); // no CRLF - try t.expectError(error.InvalidDomain, ehlo(" \r\n")); // empty - try t.expectError(error.InvalidDomain, ehlo(" bad_domain!\r\n")); - try t.expectError(error.Unexpected, ehlo(" [1.2.3.4\r\n")); // unclosed - try t.expectError(error.InvalidAddressLiteral, ehlo(" [not.an.ip]\r\n")); -} - -test "helo: domain and errors" { - const id = try helo(" example.org\r\n"); - try t.expectEqualStrings("example.org", id.domain); - // try t.expectError(anyerror{}, helo(" [1.2.3.4]\r\n")); - try t.expectError(Parser.ParserError.Unexpected, helo("example.org\r\n")); -} - -// test "parse: dispatches EHLO/HELO case-insensitively" { -// const a = try parse("ehlo client.example\r\n"); -// try t.expectEqualStrings("client.example", a.ehlo.domain); -// const b = try parse("HELO client.example\r\n"); -// try t.expectEqualStrings("client.example", b.helo.domain); -// } -// -// test "parse: argument-less commands" { -// try t.expectEqual(Command.QUIT, (try parse("QUIT\r\n")).simple); -// try t.expectEqual(Command.NOOP, (try parse("noop\r\n")).simple); -// try t.expectError(error.Unexpected, parse("QUIT now\r\n")); -// try t.expectError(error.Unexpected, parse("QUIT\n")); -// } - -test "parse: bad input" { - try t.expectError(ServerError.InvalidCommand, parse("EH")); - try t.expectError(ServerError.UnknownCommand, parse("FOOO\r\n")); - try t.expectError(ServerError.Unimplemented, parse("MAIL FROM:<a@b.c>\r\n")); -} diff --git a/src/lib/tmp.zig b/src/lib/tmp.zig deleted file mode 100644 index 3777b31..0000000 --- a/src/lib/tmp.zig +++ /dev/null @@ -1,50 +0,0 @@ -const std = @import("std"); - -const Code = enum(u16) { - OK = 250, - UNKNOWN = 404, -}; - -const Response = struct { - code: Code, - pass: bool, - msg: []const u8, -}; - -const Message = struct { - name: []const u8, - pass: []const Code, - fail: []const Code, - handle: fn (*std.Io.Writer, *std.Io.net.Server, args: anytype) anyerror!Response, -}; - -const Messages = union(enum(u8)) { - HELO = Message{ - .name = "HELO", - .pass = .{.OK}, - .fail = .{.UNKNOWN}, - .handle = blk: { - const f = struct { - pub fn handle(w: *std.Io.Writer, s: *std.Io.net.Server, args: anytype) !Response { - var resp: Response = .{ .code = .OK, .pass = true, .contents = undefined }; - if (args.domain) |d| { - resp.contents = d; - try w.print("{d} {s}\r\n", .{ resp.code, resp.contents }); - try w.flush(); - return resp; - } - try w.print("{d} ", .{resp.code}); - var buf: [64]u8 = undefined; - var fw: std.Io.Writer = .fixed(&buf); - try s.socket.address.format(&fw); - const full = fw.buffered(); - const host = if (std.mem.lastIndexOfScalar(u8, full, ':')) |i| full[0..i] else full; - try w.print("[{s}]\r\n", .{host}); - resp.contents = host; - return resp; - } - }; - break :blk f.handle; - }, - }, -}; |
