client.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 (for debugging)
  38. response bytes.Buffer
  39. bufErr error
  40. conn net.Conn
  41. bufin *smtpBufferedReader
  42. bufout *bufio.Writer
  43. smtpReader *textproto.Reader
  44. ar *adjustableLimitedReader
  45. // guards access to conn
  46. connGuard sync.Mutex
  47. log log.Logger
  48. }
  49. // NewClient allocates a new client.
  50. func NewClient(conn net.Conn, clientID uint64, logger log.Logger, envelope *mail.Pool) *client {
  51. c := &client{
  52. conn: conn,
  53. // Envelope will be borrowed from the envelope pool
  54. // the envelope could be 'detached' from the client later when processing
  55. Envelope: envelope.Borrow(getRemoteAddr(conn), clientID),
  56. ConnectedAt: time.Now(),
  57. bufin: newSMTPBufferedReader(conn),
  58. bufout: bufio.NewWriter(conn),
  59. ID: clientID,
  60. log: logger,
  61. }
  62. // used for reading the DATA state
  63. c.smtpReader = textproto.NewReader(c.bufin.Reader)
  64. return c
  65. }
  66. // sendResponse adds a response to be written on the next turn
  67. // the response gets buffered
  68. func (c *client) sendResponse(r ...interface{}) {
  69. c.bufout.Reset(c.conn)
  70. if c.log.IsDebug() {
  71. // an additional buffer so that we can log the response in debug mode only
  72. c.response.Reset()
  73. }
  74. var out string
  75. if c.bufErr != nil {
  76. c.bufErr = nil
  77. }
  78. for _, item := range r {
  79. switch v := item.(type) {
  80. case error:
  81. out = v.Error()
  82. case fmt.Stringer:
  83. out = v.String()
  84. case string:
  85. out = v
  86. }
  87. if _, c.bufErr = c.bufout.WriteString(out); c.bufErr != nil {
  88. c.log.WithError(c.bufErr).Error("could not write to c.bufout")
  89. }
  90. if c.log.IsDebug() {
  91. c.response.WriteString(out)
  92. }
  93. if c.bufErr != nil {
  94. return
  95. }
  96. }
  97. _, c.bufErr = 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 (c *client) upgradeToTLS(tlsConfig *tls.Config) error {
  164. var tlsConn *tls.Conn
  165. // wrap c.conn in a new TLS server side connection
  166. tlsConn = tls.Server(c.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. c.conn = net.Conn(tlsConn)
  174. c.bufout.Reset(c.conn)
  175. c.bufin.Reset(c.conn)
  176. c.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. }