client.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package guerrilla
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/tls"
  6. "fmt"
  7. "net"
  8. "net/textproto"
  9. "sync"
  10. "time"
  11. "github.com/flashmob/go-guerrilla/log"
  12. "github.com/flashmob/go-guerrilla/mail"
  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. // NewClient allocates a new client.
  49. func NewClient(conn net.Conn, clientID uint64, logger log.Logger, envelope *mail.Pool) *client {
  50. c := &client{
  51. conn: conn,
  52. // Envelope will be borrowed from the envelope pool
  53. // the envelope could be 'detached' from the client later when processing
  54. Envelope: envelope.Borrow(getRemoteAddr(conn), clientID),
  55. ConnectedAt: time.Now(),
  56. bufin: newSMTPBufferedReader(conn),
  57. bufout: bufio.NewWriter(conn),
  58. ID: clientID,
  59. log: logger,
  60. }
  61. // used for reading the DATA state
  62. c.smtpReader = textproto.NewReader(c.bufin.Reader)
  63. return c
  64. }
  65. // setResponse adds a response to be written on the next turn
  66. func (c *client) sendResponse(r ...interface{}) {
  67. c.bufout.Reset(c.conn)
  68. if c.log.IsDebug() {
  69. // us additional buffer so that we can log the response in debug mode only
  70. c.response.Reset()
  71. }
  72. for _, item := range r {
  73. switch v := item.(type) {
  74. case string:
  75. if _, err := c.bufout.WriteString(v); err != nil {
  76. c.log.WithError(err).Error("could not write to c.bufout")
  77. }
  78. if c.log.IsDebug() {
  79. c.response.WriteString(v)
  80. }
  81. case error:
  82. if _, err := c.bufout.WriteString(v.Error()); err != nil {
  83. c.log.WithError(err).Error("could not write to c.bufout")
  84. }
  85. if c.log.IsDebug() {
  86. c.response.WriteString(v.Error())
  87. }
  88. case fmt.Stringer:
  89. if _, err := c.bufout.WriteString(v.String()); err != nil {
  90. c.log.WithError(err).Error("could not write to c.bufout")
  91. }
  92. if c.log.IsDebug() {
  93. c.response.WriteString(v.String())
  94. }
  95. }
  96. }
  97. c.bufout.WriteString("\r\n")
  98. if c.log.IsDebug() {
  99. c.response.WriteString("\r\n")
  100. }
  101. }
  102. // resetTransaction resets the SMTP transaction, ready for the next email (doesn't disconnect)
  103. // Transaction ends on:
  104. // -HELO/EHLO/REST command
  105. // -End of DATA command
  106. // TLS handhsake
  107. func (c *client) resetTransaction() {
  108. c.Envelope.ResetTransaction()
  109. }
  110. // isInTransaction returns true if the connection is inside a transaction.
  111. // A transaction starts after a MAIL command gets issued by the client.
  112. // Call resetTransaction to end the transaction
  113. func (c *client) isInTransaction() bool {
  114. isMailFromEmpty := c.MailFrom == (mail.Address{})
  115. if isMailFromEmpty {
  116. return false
  117. }
  118. return true
  119. }
  120. // kill flags the connection to close on the next turn
  121. func (c *client) kill() {
  122. c.KilledAt = time.Now()
  123. }
  124. // isAlive returns true if the client is to close on the next turn
  125. func (c *client) isAlive() bool {
  126. return c.KilledAt.IsZero()
  127. }
  128. // setTimeout adjust the timeout on the connection, goroutine safe
  129. func (c *client) setTimeout(t time.Duration) {
  130. defer c.connGuard.Unlock()
  131. c.connGuard.Lock()
  132. if c.conn != nil {
  133. c.conn.SetDeadline(time.Now().Add(t * time.Second))
  134. }
  135. }
  136. // closeConn closes a client connection, , goroutine safe
  137. func (c *client) closeConn() {
  138. defer c.connGuard.Unlock()
  139. c.connGuard.Lock()
  140. c.conn.Close()
  141. c.conn = nil
  142. }
  143. // init is called after the client is borrowed from the pool, to get it ready for the connection
  144. func (c *client) init(conn net.Conn, clientID uint64, ep *mail.Pool) {
  145. c.conn = conn
  146. // reset our reader & writer
  147. c.bufout.Reset(conn)
  148. c.bufin.Reset(conn)
  149. // reset session data
  150. c.state = 0
  151. c.KilledAt = time.Time{}
  152. c.ConnectedAt = time.Now()
  153. c.ID = clientID
  154. c.errors = 0
  155. // borrow an envelope from the envelope pool
  156. c.Envelope = ep.Borrow(getRemoteAddr(conn), clientID)
  157. }
  158. // getID returns the client's unique ID
  159. func (c *client) getID() uint64 {
  160. return c.ID
  161. }
  162. // UpgradeToTLS upgrades a client connection to TLS
  163. func (client *client) upgradeToTLS(tlsConfig *tls.Config) error {
  164. var tlsConn *tls.Conn
  165. // load the config thread-safely
  166. tlsConn = tls.Server(client.conn, tlsConfig)
  167. // Call handshake here to get any handshake error before reading starts
  168. err := tlsConn.Handshake()
  169. if err != nil {
  170. return err
  171. }
  172. // convert tlsConn to net.Conn
  173. client.conn = net.Conn(tlsConn)
  174. client.bufout.Reset(client.conn)
  175. client.bufin.Reset(client.conn)
  176. client.TLS = true
  177. return err
  178. }
  179. func getRemoteAddr(conn net.Conn) string {
  180. if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
  181. // we just want the IP (not the port)
  182. return addr.IP.String()
  183. } else {
  184. return conn.RemoteAddr().Network()
  185. }
  186. }