1
0
mirror of https://github.com/jhillyerd/inbucket.git synced 2025-12-17 09:37:02 +00:00

gofmt on smtpd

This commit is contained in:
James Hillyerd
2012-10-07 17:04:39 -07:00
parent cb388e94b2
commit cbba067673
2 changed files with 295 additions and 298 deletions

View File

@@ -1,75 +1,75 @@
package smtpd package smtpd
import ( import (
"bufio" "bufio"
"container/list" "container/list"
"fmt" "fmt"
"net" "net"
"strings" "strings"
"time" "time"
) )
type State int type State int
const ( const (
GREET State = iota // Waiting for HELO GREET State = iota // Waiting for HELO
READY // Got HELO, waiting for MAIL READY // Got HELO, waiting for MAIL
MAIL // Got MAIL, accepting RCPTs MAIL // Got MAIL, accepting RCPTs
DATA // Got DATA, waiting for "." DATA // Got DATA, waiting for "."
QUIT // Close session QUIT // Close session
) )
func (s State) String() string { func (s State) String() string {
switch s { switch s {
case GREET: case GREET:
return "GREET" return "GREET"
case READY: case READY:
return "READY" return "READY"
case MAIL: case MAIL:
return "MAIL" return "MAIL"
case DATA: case DATA:
return "DATA" return "DATA"
case QUIT: case QUIT:
return "QUIT" return "QUIT"
} }
return "Unknown" return "Unknown"
} }
var commands = map[string] bool { var commands = map[string]bool{
"HELO": true, "HELO": true,
"MAIL": true, "MAIL": true,
"RCPT": true, "RCPT": true,
"DATA": true, "DATA": true,
"RSET": true, "RSET": true,
"SEND": true, "SEND": true,
"SOML": true, "SOML": true,
"SAML": true, "SAML": true,
"VRFY": true, "VRFY": true,
"EXPN": true, "EXPN": true,
"HELP": true, "HELP": true,
"NOOP": true, "NOOP": true,
"QUIT": true, "QUIT": true,
"TURN": true, "TURN": true,
} }
type Session struct { type Session struct {
server *Server server *Server
id int id int
conn net.Conn conn net.Conn
sendError error sendError error
state State state State
reader *bufio.Reader reader *bufio.Reader
from string from string
recipients *list.List recipients *list.List
} }
func NewSession(server *Server, id int, conn net.Conn) *Session { func NewSession(server *Server, id int, conn net.Conn) *Session {
reader := bufio.NewReader(conn) reader := bufio.NewReader(conn)
return &Session{server: server, id: id, conn: conn, state: GREET, reader: reader} return &Session{server: server, id: id, conn: conn, state: GREET, reader: reader}
} }
func (ss *Session) String() string { func (ss *Session) String() string {
return fmt.Sprintf("Session{id: %v, state: %v}", ss.id, ss.state) return fmt.Sprintf("Session{id: %v, state: %v}", ss.id, ss.state)
} }
/* Session flow: /* Session flow:
@@ -80,282 +80,280 @@ func (ss *Session) String() string {
* 5. Goto 2 * 5. Goto 2
*/ */
func (s *Server) startSession(id int, conn net.Conn) { func (s *Server) startSession(id int, conn net.Conn) {
s.trace("Starting session <%v>", id) s.trace("Starting session <%v>", id)
defer conn.Close() defer conn.Close()
ss := NewSession(s, id, conn) ss := NewSession(s, id, conn)
ss.greet() ss.greet()
// This is our command reading loop // This is our command reading loop
for ss.state != QUIT && ss.sendError == nil { for ss.state != QUIT && ss.sendError == nil {
if ss.state == DATA { if ss.state == DATA {
// Special case, does not use SMTP command format // Special case, does not use SMTP command format
ss.dataHandler() ss.dataHandler()
continue continue
} }
line, err := ss.readLine() line, err := ss.readLine()
if err == nil { if err == nil {
if cmd, arg, ok := ss.parseCmd(line); ok { if cmd, arg, ok := ss.parseCmd(line); ok {
// Check against valid SMTP commands // Check against valid SMTP commands
if cmd == "" { if cmd == "" {
ss.send("500 Speak up") ss.send("500 Speak up")
continue continue
} }
if !commands[cmd] { if !commands[cmd] {
ss.send(fmt.Sprintf("500 Syntax error, %v command unrecognized", cmd)) ss.send(fmt.Sprintf("500 Syntax error, %v command unrecognized", cmd))
continue continue
} }
// Commands we handle in any state // Commands we handle in any state
switch cmd { switch cmd {
case "SEND", "SOML", "SAML", "VRFY", "EXPN", "HELP", "TURN": case "SEND", "SOML", "SAML", "VRFY", "EXPN", "HELP", "TURN":
// These commands are not implemented in any state // These commands are not implemented in any state
ss.send(fmt.Sprintf("502 %v command not implemented", cmd)) ss.send(fmt.Sprintf("502 %v command not implemented", cmd))
ss.warn("Command %v not implemented by Inbucket", cmd) ss.warn("Command %v not implemented by Inbucket", cmd)
continue continue
case "NOOP": case "NOOP":
ss.send("250 I have sucessfully done nothing") ss.send("250 I have sucessfully done nothing")
continue continue
case "RSET": case "RSET":
// Reset session // Reset session
ss.reset() ss.reset()
continue continue
case "QUIT": case "QUIT":
ss.send("221 Goodnight and good luck") ss.send("221 Goodnight and good luck")
ss.enterState(QUIT) ss.enterState(QUIT)
continue continue
} }
// Send command to handler for current state // Send command to handler for current state
switch ss.state { switch ss.state {
case GREET: case GREET:
ss.greetHandler(cmd, arg) ss.greetHandler(cmd, arg)
continue continue
case READY: case READY:
ss.readyHandler(cmd, arg) ss.readyHandler(cmd, arg)
continue continue
case MAIL: case MAIL:
ss.mailHandler(cmd, arg) ss.mailHandler(cmd, arg)
continue continue
}
ss.error("Session entered unexpected state %v", ss.state)
break
} else {
ss.send("500 Syntax error, command garbled")
}
} else {
// readLine() returned an error
ss.error("Connection error: %v", err)
if netErr, ok := err.(net.Error); ok {
if netErr.Timeout() {
ss.send("221 Idle timeout, bye bye")
break
}
}
ss.send("221 Connection error, sorry")
break
}
} }
ss.error("Session entered unexpected state %v", ss.state) if ss.sendError != nil {
break ss.error("Network send error: %v", ss.sendError)
} else {
ss.send("500 Syntax error, command garbled")
}
} else {
// readLine() returned an error
ss.error("Connection error: %v", err)
if netErr, ok := err.(net.Error); ok {
if netErr.Timeout() {
ss.send("221 Idle timeout, bye bye")
break
} }
} ss.info("Closing connection")
ss.send("221 Connection error, sorry")
break
}
}
if ss.sendError != nil {
ss.error("Network send error: %v", ss.sendError)
}
ss.info("Closing connection")
} }
// GREET state -> waiting for HELO // GREET state -> waiting for HELO
func (ss *Session) greetHandler(cmd string, arg string) { func (ss *Session) greetHandler(cmd string, arg string) {
if cmd == "HELO" { if cmd == "HELO" {
ss.send("250 Great, let's get this show on the road") ss.send("250 Great, let's get this show on the road")
ss.enterState(READY) ss.enterState(READY)
} else { } else {
ss.ooSeq(cmd) ss.ooSeq(cmd)
} }
} }
// READY state -> waiting for MAIL // READY state -> waiting for MAIL
func (ss *Session) readyHandler(cmd string, arg string) { func (ss *Session) readyHandler(cmd string, arg string) {
if cmd == "MAIL" { if cmd == "MAIL" {
if (len(arg) < 6) || (strings.ToUpper(arg[0:5]) != "FROM:") { if (len(arg) < 6) || (strings.ToUpper(arg[0:5]) != "FROM:") {
ss.send("501 Was expecting MAIL arg syntax of FROM:<address>") ss.send("501 Was expecting MAIL arg syntax of FROM:<address>")
ss.warn("Bad MAIL argument: \"%v\"", arg) ss.warn("Bad MAIL argument: \"%v\"", arg)
return return
} }
// This trim is probably too forgiving // This trim is probably too forgiving
from := strings.Trim(arg[5:], "<> ") from := strings.Trim(arg[5:], "<> ")
ss.from = from ss.from = from
ss.recipients = list.New() ss.recipients = list.New()
ss.info("Mail from: %v", from) ss.info("Mail from: %v", from)
ss.send(fmt.Sprintf("250 Roger, accepting mail from <%v>", from)) ss.send(fmt.Sprintf("250 Roger, accepting mail from <%v>", from))
ss.enterState(MAIL) ss.enterState(MAIL)
} else { } else {
ss.ooSeq(cmd) ss.ooSeq(cmd)
} }
} }
// MAIL state -> waiting for RCPTs followed by DATA // MAIL state -> waiting for RCPTs followed by DATA
func (ss *Session) mailHandler(cmd string, arg string) { func (ss *Session) mailHandler(cmd string, arg string) {
switch cmd { switch cmd {
case "RCPT": case "RCPT":
if (len(arg) < 4) || (strings.ToUpper(arg[0:3]) != "TO:") { if (len(arg) < 4) || (strings.ToUpper(arg[0:3]) != "TO:") {
ss.send("501 Was expecting RCPT arg syntax of TO:<address>") ss.send("501 Was expecting RCPT arg syntax of TO:<address>")
ss.warn("Bad RCPT argument: \"%v\"", arg) ss.warn("Bad RCPT argument: \"%v\"", arg)
return return
} }
// This trim is probably too forgiving // This trim is probably too forgiving
recip := strings.Trim(arg[3:], "<> ") recip := strings.Trim(arg[3:], "<> ")
if ss.recipients.Len() >= ss.server.maxRecips { if ss.recipients.Len() >= ss.server.maxRecips {
ss.warn("Maximum limit of %v recipients reached", ss.server.maxRecips) ss.warn("Maximum limit of %v recipients reached", ss.server.maxRecips)
ss.send(fmt.Sprintf("552 Maximum limit of %v recipients reached", ss.server.maxRecips)) ss.send(fmt.Sprintf("552 Maximum limit of %v recipients reached", ss.server.maxRecips))
return return
} }
ss.recipients.PushBack(recip) ss.recipients.PushBack(recip)
ss.info("Recipient: %v", recip) ss.info("Recipient: %v", recip)
ss.send(fmt.Sprintf("250 I'll make sure <%v> gets this", recip)) ss.send(fmt.Sprintf("250 I'll make sure <%v> gets this", recip))
return return
case "DATA": case "DATA":
if arg != "" { if arg != "" {
ss.send("501 DATA command should not have any arguments") ss.send("501 DATA command should not have any arguments")
ss.warn("Got unexpected args on DATA: \"%v\"", arg) ss.warn("Got unexpected args on DATA: \"%v\"", arg)
return return
} }
if ss.recipients.Len() > 0 { if ss.recipients.Len() > 0 {
// We have recipients, go to accept data // We have recipients, go to accept data
ss.enterState(DATA) ss.enterState(DATA)
return return
} else { } else {
// DATA out of sequence // DATA out of sequence
ss.ooSeq(cmd) ss.ooSeq(cmd)
return return
} }
} }
ss.ooSeq(cmd) ss.ooSeq(cmd)
} }
// DATA // DATA
func (ss *Session) dataHandler() { func (ss *Session) dataHandler() {
var msgSize uint64 = 0 var msgSize uint64 = 0
ss.send("354 Start mail input; end with <CRLF>.<CRLF>") ss.send("354 Start mail input; end with <CRLF>.<CRLF>")
for { for {
line, err := ss.readLine() line, err := ss.readLine()
if err != nil { if err != nil {
if netErr, ok := err.(net.Error); ok { if netErr, ok := err.(net.Error); ok {
if netErr.Timeout() { if netErr.Timeout() {
ss.send("221 Idle timeout, bye bye") ss.send("221 Idle timeout, bye bye")
}
}
ss.error("Error: %v while reading", err)
ss.enterState(QUIT)
return
}
if line == ".\r\n" || line == ".\n" {
// Mail data complete
ss.send("250 Mail accepted for delivery")
ss.info("Message size %v bytes", msgSize)
ss.enterState(READY)
return
}
if line != "" && line[0] == '.' {
line = line[1:]
}
msgSize += uint64(len(line))
// TODO: Add variable line to something!
} }
}
ss.error("Error: %v while reading", err)
ss.enterState(QUIT)
return
}
if line == ".\r\n" || line == ".\n" {
// Mail data complete
ss.send("250 Mail accepted for delivery")
ss.info("Message size %v bytes", msgSize)
ss.enterState(READY)
return
}
if line != "" && line[0] == '.' {
line = line[1:]
}
msgSize += uint64(len(line))
// TODO: Add variable line to something!
}
} }
func (ss *Session) enterState(state State) { func (ss *Session) enterState(state State) {
ss.state = state ss.state = state
ss.trace("Entering state %v", state) ss.trace("Entering state %v", state)
} }
func (ss *Session) greet() { func (ss *Session) greet() {
ss.send(fmt.Sprintf("220 %v Inbucket SMTP ready", ss.server.domain)) ss.send(fmt.Sprintf("220 %v Inbucket SMTP ready", ss.server.domain))
} }
// Calculate the next read or write deadline based on maxIdleSeconds // Calculate the next read or write deadline based on maxIdleSeconds
func (ss *Session) nextDeadline() time.Time { func (ss *Session) nextDeadline() time.Time {
return time.Now().Add(time.Duration(ss.server.maxIdleSeconds)*time.Second) return time.Now().Add(time.Duration(ss.server.maxIdleSeconds) * time.Second)
} }
// Send requested message, store errors in Session.sendError // Send requested message, store errors in Session.sendError
func (ss *Session) send(msg string) { func (ss *Session) send(msg string) {
if err := ss.conn.SetWriteDeadline(ss.nextDeadline()); err != nil { if err := ss.conn.SetWriteDeadline(ss.nextDeadline()); err != nil {
ss.sendError = err ss.sendError = err
return return
} }
if _, err := fmt.Fprint(ss.conn, msg + "\r\n"); err != nil { if _, err := fmt.Fprint(ss.conn, msg+"\r\n"); err != nil {
ss.sendError = err ss.sendError = err
ss.error("Failed to send: \"%v\"", msg) ss.error("Failed to send: \"%v\"", msg)
return return
} }
ss.trace("Sent: \"%v\"", msg) ss.trace("Sent: \"%v\"", msg)
} }
// Reads a line of input // Reads a line of input
func (ss *Session) readLine() (line string, err error) { func (ss *Session) readLine() (line string, err error) {
if err = ss.conn.SetReadDeadline(ss.nextDeadline()); err != nil { if err = ss.conn.SetReadDeadline(ss.nextDeadline()); err != nil {
return "", err return "", err
} }
line, err = ss.reader.ReadString('\n') line, err = ss.reader.ReadString('\n')
if err != nil { if err != nil {
return "", err return "", err
} }
ss.trace("Read: \"%v\"", strings.TrimRight(line, "\r\n")) ss.trace("Read: \"%v\"", strings.TrimRight(line, "\r\n"))
return line, nil return line, nil
} }
func (ss *Session) parseCmd(line string) (cmd string, arg string, ok bool) { func (ss *Session) parseCmd(line string) (cmd string, arg string, ok bool) {
line = strings.TrimRight(line, "\r\n") line = strings.TrimRight(line, "\r\n")
l := len(line) l := len(line)
switch { switch {
case l == 0: case l == 0:
return "", "", true return "", "", true
case l < 4: case l < 4:
ss.error("Command too short: \"%v\"", line) ss.error("Command too short: \"%v\"", line)
return "", "", false return "", "", false
case l == 4: case l == 4:
return strings.ToUpper(line), "", true return strings.ToUpper(line), "", true
case l == 5: case l == 5:
// Too long to be only command, too short to have args // Too long to be only command, too short to have args
ss.error("Mangled command: \"%v\"", line) ss.error("Mangled command: \"%v\"", line)
return "", "", false return "", "", false
} }
// If we made it here, command is long enough to have args // If we made it here, command is long enough to have args
if line[4] != ' ' { if line[4] != ' ' {
// There wasn't a space after the command? // There wasn't a space after the command?
ss.error("Mangled command: \"%v\"", line) ss.error("Mangled command: \"%v\"", line)
return "", "", false return "", "", false
} }
// I'm not sure if we should trim the args or not, but we will for now // I'm not sure if we should trim the args or not, but we will for now
return strings.ToUpper(line[0:4]), strings.Trim(line[5:], " "), true return strings.ToUpper(line[0:4]), strings.Trim(line[5:], " "), true
} }
func (ss *Session) reset() { func (ss *Session) reset() {
ss.info("Resetting session state on RSET request") ss.info("Resetting session state on RSET request")
ss.enterState(READY) ss.enterState(READY)
ss.from = "" ss.from = ""
ss.recipients = nil ss.recipients = nil
} }
func (ss *Session) ooSeq(cmd string) { func (ss *Session) ooSeq(cmd string) {
ss.send(fmt.Sprintf("503 Command %v is out of sequence", cmd)) ss.send(fmt.Sprintf("503 Command %v is out of sequence", cmd))
ss.warn("Wasn't expecting %v here", cmd) ss.warn("Wasn't expecting %v here", cmd)
} }
// Session specific logging methods // Session specific logging methods
func (ss *Session) trace(msg string, args ...interface {}) { func (ss *Session) trace(msg string, args ...interface{}) {
ss.server.trace("<%v> %v", ss.id, fmt.Sprintf(msg, args...)) ss.server.trace("<%v> %v", ss.id, fmt.Sprintf(msg, args...))
} }
func (ss *Session) info(msg string, args ...interface {}) { func (ss *Session) info(msg string, args ...interface{}) {
ss.server.info("<%v> %v", ss.id, fmt.Sprintf(msg, args...)) ss.server.info("<%v> %v", ss.id, fmt.Sprintf(msg, args...))
} }
func (ss *Session) warn(msg string, args ...interface {}) { func (ss *Session) warn(msg string, args ...interface{}) {
ss.server.warn("<%v> %v", ss.id, fmt.Sprintf(msg, args...)) ss.server.warn("<%v> %v", ss.id, fmt.Sprintf(msg, args...))
} }
func (ss *Session) error(msg string, args ...interface {}) { func (ss *Session) error(msg string, args ...interface{}) {
ss.server.error("<%v> %v", ss.id, fmt.Sprintf(msg, args...)) ss.server.error("<%v> %v", ss.id, fmt.Sprintf(msg, args...))
} }

View File

@@ -1,54 +1,53 @@
package smtpd package smtpd
import ( import (
"fmt" "fmt"
"net" "net"
) )
// Real server code starts here // Real server code starts here
type Server struct { type Server struct {
domain string domain string
port int port int
maxRecips int maxRecips int
maxIdleSeconds int maxIdleSeconds int
} }
// Init a new Server object // Init a new Server object
func New(domain string, port int) *Server { func New(domain string, port int) *Server {
return &Server{domain: domain, port: port, maxRecips: 3, maxIdleSeconds: 10} return &Server{domain: domain, port: port, maxRecips: 3, maxIdleSeconds: 10}
} }
// Loggers // Loggers
func (s *Server) trace(msg string, args ...interface {}) { func (s *Server) trace(msg string, args ...interface{}) {
fmt.Printf("[trace] %s\n", fmt.Sprintf(msg, args...)) fmt.Printf("[trace] %s\n", fmt.Sprintf(msg, args...))
} }
func (s *Server) info(msg string, args ...interface {}) { func (s *Server) info(msg string, args ...interface{}) {
fmt.Printf("[info ] %s\n", fmt.Sprintf(msg, args...)) fmt.Printf("[info ] %s\n", fmt.Sprintf(msg, args...))
} }
func (s *Server) warn(msg string, args ...interface {}) { func (s *Server) warn(msg string, args ...interface{}) {
fmt.Printf("[warn ] %s\n", fmt.Sprintf(msg, args...)) fmt.Printf("[warn ] %s\n", fmt.Sprintf(msg, args...))
} }
func (s *Server) error(msg string, args ...interface {}) { func (s *Server) error(msg string, args ...interface{}) {
fmt.Printf("[error] %s\n", fmt.Sprintf(msg, args...)) fmt.Printf("[error] %s\n", fmt.Sprintf(msg, args...))
} }
// Main listener loop // Main listener loop
func (s *Server) Start() { func (s *Server) Start() {
s.trace("Server Start() called") s.trace("Server Start() called")
ln, err := net.Listen("tcp", fmt.Sprintf(":%v", s.port)) ln, err := net.Listen("tcp", fmt.Sprintf(":%v", s.port))
if err != nil { if err != nil {
panic(err) panic(err)
} }
for sid := 1; ; sid++ { for sid := 1; ; sid++ {
if conn, err := ln.Accept(); err != nil { if conn, err := ln.Accept(); err != nil {
panic(err) panic(err)
} else { } else {
go s.startSession(sid, conn) go s.startSession(sid, conn)
} }
} }
} }