14 "golang.org/x/text/encoding/ianaindex"
16 "github.com/mjl-/mox/dns"
17 "github.com/mjl-/mox/message"
18 "github.com/mjl-/mox/mlog"
19 "github.com/mjl-/mox/mox-"
20 "github.com/mjl-/mox/moxio"
21 "github.com/mjl-/mox/smtp"
22 "github.com/mjl-/mox/store"
25// 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.
27var wordDecoder = mime.WordDecoder{
28 CharsetReader: func(charset string, r io.Reader) (io.Reader, error) {
29 switch strings.ToLower(charset) {
30 case "", "us-ascii", "utf-8":
33 enc, _ := ianaindex.MIME.Encoding(charset)
35 enc, _ = ianaindex.IANA.Encoding(charset)
38 return r, fmt.Errorf("unknown charset %q", charset)
40 return enc.NewDecoder().Reader(r), nil
44// Attempt q/b-word-decode name, coming from Content-Type "name" field or
45// Content-Disposition "filename" field.
47// RFC 2231 specify an encoding for non-ascii values in mime header parameters. But
48// it appears common practice to instead just q/b-word encode the values.
49// Thunderbird and gmail.com do this for the Content-Type "name" parameter.
50// gmail.com also does that for the Content-Disposition "filename" parameter, where
51// Thunderbird uses the RFC 2231-defined encoding. Go's mime.ParseMediaType parses
52// the mechanism specified in RFC 2231 only. The value for "name" we get here would
53// already be decoded properly for standards-compliant headers, like
54// "filename*0*=UTF-8”%...; filename*1*=%.... We'll look for Q/B-word encoding
55// markers ("=?"-prefix or "?="-suffix) and try to decode if present. This would
56// only cause trouble for filenames having this prefix/suffix.
57func tryDecodeParam(log mlog.Log, name string) string {
58 if name == "" || !strings.HasPrefix(name, "=?") && !strings.HasSuffix(name, "?=") {
61 // todo: find where this is allowed. it seems quite common. perhaps we should remove the pedantic check?
63 log.Debug("attachment contains rfc2047 q/b-word-encoded mime parameter instead of rfc2231-encoded", slog.String("name", name))
66 s, err := wordDecoder.DecodeHeader(name)
68 log.Debugx("q/b-word decoding mime parameter", err, slog.String("name", name))
74// todo: mime.FormatMediaType does not wrap long lines. should do it ourselves, and split header into several parts (if commonly supported).
76func messageItemMoreHeaders(moreHeaders []string, pm ParsedMessage) (l [][2]string) {
77 for _, k := range moreHeaders {
78 k = textproto.CanonicalMIMEHeaderKey(k)
79 for _, v := range pm.Headers[k] {
80 l = append(l, [2]string{k, v})
86func messageItem(log mlog.Log, m store.Message, state *msgState, moreHeaders []string) (MessageItem, error) {
87 headers := len(moreHeaders) > 0
88 pm, err := parsedMessage(log, m, state, false, true, headers)
89 if err != nil && errors.Is(err, message.ErrHeader) && headers {
90 log.Debugx("load message item without parsing headers after error", err, slog.Int64("msgid", m.ID))
91 pm, err = parsedMessage(log, m, state, false, true, false)
94 return MessageItem{}, fmt.Errorf("parsing message %d for item: %v", m.ID, err)
96 // Clear largish unused data.
99 l := messageItemMoreHeaders(moreHeaders, pm)
100 return MessageItem{m, pm.envelope, pm.attachments, pm.isSigned, pm.isEncrypted, pm.firstLine, true, l}, nil
103// formatFirstLine returns a line the client can display next to the subject line
104// in a mailbox. It will replace quoted text, and any prefixing "On ... write:"
105// line with "[...]" so only new and useful information will be displayed.
106// Trailing signatures are not included.
107func formatFirstLine(r io.Reader) (string, error) {
108 // We look quite a bit of lines ahead for trailing signatures with trailing empty lines.
110 scanner := bufio.NewScanner(r)
111 ensureLines := func() {
112 for len(lines) < 10 && scanner.Scan() {
113 lines = append(lines, strings.TrimSpace(scanner.Text()))
118 isSnipped := func(s string) bool {
119 return s == "[...]" || s == "[…]" || s == "..."
122 nextLineQuoted := func(i int) bool {
123 if i+1 < len(lines) && lines[i+1] == "" {
126 return i+1 < len(lines) && (strings.HasPrefix(lines[i+1], ">") || isSnipped(lines[i+1]))
129 // Remainder is signature if we see a line with only and minimum 2 dashes, and
130 // there are no more empty lines, and there aren't more than 5 lines left.
131 isSignature := func() bool {
132 if len(lines) == 0 || !strings.HasPrefix(lines[0], "--") || strings.Trim(strings.TrimSpace(lines[0]), "-") != "" {
136 for len(l) > 0 && l[len(l)-1] == "" {
142 for _, line := range l {
152 resultSnipped := func() bool {
153 return strings.HasSuffix(result, "[...]\n") || strings.HasSuffix(result, "[…]")
156 // Quick check for initial wrapped "On ... wrote:" line.
157 if len(lines) > 3 && strings.HasPrefix(lines[0], "On ") && !strings.HasSuffix(lines[0], "wrote:") && strings.HasSuffix(lines[1], ":") && nextLineQuoted(1) {
163 for ; len(lines) > 0 && !isSignature(); ensureLines() {
165 if strings.HasPrefix(line, ">") {
166 if !resultSnipped() {
176 // Check for a "On <date>, <person> wrote:", we require digits before a quoted
177 // line, with an optional empty line in between. If we don't have any text yet, we
178 // don't require the digits.
179 if strings.HasSuffix(line, ":") && (strings.ContainsAny(line, "0123456789") || result == "") && nextLineQuoted(0) {
180 if !resultSnipped() {
186 // Skip possibly duplicate snipping by author.
187 if !isSnipped(line) || !resultSnipped() {
188 result += line + "\n"
191 if len(result) > 250 {
195 if len(result) > 250 {
196 result = result[:230] + "..."
198 return result, scanner.Err()
201func parsedMessage(log mlog.Log, m store.Message, state *msgState, full, msgitem, msgitemHeaders bool) (pm ParsedMessage, rerr error) {
202 pm.ViewMode = store.ModeText // Valid default, in case this makes it to frontend.
205 if !state.ensurePart(m, true) {
209 pm.Part = *state.part
212 if !state.ensurePart(m, false) {
217 // todo: we should store this form in message.Part, requires a data structure update.
219 convertAddrs := func(l []message.Address) []MessageAddress {
220 r := make([]MessageAddress, len(l))
221 for i, a := range l {
222 d, err := dns.ParseDomain(a.Host)
223 log.Check(err, "parsing domain")
225 d = dns.Domain{ASCII: a.Host}
227 r[i] = MessageAddress{a.Name, a.User, d}
233 env := MessageEnvelope{}
234 if state.part.Envelope != nil {
235 e := *state.part.Envelope
237 env.Subject = e.Subject
238 env.InReplyTo = e.InReplyTo
239 env.MessageID = e.MessageID
240 env.From = convertAddrs(e.From)
241 env.Sender = convertAddrs(e.Sender)
242 env.ReplyTo = convertAddrs(e.ReplyTo)
243 env.To = convertAddrs(e.To)
244 env.CC = convertAddrs(e.CC)
245 env.BCC = convertAddrs(e.BCC)
250 if (full || msgitemHeaders) && state.part.BodyOffset > 0 {
251 hdrs, err := state.part.Header()
253 return ParsedMessage{}, fmt.Errorf("parsing headers: %w", err)
257 pm.ListReplyAddress = parseListPostAddress(hdrs.Get("List-Post"))
259 pm.Headers = map[string][]string{}
262 pm.Texts = []string{}
264 // We track attachments from multipart/mixed differently from other attachments.
265 // The others are often inline, sometimes just some logo's in HTML alternative
266 // messages. We want to have our mixed attachments at the start of the list, but
267 // our descent-first parsing would result in inline messages first in the typical
269 var attachmentsMixed []Attachment
270 var attachmentsOther []Attachment
272 addAttachment := func(a Attachment, isMixed bool) {
274 attachmentsMixed = append(attachmentsMixed, a)
276 attachmentsOther = append(attachmentsOther, a)
280 // 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.
282 var usePart func(p message.Part, index int, parent *message.Part, path []int, parentMixed bool)
283 usePart = func(p message.Part, index int, parent *message.Part, path []int, parentMixed bool) {
284 mt := p.MediaType + "/" + p.MediaSubType
285 newParentMixed := mt == "MULTIPART/MIXED"
286 for i, sp := range p.Parts {
287 if mt == "MULTIPART/SIGNED" && i >= 1 {
290 usePart(sp, i, &p, append(append([]int{}, path...), i), newParentMixed)
293 case "TEXT/PLAIN", "/":
294 // Don't include if Content-Disposition attachment.
296 disp, name, err := p.DispositionFilename()
297 if err != nil && errors.Is(err, message.ErrParamEncoding) {
298 log.Debugx("parsing disposition/filename", err)
299 } else if err != nil {
300 rerr = fmt.Errorf("reading disposition/filename: %v", err)
303 if strings.EqualFold(disp, "attachment") {
304 addAttachment(Attachment{path, name, p}, parentMixed)
310 buf, err := io.ReadAll(&moxio.LimitReader{R: p.ReaderUTF8OrBinary(), Limit: 2 * 1024 * 1024})
312 rerr = fmt.Errorf("reading text part: %v", err)
315 pm.Texts = append(pm.Texts, string(buf))
317 if msgitem && pm.firstLine == "" {
318 pm.firstLine, rerr = formatFirstLine(p.ReaderUTF8OrBinary())
320 rerr = fmt.Errorf("reading text for first line snippet: %v", rerr)
329 // todo: see if there is a common nesting messages that are both signed and encrypted.
330 if parent == nil && mt == "MULTIPART/SIGNED" {
333 if parent == nil && mt == "MULTIPART/ENCRYPTED" {
334 pm.isEncrypted = true
336 // 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?
337 if p.MediaType != "MULTIPART" {
340 parentct = parent.MediaType + "/" + parent.MediaSubType
344 if parentct == "MULTIPART/REPORT" && index == 1 && (mt == "MESSAGE/GLOBAL-DELIVERY-STATUS" || mt == "MESSAGE/DELIVERY-STATUS") {
346 buf, err := io.ReadAll(&moxio.LimitReader{R: p.ReaderUTF8OrBinary(), Limit: 1024 * 1024})
348 rerr = fmt.Errorf("reading text part: %v", err)
351 pm.Texts = append(pm.Texts, string(buf))
355 if parentct == "MULTIPART/REPORT" && index == 2 && (mt == "MESSAGE/GLOBAL-HEADERS" || mt == "TEXT/RFC822-HEADERS") {
357 buf, err := io.ReadAll(&moxio.LimitReader{R: p.ReaderUTF8OrBinary(), Limit: 1024 * 1024})
359 rerr = fmt.Errorf("reading text part: %v", err)
362 pm.Texts = append(pm.Texts, string(buf))
366 if parentct == "MULTIPART/REPORT" && index == 2 && (mt == "MESSAGE/GLOBAL" || mt == "TEXT/RFC822") {
367 addAttachment(Attachment{path, "original.eml", p}, parentMixed)
371 name := tryDecodeParam(log, p.ContentTypeParams["name"])
372 if name == "" && (full || msgitem) {
373 // todo: should have this, and perhaps all content-* headers, preparsed in message.Part?
375 log.Check(err, "parsing attachment headers", slog.Int64("msgid", m.ID))
376 cp := h.Get("Content-Disposition")
378 _, params, err := mime.ParseMediaType(cp)
379 log.Check(err, "parsing content-disposition", slog.String("cp", cp))
380 name = tryDecodeParam(log, params["filename"])
383 addAttachment(Attachment{path, name, p}, parentMixed)
387 usePart(*state.part, -1, nil, []int{}, false)
389 pm.attachments = []Attachment{}
390 pm.attachments = append(pm.attachments, attachmentsMixed...)
391 pm.attachments = append(pm.attachments, attachmentsOther...)
399// parses List-Post header, returning an address if it could be found, and nil otherwise.
400func parseListPostAddress(s string) *MessageAddress {
403 List-Post: <mailto:list@host.com>
404 List-Post: <mailto:moderator@host.com> (Postings are Moderated)
405 List-Post: <mailto:moderator@host.com?subject=list%20posting>
406 List-Post: NO (posting not allowed on this list)
407 List-Post: <https://groups.google.com/group/golang-dev/post>, <mailto:golang-dev@googlegroups.com>
409 s = strings.TrimSpace(s)
411 if !strings.HasPrefix(s, "<") {
414 addr, ns, found := strings.Cut(s[1:], ">")
418 if strings.HasPrefix(addr, "mailto:") {
419 u, err := url.Parse(addr)
423 addr, err := smtp.ParseAddress(u.Opaque)
427 return &MessageAddress{User: addr.Localpart.String(), Domain: addr.Domain}
429 s = strings.TrimSpace(ns)
430 s = strings.TrimPrefix(s, ",")
431 s = strings.TrimSpace(s)