smtpd.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package server
  2. import (
  3. "bufio"
  4. "crypto/tls"
  5. "fmt"
  6. "io"
  7. "net"
  8. "strings"
  9. "time"
  10. log "github.com/Sirupsen/logrus"
  11. guerrilla "github.com/flashmob/go-guerrilla"
  12. "github.com/flashmob/go-guerrilla/util"
  13. )
  14. type SmtpdServer struct {
  15. tlsConfig *tls.Config
  16. maxSize int // max email DATA size
  17. timeout time.Duration
  18. sem chan int // currently active client list
  19. Config guerrilla.ServerConfig
  20. allowedHostsStr string
  21. }
  22. // Upgrades the connection to TLS
  23. // Sets up buffers with the upgraded connection
  24. func (server *SmtpdServer) upgradeToTls(client *guerrilla.Client) bool {
  25. var tlsConn *tls.Conn
  26. tlsConn = tls.Server(client.Conn, server.tlsConfig)
  27. err := tlsConn.Handshake()
  28. if err == nil {
  29. client.Conn = net.Conn(tlsConn)
  30. client.Bufin = guerrilla.NewSMTPBufferedReader(client.Conn)
  31. client.Bufout = bufio.NewWriter(client.Conn)
  32. client.TLS = true
  33. return true
  34. }
  35. log.WithError(err).Warn("Failed to TLS handshake")
  36. return false
  37. }
  38. func (server *SmtpdServer) handleClient(client *guerrilla.Client, backend guerrilla.Backend) {
  39. defer server.closeClient(client)
  40. advertiseTLS := "250-STARTTLS\r\n"
  41. if server.Config.TLSAlwaysOn {
  42. if server.upgradeToTls(client) {
  43. advertiseTLS = ""
  44. }
  45. }
  46. greeting := fmt.Sprintf("220 %s SMTP guerrillad(%s) #%d (%d) %s",
  47. server.Config.Hostname, guerrilla.Version, client.ClientID,
  48. len(server.sem), time.Now().Format(time.RFC1123Z))
  49. if !server.Config.StartTLS {
  50. // STARTTLS turned off
  51. advertiseTLS = ""
  52. }
  53. for i := 0; i < 100; i++ {
  54. switch client.State {
  55. case 0:
  56. responseAdd(client, greeting)
  57. client.State = 1
  58. case 1:
  59. client.Bufin.SetLimit(guerrilla.CommandMaxLength)
  60. input, err := server.readSmtp(client)
  61. if err != nil {
  62. if err == io.EOF {
  63. log.WithError(err).Debugf("Client closed the connection already: %s", client.Address)
  64. return
  65. } else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
  66. log.WithError(err).Debugf("Timeout: %s", client.Address)
  67. return
  68. } else if err == guerrilla.InputLimitExceeded {
  69. responseAdd(client, "500 Line too long.")
  70. // kill it so that another one can connect
  71. killClient(client)
  72. }
  73. log.WithError(err).Warnf("Read error: %s", client.Address)
  74. break
  75. }
  76. input = strings.Trim(input, " \n\r")
  77. bound := len(input)
  78. if bound > 16 {
  79. bound = 16
  80. }
  81. cmd := strings.ToUpper(input[0:bound])
  82. switch {
  83. case strings.Index(cmd, "HELO") == 0:
  84. if len(input) > 5 {
  85. client.Helo = input[5:]
  86. }
  87. responseAdd(client, "250 "+server.Config.Hostname+" Hello ")
  88. case strings.Index(cmd, "EHLO") == 0:
  89. if len(input) > 5 {
  90. client.Helo = input[5:]
  91. }
  92. responseAdd(client, fmt.Sprintf(
  93. `250-%s Hello %s[%s]\r
  94. 250-SIZE %d\r
  95. 250-PIPELINING \r
  96. %s250 HELP`,
  97. server.Config.Hostname, client.Helo, client.Address,
  98. server.Config.MaxSize, advertiseTLS))
  99. case strings.Index(cmd, "HELP") == 0:
  100. responseAdd(client, "250 Help! I need somebody...")
  101. case strings.Index(cmd, "MAIL FROM:") == 0:
  102. if len(input) > 10 {
  103. client.MailFrom = input[10:]
  104. }
  105. responseAdd(client, "250 Ok")
  106. case strings.Index(cmd, "XCLIENT") == 0:
  107. // Nginx sends this
  108. // XCLIENT ADDR=212.96.64.216 NAME=[UNAVAILABLE]
  109. client.Address = input[13:]
  110. client.Address = client.Address[0:strings.Index(client.Address, " ")]
  111. fmt.Println("client address:[" + client.Address + "]")
  112. responseAdd(client, "250 OK")
  113. case strings.Index(cmd, "RCPT TO:") == 0:
  114. if len(input) > 8 {
  115. client.RcptTo = input[8:]
  116. }
  117. responseAdd(client, "250 Accepted")
  118. case strings.Index(cmd, "NOOP") == 0:
  119. responseAdd(client, "250 OK")
  120. case strings.Index(cmd, "RSET") == 0:
  121. client.MailFrom = ""
  122. client.RcptTo = ""
  123. responseAdd(client, "250 OK")
  124. case strings.Index(cmd, "DATA") == 0:
  125. responseAdd(client, "354 Enter message, ending with \".\" on a line by itself")
  126. client.State = 2
  127. case (strings.Index(cmd, "STARTTLS") == 0) &&
  128. !client.TLS &&
  129. server.Config.StartTLS:
  130. responseAdd(client, "220 Ready to start TLS")
  131. // go to start TLS state
  132. client.State = 3
  133. case strings.Index(cmd, "QUIT") == 0:
  134. responseAdd(client, "221 Bye")
  135. killClient(client)
  136. default:
  137. responseAdd(client, "500 unrecognized command: "+cmd)
  138. client.Errors++
  139. if client.Errors > 3 {
  140. responseAdd(client, "500 Too many unrecognized commands")
  141. killClient(client)
  142. }
  143. }
  144. case 2:
  145. var err error
  146. client.Bufin.SetLimit(int64(server.Config.MaxSize) + 1024000) // This is a hard limit.
  147. client.Data, err = server.readSmtp(client)
  148. if err == nil {
  149. if user, host, mailErr := util.ValidateEmailData(client, server.allowedHostsStr); mailErr == nil {
  150. resp := backend.Process(client, user, host)
  151. responseAdd(client, resp)
  152. } else {
  153. responseAdd(client, "550 Error: "+mailErr.Error())
  154. }
  155. } else {
  156. if err == guerrilla.InputLimitExceeded {
  157. // hard limit reached, end to make room for other clients
  158. responseAdd(client, "550 Error: DATA limit exceeded by more than a megabyte!")
  159. killClient(client)
  160. } else {
  161. responseAdd(client, "550 Error: "+err.Error())
  162. }
  163. log.WithError(err).Warn("DATA read error")
  164. }
  165. client.State = 1
  166. case 3:
  167. // upgrade to TLS
  168. if server.upgradeToTls(client) {
  169. advertiseTLS = ""
  170. client.State = 1
  171. }
  172. }
  173. // Send a response back to the client
  174. err := server.responseWrite(client)
  175. if err != nil {
  176. if err == io.EOF {
  177. // client closed the connection already
  178. return
  179. }
  180. if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
  181. // too slow, timeout
  182. return
  183. }
  184. }
  185. if client.KillTime > 1 {
  186. return
  187. }
  188. }
  189. }
  190. // add a response on the response buffer
  191. func responseAdd(client *guerrilla.Client, line string) {
  192. client.Response = line + "\r\n"
  193. }
  194. func (server *SmtpdServer) closeClient(client *guerrilla.Client) {
  195. client.Conn.Close()
  196. <-server.sem // Done; enable next client to run.
  197. }
  198. func killClient(client *guerrilla.Client) {
  199. client.KillTime = time.Now().Unix()
  200. }
  201. // Reads from the smtpBufferedReader, can be in command state or data state.
  202. func (server *SmtpdServer) readSmtp(client *guerrilla.Client) (input string, err error) {
  203. var reply string
  204. // Command state terminator by default
  205. suffix := "\r\n"
  206. if client.State == 2 {
  207. // DATA state ends with a dot on a line by itself
  208. suffix = "\r\n.\r\n"
  209. }
  210. for err == nil {
  211. client.Conn.SetDeadline(time.Now().Add(server.timeout * time.Second))
  212. reply, err = client.Bufin.ReadString('\n')
  213. if reply != "" {
  214. input = input + reply
  215. if len(input) > server.Config.MaxSize {
  216. err = fmt.Errorf("Maximum DATA size exceeded (%d)", server.Config.MaxSize)
  217. return input, err
  218. }
  219. if client.State == 2 {
  220. // Extract the subject while we are at it.
  221. scanSubject(client, reply)
  222. }
  223. }
  224. if err != nil {
  225. break
  226. }
  227. if strings.HasSuffix(input, suffix) {
  228. break
  229. }
  230. }
  231. return input, err
  232. }
  233. // Scan the data part for a Subject line. Can be a multi-line
  234. func scanSubject(client *guerrilla.Client, reply string) {
  235. if client.Subject == "" && (len(reply) > 8) {
  236. test := strings.ToUpper(reply[0:9])
  237. if i := strings.Index(test, "SUBJECT: "); i == 0 {
  238. // first line with \r\n
  239. client.Subject = reply[9:]
  240. }
  241. } else if strings.HasSuffix(client.Subject, "\r\n") {
  242. // chop off the \r\n
  243. client.Subject = client.Subject[0 : len(client.Subject)-2]
  244. if (strings.HasPrefix(reply, " ")) || (strings.HasPrefix(reply, "\t")) {
  245. // subject is multi-line
  246. client.Subject = client.Subject + reply[1:]
  247. }
  248. }
  249. }
  250. func (server *SmtpdServer) responseWrite(client *guerrilla.Client) (err error) {
  251. var size int
  252. client.Conn.SetDeadline(time.Now().Add(server.timeout * time.Second))
  253. size, err = client.Bufout.WriteString(client.Response)
  254. client.Bufout.Flush()
  255. client.Response = client.Response[size:]
  256. return err
  257. }