Debian Codegraph @

server/smtp_server.go

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