2 * Copyright (C) 1996-2002,2007 Michael R. Elkins <me@mutt.org>
3 * Copyright (C) 1999-2005 Thomas Roessler <roessler@does-not-exist.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * This file contains routines specific to MH and ``maildir'' style
37 #include "mutt_curses.h"
40 #include <sys/types.h>
57 #define INS_SORT_THRESHOLD 6
63 unsigned header_parsed:1;
64 #ifdef HAVE_DIRENT_D_INO
66 #endif /* HAVE_DIRENT_D_INO */
82 /* mh_sequences support */
84 #define MH_SEQ_UNSEEN (1 << 0)
85 #define MH_SEQ_REPLIED (1 << 1)
86 #define MH_SEQ_FLAGGED (1 << 2)
88 static inline struct mh_data *mh_data (CONTEXT *ctx)
90 return (struct mh_data*)ctx->data;
93 static void mhs_alloc (struct mh_sequences *mhs, int i)
98 if (i > mhs->max || !mhs->flags)
101 j = mhs->flags ? mhs->max + 1 : 0;
102 safe_realloc (&mhs->flags, sizeof (mhs->flags[0]) * (newmax + 1));
110 static void mhs_free_sequences (struct mh_sequences *mhs)
115 static short mhs_check (struct mh_sequences *mhs, int i)
117 if (!mhs->flags || i > mhs->max)
120 return mhs->flags[i];
123 static short mhs_set (struct mh_sequences *mhs, int i, short f)
127 return mhs->flags[i];
134 static short mhs_unset (struct mh_sequences *mhs, int i, short f)
138 return mhs->flags[i];
143 static void mh_read_token (char *t, int *first, int *last)
146 if ((p = strchr (t, '-')))
153 *first = *last = atoi (t);
156 static void mh_read_sequences (struct mh_sequences *mhs, const char *path)
167 char pathname[_POSIX_PATH_MAX];
168 snprintf (pathname, sizeof (pathname), "%s/.mh_sequences", path);
170 if (!(fp = fopen (pathname, "r")))
173 while ((buff = mutt_read_line (buff, &sz, fp, &line)))
175 if (!(t = strtok (buff, " \t:")))
178 if (!mutt_strcmp (t, MhUnseen))
180 else if (!mutt_strcmp (t, MhFlagged))
182 else if (!mutt_strcmp (t, MhReplied))
184 else /* unknown sequence */
187 while ((t = strtok (NULL, " \t:")))
189 mh_read_token (t, &first, &last);
190 for (; first <= last; first++)
191 mhs_set (mhs, first, f);
199 static inline mode_t mh_umask (CONTEXT* ctx)
202 struct mh_data* data = mh_data (ctx);
204 if (data && data->mh_umask)
205 return data->mh_umask;
207 if (stat (ctx->path, &st))
209 dprint (1, (debugfile, "stat failed on %s\n", ctx->path));
213 return 0777 & ~st.st_mode;
216 int mh_buffy (const char *path)
219 struct mh_sequences mhs;
220 memset (&mhs, 0, sizeof (mhs));
222 mh_read_sequences (&mhs, path);
223 for (i = 0; !r && i <= mhs.max; i++)
224 if (mhs_check (&mhs, i) & MH_SEQ_UNSEEN)
226 mhs_free_sequences (&mhs);
230 static int mh_mkstemp (CONTEXT * dest, FILE ** fp, char **tgt)
233 char path[_POSIX_PATH_MAX];
236 omask = umask (mh_umask (dest));
239 snprintf (path, _POSIX_PATH_MAX, "%s/.mutt-%s-%d-%d",
240 dest->path, NONULL (Hostname), (int) getpid (), Counter++);
241 if ((fd = open (path, O_WRONLY | O_EXCL | O_CREAT, 0666)) == -1)
252 *tgt = safe_strdup (path);
258 if ((*fp = fdopen (fd, "w")) == NULL)
260 FREE (tgt); /* __FREE_CHECKED__ */
269 static void mhs_write_one_sequence (FILE * fp, struct mh_sequences *mhs,
270 short f, const char *tag)
274 fprintf (fp, "%s:", tag);
279 for (i = 0; i <= mhs->max; i++)
281 if ((mhs_check (mhs, i) & f))
291 fprintf (fp, " %d", first);
293 fprintf (fp, " %d-%d", first, last);
303 fprintf (fp, " %d", first);
305 fprintf (fp, " %d-%d", first, last);
311 /* XXX - we don't currently remove deleted messages from sequences we don't know. Should we? */
313 static void mh_update_sequences (CONTEXT * ctx)
317 char sequences[_POSIX_PATH_MAX];
329 char seq_unseen[STRING];
330 char seq_replied[STRING];
331 char seq_flagged[STRING];
334 struct mh_sequences mhs;
335 memset (&mhs, 0, sizeof (mhs));
337 snprintf (seq_unseen, sizeof (seq_unseen), "%s:", NONULL (MhUnseen));
338 snprintf (seq_replied, sizeof (seq_replied), "%s:", NONULL (MhReplied));
339 snprintf (seq_flagged, sizeof (seq_flagged), "%s:", NONULL (MhFlagged));
341 if (mh_mkstemp (ctx, &nfp, &tmpfname) != 0)
347 snprintf (sequences, sizeof (sequences), "%s/.mh_sequences", ctx->path);
350 /* first, copy unknown sequences */
351 if ((ofp = fopen (sequences, "r")))
353 while ((buff = mutt_read_line (buff, &s, ofp, &l)))
355 if (!mutt_strncmp (buff, seq_unseen, mutt_strlen (seq_unseen)))
357 if (!mutt_strncmp (buff, seq_flagged, mutt_strlen (seq_flagged)))
359 if (!mutt_strncmp (buff, seq_replied, mutt_strlen (seq_replied)))
362 fprintf (nfp, "%s\n", buff);
367 /* now, update our unseen, flagged, and replied sequences */
368 for (l = 0; l < ctx->msgcount; l++)
370 if (ctx->hdrs[l]->deleted)
373 if ((p = strrchr (ctx->hdrs[l]->path, '/')))
376 p = ctx->hdrs[l]->path;
380 if (!ctx->hdrs[l]->read)
382 mhs_set (&mhs, i, MH_SEQ_UNSEEN);
385 if (ctx->hdrs[l]->flagged)
387 mhs_set (&mhs, i, MH_SEQ_FLAGGED);
390 if (ctx->hdrs[l]->replied)
392 mhs_set (&mhs, i, MH_SEQ_REPLIED);
397 /* write out the new sequences */
399 mhs_write_one_sequence (nfp, &mhs, MH_SEQ_UNSEEN, NONULL (MhUnseen));
401 mhs_write_one_sequence (nfp, &mhs, MH_SEQ_FLAGGED, NONULL (MhFlagged));
403 mhs_write_one_sequence (nfp, &mhs, MH_SEQ_REPLIED, NONULL (MhReplied));
405 mhs_free_sequences (&mhs);
408 /* try to commit the changes - no guarantee here */
412 if (safe_rename (tmpfname, sequences) != 0)
414 /* report an error? */
421 static void mh_sequences_add_one (CONTEXT * ctx, int n, short unseen,
422 short flagged, short replied)
424 short unseen_done = 0;
425 short flagged_done = 0;
426 short replied_done = 0;
428 FILE *ofp = NULL, *nfp = NULL;
431 char sequences[_POSIX_PATH_MAX];
433 char seq_unseen[STRING];
434 char seq_replied[STRING];
435 char seq_flagged[STRING];
441 if (mh_mkstemp (ctx, &nfp, &tmpfname) == -1)
444 snprintf (seq_unseen, sizeof (seq_unseen), "%s:", NONULL (MhUnseen));
445 snprintf (seq_replied, sizeof (seq_replied), "%s:", NONULL (MhReplied));
446 snprintf (seq_flagged, sizeof (seq_flagged), "%s:", NONULL (MhFlagged));
448 snprintf (sequences, sizeof (sequences), "%s/.mh_sequences", ctx->path);
449 if ((ofp = fopen (sequences, "r")))
451 while ((buff = mutt_read_line (buff, &sz, ofp, &line)))
453 if (unseen && !strncmp (buff, seq_unseen, mutt_strlen (seq_unseen)))
455 fprintf (nfp, "%s %d\n", buff, n);
459 && !strncmp (buff, seq_flagged, mutt_strlen (seq_flagged)))
461 fprintf (nfp, "%s %d\n", buff, n);
465 && !strncmp (buff, seq_replied, mutt_strlen (seq_replied)))
467 fprintf (nfp, "%s %d\n", buff, n);
471 fprintf (nfp, "%s\n", buff);
477 if (!unseen_done && unseen)
478 fprintf (nfp, "%s: %d\n", NONULL (MhUnseen), n);
479 if (!flagged_done && flagged)
480 fprintf (nfp, "%s: %d\n", NONULL (MhFlagged), n);
481 if (!replied_done && replied)
482 fprintf (nfp, "%s: %d\n", NONULL (MhReplied), n);
487 if (safe_rename (tmpfname, sequences) != 0)
493 static void mh_update_maildir (struct maildir *md, struct mh_sequences *mhs)
499 for (; md; md = md->next)
501 if ((p = strrchr (md->h->path, '/')))
507 f = mhs_check (mhs, i);
509 md->h->read = (f & MH_SEQ_UNSEEN) ? 0 : 1;
510 md->h->flagged = (f & MH_SEQ_FLAGGED) ? 1 : 0;
511 md->h->replied = (f & MH_SEQ_REPLIED) ? 1 : 0;
515 /* maildir support */
517 static void maildir_free_entry (struct maildir **md)
522 FREE (&(*md)->canon_fname);
524 mutt_free_header (&(*md)->h);
526 FREE (md); /* __FREE_CHECKED__ */
529 static void maildir_free_maildir (struct maildir **md)
531 struct maildir *p, *q;
536 for (p = *md; p; p = q)
539 maildir_free_entry (&p);
543 static void maildir_parse_flags (HEADER * h, const char *path)
551 if ((p = strrchr (path, ':')) != NULL && mutt_strncmp (p + 1, "2,", 2) == 0)
555 mutt_str_replace (&h->maildir_flags, p);
556 q = h->maildir_flags;
572 case 'R': /* replied */
577 case 'T': /* trashed */
590 if (q == h->maildir_flags)
591 FREE (&h->maildir_flags);
596 static void maildir_update_mtime (CONTEXT * ctx)
598 char buf[_POSIX_PATH_MAX];
600 struct mh_data *data = mh_data (ctx);
602 if (ctx->magic == M_MAILDIR)
604 snprintf (buf, sizeof (buf), "%s/%s", ctx->path, "cur");
605 if (stat (buf, &st) == 0)
606 data->mtime_cur = st.st_mtime;
607 snprintf (buf, sizeof (buf), "%s/%s", ctx->path, "new");
611 snprintf (buf, sizeof (buf), "%s/.mh_sequences", ctx->path);
612 if (stat (buf, &st) == 0)
613 data->mtime_cur = st.st_mtime;
615 strfcpy (buf, ctx->path, sizeof (buf));
618 if (stat (buf, &st) == 0)
619 ctx->mtime = st.st_mtime;
623 * Actually parse a maildir message. This may also be used to fill
624 * out a fake header structure generated by lazy maildir parsing.
626 static HEADER *maildir_parse_message (int magic, const char *fname,
627 int is_old, HEADER * _h)
633 if ((f = fopen (fname, "r")) != NULL)
636 h = mutt_new_header ();
637 h->env = mutt_read_rfc822_header (f, h, 0, 0);
639 fstat (fileno (f), &st);
643 h->received = h->date_sent;
645 if (h->content->length <= 0)
646 h->content->length = st.st_size - h->content->offset;
650 if (magic == M_MAILDIR)
653 * maildir stores its flags in the filename, so ignore the
654 * flags in the header of the message
658 maildir_parse_flags (h, fname);
665 /* Ignore the garbage files. A valid MH message consists of only
666 * digits. Deleted message get moved to a filename with a comma before
670 int mh_valid_message (const char *s)
674 if (!isdigit ((unsigned char) *s))
680 static int maildir_parse_dir (CONTEXT * ctx, struct maildir ***last,
681 const char *subdir, int *count,
682 progress_t *progress)
686 char buf[_POSIX_PATH_MAX];
688 struct maildir *entry;
693 snprintf (buf, sizeof (buf), "%s/%s", ctx->path, subdir);
694 is_old = (mutt_strcmp ("cur", subdir) == 0);
697 strfcpy (buf, ctx->path, sizeof (buf));
699 if ((dirp = opendir (buf)) == NULL)
702 while ((de = readdir (dirp)) != NULL)
704 if ((ctx->magic == M_MH && !mh_valid_message (de->d_name))
705 || (ctx->magic == M_MAILDIR && *de->d_name == '.'))
708 /* FOO - really ignore the return value? */
710 (debugfile, "%s:%d: queueing %s\n", __FILE__, __LINE__,
713 h = mutt_new_header ();
715 if (ctx->magic == M_MAILDIR)
716 maildir_parse_flags (h, de->d_name);
721 if (!ctx->quiet && progress)
722 mutt_progress_update (progress, *count, -1);
727 char tmp[_POSIX_PATH_MAX];
728 snprintf (tmp, sizeof (tmp), "%s/%s", subdir, de->d_name);
729 h->path = safe_strdup (tmp);
732 h->path = safe_strdup (de->d_name);
734 entry = safe_calloc (sizeof (struct maildir), 1);
736 #ifdef HAVE_DIRENT_D_INO
737 entry->inode = de->d_ino;
738 #endif /* HAVE_DIRENT_D_INO */
740 *last = &entry->next;
748 static int maildir_add_to_context (CONTEXT * ctx, struct maildir *md)
750 int oldmsgcount = ctx->msgcount;
755 dprint (2, (debugfile, "%s:%d maildir_add_to_context(): Considering %s\n",
756 __FILE__, __LINE__, NONULL (md->canon_fname)));
762 "%s:%d Adding header structure. Flags: %s%s%s%s%s\n", __FILE__,
763 __LINE__, md->h->flagged ? "f" : "", md->h->deleted ? "D" : "",
764 md->h->replied ? "r" : "", md->h->old ? "O" : "",
765 md->h->read ? "R" : ""));
766 if (ctx->msgcount == ctx->hdrmax)
767 mx_alloc_memory (ctx);
769 ctx->hdrs[ctx->msgcount] = md->h;
770 ctx->hdrs[ctx->msgcount]->index = ctx->msgcount;
772 md->h->content->length + md->h->content->offset -
773 md->h->content->hdr_offset;
781 if (ctx->msgcount > oldmsgcount)
783 mx_update_context (ctx, ctx->msgcount - oldmsgcount);
789 static int maildir_move_to_context (CONTEXT * ctx, struct maildir **md)
792 r = maildir_add_to_context (ctx, *md);
793 maildir_free_maildir (md);
798 static size_t maildir_hcache_keylen (const char *fn)
800 const char * p = strrchr (fn, ':');
801 return p ? (size_t) (p - fn) : mutt_strlen(fn);
805 #if HAVE_DIRENT_D_INO
806 static int md_cmp_inode (struct maildir *a, struct maildir *b)
808 return a->inode - b->inode;
812 static int md_cmp_path (struct maildir *a, struct maildir *b)
814 return strcmp (a->h->path, b->h->path);
818 * Merge two maildir lists according to the inode numbers.
820 static struct maildir* maildir_merge_lists (struct maildir *left,
821 struct maildir *right,
822 int (*cmp) (struct maildir *,
825 struct maildir* head;
826 struct maildir* tail;
830 if (cmp (left, right) < 0)
851 while (left && right)
853 if (cmp (left, right) < 0)
878 static struct maildir* maildir_ins_sort (struct maildir* list,
879 int (*cmp) (struct maildir *,
882 struct maildir *tmp, *last, *ret = NULL, *back;
892 for (tmp = ret; tmp && cmp (tmp, list) <= 0; tmp = tmp->next)
908 * Sort maildir list according to inode.
910 static struct maildir* maildir_sort (struct maildir* list, size_t len,
911 int (*cmp) (struct maildir *,
914 struct maildir* left = list;
915 struct maildir* right = list;
918 if (!list || !list->next)
923 if (len != (size_t)(-1) && len <= INS_SORT_THRESHOLD)
924 return maildir_ins_sort (list, cmp);
927 while (list && list->next)
930 list = list->next->next;
938 left = maildir_sort (left, c, cmp);
939 right = maildir_sort (right, c, cmp);
940 return maildir_merge_lists (left, right, cmp);
943 /* Sorts mailbox into it's natural order.
944 * Currently only defined for MH where files are numbered.
946 static void mh_sort_natural (CONTEXT *ctx, struct maildir **md)
948 if (!ctx || !md || !*md || ctx->magic != M_MH || Sort != SORT_ORDER)
950 dprint (4, (debugfile, "maildir: sorting %s into natural order\n",
952 *md = maildir_sort (*md, (size_t) -1, md_cmp_path);
955 #if HAVE_DIRENT_D_INO
956 static struct maildir *skip_duplicates (struct maildir *p, struct maildir **last)
959 * Skip ahead to the next non-duplicate message.
961 * p should never reach NULL, because we couldn't have reached this point unless
962 * there was a message that needed to be parsed.
964 * the check for p->header_parsed is likely unnecessary since the dupes will most
965 * likely be at the head of the list. but it is present for consistency with
966 * the check at the top of the for() loop in maildir_delayed_parsing().
968 while (!p->h || p->header_parsed) {
977 * This function does the second parsing pass
979 static void maildir_delayed_parsing (CONTEXT * ctx, struct maildir **md,
980 progress_t *progress)
982 struct maildir *p, *last = NULL;
983 char fn[_POSIX_PATH_MAX];
985 #if HAVE_DIRENT_D_INO
989 header_cache_t *hc = NULL;
991 struct timeval *when = NULL;
992 struct stat lastchanged;
996 #if HAVE_DIRENT_D_INO
997 #define DO_SORT() do { \
1000 dprint (4, (debugfile, "maildir: need to sort %s by inode\n", ctx->path)); \
1001 p = maildir_sort (p, (size_t) -1, md_cmp_inode); \
1007 p = skip_duplicates (p, &last); \
1008 snprintf (fn, sizeof (fn), "%s/%s", ctx->path, p->h->path); \
1012 #define DO_SORT() /* nothing */
1016 hc = mutt_hcache_open (HeaderCache, ctx->path, NULL);
1019 for (p = *md, count = 0; p; p = p->next, count++)
1021 if (! (p && p->h && !p->header_parsed))
1027 if (!ctx->quiet && progress)
1028 mutt_progress_update (progress, count, -1);
1030 snprintf (fn, sizeof (fn), "%s/%s", ctx->path, p->h->path);
1033 if (option(OPTHCACHEVERIFY))
1036 ret = stat(fn, &lastchanged);
1040 lastchanged.st_mtime = 0;
1044 if (ctx->magic == M_MH)
1045 data = mutt_hcache_fetch (hc, p->h->path, strlen);
1047 data = mutt_hcache_fetch (hc, p->h->path + 3, &maildir_hcache_keylen);
1048 when = (struct timeval *) data;
1050 if (data != NULL && !ret && lastchanged.st_mtime <= when->tv_sec)
1052 p->h = mutt_hcache_restore ((unsigned char *)data, &p->h);
1053 if (ctx->magic == M_MAILDIR)
1054 maildir_parse_flags (p->h, fn);
1058 #endif /* USE_HCACHE */
1061 if (maildir_parse_message (ctx->magic, fn, p->h->old, p->h))
1063 p->header_parsed = 1;
1065 if (ctx->magic == M_MH)
1066 mutt_hcache_store (hc, p->h->path, p->h, 0, strlen);
1068 mutt_hcache_store (hc, p->h->path + 3, p->h, 0, &maildir_hcache_keylen);
1071 mutt_free_header (&p->h);
1079 mutt_hcache_close (hc);
1084 mh_sort_natural (ctx, md);
1087 static int mh_close_mailbox (CONTEXT *ctx)
1094 /* Read a MH/maildir style mailbox.
1097 * ctx [IN/OUT] context for this mailbox
1098 * subdir [IN] NULL for MH mailboxes, otherwise the subdir of the
1099 * maildir mailbox to read from
1101 int mh_read_dir (CONTEXT * ctx, const char *subdir)
1104 struct mh_sequences mhs;
1105 struct maildir **last;
1106 struct mh_data *data;
1108 char msgbuf[STRING];
1109 progress_t progress;
1111 memset (&mhs, 0, sizeof (mhs));
1114 snprintf (msgbuf, sizeof (msgbuf), _("Scanning %s..."), ctx->path);
1115 mutt_progress_init (&progress, msgbuf, M_PROGRESS_MSG, ReadInc, 0);
1120 ctx->data = safe_calloc(sizeof (struct mh_data), 1);
1121 ctx->mx_close = mh_close_mailbox;
1123 data = mh_data (ctx);
1125 maildir_update_mtime (ctx);
1130 if (maildir_parse_dir (ctx, &last, subdir, &count, &progress) == -1)
1135 snprintf (msgbuf, sizeof (msgbuf), _("Reading %s..."), ctx->path);
1136 mutt_progress_init (&progress, msgbuf, M_PROGRESS_MSG, ReadInc, count);
1138 maildir_delayed_parsing (ctx, &md, &progress);
1140 if (ctx->magic == M_MH)
1142 mh_read_sequences (&mhs, ctx->path);
1143 mh_update_maildir (md, &mhs);
1144 mhs_free_sequences (&mhs);
1147 maildir_move_to_context (ctx, &md);
1149 if (!data->mh_umask)
1150 data->mh_umask = mh_umask (ctx);
1155 /* read a maildir style mailbox */
1156 int maildir_read_dir (CONTEXT * ctx)
1158 /* maildir looks sort of like MH, except that there are two subdirectories
1159 * of the main folder path from which to read messages
1161 if (mh_read_dir (ctx, "new") == -1 || mh_read_dir (ctx, "cur") == -1)
1168 * Open a new (temporary) message in an MH folder.
1171 int mh_open_new_message (MESSAGE * msg, CONTEXT * dest, HEADER * hdr)
1173 return mh_mkstemp (dest, &msg->fp, &msg->path);
1176 static int ch_compar (const void *a, const void *b)
1178 return (int)( *((const char *) a) - *((const char *) b));
1181 static void maildir_flags (char *dest, size_t destlen, HEADER * hdr)
1186 * The maildir specification requires that all files in the cur
1187 * subdirectory have the :unique string appeneded, regardless of whether
1188 * or not there are any flags. If .old is set, we know that this message
1189 * will end up in the cur directory, so we include it in the following
1190 * test even though there is no associated flag.
1193 if (hdr && (hdr->flagged || hdr->replied || hdr->read || hdr->deleted || hdr->old || hdr->maildir_flags))
1195 char tmp[LONG_STRING];
1196 snprintf (tmp, sizeof (tmp),
1198 hdr->flagged ? "F" : "",
1199 hdr->replied ? "R" : "",
1200 hdr->read ? "S" : "", hdr->deleted ? "T" : "",
1201 NONULL(hdr->maildir_flags));
1202 if (hdr->maildir_flags)
1203 qsort (tmp, strlen (tmp), 1, ch_compar);
1204 snprintf (dest, destlen, ":2,%s", tmp);
1210 * Open a new (temporary) message in a maildir folder.
1212 * Note that this uses _almost_ the maildir file name format, but
1213 * with a {cur,new} prefix.
1217 int maildir_open_new_message (MESSAGE * msg, CONTEXT * dest, HEADER * hdr)
1220 char path[_POSIX_PATH_MAX];
1227 short deleted = hdr->deleted;
1230 maildir_flags (suffix, sizeof (suffix), hdr);
1232 hdr->deleted = deleted;
1237 if (hdr && (hdr->read || hdr->old))
1238 strfcpy (subdir, "cur", sizeof (subdir));
1240 strfcpy (subdir, "new", sizeof (subdir));
1242 omask = umask (mh_umask (dest));
1245 snprintf (path, _POSIX_PATH_MAX, "%s/tmp/%s.%ld.%u_%d.%s%s",
1246 dest->path, subdir, time (NULL), (unsigned int)getpid (),
1247 Counter++, NONULL (Hostname), suffix);
1249 dprint (2, (debugfile, "maildir_open_new_message (): Trying %s.\n",
1252 if ((fd = open (path, O_WRONLY | O_EXCL | O_CREAT, 0666)) == -1)
1254 if (errno != EEXIST)
1263 dprint (2, (debugfile, "maildir_open_new_message (): Success.\n"));
1264 msg->path = safe_strdup (path);
1270 if ((msg->fp = fdopen (fd, "w")) == NULL)
1284 * Commit a message to a maildir folder.
1286 * msg->path contains the file name of a file in tmp/. We take the
1287 * flags from this file's name.
1289 * ctx is the mail folder we commit to.
1291 * hdr is a header structure to which we write the message's new
1292 * file name. This is used in the mh and maildir folder synch
1293 * routines. When this routine is invoked from mx_commit_message,
1296 * msg->path looks like this:
1298 * tmp/{cur,new}.mutt-HOSTNAME-PID-COUNTER:flags
1300 * See also maildir_open_new_message().
1304 int maildir_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr)
1308 char path[_POSIX_PATH_MAX];
1309 char full[_POSIX_PATH_MAX];
1312 if (safe_fsync_close (&msg->fp))
1314 mutt_perror (_("Could not flush message to disk"));
1318 /* extract the subdir */
1319 s = strrchr (msg->path, '/') + 1;
1320 strfcpy (subdir, s, 4);
1322 /* extract the flags */
1323 if ((s = strchr (s, ':')))
1324 strfcpy (suffix, s, sizeof (suffix));
1328 /* construct a new file name. */
1331 snprintf (path, _POSIX_PATH_MAX, "%s/%ld.%u_%d.%s%s", subdir,
1332 time (NULL), (unsigned int)getpid (), Counter++,
1333 NONULL (Hostname), suffix);
1334 snprintf (full, _POSIX_PATH_MAX, "%s/%s", ctx->path, path);
1336 dprint (2, (debugfile, "maildir_commit_message (): renaming %s to %s.\n",
1339 if (safe_rename (msg->path, full) == 0)
1342 mutt_str_replace (&hdr->path, path);
1346 * Adjust the mtime on the file to match the time at which this
1347 * message was received. Currently this is only set when copying
1348 * messages between mailboxes, so we test to ensure that it is
1355 ut.actime = msg->received;
1356 ut.modtime = msg->received;
1357 if (utime (full, &ut))
1359 mutt_perror (_("maildir_commit_message(): unable to set time on file"));
1366 else if (errno != EEXIST)
1368 mutt_perror (ctx->path);
1375 * commit a message to an MH folder.
1380 static int _mh_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr,
1386 unsigned int n, hi = 0;
1387 char path[_POSIX_PATH_MAX];
1390 if (safe_fsync_close (&msg->fp))
1392 mutt_perror (_("Could not flush message to disk"));
1396 if ((dirp = opendir (ctx->path)) == NULL)
1398 mutt_perror (ctx->path);
1402 /* figure out what the next message number is */
1403 while ((de = readdir (dirp)) != NULL)
1411 if (!isdigit ((unsigned char) *cp))
1425 * Now try to rename the file to the proper name.
1427 * Note: We may have to try multiple times, until we find a free
1434 snprintf (tmp, sizeof (tmp), "%d", hi);
1435 snprintf (path, sizeof (path), "%s/%s", ctx->path, tmp);
1436 if (safe_rename (msg->path, path) == 0)
1439 mutt_str_replace (&hdr->path, tmp);
1443 else if (errno != EEXIST)
1445 mutt_perror (ctx->path);
1450 mh_sequences_add_one (ctx, hi, !msg->flags.read, msg->flags.flagged,
1451 msg->flags.replied);
1455 int mh_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr)
1457 return _mh_commit_message (ctx, msg, hdr, 1);
1461 /* Sync a message in an MH folder.
1463 * This code is also used for attachment deletion in maildir
1467 static int mh_rewrite_message (CONTEXT * ctx, int msgno)
1469 HEADER *h = ctx->hdrs[msgno];
1474 char oldpath[_POSIX_PATH_MAX];
1475 char newpath[_POSIX_PATH_MAX];
1476 char partpath[_POSIX_PATH_MAX];
1478 long old_body_offset = h->content->offset;
1479 long old_body_length = h->content->length;
1480 long old_hdr_lines = h->lines;
1482 if ((dest = mx_open_new_message (ctx, h, 0)) == NULL)
1485 if ((rc = mutt_copy_message (dest->fp, ctx, h,
1486 M_CM_UPDATE, CH_UPDATE | CH_UPDATE_LEN)) == 0)
1488 snprintf (oldpath, _POSIX_PATH_MAX, "%s/%s", ctx->path, h->path);
1489 strfcpy (partpath, h->path, _POSIX_PATH_MAX);
1491 if (ctx->magic == M_MAILDIR)
1492 rc = maildir_commit_message (ctx, dest, h);
1494 rc = _mh_commit_message (ctx, dest, h, 0);
1496 mx_close_message (&dest);
1505 * Try to move the new message to the old place.
1508 * This is important when we are just updating flags.
1510 * Note that there is a race condition against programs which
1511 * use the first free slot instead of the maximum message
1512 * number. Mutt does _not_ behave like this.
1514 * Anyway, if this fails, the message is in the folder, so
1515 * all what happens is that a concurrently runnung mutt will
1516 * lose flag modifications.
1519 if (ctx->magic == M_MH && rc == 0)
1521 snprintf (newpath, _POSIX_PATH_MAX, "%s/%s", ctx->path, h->path);
1522 if ((rc = safe_rename (newpath, oldpath)) == 0)
1523 mutt_str_replace (&h->path, partpath);
1527 mx_close_message (&dest);
1529 if (rc == -1 && restore)
1531 h->content->offset = old_body_offset;
1532 h->content->length = old_body_length;
1533 h->lines = old_hdr_lines;
1536 mutt_free_body (&h->content->parts);
1540 static int mh_sync_message (CONTEXT * ctx, int msgno)
1542 HEADER *h = ctx->hdrs[msgno];
1544 if (h->attach_del ||
1545 (h->env && (h->env->refs_changed || h->env->irt_changed)))
1546 if (mh_rewrite_message (ctx, msgno) != 0)
1552 static int maildir_sync_message (CONTEXT * ctx, int msgno)
1554 HEADER *h = ctx->hdrs[msgno];
1556 if (h->attach_del ||
1557 (h->env && (h->env->refs_changed || h->env->irt_changed)))
1559 /* when doing attachment deletion/rethreading, fall back to the MH case. */
1560 if (mh_rewrite_message (ctx, msgno) != 0)
1565 /* we just have to rename the file. */
1567 char newpath[_POSIX_PATH_MAX];
1568 char partpath[_POSIX_PATH_MAX];
1569 char fullpath[_POSIX_PATH_MAX];
1570 char oldpath[_POSIX_PATH_MAX];
1574 if ((p = strrchr (h->path, '/')) == NULL)
1578 "maildir_sync_message: %s: unable to find subdir!\n",
1583 strfcpy (newpath, p, sizeof (newpath));
1585 /* kill the previous flags */
1586 if ((p = strchr (newpath, ':')) != NULL)
1589 maildir_flags (suffix, sizeof (suffix), h);
1591 snprintf (partpath, sizeof (partpath), "%s/%s%s",
1592 (h->read || h->old) ? "cur" : "new", newpath, suffix);
1593 snprintf (fullpath, sizeof (fullpath), "%s/%s", ctx->path, partpath);
1594 snprintf (oldpath, sizeof (oldpath), "%s/%s", ctx->path, h->path);
1596 if (mutt_strcmp (fullpath, oldpath) == 0)
1598 /* message hasn't really changed */
1602 /* record that the message is possibly marked as trashed on disk */
1603 h->trash = h->deleted;
1605 if (rename (oldpath, fullpath) != 0)
1607 mutt_perror ("rename");
1610 mutt_str_replace (&h->path, partpath);
1615 int mh_sync_mailbox (CONTEXT * ctx, int *index_hint)
1617 char path[_POSIX_PATH_MAX], tmp[_POSIX_PATH_MAX];
1620 header_cache_t *hc = NULL;
1621 #endif /* USE_HCACHE */
1622 char msgbuf[STRING];
1623 progress_t progress;
1625 if (ctx->magic == M_MH)
1626 i = mh_check_mailbox (ctx, index_hint);
1628 i = maildir_check_mailbox (ctx, index_hint);
1634 if (ctx->magic == M_MAILDIR || ctx->magic == M_MH)
1635 hc = mutt_hcache_open(HeaderCache, ctx->path, NULL);
1636 #endif /* USE_HCACHE */
1640 snprintf (msgbuf, sizeof (msgbuf), _("Writing %s..."), ctx->path);
1641 mutt_progress_init (&progress, msgbuf, M_PROGRESS_MSG, WriteInc, ctx->msgcount);
1644 for (i = 0; i < ctx->msgcount; i++)
1647 mutt_progress_update (&progress, i, -1);
1649 if (ctx->hdrs[i]->deleted
1650 && (ctx->magic != M_MAILDIR || !option (OPTMAILDIRTRASH)))
1652 snprintf (path, sizeof (path), "%s/%s", ctx->path, ctx->hdrs[i]->path);
1653 if (ctx->magic == M_MAILDIR
1654 || (option (OPTMHPURGE) && ctx->magic == M_MH))
1657 if (ctx->magic == M_MAILDIR)
1658 mutt_hcache_delete (hc, ctx->hdrs[i]->path + 3, &maildir_hcache_keylen);
1659 else if (ctx->magic == M_MH)
1660 mutt_hcache_delete (hc, ctx->hdrs[i]->path, strlen);
1661 #endif /* USE_HCACHE */
1664 else if (ctx->magic == M_MH)
1666 /* MH just moves files out of the way when you delete them */
1667 if (*ctx->hdrs[i]->path != ',')
1669 snprintf (tmp, sizeof (tmp), "%s/,%s", ctx->path,
1670 ctx->hdrs[i]->path);
1677 else if (ctx->hdrs[i]->changed || ctx->hdrs[i]->attach_del ||
1678 (ctx->magic == M_MAILDIR
1679 && (option (OPTMAILDIRTRASH) || ctx->hdrs[i]->trash)
1680 && (ctx->hdrs[i]->deleted != ctx->hdrs[i]->trash)))
1682 if (ctx->magic == M_MAILDIR)
1684 if (maildir_sync_message (ctx, i) == -1)
1689 if (mh_sync_message (ctx, i) == -1)
1696 if (ctx->magic == M_MAILDIR || ctx->magic == M_MH)
1697 mutt_hcache_close (hc);
1698 #endif /* USE_HCACHE */
1700 if (ctx->magic == M_MH)
1701 mh_update_sequences (ctx);
1703 /* XXX race condition? */
1705 maildir_update_mtime (ctx);
1707 /* adjust indices */
1711 for (i = 0, j = 0; i < ctx->msgcount; i++)
1713 if (!ctx->hdrs[i]->deleted
1714 || (ctx->magic == M_MAILDIR && option (OPTMAILDIRTRASH)))
1715 ctx->hdrs[i]->index = j++;
1723 if (ctx->magic == M_MAILDIR || ctx->magic == M_MH)
1724 mutt_hcache_close (hc);
1725 #endif /* USE_HCACHE */
1729 static char *maildir_canon_filename (char *dest, const char *src, size_t l)
1733 if ((t = strrchr (src, '/')))
1736 strfcpy (dest, src, l);
1737 if ((u = strrchr (dest, ':')))
1743 static void maildir_update_tables (CONTEXT *ctx, int *index_hint)
1749 if (Sort != SORT_ORDER)
1753 mutt_sort_headers (ctx, 1);
1757 old_count = ctx->msgcount;
1758 for (i = 0, j = 0; i < old_count; i++)
1760 if (ctx->hdrs[i]->active && index_hint && *index_hint == i)
1763 if (ctx->hdrs[i]->active)
1764 ctx->hdrs[i]->index = j++;
1767 mx_update_tables (ctx, 0);
1768 mutt_clear_threads (ctx);
1771 static void maildir_update_flags (CONTEXT *ctx, HEADER *o, HEADER *n)
1773 /* save the global state here so we can reset it at the
1774 * end of list block if required.
1776 int context_changed = ctx->changed;
1778 /* user didn't modify this message. alter the flags to match the
1779 * current state on disk. This may not actually do
1780 * anything. mutt_set_flag() will just ignore the call if the status
1781 * bits are already properly set, but it is still faster not to pass
1783 if (o->flagged != n->flagged)
1784 mutt_set_flag (ctx, o, M_FLAG, n->flagged);
1785 if (o->replied != n->replied)
1786 mutt_set_flag (ctx, o, M_REPLIED, n->replied);
1787 if (o->read != n->read)
1788 mutt_set_flag (ctx, o, M_READ, n->read);
1789 if (o->old != n->old)
1790 mutt_set_flag (ctx, o, M_OLD, n->old);
1792 /* mutt_set_flag() will set this, but we don't need to
1793 * sync the changes we made because we just updated the
1794 * context to match the current on-disk state of the
1799 /* if the mailbox was not modified before we made these
1800 * changes, unset the changed flag since nothing needs to
1803 if (!context_changed)
1808 /* This function handles arrival of new mail and reopening of
1809 * maildir folders. The basic idea here is we check to see if either
1810 * the new or cur subdirectories have changed, and if so, we scan them
1811 * for the list of files. We check for newly added messages, and
1812 * then merge the flags messages we already knew about. We don't treat
1813 * either subdirectory differently, as mail could be copied directly into
1814 * the cur directory from another agent.
1816 int maildir_check_mailbox (CONTEXT * ctx, int *index_hint)
1818 struct stat st_new; /* status of the "new" subdirectory */
1819 struct stat st_cur; /* status of the "cur" subdirectory */
1820 char buf[_POSIX_PATH_MAX];
1821 int changed = 0; /* bitmask representing which subdirectories
1822 have changed. 0x1 = new, 0x2 = cur */
1823 int occult = 0; /* messages were removed from the mailbox */
1824 int have_new = 0; /* messages were added to the mailbox */
1825 struct maildir *md; /* list of messages in the mailbox */
1826 struct maildir **last, *p;
1828 HASH *fnames; /* hash table for quickly looking up the base filename
1829 for a maildir message */
1830 struct mh_data *data = mh_data (ctx);
1832 /* XXX seems like this check belongs in mx_check_mailbox()
1835 if (!option (OPTCHECKNEW))
1838 snprintf (buf, sizeof (buf), "%s/new", ctx->path);
1839 if (stat (buf, &st_new) == -1)
1842 snprintf (buf, sizeof (buf), "%s/cur", ctx->path);
1843 if (stat (buf, &st_cur) == -1)
1846 /* determine which subdirectories need to be scanned */
1847 if (st_new.st_mtime > ctx->mtime)
1849 if (st_cur.st_mtime > data->mtime_cur)
1853 return 0; /* nothing to do */
1855 /* update the modification times on the mailbox */
1856 data->mtime_cur = st_cur.st_mtime;
1857 ctx->mtime = st_new.st_mtime;
1859 /* do a fast scan of just the filenames in
1860 * the subdirectories that have changed.
1865 maildir_parse_dir (ctx, &last, "new", NULL, NULL);
1867 maildir_parse_dir (ctx, &last, "cur", NULL, NULL);
1869 /* we create a hash table keyed off the canonical (sans flags) filename
1870 * of each message we scanned. This is used in the loop over the
1871 * existing messages below to do some correlation.
1873 fnames = hash_create (1031);
1875 for (p = md; p; p = p->next)
1877 maildir_canon_filename (buf, p->h->path, sizeof (buf));
1878 p->canon_fname = safe_strdup (buf);
1879 hash_insert (fnames, p->canon_fname, p, 0);
1882 /* check for modifications and adjust flags */
1883 for (i = 0; i < ctx->msgcount; i++)
1885 ctx->hdrs[i]->active = 0;
1886 maildir_canon_filename (buf, ctx->hdrs[i]->path, sizeof (buf));
1887 p = hash_find (fnames, buf);
1890 /* message already exists, merge flags */
1891 ctx->hdrs[i]->active = 1;
1893 /* check to see if the message has moved to a different
1894 * subdirectory. If so, update the associated filename.
1896 if (mutt_strcmp (ctx->hdrs[i]->path, p->h->path))
1897 mutt_str_replace (&ctx->hdrs[i]->path, p->h->path);
1899 /* if the user hasn't modified the flags on this message, update
1900 * the flags we just detected.
1902 if (!ctx->hdrs[i]->changed)
1903 maildir_update_flags (ctx, ctx->hdrs[i], p->h);
1905 if (ctx->hdrs[i]->deleted == ctx->hdrs[i]->trash)
1906 ctx->hdrs[i]->deleted = p->h->deleted;
1907 ctx->hdrs[i]->trash = p->h->trash;
1909 /* this is a duplicate of an existing header, so remove it */
1910 mutt_free_header (&p->h);
1912 /* This message was not in the list of messages we just scanned.
1913 * Check to see if we have enough information to know if the
1914 * message has disappeared out from underneath us.
1916 else if (((changed & 1) && (!strncmp (ctx->hdrs[i]->path, "new/", 4))) ||
1917 ((changed & 2) && (!strncmp (ctx->hdrs[i]->path, "cur/", 4))))
1919 /* This message disappeared, so we need to simulate a "reopen"
1920 * event. We know it disappeared because we just scanned the
1921 * subdirectory it used to reside in.
1927 /* This message resides in a subdirectory which was not
1928 * modified, so we assume that it is still present and
1931 ctx->hdrs[i]->active = 1;
1935 /* destroy the file name hash */
1936 hash_destroy (&fnames, NULL);
1938 /* If we didn't just get new mail, update the tables. */
1940 maildir_update_tables (ctx, index_hint);
1942 /* do any delayed parsing we need to do. */
1943 maildir_delayed_parsing (ctx, &md, NULL);
1945 /* Incorporate new messages */
1946 have_new = maildir_move_to_context (ctx, &md);
1948 return occult ? M_REOPENED : (have_new ? M_NEW_MAIL : 0);
1952 * This function handles arrival of new mail and reopening of
1953 * mh/maildir folders. Things are getting rather complex because we
1954 * don't have a well-defined "mailbox order", so the tricks from
1955 * mbox.c and mx.c won't work here.
1957 * Don't change this code unless you _really_ understand what
1962 int mh_check_mailbox (CONTEXT * ctx, int *index_hint)
1964 char buf[_POSIX_PATH_MAX];
1965 struct stat st, st_cur;
1966 short modified = 0, have_new = 0, occult = 0;
1967 struct maildir *md, *p;
1968 struct maildir **last = NULL;
1969 struct mh_sequences mhs;
1972 struct mh_data *data = mh_data (ctx);
1974 if (!option (OPTCHECKNEW))
1977 strfcpy (buf, ctx->path, sizeof (buf));
1978 if (stat (buf, &st) == -1)
1981 /* create .mh_sequences when there isn't one. */
1982 snprintf (buf, sizeof (buf), "%s/.mh_sequences", ctx->path);
1983 if ((i = stat (buf, &st_cur)) == -1 && errno == ENOENT)
1988 if (mh_mkstemp (ctx, &fp, &tmp) == 0)
1991 if (safe_rename (tmp, buf) == -1)
1997 if (i == -1 && stat (buf, &st_cur) == -1)
2000 if (st.st_mtime > ctx->mtime || st_cur.st_mtime > data->mtime_cur)
2006 data->mtime_cur = st_cur.st_mtime;
2007 ctx->mtime = st.st_mtime;
2009 memset (&mhs, 0, sizeof (mhs));
2014 maildir_parse_dir (ctx, &last, NULL, NULL, NULL);
2015 maildir_delayed_parsing (ctx, &md, NULL);
2017 mh_read_sequences (&mhs, ctx->path);
2018 mh_update_maildir (md, &mhs);
2019 mhs_free_sequences (&mhs);
2021 /* check for modifications and adjust flags */
2022 fnames = hash_create (1031);
2024 for (p = md; p; p = p->next)
2025 hash_insert (fnames, p->h->path, p, 0);
2027 for (i = 0; i < ctx->msgcount; i++)
2029 ctx->hdrs[i]->active = 0;
2031 if ((p = hash_find (fnames, ctx->hdrs[i]->path)) && p->h &&
2032 (mbox_strict_cmp_headers (ctx->hdrs[i], p->h)))
2034 ctx->hdrs[i]->active = 1;
2035 /* found the right message */
2036 if (!ctx->hdrs[i]->changed)
2037 maildir_update_flags (ctx, ctx->hdrs[i], p->h);
2039 mutt_free_header (&p->h);
2041 else /* message has disappeared */
2045 /* destroy the file name hash */
2047 hash_destroy (&fnames, NULL);
2049 /* If we didn't just get new mail, update the tables. */
2051 maildir_update_tables (ctx, index_hint);
2053 /* Incorporate new messages */
2054 have_new = maildir_move_to_context (ctx, &md);
2056 return occult ? M_REOPENED : (have_new ? M_NEW_MAIL : 0);
2063 * These functions try to find a message in a maildir folder when it
2064 * has moved under our feet. Note that this code is rather expensive, but
2065 * then again, it's called rarely.
2068 static FILE *_maildir_open_find_message (const char *folder, const char *unique,
2069 const char *subfolder)
2071 char dir[_POSIX_PATH_MAX];
2072 char tunique[_POSIX_PATH_MAX];
2073 char fname[_POSIX_PATH_MAX];
2081 snprintf (dir, sizeof (dir), "%s/%s", folder, subfolder);
2083 if ((dp = opendir (dir)) == NULL)
2089 while ((de = readdir (dp)))
2091 maildir_canon_filename (tunique, de->d_name, sizeof (tunique));
2093 if (!mutt_strcmp (tunique, unique))
2095 snprintf (fname, sizeof (fname), "%s/%s/%s", folder, subfolder,
2097 fp = fopen (fname, "r"); /* __FOPEN_CHECKED__ */
2109 FILE *maildir_open_find_message (const char *folder, const char *msg)
2111 char unique[_POSIX_PATH_MAX];
2114 static unsigned int new_hits = 0, cur_hits = 0; /* simple dynamic optimization */
2116 maildir_canon_filename (unique, msg, sizeof (unique));
2120 _maildir_open_find_message (folder, unique,
2121 new_hits > cur_hits ? "new" : "cur"))
2124 if (new_hits < UINT_MAX && cur_hits < UINT_MAX)
2126 new_hits += (new_hits > cur_hits ? 1 : 0);
2127 cur_hits += (new_hits > cur_hits ? 0 : 1);
2134 _maildir_open_find_message (folder, unique,
2135 new_hits > cur_hits ? "cur" : "new"))
2138 if (new_hits < UINT_MAX && cur_hits < UINT_MAX)
2140 new_hits += (new_hits > cur_hits ? 0 : 1);
2141 cur_hits += (new_hits > cur_hits ? 1 : 0);
2153 * 1 if there are no messages in the mailbox
2154 * 0 if there are messages in the mailbox
2157 int maildir_check_empty (const char *path)
2161 int r = 1; /* assume empty until we find a message */
2162 char realpath[_POSIX_PATH_MAX];
2165 /* Strategy here is to look for any file not beginning with a period */
2168 /* we do "cur" on the first iteration since its more likely that we'll
2169 * find old messages without having to scan both subdirs
2171 snprintf (realpath, sizeof (realpath), "%s/%s", path,
2172 iter == 0 ? "cur" : "new");
2173 if ((dp = opendir (realpath)) == NULL)
2175 while ((de = readdir (dp)))
2177 if (*de->d_name != '.')
2185 } while (r && iter < 2);
2192 * 1 if there are no messages in the mailbox
2193 * 0 if there are messages in the mailbox
2196 int mh_check_empty (const char *path)
2200 int r = 1; /* assume empty until we find a message */
2202 if ((dp = opendir (path)) == NULL)
2204 while ((de = readdir (dp)))
2206 if (mh_valid_message (de->d_name))