2 * Copyright notice from original mutt:
3 * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
5 * This file is part of mutt-ng, see http://www.muttng.org/.
6 * It's licensed under the GNU General Public License,
7 * please see the file GPL in the top level source directory.
10 /* This file contains code to parse ``mbox'' style mailboxes */
12 #include <lib-lib/lib-lib.h>
14 #include <lib-ui/lib-ui.h>
15 #include <lib-sys/mutt_signal.h>
26 /* struct used by mutt_sync_mailbox() to store new offsets */
35 static int mbox_open_new_message(MESSAGE *msg, CONTEXT *dest, HEADER *hdr)
42 static int mbox_reopen_mailbox (CONTEXT*, int*);
45 * ctx - context to lock
46 * excl - exclusive lock?
47 * retry - should retry if unable to lock?
49 int mbox_lock_mailbox(CONTEXT *ctx, int excl, int retry)
53 if ((r = mx_lock_file(ctx->path, fileno(ctx->fp), excl, 1, retry)) == 0)
55 else if (retry && !excl) {
63 static void mbox_unlock_mailbox (CONTEXT * ctx)
68 mx_unlock_file (ctx->path, fileno (ctx->fp), 1);
73 /* Note that this function is also called when new mail is appended to the
74 * currently open folder, and NOT just when the mailbox is initially read.
76 * NOTE: it is assumed that the mailbox being read has been locked before
77 * this routine gets called. Strange things could happen if it's not!
79 static int mbox_parse_mailbox (CONTEXT * ctx)
82 char buf[HUGE_STRING], return_path[STRING];
85 int count = 0, lines = 0;
88 /* Save information about the folder at the time we opened it. */
89 if (stat (ctx->path, &sb) == -1) {
90 mutt_perror (ctx->path);
94 ctx->size = sb.st_size;
95 ctx->mtime = sb.st_mtime;
98 ctx->readonly = access (ctx->path, W_OK) ? 1 : 0;
100 /* precompute the local timezone to speed up calculation of the
103 tz = localtime(&t)->tm_gmtoff;
105 loc = ftello (ctx->fp);
106 while (fgets (buf, sizeof (buf), ctx->fp) != NULL) {
107 if (is_from (buf, return_path, sizeof (return_path), &t)) {
108 /* Save the Content-Length of the previous message */
110 #define PREV ctx->hdrs[ctx->msgcount-1]
112 if (PREV->content->length < 0) {
113 PREV->content->length = loc - PREV->content->offset - 1;
114 if (PREV->content->length < 0)
115 PREV->content->length = 0;
118 PREV->lines = lines ? lines - 1 : 0;
123 if (!ctx->quiet && ReadInc && ((count % ReadInc == 0) || count == 1))
124 mutt_message (_("Reading %s... %d (%d%%)"), ctx->path, count,
125 (int) (ftello (ctx->fp) / (ctx->size / 100 + 1)));
127 if (ctx->msgcount == ctx->hdrmax)
128 mx_alloc_memory (ctx);
130 curhdr = ctx->hdrs[ctx->msgcount] = header_new();
131 curhdr->received = t - tz;
132 curhdr->offset = loc;
133 curhdr->index = ctx->msgcount;
135 curhdr->env = mutt_read_rfc822_header (ctx->fp, curhdr, 0, 0);
137 /* if we know how long this message is, either just skip over the body,
138 * or if we don't know how many lines there are, count them now (this will
139 * save time by not having to search for the next message marker).
141 if (curhdr->content->length > 0) {
144 loc = ftello (ctx->fp);
145 tmploc = loc + curhdr->content->length + 1;
147 if (0 < tmploc && tmploc < ctx->size) {
149 * check to see if the content-length looks valid. we expect to
150 * to see a valid message separator at this point in the stream
152 if (fseeko (ctx->fp, tmploc, SEEK_SET) != 0 ||
153 fgets (buf, sizeof (buf), ctx->fp) == NULL ||
154 m_strncmp("From ", buf, 5) != 0) {
155 fseeko (ctx->fp, loc, SEEK_SET); /* nope, return the previous position */
156 curhdr->content->length = -1;
159 else if (tmploc != ctx->size) {
160 /* content-length would put us past the end of the file, so it
163 curhdr->content->length = -1;
166 if (curhdr->content->length != -1) {
167 /* good content-length. check to see if we know how many lines
168 * are in this message.
170 if (curhdr->lines == 0) {
171 int cl = curhdr->content->length;
173 /* count the number of lines in this message */
174 fseeko (ctx->fp, loc, SEEK_SET);
176 if (fgetc (ctx->fp) == '\n')
181 /* return to the offset of the next message separator */
182 fseeko(ctx->fp, tmploc, SEEK_SET);
188 if (!curhdr->env->return_path && return_path[0])
189 curhdr->env->return_path =
190 rfc822_parse_adrlist (curhdr->env->return_path, return_path);
192 if (!curhdr->env->from)
193 curhdr->env->from = address_list_dup (curhdr->env->return_path);
200 loc = ftello (ctx->fp);
204 * Only set the content-length of the previous message if we have read more
205 * than one message during _this_ invocation. If this routine is called
206 * when new mail is received, we need to make sure not to clobber what
207 * previously was the last message since the headers may be sorted.
210 if (PREV->content->length < 0) {
211 PREV->content->length = ftello (ctx->fp) - PREV->content->offset - 1;
212 if (PREV->content->length < 0)
213 PREV->content->length = 0;
217 PREV->lines = lines ? lines - 1 : 0;
219 mx_update_context (ctx, count);
227 /* open a mbox style mailbox */
228 static int mbox_open_mailbox (CONTEXT * ctx)
232 if (!(ctx->fp = fopen(ctx->path, "r"))) {
233 mutt_perror(ctx->path);
237 mutt_block_signals();
238 if (mbox_lock_mailbox(ctx, 0, 1) < 0) {
239 mutt_unblock_signals();
243 rc = ctx->magic == M_MBOX ? mbox_parse_mailbox(ctx) : -1;
245 mbox_unlock_mailbox(ctx);
246 mutt_unblock_signals();
250 /* check to see if the mailbox has changed on disk.
253 * M_REOPENED mailbox has been reopened
254 * M_NEW_MAIL new mail has arrived!
255 * M_LOCKED couldn't lock the file
259 static int _mbox_check_mailbox (CONTEXT * ctx, int *index_hint)
262 char buffer[LONG_STRING];
266 if (stat (ctx->path, &st) == 0) {
267 if (st.st_mtime == ctx->mtime && st.st_size == ctx->size)
270 if (st.st_size == ctx->size) {
271 /* the file was touched, but it is still the same length, so just exit */
272 ctx->mtime = st.st_mtime;
276 if (st.st_size > ctx->size) {
277 /* lock the file if it isn't already */
279 mutt_block_signals ();
280 if (mbox_lock_mailbox (ctx, 0, 0) == -1) {
281 mutt_unblock_signals ();
282 /* we couldn't lock the mailbox, but nothing serious happened:
283 * probably the new mail arrived: no reason to wait till we can
284 * parse it: we'll get it on the next pass
292 * Check to make sure that the only change to the mailbox is that
293 * message(s) were appended to this file. My heuristic is that we should
294 * see the message separator at *exactly* what used to be the end of the
297 fseeko (ctx->fp, ctx->size, SEEK_SET);
298 if (fgets (buffer, sizeof (buffer), ctx->fp) != NULL) {
299 if (ctx->magic == M_MBOX && m_strncmp("From ", buffer, 5) == 0) {
300 fseeko (ctx->fp, ctx->size, SEEK_SET);
301 mbox_parse_mailbox (ctx);
303 /* Only unlock the folder if it was locked inside of this routine.
304 * It may have been locked elsewhere, like in
305 * mutt_checkpoint_mailbox().
309 mbox_unlock_mailbox (ctx);
310 mutt_unblock_signals ();
313 return (M_NEW_MAIL); /* signal that new mail arrived */
326 if (mbox_reopen_mailbox (ctx, index_hint) != -1) {
328 mbox_unlock_mailbox (ctx);
329 mutt_unblock_signals ();
337 mbox_unlock_mailbox (ctx);
338 mx_fastclose_mailbox (ctx);
339 mutt_unblock_signals ();
340 mutt_error _("Mailbox was corrupted!");
345 static int mbox_check_mailbox(CONTEXT *ctx, int *index_hint, int lock)
350 mutt_block_signals();
351 if (mbox_lock_mailbox(ctx, 0, 0) < 0) {
352 mutt_unblock_signals();
357 rc = _mbox_check_mailbox(ctx, index_hint);
360 mutt_unblock_signals ();
361 mbox_unlock_mailbox (ctx);
370 static int mbox_sync_mailbox (CONTEXT * ctx, int unused __attribute__ ((unused)), int *index_hint)
372 char tempfile[_POSIX_PATH_MAX];
374 int i, j, save_sort = SORT_ORDER;
376 int need_sort = 0; /* flag to resort mailbox if new mail arrives */
377 int first = -1; /* first message to be written */
378 off_t offset; /* location in mailbox to write changed messages */
380 struct utimbuf utimebuf;
381 struct m_update_t *newOffset = NULL;
382 struct m_update_t *oldOffset = NULL;
385 /* sort message by their position in the mailbox on disk */
386 if (Sort != SORT_ORDER) {
389 mutt_sort_headers (ctx, 0);
394 /* need to open the file for writing in such a way that it does not truncate
395 * the file, so use read-write mode.
397 if ((ctx->fp = freopen (ctx->path, "r+", ctx->fp)) == NULL) {
398 mx_fastclose_mailbox (ctx);
399 mutt_error _("Fatal error! Could not reopen mailbox!");
404 mutt_block_signals ();
406 if (mbox_lock_mailbox (ctx, 1, 1) == -1) {
407 mutt_unblock_signals ();
408 mutt_error _("Unable to lock mailbox!");
413 /* Check to make sure that the file hasn't changed on disk */
414 if ((i = _mbox_check_mailbox (ctx, index_hint)) == M_NEW_MAIL
415 || i == M_REOPENED) {
416 /* new mail arrived, or mailbox reopened */
425 /* Create a temporary file to write the new version of the mailbox in. */
426 fp = m_tempfile(tempfile, _POSIX_PATH_MAX, NONULL(mod_core.tmpdir), NULL);
428 mutt_error _("Could not create temporary file!");
433 /* find the first deleted/changed message. we save a lot of time by only
434 * rewriting the mailbox from the point where it has actually changed.
436 for (i = 0; i < ctx->msgcount && !ctx->hdrs[i]->deleted &&
437 !ctx->hdrs[i]->changed && !ctx->hdrs[i]->attach_del; i++);
438 if (i == ctx->msgcount) {
439 /* this means ctx->changed or ctx->deleted was set, but no
440 * messages were found to be changed or deleted. This should
441 * never happen, is we presume it is a bug in mutt.
444 _("sync: mbox modified, but no modified messages! (report this bug)");
445 mutt_sleep (5); /* the mutt_error /will/ get cleared! */
450 /* save the index of the first changed/deleted message */
452 /* where to start overwriting */
453 offset = ctx->hdrs[i]->offset;
455 /* allocate space for the new offsets */
456 newOffset = p_new(struct m_update_t, ctx->msgcount - first);
457 oldOffset = p_new(struct m_update_t, ctx->msgcount - first);
459 for (i = first, j = 0; i < ctx->msgcount; i++) {
461 * back up some information which is needed to restore offsets when
465 oldOffset[i - first].valid = 1;
466 oldOffset[i - first].hdr = ctx->hdrs[i]->offset;
467 oldOffset[i - first].body = ctx->hdrs[i]->content->offset;
468 oldOffset[i - first].lines = ctx->hdrs[i]->lines;
469 oldOffset[i - first].length = ctx->hdrs[i]->content->length;
471 if (!ctx->hdrs[i]->deleted) {
473 if (!ctx->quiet && WriteInc && ((i % WriteInc) == 0 || j == 1))
474 mutt_message (_("Writing messages... %d (%d%%)"), i,
475 (int) (ftello (ctx->fp) / (ctx->size / 100 + 1)));
477 /* save the new offset for this message. we add `offset' because the
478 * temporary file only contains saved message which are located after
479 * `offset' in the real mailbox
481 newOffset[i - first].hdr = ftello (fp) + offset;
483 if (mutt_copy_message
484 (fp, ctx, ctx->hdrs[i], M_CM_UPDATE,
485 CH_FROM | CH_UPDATE | CH_UPDATE_LEN) == -1) {
486 mutt_perror (_("Can't create temporary file"));
492 /* Since messages could have been deleted, the offsets stored in memory
493 * will be wrong, so update what we can, which is the offset of this
494 * message, and the offset of the body. If this is a multipart message,
495 * we just flush the in memory cache so that the message will be reparsed
496 * if the user accesses it later.
498 newOffset[i - first].body =
499 ftello (fp) - ctx->hdrs[i]->content->length + offset;
500 body_list_wipe(&ctx->hdrs[i]->content->parts);
502 if (fputs ("\n", fp) == EOF) {
503 mutt_perror (_("Can't create temporary file"));
511 if (m_fclose(&fp) != 0) {
513 mutt_perror (_("Can't create temporary file"));
518 /* Save the state of this folder. */
519 if (stat (ctx->path, &statbuf) == -1) {
520 mutt_perror (ctx->path);
526 if ((fp = fopen (tempfile, "r")) == NULL) {
527 mutt_unblock_signals ();
528 mx_fastclose_mailbox (ctx);
529 mutt_perror (_("Can't create temporary file"));
534 if (fseeko (ctx->fp, offset, SEEK_SET) != 0 /* seek the append location */
535 /* do a sanity check to make sure the mailbox looks ok */
536 || fgets (buf, sizeof (buf), ctx->fp) == NULL
537 || (ctx->magic == M_MBOX && m_strncmp("From ", buf, 5) != 0))
542 if (fseeko (ctx->fp, offset, SEEK_SET) != 0) { /* return to proper offset */
545 /* copy the temp mailbox back into place starting at the first
546 * change/deleted message
548 mutt_message _("Committing changes...");
550 i = mutt_copy_stream (fp, ctx->fp);
552 if (ferror (ctx->fp))
556 ctx->size = ftello (ctx->fp); /* update the size of the mailbox */
557 ftruncate (fileno (ctx->fp), ctx->size);
562 mbox_unlock_mailbox (ctx);
564 if (m_fclose(&ctx->fp) != 0 || i == -1) {
565 /* error occured while writing the mailbox back, so keep the temp copy
569 char savefile[_POSIX_PATH_MAX];
571 snprintf(savefile, sizeof (savefile), "%s/mutt.%s-%u",
572 NONULL(mod_core.tmpdir), NONULL(mod_core.username), (unsigned int)getpid());
573 rename (tempfile, savefile);
574 mutt_unblock_signals ();
575 mx_fastclose_mailbox (ctx);
576 mutt_pretty_mailbox (savefile);
577 mutt_error (_("Write failed! Saved partial mailbox to %s"), savefile);
582 /* Restore the previous access/modification times */
583 utimebuf.actime = statbuf.st_atime;
584 utimebuf.modtime = statbuf.st_mtime;
585 utime (ctx->path, &utimebuf);
587 /* reopen the mailbox in read-only mode */
588 if ((ctx->fp = fopen (ctx->path, "r")) == NULL) {
590 mutt_unblock_signals ();
591 mx_fastclose_mailbox (ctx);
592 mutt_error _("Fatal error! Could not reopen mailbox!");
596 /* update the offsets of the rewritten messages */
597 for (i = first, j = first; i < ctx->msgcount; i++) {
598 if (!ctx->hdrs[i]->deleted) {
599 ctx->hdrs[i]->offset = newOffset[i - first].hdr;
600 ctx->hdrs[i]->content->hdr_offset = newOffset[i - first].hdr;
601 ctx->hdrs[i]->content->offset = newOffset[i - first].body;
602 ctx->hdrs[i]->index = j++;
605 p_delete(&newOffset);
606 p_delete(&oldOffset);
607 unlink (tempfile); /* remove partial copy of the mailbox */
608 mutt_unblock_signals ();
610 return (0); /* signal success */
612 bail: /* Come here in case of disaster */
616 /* restore offsets, as far as they are valid */
617 if (first >= 0 && oldOffset) {
618 for (i = first; i < ctx->msgcount && oldOffset[i - first].valid; i++) {
619 ctx->hdrs[i]->offset = oldOffset[i - first].hdr;
620 ctx->hdrs[i]->content->hdr_offset = oldOffset[i - first].hdr;
621 ctx->hdrs[i]->content->offset = oldOffset[i - first].body;
622 ctx->hdrs[i]->lines = oldOffset[i - first].lines;
623 ctx->hdrs[i]->content->length = oldOffset[i - first].length;
627 /* this is ok to call even if we haven't locked anything */
628 mbox_unlock_mailbox (ctx);
630 mutt_unblock_signals ();
631 p_delete(&newOffset);
632 p_delete(&oldOffset);
634 if ((ctx->fp = freopen (ctx->path, "r", ctx->fp)) == NULL) {
635 mutt_error _("Could not reopen mailbox!");
637 mx_fastclose_mailbox (ctx);
642 /* if the mailbox was reopened, the thread tree will be invalid so make
643 * sure to start threading from scratch. */
644 mutt_sort_headers (ctx, (need_sort == M_REOPENED));
649 /* close a mailbox opened in write-mode */
650 int mbox_close_mailbox (CONTEXT * ctx)
652 mx_unlock_file (ctx->path, fileno (ctx->fp), 1);
655 mutt_slow_close_compressed (ctx);
657 mutt_unblock_signals ();
658 mx_fastclose_mailbox (ctx);
662 static int mbox_reopen_mailbox (CONTEXT * ctx, int *index_hint)
664 int (*cmp_headers) (const HEADER *, const HEADER *) = NULL;
672 /* silent operations */
675 mutt_message _("Reopening mailbox...");
677 /* our heuristics require the old mailbox to be unsorted */
678 if (Sort != SORT_ORDER) {
683 mutt_sort_headers (ctx, 1);
690 /* simulate a close */
692 hash_delete (&ctx->id_hash, NULL);
694 hash_delete (&ctx->subj_hash, NULL);
695 mutt_clear_threads (ctx);
698 for (i = 0; i < ctx->msgcount; i++)
699 header_delete(&(ctx->hdrs[i])); /* nothing to do! */
700 p_delete(&ctx->hdrs);
703 /* save the old headers */
704 old_msgcount = ctx->msgcount;
705 old_hdrs = ctx->hdrs;
709 ctx->hdrmax = 0; /* force allocation of new headers */
719 ctx->subj_hash = NULL;
721 if (ctx->magic == M_MBOX && !fseeko(ctx->fp, 0, SEEK_SET)) {
722 cmp_headers = mutt_cmp_header;
723 rc = mbox_parse_mailbox (ctx);
729 /* free the old headers */
730 for (j = 0; j < old_msgcount; j++)
731 header_delete(&(old_hdrs[j]));
738 /* now try to recover the old flags */
740 index_hint_set = (index_hint == NULL);
742 if (!ctx->readonly) {
743 for (i = 0; i < ctx->msgcount; i++) {
746 /* some messages have been deleted, and new messages have been
747 * appended at the end; the heuristic is that old messages have then
748 * "advanced" towards the beginning of the folder, so we begin the
749 * search at index "i"
751 for (j = i; j < old_msgcount; j++) {
752 if (old_hdrs[j] == NULL)
754 if (cmp_headers (ctx->hdrs[i], old_hdrs[j])) {
760 for (j = 0; j < i && j < old_msgcount; j++) {
761 if (old_hdrs[j] == NULL)
763 if (cmp_headers (ctx->hdrs[i], old_hdrs[j])) {
771 /* this is best done here */
772 if (!index_hint_set && *index_hint == j)
775 if (old_hdrs[j]->changed) {
776 /* Only update the flags if the old header was changed;
777 * otherwise, the header may have been modified externally,
778 * and we don't want to lose _those_ changes
780 mutt_set_flag (ctx, ctx->hdrs[i], M_FLAG, old_hdrs[j]->flagged);
781 mutt_set_flag (ctx, ctx->hdrs[i], M_REPLIED, old_hdrs[j]->replied);
782 mutt_set_flag (ctx, ctx->hdrs[i], M_OLD, old_hdrs[j]->old);
783 mutt_set_flag (ctx, ctx->hdrs[i], M_READ, old_hdrs[j]->read);
785 mutt_set_flag (ctx, ctx->hdrs[i], M_DELETE, old_hdrs[j]->deleted);
786 mutt_set_flag (ctx, ctx->hdrs[i], M_TAG, old_hdrs[j]->tagged);
788 /* we don't need this header any more */
789 header_delete(&(old_hdrs[j]));
793 /* free the remaining old headers */
794 for (j = 0; j < old_msgcount; j++) {
796 header_delete(&(old_hdrs[j]));
805 return ((ctx->changed || msg_mod) ? M_REOPENED : M_NEW_MAIL);
810 * 1 if the mailbox is not empty
811 * 0 if the mailbox is empty
814 int mbox_check_empty (const char *path)
818 if (stat (path, &st) == -1)
821 return ((st.st_size == 0));
824 int mbox_is_magic (const char* path, struct stat* st)
828 char tmp[_POSIX_PATH_MAX];
830 if (S_ISDIR(st->st_mode))
833 if (st->st_size == 0) {
836 else if ((f = fopen (path, "r")) != NULL) {
837 struct utimbuf times;
839 fgets (tmp, sizeof (tmp), f);
840 if (m_strncmp("From ", tmp, 5) == 0)
844 /* need to restore the times here, the file was not really accessed,
845 * only the type was accessed. This is important, because detection
846 * of "new mail" depends on those times set correctly.
848 times.actime = st->st_atime;
849 times.modtime = st->st_mtime;
850 utime (path, ×);
853 return (-1); /* fopen failed */
856 if (magic == -1 && mutt_can_read_compressed (path))
857 return (M_COMPRESSED);
861 static int mbox_commit_message (MESSAGE* msg, CONTEXT* ctx) {
862 if (fputc ('\n', msg->fp) == EOF)
864 if ((fflush (msg->fp) == EOF || fsync (fileno (msg->fp)) == -1)) {
865 mutt_perror (_("Can't write message"));
871 mx_t const mbox_mx = {
878 mbox_open_new_message,