From 5294c5740f8ee7904ff8994c27059458cb8f5f6a Mon Sep 17 00:00:00 2001 From: Runxi Yu Date: Sun, 12 Jan 2025 18:22:02 +0800 Subject: Restructure mta_recv -> mx_recv --- config.go | 7 +- main.go | 3 +- mta_recv.go | 209 -------------------------------------------------------- mx_recv.go | 224 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 228 insertions(+), 215 deletions(-) delete mode 100644 mta_recv.go create mode 100644 mx_recv.go diff --git a/config.go b/config.go index f8f575e..c58071b 100644 --- a/config.go +++ b/config.go @@ -12,8 +12,7 @@ import ( ) var config struct { - Server_name string `scfg:"server_name"` - Routes map[string]string `scfg:"routes"` + Server_name string `scfg:"server_name"` TLS struct { Cert string `scfg:"cert"` Key string `scfg:"key"` @@ -25,8 +24,8 @@ var config struct { _tls_config *tls.Config } var ( - config_mutex sync.RWMutex // covers things like the database too - global_db *pgxpool.Pool + config_mutex sync.RWMutex // covers things like the database too + global_db *pgxpool.Pool // only call Close() after replacing this global variable ) // load_config loads the configuration file and sets up global things according diff --git a/main.go b/main.go index 378ac44..274e9b7 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,6 @@ package main import ( - "bufio" "errors" "flag" "io" @@ -34,7 +33,7 @@ func main() { } go func() { - err := handle_incoming_server_connection(bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)), &conn) + err := handle_mx_recv_conn(conn) if err != nil && !errors.Is(err, io.EOF) { clog.Error("connection handler returned error", "err", err) } diff --git a/mta_recv.go b/mta_recv.go deleted file mode 100644 index b67beb4..0000000 --- a/mta_recv.go +++ /dev/null @@ -1,209 +0,0 @@ -package main - -import ( - "bufio" - "bytes" - "crypto/tls" - "net" - "slices" - "strings" - - "go.lindenii.runxiyu.org/lindenii-common/mailkit" -) - -type server_state_t uint - -const ( - server_state_begin server_state_t = iota - server_state_helo - server_state_mail - server_state_rcpt -) - -func handle_incoming_server_connection(buf_conn *bufio.ReadWriter, net_conn *net.Conn) error { - var tls_conn *tls.Conn - var my_server_name string - var routes map[string]string - var tls_config *tls.Config - config_consistent_run(func() { - my_server_name = config.Server_name - routes = config.Routes - tls_config = config._tls_config - }) - _, _ = buf_conn.WriteString("220 " + my_server_name + " " + VERSION + "\r\n") - _ = buf_conn.Flush() - server_state := server_state_begin - var remote_server_name string - var current_mail_from string - var current_rcpt_to []string - for { - line, err := buf_conn.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 "STARTTLS": - if param != "" { - _, _ = buf_conn.WriteString("501 5.5.4 Syntax error (no parameters allowed)\r\n") - _ = buf_conn.Flush() - break - } - if tls_conn != nil { - _, _ = buf_conn.WriteString("554 5.5.1 Error: TLS already active\r\n") - _ = buf_conn.Flush() - break - } - _, _ = buf_conn.WriteString("220 2.0.0 Ready to start TLS\r\n") - _ = buf_conn.Flush() - tls_conn = tls.Server(*net_conn, tls_config) - buf_conn = bufio.NewReadWriter(bufio.NewReader(tls_conn), bufio.NewWriter(tls_conn)) - server_state = server_state_begin - current_mail_from = "" - current_rcpt_to = []string{""} - case "HELO": - if param == "" { // TODO: actually validate the hostname - _, _ = buf_conn.WriteString("501 Syntax: HELO hostname\r\n") - _ = buf_conn.Flush() - break - } - remote_server_name = param - _ = remote_server_name // TODO - server_state = server_state_helo - _, _ = buf_conn.WriteString("250 " + my_server_name + "\r\n") - _ = buf_conn.Flush() - case "MAIL": - switch server_state { - case server_state_begin: - _, _ = buf_conn.WriteString("503 5.5.1 Error: send HELO/EHLO first\r\n") - _ = buf_conn.Flush() - break switch_cmd - case server_state_helo: - break - case server_state_mail: - _, _ = buf_conn.WriteString("503 5.5.1 Error: nested MAIL command\r\n") - _ = buf_conn.Flush() - break switch_cmd - } - if len(param) <= len("FROM:") || strings.ToUpper(param[:len("FROM:")]) != "FROM:" { - _, _ = buf_conn.WriteString("501 5.5.4 Syntax: MAIL FROM:
\r\n") - _ = buf_conn.Flush() - break - } - current_mail_from = param[len("FROM:"):] - current_rcpt_to = []string{} - server_state = server_state_mail - _, _ = buf_conn.WriteString("250 2.1.0 Ok\r\n") - _ = buf_conn.Flush() - // TODO: Address validation - case "RCPT": - if server_state != server_state_mail && server_state != server_state_rcpt { - _, _ = buf_conn.WriteString("503 5.5.1 Error: need MAIL command\r\n") - _ = buf_conn.Flush() - break - } - if len(param) <= len("TO:") || strings.ToUpper(param[:len("TO:")]) != "TO:" { - _, _ = buf_conn.WriteString("501 5.5.4 Syntax: RCPT TO:
\r\n") - _ = buf_conn.Flush() - break - } - recipient, _, _ := mailkit.Strip_angle_brackets(param[len("TO:"):]) - _, ok := routes[recipient] - if !ok { - _, _ = buf_conn.WriteString("550 5.1.1 <" + recipient + ">: Recipient address rejected: User unknown in local recipient table\r\n") - _ = buf_conn.Flush() - break switch_cmd - } - current_rcpt_to = append(current_rcpt_to, recipient) - server_state = server_state_rcpt - _, _ = buf_conn.WriteString("250 2.1.5 Ok\r\n") - _ = buf_conn.Flush() - case "DATA": - if server_state != server_state_rcpt { - _, _ = buf_conn.WriteString("503 5.5.1 Error: need RCPT command\r\n") - _ = buf_conn.Flush() - break - } - _, _ = buf_conn.WriteString("354 End data with .\r\n") - _ = buf_conn.Flush() - var current_data []byte - for { - tmp, err := buf_conn.ReadSlice('\r') - if err != nil { - return err - } - - // buf_conn.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) - - next_four, err := buf_conn.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]) - break - } - current_data = slices.Concat(current_data, data_part) - } - _, err := buf_conn.Discard(4) - if err != nil { - return err - } - { - inboxes_to_deliver_to := make(map[string]struct{}) - for _, recipient := range current_rcpt_to { - inbox, ok := routes[recipient] - if !ok { - _, _ = buf_conn.WriteString("550 5.1.1 <" + recipient + ">: Recipient address rejected: User unknown in local recipient table\r\n") - break switch_cmd - } - inboxes_to_deliver_to[inbox] = struct{}{} - } - for inbox := range inboxes_to_deliver_to { - err = deliver_to_local_directory(current_mail_from, current_rcpt_to, current_data, inbox) - } - } - if err == nil { - _, _ = buf_conn.WriteString("250 2.0.0 Ok: Accepted\r\n") - } else { - _, _ = buf_conn.WriteString("500 2.0.0 Error: " + err.Error() + "\r\n") - } - _ = buf_conn.Flush() - server_state = server_state_helo - case "QUIT": - _, _ = buf_conn.WriteString("221 2.0.0 Bye\r\n") - _ = buf_conn.Flush() - return nil - case "NOOP": - _, _ = buf_conn.WriteString("250 2.0.0 Ok\r\n") - _ = buf_conn.Flush() - case "RSET": - if server_state != server_state_begin { - server_state = server_state_helo - } - _, _ = buf_conn.WriteString("250 2.0.0 Ok\r\n") - _ = buf_conn.Flush() - default: - _, _ = buf_conn.WriteString("500 5.5.2 Error: command not recognized\r\n") - _ = buf_conn.Flush() - } - } -} diff --git a/mx_recv.go b/mx_recv.go new file mode 100644 index 0000000..bcba494 --- /dev/null +++ b/mx_recv.go @@ -0,0 +1,224 @@ +package main + +import ( + "bufio" + "bytes" + "crypto/tls" + "net" + "slices" + "strings" + + "github.com/jackc/pgx/v5/pgxpool" + "go.lindenii.runxiyu.org/lindenii-common/mailkit" +) + +type server_state_t uint + +const ( + server_state_begin server_state_t = iota + server_state_helo + server_state_mail + server_state_rcpt +) + +type mx_recv_session struct { + buf_conn *bufio.ReadWriter + net_conn net.Conn + tls_conn *tls.Conn + my_server_name string + tls_config *tls.Config + db *pgxpool.Pool + remote_server_name string + current_mail_from string + current_rcpt_to []string + // ctx context.Context +} + +func (session *mx_recv_session) handle() error { + session.buf_conn = bufio.NewReadWriter(bufio.NewReader(session.net_conn), bufio.NewWriter(session.net_conn)) + config_consistent_run(func() { + session.my_server_name = config.Server_name + session.tls_config = config._tls_config + session.db = global_db + }) + _, _ = session.buf_conn.WriteString("220 " + session.my_server_name + " " + VERSION + "\r\n") + _ = session.buf_conn.Flush() + server_state := server_state_begin + for { + line, err := session.buf_conn.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 "STARTTLS": + if param != "" { + _, _ = session.buf_conn.WriteString("501 5.5.4 Syntax error (no parameters allowed)\r\n") + _ = session.buf_conn.Flush() + break + } + if session.tls_conn != nil { + _, _ = session.buf_conn.WriteString("554 5.5.1 Error: TLS already active\r\n") + _ = session.buf_conn.Flush() + break + } + _, _ = session.buf_conn.WriteString("220 2.0.0 Ready to start TLS\r\n") + _ = session.buf_conn.Flush() + session.tls_conn = tls.Server(session.net_conn, session.tls_config) + session.buf_conn = bufio.NewReadWriter(bufio.NewReader(session.tls_conn), bufio.NewWriter(session.tls_conn)) + server_state = server_state_begin + session.current_mail_from = "" + session.current_rcpt_to = []string{""} + case "HELO": + if param == "" { // TODO: actually validate the hostname + _, _ = session.buf_conn.WriteString("501 Syntax: HELO hostname\r\n") + _ = session.buf_conn.Flush() + break + } + session.remote_server_name = param + _ = session.remote_server_name // TODO + server_state = server_state_helo + _, _ = session.buf_conn.WriteString("250 " + session.my_server_name + "\r\n") + _ = session.buf_conn.Flush() + case "MAIL": + switch server_state { + case server_state_begin: + _, _ = session.buf_conn.WriteString("503 5.5.1 Error: send HELO/EHLO first\r\n") + _ = session.buf_conn.Flush() + break switch_cmd + case server_state_helo: + break + case server_state_mail: + _, _ = session.buf_conn.WriteString("503 5.5.1 Error: nested MAIL command\r\n") + _ = session.buf_conn.Flush() + break switch_cmd + } + if len(param) <= len("FROM:") || strings.ToUpper(param[:len("FROM:")]) != "FROM:" { + _, _ = session.buf_conn.WriteString("501 5.5.4 Syntax: MAIL FROM:
\r\n") + _ = session.buf_conn.Flush() + break + } + session.current_mail_from = param[len("FROM:"):] + session.current_rcpt_to = []string{} + server_state = server_state_mail + _, _ = session.buf_conn.WriteString("250 2.1.0 Ok\r\n") + _ = session.buf_conn.Flush() + // TODO: Address validation + case "RCPT": + if server_state != server_state_mail && server_state != server_state_rcpt { + _, _ = session.buf_conn.WriteString("503 5.5.1 Error: need MAIL command\r\n") + _ = session.buf_conn.Flush() + break + } + if len(param) <= len("TO:") || strings.ToUpper(param[:len("TO:")]) != "TO:" { + _, _ = session.buf_conn.WriteString("501 5.5.4 Syntax: RCPT TO:
\r\n") + _ = session.buf_conn.Flush() + break + } + recipient, _, _ := mailkit.Strip_angle_brackets(param[len("TO:"):]) + ok := true // XXX: Check routing table + if !ok { + _, _ = session.buf_conn.WriteString("550 5.1.1 <" + recipient + ">: Recipient address rejected: User unknown in local recipient table\r\n") + _ = session.buf_conn.Flush() + break switch_cmd + } + session.current_rcpt_to = append(session.current_rcpt_to, recipient) + server_state = server_state_rcpt + _, _ = session.buf_conn.WriteString("250 2.1.5 Ok\r\n") + _ = session.buf_conn.Flush() + case "DATA": + if server_state != server_state_rcpt { + _, _ = session.buf_conn.WriteString("503 5.5.1 Error: need RCPT command\r\n") + _ = session.buf_conn.Flush() + break + } + _, _ = session.buf_conn.WriteString("354 End data with .\r\n") + _ = session.buf_conn.Flush() + var current_data []byte + for { + tmp, err := session.buf_conn.ReadSlice('\r') + if err != nil { + return err + } + + // session.buf_conn.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) + + next_four, err := session.buf_conn.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]) + break + } + current_data = slices.Concat(current_data, data_part) + } + _, err := session.buf_conn.Discard(4) + if err != nil { + return err + } + { + inboxes_to_deliver_to := make(map[string]struct{}) + for _, recipient := range session.current_rcpt_to { + inbox, ok := "/tmp", true // XXX: Check routing table + if !ok { + _, _ = session.buf_conn.WriteString("550 5.1.1 <" + recipient + ">: Recipient address rejected: User unknown in local recipient table\r\n") + break switch_cmd + } + inboxes_to_deliver_to[inbox] = struct{}{} + } + for inbox := range inboxes_to_deliver_to { + err = deliver_to_local_directory(session.current_mail_from, session.current_rcpt_to, current_data, inbox) + } + } + if err == nil { + _, _ = session.buf_conn.WriteString("250 2.0.0 Ok: Accepted\r\n") + } else { + _, _ = session.buf_conn.WriteString("500 2.0.0 Error: " + err.Error() + "\r\n") + } + _ = session.buf_conn.Flush() + server_state = server_state_helo + case "QUIT": + _, _ = session.buf_conn.WriteString("221 2.0.0 Bye\r\n") + _ = session.buf_conn.Flush() + return nil + case "NOOP": + _, _ = session.buf_conn.WriteString("250 2.0.0 Ok\r\n") + _ = session.buf_conn.Flush() + case "RSET": + if server_state != server_state_begin { + server_state = server_state_helo + } + _, _ = session.buf_conn.WriteString("250 2.0.0 Ok\r\n") + _ = session.buf_conn.Flush() + default: + _, _ = session.buf_conn.WriteString("500 5.5.2 Error: command not recognized\r\n") + _ = session.buf_conn.Flush() + } + } +} + +func handle_mx_recv_conn(net_conn net.Conn) error { + session := mx_recv_session{ + net_conn: net_conn, + } + return session.handle() +} -- cgit v1.2.3