18 "github.com/mjl-/bstore"
20 "github.com/mjl-/mox/mlog"
23// Archiver can archive multiple mailboxes and their messages.
24type Archiver interface {
25 // Add file to archive. If name ends with a slash, it is created as a directory and
26 // the returned io.WriteCloser can be ignored.
27 Create(name string, size int64, mtime time.Time) (io.WriteCloser, error)
31// TarArchiver is an Archiver that writes to a tar file.
32type TarArchiver struct {
36// Create adds a file header to the tar file.
37func (a TarArchiver) Create(name string, size int64, mtime time.Time) (io.WriteCloser, error) {
43 Format: tar.FormatPAX,
45 if err := a.WriteHeader(&hdr); err != nil {
48 return nopCloser{a}, nil
51// ZipArchiver is an Archiver that writes to a zip file.
52type ZipArchiver struct {
56// Create adds a file header to the zip file.
57func (a ZipArchiver) Create(name string, size int64, mtime time.Time) (io.WriteCloser, error) {
58 hdr := zip.FileHeader{
62 UncompressedSize64: uint64(size),
64 w, err := a.CreateHeader(&hdr)
68 return nopCloser{w}, nil
71type nopCloser struct {
76func (nopCloser) Close() error {
80// DirArchiver is an Archiver that writes to a directory.
81type DirArchiver struct {
85// Create creates name in the file system, in dir.
86// name must always use forwarded slashes.
87func (a DirArchiver) Create(name string, size int64, mtime time.Time) (io.WriteCloser, error) {
88 isdir := strings.HasSuffix(name, "/")
89 name = strings.TrimSuffix(name, "/")
90 p := filepath.Join(a.Dir, filepath.FromSlash(name))
91 os.MkdirAll(filepath.Dir(p), 0770)
93 return nil, os.Mkdir(p, 0770)
95 return os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
98// Close on a dir does nothing.
99func (a DirArchiver) Close() error {
103// MboxArchive fakes being an archiver to which a single mbox file can be written.
104// It returns an error when a second file is added. It returns its writer for the
105// first file to be written, leaving parameters unused.
106type MboxArchiver struct {
111// Create returns the underlying writer for the first call, and an error on later calls.
112func (a *MboxArchiver) Create(name string, size int64, mtime time.Time) (io.WriteCloser, error) {
114 return nil, fmt.Errorf("cannot export multiple files with mbox")
117 return nopCloser{a.Writer}, nil
120// Close on an mbox archiver does nothing.
121func (a *MboxArchiver) Close() error {
125// ExportMessages writes messages to archiver. Either in maildir format, or otherwise in
126// mbox. If mailboxOpt is empty, all mailboxes are exported, otherwise only the
129// Some errors are not fatal and result in skipped messages. In that happens, a
130// file "errors.txt" is added to the archive describing the errors. The goal is to
131// let users export (hopefully) most messages even in the face of errors.
132func ExportMessages(ctx context.Context, log mlog.Log, db *bstore.DB, accountDir string, archiver Archiver, maildir bool, mailboxOpt string, recursive bool) error {
133 // todo optimize: should prepare next file to add to archive (can be an mbox with many messages) while writing a file to the archive (which typically compresses, which takes time).
135 // Start transaction without closure, we are going to close it early, but don't
136 // want to deal with declaring many variables now to be able to assign them in a
137 // closure and use them afterwards.
138 tx, err := db.Begin(ctx, false)
140 return fmt.Errorf("transaction: %v", err)
144 log.Check(err, "transaction rollback")
149 // We keep track of errors reading message files. We continue exporting and add an
150 // errors.txt file to the archive. In case of errors, the user can get (hopefully)
151 // most of their emails, and see something went wrong. For other errors, like
152 // writing to the archiver (e.g. a browser), we abort, because we don't want to
153 // continue with useless work.
156 // Process mailboxes sorted by name, so submaildirs come after their parent.
157 prefix := mailboxOpt + "/"
158 var trimPrefix string
159 if mailboxOpt != "" {
160 // If exporting a specific mailbox, trim its parent path from stored file names.
161 trimPrefix = path.Dir(mailboxOpt) + "/"
163 q := bstore.QueryTx[Mailbox](tx)
164 q.FilterFn(func(mb Mailbox) bool {
165 return mailboxOpt == "" || mb.Name == mailboxOpt || recursive && strings.HasPrefix(mb.Name, prefix)
168 err = q.ForEach(func(mb Mailbox) error {
169 mailboxName := mb.Name
170 if trimPrefix != "" {
171 mailboxName = strings.TrimPrefix(mailboxName, trimPrefix)
173 errmsgs, err := exportMailbox(log, tx, accountDir, mb.ID, mailboxName, archiver, maildir, start)
181 return fmt.Errorf("query mailboxes: %w", err)
185 w, err := archiver.Create("errors.txt", int64(len(errors)), time.Now())
187 log.Errorx("adding errors.txt to archive", err)
190 if _, err := w.Write([]byte(errors)); err != nil {
191 log.Errorx("writing errors.txt to archive", err)
193 log.Check(xerr, "closing errors.txt after error")
196 if err := w.Close(); err != nil {
203func exportMailbox(log mlog.Log, tx *bstore.Tx, accountDir string, mailboxID int64, mailboxName string, archiver Archiver, maildir bool, start time.Time) (string, error) {
207 var mboxwriter *bufio.Writer
210 CloseRemoveTempFile(log, mboxtmp, "mbox")
214 // For dovecot-keyword-style flags not in standard maildir.
215 maildirFlags := map[string]int{}
216 var maildirFlaglist []string
217 maildirFlag := func(flag string) string {
218 i, ok := maildirFlags[flag]
220 if len(maildirFlags) >= 26 {
221 // Max 26 flag characters.
224 i = len(maildirFlags)
225 maildirFlags[flag] = i
226 maildirFlaglist = append(maildirFlaglist, flag)
228 return string(rune('a' + i))
231 finishMailbox := func() error {
233 if len(maildirFlags) == 0 {
238 for i, flag := range maildirFlaglist {
239 if _, err := fmt.Fprintf(&b, "%d %s\n", i, flag); err != nil {
243 w, err := archiver.Create(mailboxName+"/dovecot-keywords", int64(b.Len()), start)
245 return fmt.Errorf("adding dovecot-keywords: %v", err)
247 if _, err := w.Write(b.Bytes()); err != nil {
249 log.Check(xerr, "closing dovecot-keywords file after closing")
250 return fmt.Errorf("writing dovecot-keywords: %v", err)
252 maildirFlags = map[string]int{}
253 maildirFlaglist = nil
257 if err := mboxwriter.Flush(); err != nil {
258 return fmt.Errorf("flush mbox writer: %v", err)
260 fi, err := mboxtmp.Stat()
262 return fmt.Errorf("stat temporary mbox file: %v", err)
264 if _, err := mboxtmp.Seek(0, 0); err != nil {
265 return fmt.Errorf("seek to start of temporary mbox file")
267 w, err := archiver.Create(mailboxName+".mbox", fi.Size(), fi.ModTime())
269 return fmt.Errorf("add mbox to archive: %v", err)
271 if _, err := io.Copy(w, mboxtmp); err != nil {
273 log.Check(xerr, "closing mbox message file after error")
274 return fmt.Errorf("copying temp mbox file to archive: %v", err)
276 if err := w.Close(); err != nil {
277 return fmt.Errorf("closing message file: %v", err)
279 name := mboxtmp.Name()
280 err = mboxtmp.Close()
281 log.Check(err, "closing temporary mbox file")
282 err = os.Remove(name)
283 log.Check(err, "removing temporary mbox file", slog.String("path", name))
289 exportMessage := func(m Message) error {
290 mp := filepath.Join(accountDir, "msg", MessagePath(m.ID))
292 if m.Size == int64(len(m.MsgPrefix)) {
293 mr = io.NopCloser(bytes.NewReader(m.MsgPrefix))
295 mf, err := os.Open(mp)
297 errors += fmt.Sprintf("open message file for id %d, path %s: %v (message skipped)\n", m.ID, mp, err)
302 log.Check(err, "closing message file after export")
306 errors += fmt.Sprintf("stat message file for id %d, path %s: %v (message skipped)\n", m.ID, mp, err)
309 size := st.Size() + int64(len(m.MsgPrefix))
311 errors += fmt.Sprintf("message size mismatch for message id %d, database has %d, size is %d+%d=%d, using calculated size\n", m.ID, m.Size, len(m.MsgPrefix), st.Size(), size)
313 mr = FileMsgReader(m.MsgPrefix, mf)
319 p = filepath.Join(p, "cur")
321 p = filepath.Join(p, "new")
323 name := fmt.Sprintf("%d.%d.mox:2,", m.Received.Unix(), m.ID)
325 // Standard flags. May need to be sorted.
332 if m.Flags.Answered {
342 // Non-standard flag. We set them with a dovecot-keywords file.
343 if m.Flags.Forwarded {
344 name += maildirFlag("$Forwarded")
347 name += maildirFlag("$Junk")
350 name += maildirFlag("$NotJunk")
352 if m.Flags.Phishing {
353 name += maildirFlag("$Phishing")
356 name += maildirFlag("$MDNSent")
359 p = filepath.Join(p, name)
361 // We store messages with \r\n, maildir needs without. But we need to know the
362 // final size. So first convert, then create file with size, and write from buffer.
363 // todo: for large messages, we should go through a temporary file instead of memory.
365 r := bufio.NewReader(mr)
367 line, rerr := r.ReadBytes('\n')
368 if rerr != io.EOF && rerr != nil {
369 errors += fmt.Sprintf("reading from message for id %d: %v (message skipped)\n", m.ID, rerr)
373 if bytes.HasSuffix(line, []byte("\r\n")) {
374 line = line[:len(line)-1]
375 line[len(line)-1] = '\n'
377 if _, err := dst.Write(line); err != nil {
378 return fmt.Errorf("writing message: %v", err)
385 size := int64(dst.Len())
386 w, err := archiver.Create(p, size, m.Received)
388 return fmt.Errorf("adding message to archive: %v", err)
390 if _, err := io.Copy(w, &dst); err != nil {
392 log.Check(xerr, "closing message")
393 return fmt.Errorf("copying message to archive: %v", err)
399 if m.MailFrom != "" {
400 mailfrom = m.MailFrom
402 if _, err := fmt.Fprintf(mboxwriter, "From %s %s\n", mailfrom, m.Received.Format(time.ANSIC)); err != nil {
403 return fmt.Errorf("write message line to mbox temp file: %v", err)
406 // Write message flags in the three headers that mbox consumers may (or may not) understand.
408 if _, err := fmt.Fprintf(mboxwriter, "Status: R\n"); err != nil {
409 return fmt.Errorf("writing status header: %v", err)
426 if _, err := fmt.Fprintf(mboxwriter, "X-Status: %s\n", xstatus); err != nil {
427 return fmt.Errorf("writing x-status header: %v", err)
430 var xkeywords []string
432 xkeywords = append(xkeywords, "$Forwarded")
434 if m.Junk && !m.Notjunk {
435 xkeywords = append(xkeywords, "$Junk")
437 if m.Notjunk && !m.Junk {
438 xkeywords = append(xkeywords, "$NotJunk")
441 xkeywords = append(xkeywords, "$Phishing")
444 xkeywords = append(xkeywords, "$MDNSent")
446 if len(xkeywords) > 0 {
447 if _, err := fmt.Fprintf(mboxwriter, "X-Keywords: %s\n", strings.Join(xkeywords, ",")); err != nil {
448 return fmt.Errorf("writing x-keywords header: %v", err)
453 r := bufio.NewReader(mr)
455 line, rerr := r.ReadBytes('\n')
456 if rerr != io.EOF && rerr != nil {
457 return fmt.Errorf("reading message: %v", rerr)
460 if bytes.HasSuffix(line, []byte("\r\n")) {
461 line = line[:len(line)-1]
462 line[len(line)-1] = '\n'
464 if header && len(line) == 1 {
468 // Skip any previously stored flag-holding or now incorrect content-length headers.
469 // This assumes these headers are just a single line.
470 switch strings.ToLower(string(bytes.SplitN(line, []byte(":"), 2)[0])) {
471 case "status", "x-status", "x-keywords", "content-length":
475 if bytes.HasPrefix(bytes.TrimLeft(line, ">"), []byte("From ")) {
476 if _, err := fmt.Fprint(mboxwriter, ">"); err != nil {
477 return fmt.Errorf("writing escaping >: %v", err)
480 if _, err := mboxwriter.Write(line); err != nil {
481 return fmt.Errorf("writing line: %v", err)
488 if _, err := fmt.Fprint(mboxwriter, "\n"); err != nil {
489 return fmt.Errorf("writing end of message newline: %v", err)
495 // Create the directories that show this is a maildir.
496 if _, err := archiver.Create(mailboxName+"/new/", 0, start); err != nil {
497 return errors, fmt.Errorf("adding maildir new directory: %v", err)
499 if _, err := archiver.Create(mailboxName+"/cur/", 0, start); err != nil {
500 return errors, fmt.Errorf("adding maildir cur directory: %v", err)
502 if _, err := archiver.Create(mailboxName+"/tmp/", 0, start); err != nil {
503 return errors, fmt.Errorf("adding maildir tmp directory: %v", err)
507 mboxtmp, err = os.CreateTemp("", "mox-mail-export-mbox")
509 return errors, fmt.Errorf("creating temp mbox file: %v", err)
511 mboxwriter = bufio.NewWriter(mboxtmp)
514 // Fetch all messages for mailbox.
515 q := bstore.QueryTx[Message](tx)
516 q.FilterNonzero(Message{MailboxID: mailboxID})
517 q.FilterEqual("Expunged", false)
518 q.SortAsc("Received", "ID")
519 err := q.ForEach(func(m Message) error {
520 return exportMessage(m)
525 if err := finishMailbox(); err != nil {