16 "golang.org/x/exp/maps"
18 "github.com/mjl-/mox/mlog"
21// MsgSource is implemented by readers for mailbox file formats.
22type MsgSource interface {
23 // Return next message, or io.EOF when there are no more.
24 Next() (*Message, *os.File, string, error)
27// MboxReader reads messages from an mbox file, implementing MsgSource.
28type MboxReader struct {
30 createTemp func(log mlog.Log, pattern string) (*os.File, error)
37 fromLine string // "From "-line for this message.
38 header bool // Now in header section.
41func NewMboxReader(log mlog.Log, createTemp func(log mlog.Log, pattern string) (*os.File, error), filename string, r io.Reader) *MboxReader {
44 createTemp: createTemp,
47 r: bufio.NewReader(r),
51// Position returns "<filename>:<lineno>" for the current position.
52func (mr *MboxReader) Position() string {
53 return fmt.Sprintf("%s:%d", mr.path, mr.line)
56// Next returns the next message read from the mbox file. The file is a temporary
57// file and must be removed/consumed. The third return value is the position in the
59func (mr *MboxReader) Next() (*Message, *os.File, string, error) {
61 return nil, nil, "", io.EOF
64 from := []byte("From ")
68 // First read, we're at the beginning of the file.
69 line, err := mr.r.ReadBytes('\n')
71 return nil, nil, "", io.EOF
75 if !bytes.HasPrefix(line, from) {
76 return nil, nil, mr.Position(), fmt.Errorf(`first line does not start with "From "`)
79 mr.fromLine = strings.TrimSpace(string(line))
82 f, err := mr.createTemp(mr.log, "mboxreader")
84 return nil, nil, mr.Position(), err
88 CloseRemoveTempFile(mr.log, f, "message after mbox read error")
92 fromLine := mr.fromLine
93 bf := bufio.NewWriter(f)
95 keywords := map[string]bool{}
98 line, err := mr.r.ReadBytes('\n')
99 if err != nil && err != io.EOF {
100 return nil, nil, mr.Position(), fmt.Errorf("reading from mbox: %v", err)
104 // We store data with crlf, adjust any imported messages with bare newlines.
105 if !bytes.HasSuffix(line, []byte("\r\n")) {
106 line = append(line[:len(line)-1], "\r\n"...)
110 // See https://doc.dovecot.org/admin_manual/mailbox_formats/mbox/
111 if bytes.HasPrefix(line, []byte("Status:")) {
112 s := strings.TrimSpace(strings.SplitN(string(line), ":", 2)[1])
113 for _, c := range s {
119 } else if bytes.HasPrefix(line, []byte("X-Status:")) {
120 s := strings.TrimSpace(strings.SplitN(string(line), ":", 2)[1])
121 for _, c := range s {
124 flags.Answered = true
133 } else if bytes.HasPrefix(line, []byte("X-Keywords:")) {
134 s := strings.TrimSpace(strings.SplitN(string(line), ":", 2)[1])
135 for _, t := range strings.Split(s, ",") {
136 word := strings.ToLower(strings.TrimSpace(t))
138 case "forwarded", "$forwarded":
139 flags.Forwarded = true
140 case "junk", "$junk":
142 case "notjunk", "$notjunk", "nonjunk", "$nonjunk":
144 case "phishing", "$phishing":
145 flags.Phishing = true
146 case "mdnsent", "$mdnsent":
149 if err := CheckKeyword(word); err == nil {
150 keywords[word] = true
156 if bytes.Equal(line, []byte("\r\n")) {
160 // Next mail message starts at bare From word.
161 if mr.prevempty && bytes.HasPrefix(line, from) {
162 mr.fromLine = strings.TrimSpace(string(line))
166 if bytes.HasPrefix(line, []byte(">")) && bytes.HasPrefix(bytes.TrimLeft(line, ">"), []byte("From ")) {
169 n, err := bf.Write(line)
171 return nil, nil, mr.Position(), fmt.Errorf("writing message to file: %v", err)
174 mr.prevempty = bytes.Equal(line, []byte("\r\n"))
181 if err := bf.Flush(); err != nil {
182 return nil, nil, mr.Position(), fmt.Errorf("flush: %v", err)
185 m := &Message{Flags: flags, Keywords: maps.Keys(keywords), Size: size}
187 if t := strings.SplitN(fromLine, " ", 3); len(t) == 3 {
188 layouts := []string{time.ANSIC, time.UnixDate, time.RubyDate}
189 for _, l := range layouts {
190 t, err := time.Parse(l, t[2])
198 // Prevent cleanup by defer.
202 return m, mf, mr.Position(), nil
205type MaildirReader struct {
207 createTemp func(log mlog.Log, pattern string) (*os.File, error)
209 f *os.File // File we are currently reading from. We first read newf, then curf.
210 dir string // Name of directory for f. Can be empty on first call.
211 entries []os.DirEntry
212 dovecotFlags []string // Lower-case flags/keywords.
215func NewMaildirReader(log mlog.Log, createTemp func(log mlog.Log, pattern string) (*os.File, error), newf, curf *os.File) *MaildirReader {
216 mr := &MaildirReader{
218 createTemp: createTemp,
224 // Best-effort parsing of dovecot keywords.
225 kf, err := os.Open(filepath.Join(filepath.Dir(newf.Name()), "dovecot-keywords"))
227 mr.dovecotFlags, err = ParseDovecotKeywordsFlags(kf, log)
228 log.Check(err, "parsing dovecot keywords file")
230 log.Check(err, "closing dovecot-keywords file")
236func (mr *MaildirReader) Next() (*Message, *os.File, string, error) {
241 if len(mr.entries) == 0 {
243 mr.entries, err = mr.f.ReadDir(100)
244 if err != nil && err != io.EOF {
245 return nil, nil, "", err
247 if len(mr.entries) == 0 {
249 return nil, nil, "", io.EOF
257 p := filepath.Join(mr.dir, mr.entries[0].Name())
258 mr.entries = mr.entries[1:]
259 sf, err := os.Open(p)
261 return nil, nil, p, fmt.Errorf("open message in maildir: %s", err)
265 mr.log.Check(err, "closing message file after error")
267 f, err := mr.createTemp(mr.log, "maildirreader")
269 return nil, nil, p, err
275 mr.log.Check(err, "closing temporary message file after maildir read error")
276 err = os.Remove(name)
277 mr.log.Check(err, "removing temporary message file after maildir read error", slog.String("path", name))
281 // Copy data, changing bare \n into \r\n.
282 r := bufio.NewReader(sf)
283 w := bufio.NewWriter(f)
286 line, err := r.ReadBytes('\n')
287 if err != nil && err != io.EOF {
288 return nil, nil, p, fmt.Errorf("reading message: %v", err)
291 if !bytes.HasSuffix(line, []byte("\r\n")) {
292 line = append(line[:len(line)-1], "\r\n"...)
295 if n, err := w.Write(line); err != nil {
296 return nil, nil, p, fmt.Errorf("writing message: %v", err)
305 if err := w.Flush(); err != nil {
306 return nil, nil, p, fmt.Errorf("writing message: %v", err)
309 // Take received time from filename, falling back to mtime for maildirs
310 // reconstructed some other sources of message files.
311 var received time.Time
312 t := strings.SplitN(filepath.Base(sf.Name()), ".", 3)
313 if v, err := strconv.ParseInt(t[0], 10, 64); len(t) == 3 && err == nil {
314 received = time.Unix(v, 0)
315 } else if fi, err := sf.Stat(); err == nil {
316 received = fi.ModTime()
319 // Parse flags. See https://cr.yp.to/proto/maildir.html.
321 keywords := map[string]bool{}
322 t = strings.SplitN(filepath.Base(sf.Name()), ":2,", 2)
324 for _, c := range t[1] {
327 // Passed, doesn't map to a common IMAP flag.
329 flags.Answered = true
339 if c >= 'a' && c <= 'z' {
340 index := int(c - 'a')
341 if index >= len(mr.dovecotFlags) {
344 kw := mr.dovecotFlags[index]
346 case "$forwarded", "forwarded":
347 flags.Forwarded = true
348 case "$junk", "junk":
350 case "$notjunk", "notjunk", "nonjunk":
352 case "$mdnsent", "mdnsent":
354 case "$phishing", "phishing":
355 flags.Phishing = true
364 m := &Message{Received: received, Flags: flags, Keywords: maps.Keys(keywords), Size: size}
366 // Prevent cleanup by defer.
373// ParseDovecotKeywordsFlags attempts to parse a dovecot-keywords file. It only
374// returns valid flags/keywords, as lower-case. If an error is encountered and
375// returned, any keywords that were found are still returned. The returned list has
376// both system/well-known flags and custom keywords.
377func ParseDovecotKeywordsFlags(r io.Reader, log mlog.Log) ([]string, error) {
379 If the dovecot-keywords file is present, we parse its additional flags, see
380 https://doc.dovecot.org/admin_manual/mailbox_formats/maildir/
388 keywords := make([]string, 26)
390 scanner := bufio.NewScanner(r)
394 t := strings.SplitN(s, " ", 2)
396 errs = append(errs, fmt.Sprintf("unexpected dovecot keyword line: %q", s))
399 v, err := strconv.ParseInt(t[0], 10, 32)
401 errs = append(errs, fmt.Sprintf("unexpected dovecot keyword index: %q", s))
404 if v < 0 || v >= int64(len(keywords)) {
405 errs = append(errs, fmt.Sprintf("dovecot keyword index too big: %q", s))
409 if keywords[index] != "" {
410 errs = append(errs, fmt.Sprintf("duplicate dovecot keyword: %q", s))
413 kw := strings.ToLower(t[1])
414 if !systemWellKnownFlags[kw] {
415 if err := CheckKeyword(kw); err != nil {
416 errs = append(errs, fmt.Sprintf("invalid keyword %q", kw))
425 if err := scanner.Err(); err != nil {
426 errs = append(errs, fmt.Sprintf("reading dovecot keywords file: %v", err))
430 err = errors.New(strings.Join(errs, "; "))
432 return keywords[:end], err