13 "golang.org/x/text/encoding/ianaindex"
15 "github.com/mjl-/mox/dns"
16 "github.com/mjl-/mox/message"
17 "github.com/mjl-/mox/mlog"
18 "github.com/mjl-/mox/mox-"
19 "github.com/mjl-/mox/moxio"
20 "github.com/mjl-/mox/smtp"
21 "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, true, l}, nil
103func parsedMessage(log mlog.Log, m *store.Message, state *msgState, full, msgitem, msgitemHeaders bool) (pm ParsedMessage, rerr error) {
104 pm.ViewMode = store.ModeText // Valid default, in case this makes it to frontend.
106 if full || msgitem || state.newPreviews != nil && m.Preview == nil {
107 if !state.ensurePart(*m, true) {
111 pm.Part = *state.part
114 if !state.ensurePart(*m, false) {
118 if state.newPreviews != nil && m.Preview == nil {
119 s, err := state.part.Preview(log)
121 log.Infox("generating preview", err, slog.Int64("msgid", m.ID))
123 // Set preview on m now, and let it be saved later on.
125 state.newPreviews[m.ID] = s
128 // todo: we should store this form in message.Part, requires a data structure update.
130 convertAddrs := func(l []message.Address) []MessageAddress {
131 r := make([]MessageAddress, len(l))
132 for i, a := range l {
133 d, err := dns.ParseDomain(a.Host)
134 log.Check(err, "parsing domain")
136 d = dns.Domain{ASCII: a.Host}
138 r[i] = MessageAddress{a.Name, a.User, d}
144 env := MessageEnvelope{}
145 if state.part.Envelope != nil {
146 e := *state.part.Envelope
148 env.Subject = e.Subject
149 env.InReplyTo = e.InReplyTo
150 env.MessageID = e.MessageID
151 env.From = convertAddrs(e.From)
152 env.Sender = convertAddrs(e.Sender)
153 env.ReplyTo = convertAddrs(e.ReplyTo)
154 env.To = convertAddrs(e.To)
155 env.CC = convertAddrs(e.CC)
156 env.BCC = convertAddrs(e.BCC)
161 if (full || msgitemHeaders) && state.part.BodyOffset > 0 {
162 hdrs, err := state.part.Header()
164 return ParsedMessage{}, fmt.Errorf("parsing headers: %w", err)
168 pm.ListReplyAddress = parseListPostAddress(hdrs.Get("List-Post"))
170 pm.Headers = map[string][]string{}
173 pm.Texts = []string{}
175 // We track attachments from multipart/mixed differently from other attachments.
176 // The others are often inline, sometimes just some logo's in HTML alternative
177 // messages. We want to have our mixed attachments at the start of the list, but
178 // our descent-first parsing would result in inline messages first in the typical
180 var attachmentsMixed []Attachment
181 var attachmentsOther []Attachment
183 addAttachment := func(a Attachment, isMixed bool) {
185 attachmentsMixed = append(attachmentsMixed, a)
187 attachmentsOther = append(attachmentsOther, a)
191 // 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.
193 var usePart func(p message.Part, index int, parent *message.Part, path []int, parentMixed bool)
194 usePart = func(p message.Part, index int, parent *message.Part, path []int, parentMixed bool) {
195 mt := p.MediaType + "/" + p.MediaSubType
196 newParentMixed := mt == "MULTIPART/MIXED"
197 for i, sp := range p.Parts {
198 if mt == "MULTIPART/SIGNED" && i >= 1 {
201 usePart(sp, i, &p, append(slices.Clone(path), i), newParentMixed)
204 case "TEXT/PLAIN", "/":
205 // Don't include if Content-Disposition attachment.
207 disp, name, err := p.DispositionFilename()
208 if err != nil && errors.Is(err, message.ErrParamEncoding) {
209 log.Debugx("parsing disposition/filename", err)
210 } else if err != nil {
211 rerr = fmt.Errorf("reading disposition/filename: %v", err)
214 if strings.EqualFold(disp, "attachment") {
215 addAttachment(Attachment{path, name, p}, parentMixed)
221 buf, err := io.ReadAll(&moxio.LimitReader{R: p.ReaderUTF8OrBinary(), Limit: 2 * 1024 * 1024})
223 rerr = fmt.Errorf("reading text part: %v", err)
226 pm.Texts = append(pm.Texts, string(buf))
227 pm.TextPaths = append(pm.TextPaths, slices.Clone(path))
232 if full && pm.HTMLPath == nil {
233 pm.HTMLPath = slices.Clone(path)
237 // todo: see if there is a common nesting messages that are both signed and encrypted.
238 if parent == nil && mt == "MULTIPART/SIGNED" {
241 if parent == nil && mt == "MULTIPART/ENCRYPTED" {
242 pm.isEncrypted = true
244 // 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?
245 if p.MediaType != "MULTIPART" {
248 parentct = parent.MediaType + "/" + parent.MediaSubType
252 if parentct == "MULTIPART/REPORT" && index == 1 && (mt == "MESSAGE/GLOBAL-DELIVERY-STATUS" || mt == "MESSAGE/DELIVERY-STATUS") {
254 buf, err := io.ReadAll(&moxio.LimitReader{R: p.ReaderUTF8OrBinary(), Limit: 1024 * 1024})
256 rerr = fmt.Errorf("reading text part: %v", err)
259 pm.Texts = append(pm.Texts, string(buf))
260 pm.TextPaths = append(pm.TextPaths, slices.Clone(path))
264 if parentct == "MULTIPART/REPORT" && index == 2 && (mt == "MESSAGE/GLOBAL-HEADERS" || mt == "TEXT/RFC822-HEADERS") {
266 buf, err := io.ReadAll(&moxio.LimitReader{R: p.ReaderUTF8OrBinary(), Limit: 1024 * 1024})
268 rerr = fmt.Errorf("reading text part: %v", err)
271 pm.Texts = append(pm.Texts, string(buf))
272 pm.TextPaths = append(pm.TextPaths, slices.Clone(path))
276 if parentct == "MULTIPART/REPORT" && index == 2 && (mt == "MESSAGE/GLOBAL" || mt == "TEXT/RFC822") {
277 addAttachment(Attachment{path, "original.eml", p}, parentMixed)
281 name := tryDecodeParam(log, p.ContentTypeParams["name"])
282 if name == "" && (full || msgitem) {
283 // todo: should have this, and perhaps all content-* headers, preparsed in message.Part?
285 log.Check(err, "parsing attachment headers", slog.Int64("msgid", m.ID))
286 cp := h.Get("Content-Disposition")
288 _, params, err := mime.ParseMediaType(cp)
289 log.Check(err, "parsing content-disposition", slog.String("cp", cp))
290 name = tryDecodeParam(log, params["filename"])
293 addAttachment(Attachment{path, name, p}, parentMixed)
297 usePart(*state.part, -1, nil, []int{}, false)
299 pm.attachments = []Attachment{}
300 pm.attachments = append(pm.attachments, attachmentsMixed...)
301 pm.attachments = append(pm.attachments, attachmentsOther...)
309// parses List-Post header, returning an address if it could be found, and nil otherwise.
310func parseListPostAddress(s string) *MessageAddress {
313 List-Post: <mailto:list@host.com>
314 List-Post: <mailto:moderator@host.com> (Postings are Moderated)
315 List-Post: <mailto:moderator@host.com?subject=list%20posting>
316 List-Post: NO (posting not allowed on this list)
317 List-Post: <https://groups.google.com/group/golang-dev/post>, <mailto:golang-dev@googlegroups.com>
319 s = strings.TrimSpace(s)
321 if !strings.HasPrefix(s, "<") {
324 addr, ns, found := strings.Cut(s[1:], ">")
328 if strings.HasPrefix(addr, "mailto:") {
329 u, err := url.Parse(addr)
333 addr, err := smtp.ParseAddress(u.Opaque)
337 return &MessageAddress{User: addr.Localpart.String(), Domain: addr.Domain}
339 s = strings.TrimSpace(ns)
340 s = strings.TrimPrefix(s, ",")
341 s = strings.TrimSpace(s)