client.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. package guerrilla
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/tls"
  6. "fmt"
  7. "github.com/flashmob/go-guerrilla/log"
  8. "github.com/flashmob/go-guerrilla/mail"
  9. "net"
  10. "net/textproto"
  11. "sync"
  12. "time"
  13. )
  14. // ClientState indicates which part of the SMTP transaction a given client is in.
  15. type ClientState int
  16. const (
  17. // The client has connected, and is awaiting our first response
  18. ClientGreeting = iota
  19. // We have responded to the client's connection and are awaiting a command
  20. ClientCmd
  21. // We have received the sender and recipient information
  22. ClientData
  23. // We have agreed with the client to secure the connection over TLS
  24. ClientStartTLS
  25. // Server will shutdown, client to shutdown on next command turn
  26. ClientShutdown
  27. )
  28. type client struct {
  29. *mail.Envelope
  30. ID uint64
  31. ConnectedAt time.Time
  32. KilledAt time.Time
  33. // Number of errors encountered during session with this client
  34. errors int
  35. state ClientState
  36. messagesSent int
  37. // Response to be written to the client
  38. response bytes.Buffer
  39. conn net.Conn
  40. bufin *smtpBufferedReader
  41. bufout *bufio.Writer
  42. smtpReader *textproto.Reader
  43. ar *adjustableLimitedReader
  44. // guards access to conn
  45. connGuard sync.Mutex
  46. log log.Logger
  47. }
  48. // Allocate a new client
  49. func NewClient(conn net.Conn, clientID uint64, logger log.Logger) *client {
  50. c := &client{
  51. conn: conn,
  52. Envelope: mail.NewEnvelope(getRemoteAddr(conn), clientID),
  53. ConnectedAt: time.Now(),
  54. bufin: newSMTPBufferedReader(conn),
  55. bufout: bufio.NewWriter(conn),
  56. ID: clientID,
  57. log: logger,
  58. }
  59. // used for reading the DATA state
  60. c.smtpReader = textproto.NewReader(c.bufin.Reader)
  61. return c
  62. }
  63. // setResponse adds a response to be written on the next turn
  64. func (c *client) sendResponse(r ...interface{}) {
  65. c.bufout.Reset(c.conn)
  66. if c.log.IsDebug() {
  67. // us additional buffer so that we can log the response in debug mode only
  68. c.response.Reset()
  69. }
  70. for _, item := range r {
  71. switch v := item.(type) {
  72. case string:
  73. if _, err := c.bufout.WriteString(v); err != nil {
  74. c.log.WithError(err).Error("could not write to c.bufout")
  75. }
  76. if c.log.IsDebug() {
  77. c.response.WriteString(v)
  78. }
  79. case error:
  80. if _, err := c.bufout.WriteString(v.Error()); err != nil {
  81. c.log.WithError(err).Error("could not write to c.bufout")
  82. }
  83. if c.log.IsDebug() {
  84. c.response.WriteString(v.Error())
  85. }
  86. case fmt.Stringer:
  87. if _, err := c.bufout.WriteString(v.String()); err != nil {
  88. c.log.WithError(err).Error("could not write to c.bufout")
  89. }
  90. if c.log.IsDebug() {
  91. c.response.WriteString(v.String())
  92. }
  93. }
  94. }
  95. c.bufout.WriteString("\r\n")
  96. if c.log.IsDebug() {
  97. c.response.WriteString("\r\n")
  98. }
  99. }
  100. // resetTransaction resets the SMTP transaction, ready for the next email (doesn't disconnect)
  101. // Transaction ends on:
  102. // -HELO/EHLO/REST command
  103. // -End of DATA command
  104. // TLS handhsake
  105. func (c *client) resetTransaction() {
  106. c.Envelope.ResetTransaction()
  107. }
  108. // isInTransaction returns true if the connection is inside a transaction.
  109. // A transaction starts after a MAIL command gets issued by the client.
  110. // Call resetTransaction to end the transaction
  111. func (c *client) isInTransaction() bool {
  112. isMailFromEmpty := c.MailFrom == (mail.Address{})
  113. if isMailFromEmpty {
  114. return false
  115. }
  116. return true
  117. }
  118. // kill flags the connection to close on the next turn
  119. func (c *client) kill() {
  120. c.KilledAt = time.Now()
  121. }
  122. // isAlive returns true if the client is to close on the next turn
  123. func (c *client) isAlive() bool {
  124. return c.KilledAt.IsZero()
  125. }
  126. // setTimeout adjust the timeout on the connection, goroutine safe
  127. func (c *client) setTimeout(t time.Duration) {
  128. defer c.connGuard.Unlock()
  129. c.connGuard.Lock()
  130. if c.conn != nil {
  131. c.conn.SetDeadline(time.Now().Add(t * time.Second))
  132. }
  133. }
  134. // closeConn closes a client connection, , goroutine safe
  135. func (c *client) closeConn() {
  136. defer c.connGuard.Unlock()
  137. c.connGuard.Lock()
  138. c.conn.Close()
  139. c.conn = nil
  140. }
  141. // init is called after the client is borrowed from the pool, to get it ready for the connection
  142. func (c *client) init(conn net.Conn, clientID uint64) {
  143. c.conn = conn
  144. // reset our reader & writer
  145. c.bufout.Reset(conn)
  146. c.bufin.Reset(conn)
  147. // reset session data
  148. c.state = 0
  149. c.KilledAt = time.Time{}
  150. c.ConnectedAt = time.Now()
  151. c.ID = clientID
  152. c.errors = 0
  153. c.Envelope.Reseed(getRemoteAddr(conn), clientID)
  154. }
  155. // getID returns the client's unique ID
  156. func (c *client) getID() uint64 {
  157. return c.ID
  158. }
  159. // UpgradeToTLS upgrades a client connection to TLS
  160. func (client *client) upgradeToTLS(tlsConfig *tls.Config) error {
  161. var tlsConn *tls.Conn
  162. // load the config thread-safely
  163. tlsConn = tls.Server(client.conn, tlsConfig)
  164. // Call handshake here to get any handshake error before reading starts
  165. err := tlsConn.Handshake()
  166. if err != nil {
  167. return err
  168. }
  169. // convert tlsConn to net.Conn
  170. client.conn = net.Conn(tlsConn)
  171. client.bufout.Reset(client.conn)
  172. client.bufin.Reset(client.conn)
  173. client.TLS = true
  174. return err
  175. }
  176. func getRemoteAddr(conn net.Conn) string {
  177. if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
  178. // we just want the IP (not the port)
  179. return addr.IP.String()
  180. } else {
  181. return conn.RemoteAddr().Network()
  182. }
  183. }