aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: 210c4f7c7b8381a9b1ee602a09dc0ec5fe0f0fbb (plain) (blame)
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
package main

import (
	"bufio"
	"bytes"
	"net"
	"os"
	"slices"
	"strings"

	"go.lindenii.runxiyu.org/lindenii-common/clog"
	"go.lindenii.runxiyu.org/lindenii-common/scfg"
)

const VERSION = "lindenii-maild v0.0.0"

func main() {
	config_file, err := os.Open("maild.scfg")
	if err != nil {
		panic(err)
	}

	err = scfg.NewDecoder(bufio.NewReader(config_file)).Decode(&config)
	if err != nil {
		panic(err)
	}

	listener, err := net.Listen("tcp", ":25")
	if err != nil {
		panic(err)
	}
	defer listener.Close()

	for {
		conn, err := listener.Accept()
		if err != nil {
			panic(err)
		}

		go func() {
			err := handle_connection(bufio.NewReader(conn), bufio.NewWriter(conn))
			if err != nil {
				clog.Error("connection handler returned error", "err", err)
			}
		}()
	}

}

type server_state_t uint

const (
	server_state_begin server_state_t = iota
	server_state_helo
	server_state_mail
	server_state_rcpt
)

func handle_connection(reader *bufio.Reader, writer *bufio.Writer) error {
	_, _ = writer.WriteString("220 " + config.Server_name + " " + VERSION + "\r\n")
	_ = writer.Flush()
	server_state := server_state_begin
	var remote_server_name string
	var current_mail_from string
	var current_rcpt_to []string
	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			return err
		}
		line = strings.TrimSuffix(line, "\n")
		line = strings.TrimSuffix(line, "\r")
		cmd_end := strings.IndexByte(line, ' ')
		var param_start int
		if cmd_end == -1 {
			cmd_end = len(line)
			param_start = len(line)
		} else {
			param_start = cmd_end + 1
		}
		cmd := strings.ToUpper(line[:cmd_end])
		param := line[param_start:]
	switch_cmd:
		switch cmd {
		case "HELO":
			if param == "" { // TODO: actually validate the hostname
				_, _ = writer.WriteString("501 Syntax: HELO hostname\r\n")
				_ = writer.Flush()
				break
			}
			remote_server_name = param
			_ = remote_server_name // TODO
			server_state = server_state_helo
			_, _ = writer.WriteString("250 " + config.Server_name + "\r\n")
			_ = writer.Flush()
		case "MAIL":
			switch server_state {
			case server_state_begin:
				_, _ = writer.WriteString("503 5.5.1 Error: send HELO/EHLO first\r\n")
				_ = writer.Flush()
				break switch_cmd
			case server_state_helo:
				break
			case server_state_mail:
				_, _ = writer.WriteString("503 5.5.1 Error: nested MAIL command\r\n")
				_ = writer.Flush()
				break switch_cmd
			}
			if len(param) <= len("FROM:") || strings.ToUpper(param[:len("FROM:")]) != "FROM:" {
				_, _ = writer.WriteString("501 5.5.4 Syntax: MAIL FROM:<address>\r\n")
				_ = writer.Flush()
				break
			}
			current_mail_from = param[len("FROM:"):]
			current_rcpt_to = []string{}
			server_state = server_state_mail
			_, _ = writer.WriteString("250 2.1.0 Ok\r\n")
			_ = writer.Flush()
			// TODO: Address validation
		case "RCPT":
			if server_state != server_state_mail && server_state != server_state_rcpt {
				_, _ = writer.WriteString("503 5.5.1 Error: need MAIL command\r\n")
				_ = writer.Flush()
				break
			}
			if len(param) <= len("TO:") || strings.ToUpper(param[:len("TO:")]) != "TO:" {
				_, _ = writer.WriteString("501 5.5.4 Syntax: RCPT TO:<address>\r\n")
				_ = writer.Flush()
				break
			}
			current_rcpt_to = append(current_rcpt_to, param[len("TO:"):])
			server_state = server_state_rcpt
			_, _ = writer.WriteString("250 2.1.5 Ok\r\n")
			_ = writer.Flush()
		case "DATA":
			if server_state != server_state_rcpt {
				_, _ = writer.WriteString("503 5.5.1 Error: need RCPT command\r\n")
				_ = writer.Flush()
				break
			}
			_, _ = writer.WriteString("354 End data with <CR><LF>.<CR><LF>\r\n")
			_ = writer.Flush()
			var current_data []byte
			for {
				tmp, err := reader.ReadSlice('\r')
				if err != nil {
					return err
				}

				// reader.ReadSlice returns an internal buffer that gets
				// overwritten on the next reader operation. So we must
				// make a copy; also we have to allocate data_part to
				// the correct length because [[builtin.copy]] copies
				// min(len(dst), len(src)) items.
				data_part := make([]byte, len(tmp))
				copy(data_part, tmp)

				clog.Debug("e", "e", string(data_part))
				next_four, err := reader.Peek(4)
				if err != nil {
					return err
				}
				if bytes.Equal(next_four, []byte{'\n', '.', '\r', '\n'}) {
					current_data = slices.Concat(current_data, data_part[:len(data_part)-1])
					clog.Debug("eee", string(next_four)) // shut up go
					break
				}
				clog.Debug("pre concat", "current_data", string(current_data), "data_part", string(data_part))
				current_data = slices.Concat(current_data, data_part)
				clog.Debug("post concat", "current_data", string(current_data), "data_part", string(data_part))
			}
			_, err := reader.Discard(4)
			if err != nil {
				return err
			}
			deliver_incoming(current_mail_from, current_rcpt_to, current_data)
			server_state = server_state_helo
			_, _ = writer.WriteString("250 2.0.0 Ok: Accepted\r\n")
			_ = writer.Flush()
		default:
			_, _ = writer.WriteString("500 5.5.2 Error: command not recognized\r\n")
			_ = writer.Flush()
		}
	}
}

func deliver_incoming(envelope_from string, envelope_recipients []string, data []byte) {
	clog.Debug(
		"incoming_mail",
		"envelope_from", envelope_from,
		"envelope_recipients", envelope_recipients,
		"data", string(data),
	)
}