smtp_server.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. return nil
  156. })
  157. }
  158. func (s *smtpSession) publishMessage(m *message) error {
  159. // Extract remote address (for rate limiting)
  160. remoteAddr, _, err := net.SplitHostPort(s.conn.Conn().RemoteAddr().String())
  161. if err != nil {
  162. remoteAddr = s.conn.Conn().RemoteAddr().String()
  163. }
  164. // Call HTTP handler with fake HTTP request
  165. url := fmt.Sprintf("%s/%s", s.backend.config.BaseURL, m.Topic)
  166. req, err := http.NewRequest("POST", url, strings.NewReader(m.Message))
  167. req.RequestURI = "/" + m.Topic // just for the logs
  168. req.RemoteAddr = remoteAddr // rate limiting!!
  169. req.Header.Set("X-Forwarded-For", remoteAddr)
  170. if err != nil {
  171. return err
  172. }
  173. if m.Title != "" {
  174. req.Header.Set("Title", m.Title)
  175. }
  176. if s.token != "" {
  177. req.Header.Add("Authorization", "Bearer "+s.token)
  178. }
  179. rr := httptest.NewRecorder()
  180. s.backend.handler(rr, req)
  181. if rr.Code != http.StatusOK {
  182. return errors.New("error: " + rr.Body.String())
  183. }
  184. return nil
  185. }
  186. func (s *smtpSession) Reset() {
  187. s.mu.Lock()
  188. s.topic = ""
  189. s.mu.Unlock()
  190. }
  191. func (s *smtpSession) Logout() error {
  192. return nil
  193. }
  194. func (s *smtpSession) withFailCount(fn func() error) error {
  195. err := fn()
  196. s.backend.mu.Lock()
  197. defer s.backend.mu.Unlock()
  198. if err != nil {
  199. // Almost all of these errors are parse errors, and user input errors.
  200. // We do not want to spam the log with WARN messages.
  201. logem(s.conn).Err(err).Debug("Incoming mail error")
  202. s.backend.failure++
  203. }
  204. return err
  205. }
  206. func readMailBody(body io.Reader, header mail.Header) (string, error) {
  207. if header.Get("Content-Type") == "" {
  208. return readPlainTextMailBody(body, header.Get("Content-Transfer-Encoding"))
  209. }
  210. contentType, params, err := mime.ParseMediaType(header.Get("Content-Type"))
  211. if err != nil {
  212. return "", err
  213. }
  214. if strings.ToLower(contentType) == "text/plain" {
  215. return readPlainTextMailBody(body, header.Get("Content-Transfer-Encoding"))
  216. } else if strings.HasPrefix(strings.ToLower(contentType), "multipart/") {
  217. return readMultipartMailBody(body, params, 0)
  218. }
  219. return "", errUnsupportedContentType
  220. }
  221. func readMultipartMailBody(body io.Reader, params map[string]string, depth int) (string, error) {
  222. if depth >= maxMultipartDepth {
  223. return "", errMultipartNestedTooDeep
  224. }
  225. mr := multipart.NewReader(body, params["boundary"])
  226. for {
  227. part, err := mr.NextPart()
  228. if err != nil { // may be io.EOF
  229. return "", err
  230. }
  231. partContentType, partParams, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
  232. if err != nil {
  233. return "", err
  234. }
  235. if strings.ToLower(partContentType) == "text/plain" {
  236. return readPlainTextMailBody(part, part.Header.Get("Content-Transfer-Encoding"))
  237. } else if strings.HasPrefix(strings.ToLower(partContentType), "multipart/") {
  238. return readMultipartMailBody(part, partParams, depth+1)
  239. }
  240. // Continue with next part
  241. }
  242. }
  243. func readPlainTextMailBody(reader io.Reader, transferEncoding string) (string, error) {
  244. if strings.ToLower(transferEncoding) == "base64" {
  245. reader = base64.NewDecoder(base64.StdEncoding, reader)
  246. }
  247. body, err := io.ReadAll(reader)
  248. if err != nil {
  249. return "", err
  250. }
  251. return string(body), nil
  252. }