smtp_server.go 9.0 KB

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