summaryrefslogtreecommitdiff
path: root/src/lib/smtp_parse.zig
blob: 886ae4443d7366aa53a6cda83cf706d90a03ab70 (plain)
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
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,
    };
}

fn ehlo(msg: []const u8) !Identity {
    var parser: Parser = .{ .str = msg };
    try parser.consume(' ');
    const ip6 = net.Ip6Address.parse(msg[1 .. msg.len - 2], 0) catch blk: {
        // std.debug.print("IP6: {s}\nERR: {}\n", .{ msg[1 .. msg.len - 2], e });
        break :blk null;
    };
    const ip4 = net.Ip4Address.parse(msg[1 .. msg.len - 2], 0) catch blk: {
        // std.debug.print("IP4: {s}\nERR: {}\n", .{ msg[1 .. msg.len - 2], e });
        break :blk null;
    };
    const ipaddr = if (ip6) |ip|
        net.IpAddress{ .ip6 = ip }
    else if (ip4) |ip|
        net.IpAddress{ .ip4 = ip }
    else
        null;

    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(" 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"));
}