1package webmail
2
3import (
4 "bufio"
5 "fmt"
6 "io"
7 "log/slog"
8 "mime"
9 "net/url"
10 "strings"
11
12 "golang.org/x/text/encoding/ianaindex"
13
14 "github.com/mjl-/mox/dns"
15 "github.com/mjl-/mox/message"
16 "github.com/mjl-/mox/mlog"
17 "github.com/mjl-/mox/mox-"
18 "github.com/mjl-/mox/moxio"
19 "github.com/mjl-/mox/smtp"
20 "github.com/mjl-/mox/store"
21)
22
23// todo: we should have all needed information for messageItem in store.Message (perhaps some data in message.Part) for fast access, not having to parse the on-disk message file.
24
25var wordDecoder = mime.WordDecoder{
26 CharsetReader: func(charset string, r io.Reader) (io.Reader, error) {
27 switch strings.ToLower(charset) {
28 case "", "us-ascii", "utf-8":
29 return r, nil
30 }
31 enc, _ := ianaindex.MIME.Encoding(charset)
32 if enc == nil {
33 enc, _ = ianaindex.IANA.Encoding(charset)
34 }
35 if enc == nil {
36 return r, fmt.Errorf("unknown charset %q", charset)
37 }
38 return enc.NewDecoder().Reader(r), nil
39 },
40}
41
42// Attempt q/b-word-decode name, coming from Content-Type "name" field or
43// Content-Disposition "filename" field.
44//
45// RFC 2231 specify an encoding for non-ascii values in mime header parameters. But
46// it appears common practice to instead just q/b-word encode the values.
47// Thunderbird and gmail.com do this for the Content-Type "name" parameter.
48// gmail.com also does that for the Content-Disposition "filename" parameter, where
49// Thunderbird uses the RFC 2231-defined encoding. Go's mime.ParseMediaType parses
50// the mechanism specified in RFC 2231 only. The value for "name" we get here would
51// already be decoded properly for standards-compliant headers, like
52// "filename*0*=UTF-8”%...; filename*1*=%.... We'll look for Q/B-word encoding
53// markers ("=?"-prefix or "?="-suffix) and try to decode if present. This would
54// only cause trouble for filenames having this prefix/suffix.
55func tryDecodeParam(log mlog.Log, name string) string {
56 if name == "" || !strings.HasPrefix(name, "=?") && !strings.HasSuffix(name, "?=") {
57 return name
58 }
59 // todo: find where this is allowed. it seems quite common. perhaps we should remove the pedantic check?
60 if mox.Pedantic {
61 log.Debug("attachment contains rfc2047 q/b-word-encoded mime parameter instead of rfc2231-encoded", slog.String("name", name))
62 return name
63 }
64 s, err := wordDecoder.DecodeHeader(name)
65 if err != nil {
66 log.Debugx("q/b-word decoding mime parameter", err, slog.String("name", name))
67 return name
68 }
69 return s
70}
71
72// todo: mime.FormatMediaType does not wrap long lines. should do it ourselves, and split header into several parts (if commonly supported).
73
74func messageItem(log mlog.Log, m store.Message, state *msgState) (MessageItem, error) {
75 pm, err := parsedMessage(log, m, state, false, true)
76 if err != nil {
77 return MessageItem{}, fmt.Errorf("parsing message %d for item: %v", m.ID, err)
78 }
79 // Clear largish unused data.
80 m.MsgPrefix = nil
81 m.ParsedBuf = nil
82 return MessageItem{m, pm.envelope, pm.attachments, pm.isSigned, pm.isEncrypted, pm.firstLine, true}, nil
83}
84
85// formatFirstLine returns a line the client can display next to the subject line
86// in a mailbox. It will replace quoted text, and any prefixing "On ... write:"
87// line with "[...]" so only new and useful information will be displayed.
88// Trailing signatures are not included.
89func formatFirstLine(r io.Reader) (string, error) {
90 // We look quite a bit of lines ahead for trailing signatures with trailing empty lines.
91 var lines []string
92 scanner := bufio.NewScanner(r)
93 ensureLines := func() {
94 for len(lines) < 10 && scanner.Scan() {
95 lines = append(lines, strings.TrimSpace(scanner.Text()))
96 }
97 }
98 ensureLines()
99
100 isSnipped := func(s string) bool {
101 return s == "[...]" || s == "[…]" || s == "..."
102 }
103
104 nextLineQuoted := func(i int) bool {
105 if i+1 < len(lines) && lines[i+1] == "" {
106 i++
107 }
108 return i+1 < len(lines) && (strings.HasPrefix(lines[i+1], ">") || isSnipped(lines[i+1]))
109 }
110
111 // Remainder is signature if we see a line with only and minimum 2 dashes, and
112 // there are no more empty lines, and there aren't more than 5 lines left.
113 isSignature := func() bool {
114 if len(lines) == 0 || !strings.HasPrefix(lines[0], "--") || strings.Trim(strings.TrimSpace(lines[0]), "-") != "" {
115 return false
116 }
117 l := lines[1:]
118 for len(l) > 0 && l[len(l)-1] == "" {
119 l = l[:len(l)-1]
120 }
121 if len(l) >= 5 {
122 return false
123 }
124 for _, line := range l {
125 if line == "" {
126 return false
127 }
128 }
129 return true
130 }
131
132 result := ""
133
134 resultSnipped := func() bool {
135 return strings.HasSuffix(result, "[...]\n") || strings.HasSuffix(result, "[…]")
136 }
137
138 // Quick check for initial wrapped "On ... wrote:" line.
139 if len(lines) > 3 && strings.HasPrefix(lines[0], "On ") && !strings.HasSuffix(lines[0], "wrote:") && strings.HasSuffix(lines[1], ":") && nextLineQuoted(1) {
140 result = "[...]\n"
141 lines = lines[3:]
142 ensureLines()
143 }
144
145 for ; len(lines) > 0 && !isSignature(); ensureLines() {
146 line := lines[0]
147 if strings.HasPrefix(line, ">") {
148 if !resultSnipped() {
149 result += "[...]\n"
150 }
151 lines = lines[1:]
152 continue
153 }
154 if line == "" {
155 lines = lines[1:]
156 continue
157 }
158 // Check for a "On <date>, <person> wrote:", we require digits before a quoted
159 // line, with an optional empty line in between. If we don't have any text yet, we
160 // don't require the digits.
161 if strings.HasSuffix(line, ":") && (strings.ContainsAny(line, "0123456789") || result == "") && nextLineQuoted(0) {
162 if !resultSnipped() {
163 result += "[...]\n"
164 }
165 lines = lines[1:]
166 continue
167 }
168 // Skip possibly duplicate snipping by author.
169 if !isSnipped(line) || !resultSnipped() {
170 result += line + "\n"
171 }
172 lines = lines[1:]
173 if len(result) > 250 {
174 break
175 }
176 }
177 if len(result) > 250 {
178 result = result[:230] + "..."
179 }
180 return result, scanner.Err()
181}
182
183func parsedMessage(log mlog.Log, m store.Message, state *msgState, full, msgitem bool) (pm ParsedMessage, rerr error) {
184 if full || msgitem {
185 if !state.ensurePart(m, true) {
186 return pm, state.err
187 }
188 if full {
189 pm.Part = *state.part
190 }
191 } else {
192 if !state.ensurePart(m, false) {
193 return pm, state.err
194 }
195 }
196
197 // todo: we should store this form in message.Part, requires a data structure update.
198
199 convertAddrs := func(l []message.Address) []MessageAddress {
200 r := make([]MessageAddress, len(l))
201 for i, a := range l {
202 d, err := dns.ParseDomain(a.Host)
203 log.Check(err, "parsing domain")
204 if err != nil {
205 d = dns.Domain{ASCII: a.Host}
206 }
207 r[i] = MessageAddress{a.Name, a.User, d}
208 }
209 return r
210 }
211
212 if full || msgitem {
213 env := MessageEnvelope{}
214 if state.part.Envelope != nil {
215 e := *state.part.Envelope
216 env.Date = e.Date
217 env.Subject = e.Subject
218 env.InReplyTo = e.InReplyTo
219 env.MessageID = e.MessageID
220 env.From = convertAddrs(e.From)
221 env.Sender = convertAddrs(e.Sender)
222 env.ReplyTo = convertAddrs(e.ReplyTo)
223 env.To = convertAddrs(e.To)
224 env.CC = convertAddrs(e.CC)
225 env.BCC = convertAddrs(e.BCC)
226 }
227 pm.envelope = env
228 }
229
230 if full && state.part.BodyOffset > 0 {
231 hdrs, err := state.part.Header()
232 if err != nil {
233 return ParsedMessage{}, fmt.Errorf("parsing headers: %v", err)
234 }
235 pm.Headers = hdrs
236
237 pm.ListReplyAddress = parseListPostAddress(hdrs.Get("List-Post"))
238 } else {
239 pm.Headers = map[string][]string{}
240 }
241
242 pm.Texts = []string{}
243
244 // We track attachments from multipart/mixed differently from other attachments.
245 // The others are often inline, sometimes just some logo's in HTML alternative
246 // messages. We want to have our mixed attachments at the start of the list, but
247 // our descent-first parsing would result in inline messages first in the typical
248 // message.
249 var attachmentsMixed []Attachment
250 var attachmentsOther []Attachment
251
252 addAttachment := func(a Attachment, isMixed bool) {
253 if isMixed {
254 attachmentsMixed = append(attachmentsMixed, a)
255 } else {
256 attachmentsOther = append(attachmentsOther, a)
257 }
258 }
259
260 // todo: how should we handle messages where a user prefers html, and we want to show it, but it's a DSN that also has textual-only parts? e.g. gmail's dsn where the first part is multipart/related with multipart/alternative, and second part is the regular message/delivery-status. we want to display both the html and the text.
261
262 var usePart func(p message.Part, index int, parent *message.Part, path []int, parentMixed bool)
263 usePart = func(p message.Part, index int, parent *message.Part, path []int, parentMixed bool) {
264 mt := p.MediaType + "/" + p.MediaSubType
265 newParentMixed := mt == "MULTIPART/MIXED"
266 for i, sp := range p.Parts {
267 if mt == "MULTIPART/SIGNED" && i >= 1 {
268 continue
269 }
270 usePart(sp, i, &p, append(append([]int{}, path...), i), newParentMixed)
271 }
272 switch mt {
273 case "TEXT/PLAIN", "/":
274 // Don't include if Content-Disposition attachment.
275 if full || msgitem {
276 // todo: should have this, and perhaps all content-* headers, preparsed in message.Part?
277 h, err := p.Header()
278 log.Check(err, "parsing attachment headers", slog.Int64("msgid", m.ID))
279 cp := h.Get("Content-Disposition")
280 if cp != "" {
281 disp, params, err := mime.ParseMediaType(cp)
282 log.Check(err, "parsing content-disposition", slog.String("cp", cp))
283 if strings.EqualFold(disp, "attachment") {
284 name := tryDecodeParam(log, p.ContentTypeParams["name"])
285 if name == "" {
286 name = tryDecodeParam(log, params["filename"])
287 }
288 addAttachment(Attachment{path, name, p}, parentMixed)
289 return
290 }
291 }
292 }
293
294 if full {
295 buf, err := io.ReadAll(&moxio.LimitReader{R: p.ReaderUTF8OrBinary(), Limit: 2 * 1024 * 1024})
296 if err != nil {
297 rerr = fmt.Errorf("reading text part: %v", err)
298 return
299 }
300 pm.Texts = append(pm.Texts, string(buf))
301 }
302 if msgitem && pm.firstLine == "" {
303 pm.firstLine, rerr = formatFirstLine(p.ReaderUTF8OrBinary())
304 if rerr != nil {
305 rerr = fmt.Errorf("reading text for first line snippet: %v", rerr)
306 return
307 }
308 }
309
310 case "TEXT/HTML":
311 pm.HasHTML = true
312
313 default:
314 // todo: see if there is a common nesting messages that are both signed and encrypted.
315 if parent == nil && mt == "MULTIPART/SIGNED" {
316 pm.isSigned = true
317 }
318 if parent == nil && mt == "MULTIPART/ENCRYPTED" {
319 pm.isEncrypted = true
320 }
321 // todo: possibly do not include anything below multipart/alternative that starts with text/html, they may be cids. perhaps have a separate list of attachments for the text vs html version?
322 if p.MediaType != "MULTIPART" {
323 var parentct string
324 if parent != nil {
325 parentct = parent.MediaType + "/" + parent.MediaSubType
326 }
327
328 // Recognize DSNs.
329 if parentct == "MULTIPART/REPORT" && index == 1 && (mt == "MESSAGE/GLOBAL-DELIVERY-STATUS" || mt == "MESSAGE/DELIVERY-STATUS") {
330 if full {
331 buf, err := io.ReadAll(&moxio.LimitReader{R: p.ReaderUTF8OrBinary(), Limit: 1024 * 1024})
332 if err != nil {
333 rerr = fmt.Errorf("reading text part: %v", err)
334 return
335 }
336 pm.Texts = append(pm.Texts, string(buf))
337 }
338 return
339 }
340 if parentct == "MULTIPART/REPORT" && index == 2 && (mt == "MESSAGE/GLOBAL-HEADERS" || mt == "TEXT/RFC822-HEADERS") {
341 if full {
342 buf, err := io.ReadAll(&moxio.LimitReader{R: p.ReaderUTF8OrBinary(), Limit: 1024 * 1024})
343 if err != nil {
344 rerr = fmt.Errorf("reading text part: %v", err)
345 return
346 }
347 pm.Texts = append(pm.Texts, string(buf))
348 }
349 return
350 }
351 if parentct == "MULTIPART/REPORT" && index == 2 && (mt == "MESSAGE/GLOBAL" || mt == "TEXT/RFC822") {
352 addAttachment(Attachment{path, "original.eml", p}, parentMixed)
353 return
354 }
355
356 name := tryDecodeParam(log, p.ContentTypeParams["name"])
357 if name == "" && (full || msgitem) {
358 // todo: should have this, and perhaps all content-* headers, preparsed in message.Part?
359 h, err := p.Header()
360 log.Check(err, "parsing attachment headers", slog.Int64("msgid", m.ID))
361 cp := h.Get("Content-Disposition")
362 if cp != "" {
363 _, params, err := mime.ParseMediaType(cp)
364 log.Check(err, "parsing content-disposition", slog.String("cp", cp))
365 name = tryDecodeParam(log, params["filename"])
366 }
367 }
368 addAttachment(Attachment{path, name, p}, parentMixed)
369 }
370 }
371 }
372 usePart(*state.part, -1, nil, []int{}, false)
373
374 pm.attachments = []Attachment{}
375 pm.attachments = append(pm.attachments, attachmentsMixed...)
376 pm.attachments = append(pm.attachments, attachmentsOther...)
377
378 if rerr == nil {
379 pm.ID = m.ID
380 }
381 return
382}
383
384// parses List-Post header, returning an address if it could be found, and nil otherwise.
385func parseListPostAddress(s string) *MessageAddress {
386 /*
387 Examples:
388 List-Post: <mailto:list@host.com>
389 List-Post: <mailto:moderator@host.com> (Postings are Moderated)
390 List-Post: <mailto:moderator@host.com?subject=list%20posting>
391 List-Post: NO (posting not allowed on this list)
392 List-Post: <https://groups.google.com/group/golang-dev/post>, <mailto:golang-dev@googlegroups.com>
393 */
394 s = strings.TrimSpace(s)
395 for s != "" {
396 if !strings.HasPrefix(s, "<") {
397 return nil
398 }
399 addr, ns, found := strings.Cut(s[1:], ">")
400 if !found {
401 return nil
402 }
403 if strings.HasPrefix(addr, "mailto:") {
404 u, err := url.Parse(addr)
405 if err != nil {
406 return nil
407 }
408 addr, err := smtp.ParseAddress(u.Opaque)
409 if err != nil {
410 return nil
411 }
412 return &MessageAddress{User: addr.Localpart.String(), Domain: addr.Domain}
413 }
414 s = strings.TrimSpace(ns)
415 s = strings.TrimPrefix(s, ",")
416 s = strings.TrimSpace(s)
417 }
418 return nil
419}
420