smtp_server.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package server
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "github.com/emersion/go-smtp"
  7. "io"
  8. "mime"
  9. "mime/multipart"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/mail"
  13. "strings"
  14. "sync"
  15. )
  16. var (
  17. errInvalidDomain = errors.New("invalid domain")
  18. errInvalidAddress = errors.New("invalid address")
  19. errInvalidTopic = errors.New("invalid topic")
  20. errTooManyRecipients = errors.New("too many recipients")
  21. errUnsupportedContentType = errors.New("unsupported content type")
  22. )
  23. // smtpBackend implements SMTP server methods.
  24. type smtpBackend struct {
  25. config *Config
  26. handler func(http.ResponseWriter, *http.Request)
  27. success int64
  28. failure int64
  29. mu sync.Mutex
  30. }
  31. func newMailBackend(conf *Config, handler func(http.ResponseWriter, *http.Request)) *smtpBackend {
  32. return &smtpBackend{
  33. config: conf,
  34. handler: handler,
  35. }
  36. }
  37. func (b *smtpBackend) Login(state *smtp.ConnectionState, username, password string) (smtp.Session, error) {
  38. return &smtpSession{backend: b, remoteAddr: state.RemoteAddr.String()}, nil
  39. }
  40. func (b *smtpBackend) AnonymousLogin(state *smtp.ConnectionState) (smtp.Session, error) {
  41. return &smtpSession{backend: b, remoteAddr: state.RemoteAddr.String()}, nil
  42. }
  43. func (b *smtpBackend) Counts() (success int64, failure int64) {
  44. b.mu.Lock()
  45. defer b.mu.Unlock()
  46. return b.success, b.failure
  47. }
  48. // smtpSession is returned after EHLO.
  49. type smtpSession struct {
  50. backend *smtpBackend
  51. remoteAddr string
  52. topic string
  53. mu sync.Mutex
  54. }
  55. func (s *smtpSession) AuthPlain(username, password string) error {
  56. return nil
  57. }
  58. func (s *smtpSession) Mail(from string, opts smtp.MailOptions) error {
  59. return nil
  60. }
  61. func (s *smtpSession) Rcpt(to string) error {
  62. return s.withFailCount(func() error {
  63. conf := s.backend.config
  64. addressList, err := mail.ParseAddressList(to)
  65. if err != nil {
  66. return err
  67. } else if len(addressList) != 1 {
  68. return errTooManyRecipients
  69. }
  70. to = addressList[0].Address
  71. if !strings.HasSuffix(to, "@"+conf.SMTPServerDomain) {
  72. return errInvalidDomain
  73. }
  74. to = strings.TrimSuffix(to, "@"+conf.SMTPServerDomain)
  75. if conf.SMTPServerAddrPrefix != "" {
  76. if !strings.HasPrefix(to, conf.SMTPServerAddrPrefix) {
  77. return errInvalidAddress
  78. }
  79. to = strings.TrimPrefix(to, conf.SMTPServerAddrPrefix)
  80. }
  81. if !topicRegex.MatchString(to) {
  82. return errInvalidTopic
  83. }
  84. s.mu.Lock()
  85. s.topic = to
  86. s.mu.Unlock()
  87. return nil
  88. })
  89. }
  90. func (s *smtpSession) Data(r io.Reader) error {
  91. return s.withFailCount(func() error {
  92. conf := s.backend.config
  93. b, err := io.ReadAll(r) // Protected by MaxMessageBytes
  94. if err != nil {
  95. return err
  96. }
  97. msg, err := mail.ReadMessage(bytes.NewReader(b))
  98. if err != nil {
  99. return err
  100. }
  101. body, err := readMailBody(msg)
  102. if err != nil {
  103. return err
  104. }
  105. body = strings.TrimSpace(body)
  106. if len(body) > conf.MessageLimit {
  107. body = body[:conf.MessageLimit]
  108. }
  109. m := newDefaultMessage(s.topic, body)
  110. subject := strings.TrimSpace(msg.Header.Get("Subject"))
  111. if subject != "" {
  112. dec := mime.WordDecoder{}
  113. subject, err := dec.DecodeHeader(subject)
  114. if err != nil {
  115. return err
  116. }
  117. m.Title = subject
  118. }
  119. if m.Title != "" && m.Message == "" {
  120. m.Message = m.Title // Flip them, this makes more sense
  121. m.Title = ""
  122. }
  123. if err := s.publishMessage(m); err != nil {
  124. return err
  125. }
  126. s.backend.mu.Lock()
  127. s.backend.success++
  128. s.backend.mu.Unlock()
  129. return nil
  130. })
  131. }
  132. func (s *smtpSession) publishMessage(m *message) error {
  133. url := fmt.Sprintf("%s/%s", s.backend.config.BaseURL, m.Topic)
  134. req, err := http.NewRequest("PUT", url, strings.NewReader(m.Message))
  135. req.RemoteAddr = s.remoteAddr // rate limiting!!
  136. if err != nil {
  137. return err
  138. }
  139. if m.Title != "" {
  140. req.Header.Set("Title", m.Title)
  141. }
  142. rr := httptest.NewRecorder()
  143. s.backend.handler(rr, req)
  144. if rr.Code != http.StatusOK {
  145. return errors.New("error: " + rr.Body.String())
  146. }
  147. return nil
  148. }
  149. func (s *smtpSession) Reset() {
  150. s.mu.Lock()
  151. s.topic = ""
  152. s.mu.Unlock()
  153. }
  154. func (s *smtpSession) Logout() error {
  155. return nil
  156. }
  157. func (s *smtpSession) withFailCount(fn func() error) error {
  158. err := fn()
  159. s.backend.mu.Lock()
  160. defer s.backend.mu.Unlock()
  161. if err != nil {
  162. s.backend.failure++
  163. }
  164. return err
  165. }
  166. func readMailBody(msg *mail.Message) (string, error) {
  167. if msg.Header.Get("Content-Type") == "" {
  168. return readPlainTextMailBody(msg)
  169. }
  170. contentType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
  171. if err != nil {
  172. return "", err
  173. }
  174. if contentType == "text/plain" {
  175. return readPlainTextMailBody(msg)
  176. } else if strings.HasPrefix(contentType, "multipart/") {
  177. return readMultipartMailBody(msg, params)
  178. }
  179. return "", errUnsupportedContentType
  180. }
  181. func readPlainTextMailBody(msg *mail.Message) (string, error) {
  182. body, err := io.ReadAll(msg.Body)
  183. if err != nil {
  184. return "", err
  185. }
  186. return string(body), nil
  187. }
  188. func readMultipartMailBody(msg *mail.Message, params map[string]string) (string, error) {
  189. mr := multipart.NewReader(msg.Body, params["boundary"])
  190. for {
  191. part, err := mr.NextPart()
  192. if err != nil { // may be io.EOF
  193. return "", err
  194. }
  195. partContentType, _, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
  196. if err != nil {
  197. return "", err
  198. }
  199. if partContentType != "text/plain" {
  200. continue
  201. }
  202. body, err := io.ReadAll(part)
  203. if err != nil {
  204. return "", err
  205. }
  206. return string(body), nil
  207. }
  208. }