smtp_server.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package server
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "github.com/emersion/go-smtp"
  8. "io"
  9. "mime"
  10. "mime/multipart"
  11. "net"
  12. "net/http"
  13. "net/http/httptest"
  14. "net/mail"
  15. "strings"
  16. "sync"
  17. )
  18. var (
  19. errInvalidDomain = errors.New("invalid domain")
  20. errInvalidAddress = errors.New("invalid address")
  21. errInvalidTopic = errors.New("invalid topic")
  22. errTooManyRecipients = errors.New("too many recipients")
  23. errMultipartNestedTooDeep = errors.New("multipart message nested too deep")
  24. errUnsupportedContentType = errors.New("unsupported content type")
  25. )
  26. const (
  27. maxMultipartDepth = 2
  28. )
  29. // smtpBackend implements SMTP server methods.
  30. type smtpBackend struct {
  31. config *Config
  32. handler func(http.ResponseWriter, *http.Request)
  33. success int64
  34. failure int64
  35. mu sync.Mutex
  36. }
  37. var _ smtp.Backend = (*smtpBackend)(nil)
  38. var _ smtp.Session = (*smtpSession)(nil)
  39. func newMailBackend(conf *Config, handler func(http.ResponseWriter, *http.Request)) *smtpBackend {
  40. return &smtpBackend{
  41. config: conf,
  42. handler: handler,
  43. }
  44. }
  45. func (b *smtpBackend) NewSession(conn *smtp.Conn) (smtp.Session, error) {
  46. logem(conn).Debug("Incoming mail")
  47. return &smtpSession{backend: b, conn: conn}, nil
  48. }
  49. func (b *smtpBackend) Counts() (total int64, success int64, failure int64) {
  50. b.mu.Lock()
  51. defer b.mu.Unlock()
  52. return b.success + b.failure, b.success, b.failure
  53. }
  54. // smtpSession is returned after EHLO.
  55. type smtpSession struct {
  56. backend *smtpBackend
  57. conn *smtp.Conn
  58. topic string
  59. token string
  60. mu sync.Mutex
  61. }
  62. func (s *smtpSession) AuthPlain(username, _ string) error {
  63. logem(s.conn).Field("smtp_username", username).Debug("AUTH PLAIN (with username %s)", username)
  64. return nil
  65. }
  66. func (s *smtpSession) Mail(from string, opts *smtp.MailOptions) error {
  67. logem(s.conn).Field("smtp_mail_from", from).Debug("MAIL FROM: %s", from)
  68. return nil
  69. }
  70. func (s *smtpSession) Rcpt(to string) error {
  71. logem(s.conn).Field("smtp_rcpt_to", to).Debug("RCPT TO: %s", to)
  72. return s.withFailCount(func() error {
  73. token := ""
  74. conf := s.backend.config
  75. addressList, err := mail.ParseAddressList(to)
  76. if err != nil {
  77. return err
  78. } else if len(addressList) != 1 {
  79. return errTooManyRecipients
  80. }
  81. to = addressList[0].Address
  82. if !strings.HasSuffix(to, "@"+conf.SMTPServerDomain) {
  83. return errInvalidDomain
  84. }
  85. // Remove @ntfy.sh from end of email
  86. to = strings.TrimSuffix(to, "@"+conf.SMTPServerDomain)
  87. if conf.SMTPServerAddrPrefix != "" {
  88. if !strings.HasPrefix(to, conf.SMTPServerAddrPrefix) {
  89. return errInvalidAddress
  90. }
  91. // remove ntfy- from beginning of email
  92. to = strings.TrimPrefix(to, conf.SMTPServerAddrPrefix)
  93. }
  94. // If email contains token, split topic and token
  95. if strings.Contains(to, "+") {
  96. parts := strings.Split(to, "+")
  97. to = parts[0]
  98. token = parts[1]
  99. }
  100. if !topicRegex.MatchString(to) {
  101. return errInvalidTopic
  102. }
  103. s.mu.Lock()
  104. s.topic = to
  105. s.token = token
  106. s.mu.Unlock()
  107. return nil
  108. })
  109. }
  110. func (s *smtpSession) Data(r io.Reader) error {
  111. return s.withFailCount(func() error {
  112. conf := s.backend.config
  113. b, err := io.ReadAll(r) // Protected by MaxMessageBytes
  114. if err != nil {
  115. return err
  116. }
  117. ev := logem(s.conn)
  118. if ev.IsTrace() {
  119. ev.Field("smtp_data", string(b)).Trace("DATA")
  120. } else if ev.IsDebug() {
  121. ev.Field("smtp_data_len", len(b)).Debug("DATA")
  122. }
  123. msg, err := mail.ReadMessage(bytes.NewReader(b))
  124. if err != nil {
  125. return err
  126. }
  127. body, err := readMailBody(msg.Body, msg.Header)
  128. if err != nil {
  129. return err
  130. }
  131. body = strings.TrimSpace(body)
  132. if len(body) > conf.MessageLimit {
  133. body = body[:conf.MessageLimit]
  134. }
  135. m := newDefaultMessage(s.topic, body)
  136. subject := strings.TrimSpace(msg.Header.Get("Subject"))
  137. if subject != "" {
  138. dec := mime.WordDecoder{}
  139. subject, err := dec.DecodeHeader(subject)
  140. if err != nil {
  141. return err
  142. }
  143. m.Title = subject
  144. }
  145. if m.Title != "" && m.Message == "" {
  146. m.Message = m.Title // Flip them, this makes more sense
  147. m.Title = ""
  148. }
  149. if err := s.publishMessage(m); err != nil {
  150. return err
  151. }
  152. s.backend.mu.Lock()
  153. s.backend.success++
  154. s.backend.mu.Unlock()
  155. minc(metricEmailsReceivedSuccess)
  156. return nil
  157. })
  158. }
  159. func (s *smtpSession) publishMessage(m *message) error {
  160. // Extract remote address (for rate limiting)
  161. remoteAddr, _, err := net.SplitHostPort(s.conn.Conn().RemoteAddr().String())
  162. if err != nil {
  163. remoteAddr = s.conn.Conn().RemoteAddr().String()
  164. }
  165. // Call HTTP handler with fake HTTP request
  166. url := fmt.Sprintf("%s/%s", s.backend.config.BaseURL, m.Topic)
  167. req, err := http.NewRequest("POST", url, strings.NewReader(m.Message))
  168. req.RequestURI = "/" + m.Topic // just for the logs
  169. req.RemoteAddr = remoteAddr // rate limiting!!
  170. req.Header.Set("X-Forwarded-For", remoteAddr)
  171. if err != nil {
  172. return err
  173. }
  174. if m.Title != "" {
  175. req.Header.Set("Title", m.Title)
  176. }
  177. if s.token != "" {
  178. req.Header.Add("Authorization", "Bearer "+s.token)
  179. }
  180. rr := httptest.NewRecorder()
  181. s.backend.handler(rr, req)
  182. if rr.Code != http.StatusOK {
  183. return errors.New("error: " + rr.Body.String())
  184. }
  185. return nil
  186. }
  187. func (s *smtpSession) Reset() {
  188. s.mu.Lock()
  189. s.topic = ""
  190. s.mu.Unlock()
  191. }
  192. func (s *smtpSession) Logout() error {
  193. return nil
  194. }
  195. func (s *smtpSession) withFailCount(fn func() error) error {
  196. err := fn()
  197. s.backend.mu.Lock()
  198. defer s.backend.mu.Unlock()
  199. if err != nil {
  200. // Almost all of these errors are parse errors, and user input errors.
  201. // We do not want to spam the log with WARN messages.
  202. logem(s.conn).Err(err).Debug("Incoming mail error")
  203. s.backend.failure++
  204. minc(metricEmailsReceivedFailure)
  205. }
  206. return err
  207. }
  208. func readMailBody(body io.Reader, header mail.Header) (string, error) {
  209. if header.Get("Content-Type") == "" {
  210. return readPlainTextMailBody(body, header.Get("Content-Transfer-Encoding"))
  211. }
  212. contentType, params, err := mime.ParseMediaType(header.Get("Content-Type"))
  213. if err != nil {
  214. return "", err
  215. }
  216. if strings.ToLower(contentType) == "text/plain" {
  217. return readPlainTextMailBody(body, header.Get("Content-Transfer-Encoding"))
  218. } else if strings.HasPrefix(strings.ToLower(contentType), "multipart/") {
  219. return readMultipartMailBody(body, params, 0)
  220. }
  221. return "", errUnsupportedContentType
  222. }
  223. func readMultipartMailBody(body io.Reader, params map[string]string, depth int) (string, error) {
  224. if depth >= maxMultipartDepth {
  225. return "", errMultipartNestedTooDeep
  226. }
  227. mr := multipart.NewReader(body, params["boundary"])
  228. for {
  229. part, err := mr.NextPart()
  230. if err != nil { // may be io.EOF
  231. return "", err
  232. }
  233. partContentType, partParams, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
  234. if err != nil {
  235. return "", err
  236. }
  237. if strings.ToLower(partContentType) == "text/plain" {
  238. return readPlainTextMailBody(part, part.Header.Get("Content-Transfer-Encoding"))
  239. } else if strings.HasPrefix(strings.ToLower(partContentType), "multipart/") {
  240. return readMultipartMailBody(part, partParams, depth+1)
  241. }
  242. // Continue with next part
  243. }
  244. }
  245. func readPlainTextMailBody(reader io.Reader, transferEncoding string) (string, error) {
  246. if strings.ToLower(transferEncoding) == "base64" {
  247. reader = base64.NewDecoder(base64.StdEncoding, reader)
  248. }
  249. body, err := io.ReadAll(reader)
  250. if err != nil {
  251. return "", err
  252. }
  253. return string(body), nil
  254. }