2 * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
3 * Copyright (C) 1999-2002 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., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
21 * This file contains routines specific to MH and ``maildir'' style
37 #include <sys/types.h>
53 unsigned header_parsed:1;
63 /* mh_sequences support */
65 #define MH_SEQ_UNSEEN (1 << 0)
66 #define MH_SEQ_REPLIED (1 << 1)
67 #define MH_SEQ_FLAGGED (1 << 2)
69 static void mhs_alloc (struct mh_sequences *mhs, int i)
74 if (i > mhs->max || !mhs->flags) {
76 safe_realloc (&mhs->flags, sizeof (mhs->flags[0]) * (newmax + 1));
77 for (j = mhs->max + 1; j <= newmax; j++)
84 static void mhs_free_sequences (struct mh_sequences *mhs)
89 static short mhs_check (struct mh_sequences *mhs, int i)
91 if (!mhs->flags || i > mhs->max)
97 static short mhs_set (struct mh_sequences *mhs, int i, short f)
101 return mhs->flags[i];
108 static short mhs_unset (struct mh_sequences *mhs, int i, short f)
112 return mhs->flags[i];
117 static void mh_read_token (char *t, int *first, int *last)
121 if ((p = strchr (t, '-'))) {
127 *first = *last = atoi (t);
130 static void mh_read_sequences (struct mh_sequences *mhs, const char *path)
141 char pathname[_POSIX_PATH_MAX];
143 snprintf (pathname, sizeof (pathname), "%s/.mh_sequences", path);
145 if (!(fp = fopen (pathname, "r")))
148 while ((buff = mutt_read_line (buff, &sz, fp, &line))) {
149 if (!(t = strtok (buff, " \t:")))
152 if (!mutt_strcmp (t, MhUnseen))
154 else if (!mutt_strcmp (t, MhFlagged))
156 else if (!mutt_strcmp (t, MhReplied))
158 else /* unknown sequence */
161 while ((t = strtok (NULL, " \t:"))) {
162 mh_read_token (t, &first, &last);
163 for (; first <= last; first++)
164 mhs_set (mhs, first, f);
172 int mh_buffy (const char *path)
175 struct mh_sequences mhs;
177 memset (&mhs, 0, sizeof (mhs));
179 mh_read_sequences (&mhs, path);
180 for (i = 0; !r && i <= mhs.max; i++)
181 if (mhs_check (&mhs, i) & MH_SEQ_UNSEEN)
183 mhs_free_sequences (&mhs);
187 static int mh_mkstemp (CONTEXT * dest, FILE ** fp, char **tgt)
190 char path[_POSIX_PATH_MAX];
193 snprintf (path, _POSIX_PATH_MAX, "%s/.mutt-%s-%d-%d",
194 dest->path, NONULL (Hostname), (int) getpid (), Counter++);
196 if ((fd = open (path, O_WRONLY | O_EXCL | O_CREAT, 0666)) == -1) {
197 if (errno != EEXIST) {
203 *tgt = safe_strdup (path);
208 if ((*fp = fdopen (fd, "w")) == NULL) {
218 static void mhs_write_one_sequence (FILE * fp, struct mh_sequences *mhs,
219 short f, const char *tag)
224 fprintf (fp, "%s:", tag);
229 for (i = 0; i <= mhs->max; i++) {
230 if ((mhs_check (mhs, i) & f)) {
236 else if (first >= 0) {
238 fprintf (fp, " %d", first);
240 fprintf (fp, " %d-%d", first, last);
249 fprintf (fp, " %d", first);
251 fprintf (fp, " %d-%d", first, last);
257 /* XXX - we don't currently remove deleted messages from sequences we don't know. Should we? */
259 void mh_update_sequences (CONTEXT * ctx)
263 char sequences[_POSIX_PATH_MAX];
275 char seq_unseen[STRING];
276 char seq_replied[STRING];
277 char seq_flagged[STRING];
280 struct mh_sequences mhs;
282 memset (&mhs, 0, sizeof (mhs));
284 snprintf (seq_unseen, sizeof (seq_unseen), "%s:", NONULL (MhUnseen));
285 snprintf (seq_replied, sizeof (seq_replied), "%s:", NONULL (MhReplied));
286 snprintf (seq_flagged, sizeof (seq_flagged), "%s:", NONULL (MhFlagged));
288 if (mh_mkstemp (ctx, &nfp, &tmpfname) != 0) {
293 snprintf (sequences, sizeof (sequences), "%s/.mh_sequences", ctx->path);
296 /* first, copy unknown sequences */
297 if ((ofp = fopen (sequences, "r"))) {
298 while ((buff = mutt_read_line (buff, &s, ofp, &l))) {
299 if (!mutt_strncmp (buff, seq_unseen, mutt_strlen (seq_unseen)))
301 if (!mutt_strncmp (buff, seq_flagged, mutt_strlen (seq_flagged)))
303 if (!mutt_strncmp (buff, seq_replied, mutt_strlen (seq_replied)))
306 fprintf (nfp, "%s\n", buff);
311 /* now, update our unseen, flagged, and replied sequences */
312 for (l = 0; l < ctx->msgcount; l++) {
313 if (ctx->hdrs[l]->deleted)
316 if ((p = strrchr (ctx->hdrs[l]->path, '/')))
319 p = ctx->hdrs[l]->path;
323 if (!ctx->hdrs[l]->read) {
324 mhs_set (&mhs, i, MH_SEQ_UNSEEN);
327 if (ctx->hdrs[l]->flagged) {
328 mhs_set (&mhs, i, MH_SEQ_FLAGGED);
331 if (ctx->hdrs[l]->replied) {
332 mhs_set (&mhs, i, MH_SEQ_REPLIED);
337 /* write out the new sequences */
339 mhs_write_one_sequence (nfp, &mhs, MH_SEQ_UNSEEN, NONULL (MhUnseen));
341 mhs_write_one_sequence (nfp, &mhs, MH_SEQ_FLAGGED, NONULL (MhFlagged));
343 mhs_write_one_sequence (nfp, &mhs, MH_SEQ_REPLIED, NONULL (MhReplied));
345 mhs_free_sequences (&mhs);
348 /* try to commit the changes - no guarantee here */
352 if (safe_rename (tmpfname, sequences) != 0) {
353 /* report an error? */
360 static void mh_sequences_add_one (CONTEXT * ctx, int n, short unseen,
361 short flagged, short replied)
363 short unseen_done = 0;
364 short flagged_done = 0;
365 short replied_done = 0;
367 FILE *ofp = NULL, *nfp = NULL;
370 char sequences[_POSIX_PATH_MAX];
372 char seq_unseen[STRING];
373 char seq_replied[STRING];
374 char seq_flagged[STRING];
380 if (mh_mkstemp (ctx, &nfp, &tmpfname) == -1)
383 snprintf (seq_unseen, sizeof (seq_unseen), "%s:", NONULL (MhUnseen));
384 snprintf (seq_replied, sizeof (seq_replied), "%s:", NONULL (MhReplied));
385 snprintf (seq_flagged, sizeof (seq_flagged), "%s:", NONULL (MhFlagged));
387 snprintf (sequences, sizeof (sequences), "%s/.mh_sequences", ctx->path);
388 if ((ofp = fopen (sequences, "r"))) {
389 while ((buff = mutt_read_line (buff, &sz, ofp, &line))) {
390 if (unseen && !strncmp (buff, seq_unseen, mutt_strlen (seq_unseen))) {
391 fprintf (nfp, "%s %d\n", buff, n);
395 && !strncmp (buff, seq_flagged, mutt_strlen (seq_flagged))) {
396 fprintf (nfp, "%s %d\n", buff, n);
400 && !strncmp (buff, seq_replied, mutt_strlen (seq_replied))) {
401 fprintf (nfp, "%s %d\n", buff, n);
405 fprintf (nfp, "%s\n", buff);
411 if (!unseen_done && unseen)
412 fprintf (nfp, "%s: %d\n", NONULL (MhUnseen), n);
413 if (!flagged_done && flagged)
414 fprintf (nfp, "%s: %d\n", NONULL (MhFlagged), n);
415 if (!replied_done && replied)
416 fprintf (nfp, "%s: %d\n", NONULL (MhReplied), n);
421 if (safe_rename (tmpfname, sequences) != 0)
427 static void mh_update_maildir (struct maildir *md, struct mh_sequences *mhs)
433 for (; md; md = md->next) {
434 if ((p = strrchr (md->h->path, '/')))
440 f = mhs_check (mhs, i);
442 md->h->read = (f & MH_SEQ_UNSEEN) ? 0 : 1;
443 md->h->flagged = (f & MH_SEQ_FLAGGED) ? 1 : 0;
444 md->h->replied = (f & MH_SEQ_REPLIED) ? 1 : 0;
448 /* maildir support */
450 static void maildir_free_entry (struct maildir **md)
455 FREE (&(*md)->canon_fname);
457 mutt_free_header (&(*md)->h);
462 static void maildir_free_maildir (struct maildir **md)
464 struct maildir *p, *q;
469 for (p = *md; p; p = q) {
471 maildir_free_entry (&p);
475 static void maildir_parse_flags (HEADER * h, const char *path)
483 if ((p = strrchr (path, ':')) != NULL && mutt_strncmp (p + 1, "2,", 2) == 0) {
486 mutt_str_replace (&h->maildir_flags, p);
487 q = h->maildir_flags;
501 case 'R': /* replied */
506 case 'T': /* trashed */
519 if (q == h->maildir_flags)
520 FREE (&h->maildir_flags);
525 static void maildir_update_mtime (CONTEXT * ctx)
527 char buf[_POSIX_PATH_MAX];
530 if (ctx->magic == M_MAILDIR) {
531 snprintf (buf, sizeof (buf), "%s/%s", ctx->path, "cur");
532 if (stat (buf, &st) == 0)
533 ctx->mtime_cur = st.st_mtime;
534 snprintf (buf, sizeof (buf), "%s/%s", ctx->path, "new");
537 snprintf (buf, sizeof (buf), "%s/.mh_sequences", ctx->path);
538 if (stat (buf, &st) == 0)
539 ctx->mtime_cur = st.st_mtime;
541 strfcpy (buf, ctx->path, sizeof (buf));
544 if (stat (buf, &st) == 0)
545 ctx->mtime = st.st_mtime;
549 * Actually parse a maildir message. This may also be used to fill
550 * out a fake header structure generated by lazy maildir parsing.
552 static HEADER *maildir_parse_message (int magic, const char *fname,
553 int is_old, HEADER * _h)
559 if ((f = fopen (fname, "r")) != NULL) {
561 h = mutt_new_header ();
562 h->env = mutt_read_rfc822_header (f, h, 0, 0);
564 fstat (fileno (f), &st);
568 h->received = h->date_sent;
570 if (h->content->length <= 0)
571 h->content->length = st.st_size - h->content->offset;
575 if (magic == M_MAILDIR) {
577 * maildir stores its flags in the filename, so ignore the
578 * flags in the header of the message
582 maildir_parse_flags (h, fname);
590 * Note that this routine will _not_ modify the context given by
593 * It's used in the first parsing pass on maildir and MH folders.
594 * In the MH case, this means full parsing of the folder. In the
595 * maildir case, it means that we only look at flags, and create a
596 * fake HEADER structure, which may later be filled in by
597 * maildir_parse_message(), when called from
598 * maildir_delayed_parsing().
602 static int maildir_parse_entry (CONTEXT * ctx, struct maildir ***last,
603 const char *subdir, const char *fname,
604 int *count, int is_old, ino_t inode)
606 struct maildir *entry;
608 char buf[_POSIX_PATH_MAX];
611 snprintf (buf, sizeof (buf), "%s/%s/%s", ctx->path, subdir, fname);
613 snprintf (buf, sizeof (buf), "%s/%s", ctx->path, fname);
615 if (ctx->magic == M_MH)
616 h = maildir_parse_message (ctx->magic, buf, is_old, NULL);
618 h = mutt_new_header ();
620 maildir_parse_flags (h, buf);
626 if (!ctx->quiet && ReadInc && ((*count % ReadInc) == 0 || *count == 1))
627 mutt_message (_("Reading %s... %d"), ctx->path, *count);
631 snprintf (buf, sizeof (buf), "%s/%s", subdir, fname);
632 h->path = safe_strdup (buf);
635 h->path = safe_strdup (fname);
637 entry = safe_calloc (sizeof (struct maildir), 1);
639 entry->header_parsed = (ctx->magic == M_MH);
640 entry->inode = inode;
642 *last = &entry->next;
652 /* Ignore the garbage files. A valid MH message consists of only
653 * digits. Deleted message get moved to a filename with a comma before
657 int mh_valid_message (const char *s)
660 if (!isdigit ((unsigned char) *s))
666 static int maildir_parse_dir (CONTEXT * ctx, struct maildir ***last,
667 const char *subdir, int *count)
671 char buf[_POSIX_PATH_MAX];
675 snprintf (buf, sizeof (buf), "%s/%s", ctx->path, subdir);
676 is_old = (mutt_strcmp ("cur", subdir) == 0);
679 strfcpy (buf, ctx->path, sizeof (buf));
681 if ((dirp = opendir (buf)) == NULL)
684 while ((de = readdir (dirp)) != NULL) {
686 if ((ctx->magic == M_MH && !mh_valid_message (de->d_name))
687 || (ctx->magic == M_MAILDIR && *de->d_name == '.'))
690 /* FOO - really ignore the return value? */
693 (debugfile, "%s:%d: parsing %s\n", __FILE__, __LINE__,
695 maildir_parse_entry (ctx, last, subdir, de->d_name, count, is_old,
703 static int maildir_add_to_context (CONTEXT * ctx, struct maildir *md)
705 int oldmsgcount = ctx->msgcount;
709 dprint (2, (debugfile, "%s:%d maildir_add_to_context(): Considering %s\n",
710 __FILE__, __LINE__, NONULL (md->canon_fname)));
715 "%s:%d Adding header structure. Flags: %s%s%s%s%s\n", __FILE__,
716 __LINE__, md->h->flagged ? "f" : "", md->h->deleted ? "D" : "",
717 md->h->replied ? "r" : "", md->h->old ? "O" : "",
718 md->h->read ? "R" : ""));
719 if (ctx->msgcount == ctx->hdrmax)
720 mx_alloc_memory (ctx);
722 ctx->hdrs[ctx->msgcount] = md->h;
723 ctx->hdrs[ctx->msgcount]->index = ctx->msgcount;
725 md->h->content->length + md->h->content->offset -
726 md->h->content->hdr_offset;
734 if (ctx->msgcount > oldmsgcount) {
735 mx_update_context (ctx, ctx->msgcount - oldmsgcount);
741 static int maildir_move_to_context (CONTEXT * ctx, struct maildir **md)
745 r = maildir_add_to_context (ctx, *md);
746 maildir_free_maildir (md);
751 * Merge two maildir lists according to the inode numbers.
753 static struct maildir *maildir_merge_inode (struct maildir *left,
754 struct maildir *right)
756 struct maildir *head;
757 struct maildir *tail;
760 if (left->inode < right->inode) {
778 while (left && right) {
779 if (left->inode < right->inode) {
801 * Sort maildir list according to inode.
803 static struct maildir *maildir_sort_inode (struct maildir *list)
805 struct maildir *left = list;
806 struct maildir *right = list;
808 if (!list || !list->next) {
813 while (list && list->next) {
815 list = list->next->next;
822 left = maildir_sort_inode (left);
823 right = maildir_sort_inode (right);
824 return maildir_merge_inode (left, right);
828 static size_t maildir_hcache_keylen (const char *fn)
830 const char *p = strchr (fn, ':');
832 return p ? (size_t) (p - fn) : mutt_strlen (fn);
837 * This function does the second parsing pass for a maildir-style
840 void maildir_delayed_parsing (CONTEXT * ctx, struct maildir *md)
843 char fn[_POSIX_PATH_MAX];
849 struct timeval *when = NULL;
850 struct stat lastchanged;
853 hc = mutt_hcache_open (HeaderCache, ctx->path);
856 for (p = md, count = 0; p; p = p->next, count++) {
857 if (!(p && p->h && !p->header_parsed))
861 data = mutt_hcache_fetch (hc, p->h->path + 3, &maildir_hcache_keylen);
862 when = (struct timeval *) data;
865 if (!ctx->quiet && ReadInc && ((count % ReadInc) == 0 || count == 1))
866 mutt_message (_("Reading %s... %d"), ctx->path, count);
867 snprintf (fn, sizeof (fn), "%s/%s", ctx->path, p->h->path);
870 if (option (OPTHCACHEVERIFY)) {
871 ret = stat (fn, &lastchanged);
874 lastchanged.st_mtime = 0;
878 if (data != NULL && !ret && lastchanged.st_mtime <= when->tv_sec) {
879 p->h = mutt_hcache_restore ((unsigned char *) data, &p->h);
880 maildir_parse_flags (p->h, fn);
884 if (maildir_parse_message (ctx->magic, fn, p->h->old, p->h)) {
885 p->header_parsed = 1;
886 maildir_parse_flags (p->h, fn);
888 mutt_hcache_store (hc, p->h->path + 3, p->h, 0, &maildir_hcache_keylen);
892 mutt_free_header (&p->h);
898 mutt_hcache_close (hc);
902 /* Read a MH/maildir style mailbox.
905 * ctx [IN/OUT] context for this mailbox
906 * subdir [IN] NULL for MH mailboxes, otherwise the subdir of the
907 * maildir mailbox to read from
909 int mh_read_dir (CONTEXT * ctx, const char *subdir)
912 struct mh_sequences mhs;
913 struct maildir **last;
917 memset (&mhs, 0, sizeof (mhs));
919 maildir_update_mtime (ctx);
924 if (maildir_parse_dir (ctx, &last, subdir, &count) == -1)
927 if (ctx->magic == M_MH) {
928 mh_read_sequences (&mhs, ctx->path);
929 mh_update_maildir (md, &mhs);
930 mhs_free_sequences (&mhs);
933 md = maildir_sort_inode (md);
935 if (ctx->magic == M_MAILDIR)
936 maildir_delayed_parsing (ctx, md);
938 maildir_move_to_context (ctx, &md);
942 /* read a maildir style mailbox */
943 int maildir_read_dir (CONTEXT * ctx)
945 /* maildir looks sort of like MH, except that there are two subdirectories
946 * of the main folder path from which to read messages
948 if (mh_read_dir (ctx, "new") == -1 || mh_read_dir (ctx, "cur") == -1)
955 * Open a new (temporary) message in an MH folder.
958 int mh_open_new_message (MESSAGE * msg, CONTEXT * dest, HEADER * hdr)
960 return mh_mkstemp (dest, &msg->fp, &msg->path);
963 int ch_compar (const void *a, const void *b)
965 return (int) (*((const char *) a) - *((const char *) b));
968 static void maildir_flags (char *dest, size_t destlen, HEADER * hdr)
973 * The maildir specification requires that all files in the cur
974 * subdirectory have the :unique string appeneded, regardless of whether
975 * or not there are any flags. If .old is set, we know that this message
976 * will end up in the cur directory, so we include it in the following
977 * test even though there is no associated flag.
981 && (hdr->flagged || hdr->replied || hdr->read || hdr->deleted
982 || hdr->old || hdr->maildir_flags)) {
983 char tmp[LONG_STRING];
985 snprintf (tmp, sizeof (tmp),
987 hdr->flagged ? "F" : "",
988 hdr->replied ? "R" : "",
989 hdr->read ? "S" : "", hdr->deleted ? "T" : "",
990 NONULL (hdr->maildir_flags));
991 if (hdr->maildir_flags)
992 qsort (tmp, strlen (tmp), 1, ch_compar);
993 snprintf (dest, destlen, ":2,%s", tmp);
999 * Open a new (temporary) message in a maildir folder.
1001 * Note that this uses _almost_ the maildir file name format, but
1002 * with a {cur,new} prefix.
1006 int maildir_open_new_message (MESSAGE * msg, CONTEXT * dest, HEADER * hdr)
1009 char path[_POSIX_PATH_MAX];
1014 short deleted = hdr->deleted;
1018 maildir_flags (suffix, sizeof (suffix), hdr);
1020 hdr->deleted = deleted;
1025 if (hdr && (hdr->read || hdr->old))
1026 strfcpy (subdir, "cur", sizeof (subdir));
1028 strfcpy (subdir, "new", sizeof (subdir));
1031 snprintf (path, _POSIX_PATH_MAX, "%s/tmp/%s.%ld.%u_%d.%s%s",
1032 dest->path, subdir, (long) time (NULL),
1033 (unsigned int) getpid (), Counter++, NONULL (Hostname), suffix);
1035 dprint (2, (debugfile, "maildir_open_new_message (): Trying %s.\n",
1039 if ((fd = open (path, O_WRONLY | O_EXCL | O_CREAT, 0666)) == -1) {
1040 if (errno != EEXIST) {
1046 dprint (2, (debugfile, "maildir_open_new_message (): Success.\n"));
1047 msg->path = safe_strdup (path);
1052 if ((msg->fp = fdopen (fd, "w")) == NULL) {
1065 * Commit a message to a maildir folder.
1067 * msg->path contains the file name of a file in tmp/. We take the
1068 * flags from this file's name.
1070 * ctx is the mail folder we commit to.
1072 * hdr is a header structure to which we write the message's new
1073 * file name. This is used in the mh and maildir folder synch
1074 * routines. When this routine is invoked from mx_commit_message,
1077 * msg->path looks like this:
1079 * tmp/{cur,new}.mutt-HOSTNAME-PID-COUNTER:flags
1081 * See also maildir_open_new_message().
1085 int maildir_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr)
1089 char path[_POSIX_PATH_MAX];
1090 char full[_POSIX_PATH_MAX];
1093 if (safe_fclose (&msg->fp) != 0)
1096 /* extract the subdir */
1097 s = strrchr (msg->path, '/') + 1;
1098 strfcpy (subdir, s, 4);
1100 /* extract the flags */
1101 if ((s = strchr (s, ':')))
1102 strfcpy (suffix, s, sizeof (suffix));
1106 /* construct a new file name. */
1108 snprintf (path, _POSIX_PATH_MAX, "%s/%ld.%u_%d.%s%s", subdir,
1109 (long) time (NULL), (unsigned int) getpid (), Counter++,
1110 NONULL (Hostname), suffix);
1111 snprintf (full, _POSIX_PATH_MAX, "%s/%s", ctx->path, path);
1113 dprint (2, (debugfile, "maildir_commit_message (): renaming %s to %s.\n",
1116 if (safe_rename (msg->path, full) == 0) {
1118 mutt_str_replace (&hdr->path, path);
1122 * Adjust the mtime on the file to match the time at which this
1123 * message was received. Currently this is only set when copying
1124 * messages between mailboxes, so we test to ensure that it is
1127 if (msg->received) {
1130 ut.actime = msg->received;
1131 ut.modtime = msg->received;
1132 if (utime (full, &ut)) {
1134 ("maildir_commit_message(): unable to set time on file"));
1141 else if (errno != EEXIST) {
1142 mutt_perror (ctx->path);
1149 * commit a message to an MH folder.
1154 static int _mh_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr,
1160 unsigned int n, hi = 0;
1161 char path[_POSIX_PATH_MAX];
1164 if (safe_fclose (&msg->fp) != 0)
1167 if ((dirp = opendir (ctx->path)) == NULL) {
1168 mutt_perror (ctx->path);
1172 /* figure out what the next message number is */
1173 while ((de = readdir (dirp)) != NULL) {
1179 if (!isdigit ((unsigned char) *cp))
1192 * Now try to rename the file to the proper name.
1194 * Note: We may have to try multiple times, until we find a free
1200 snprintf (tmp, sizeof (tmp), "%d", hi);
1201 snprintf (path, sizeof (path), "%s/%s", ctx->path, tmp);
1202 if (safe_rename (msg->path, path) == 0) {
1204 mutt_str_replace (&hdr->path, tmp);
1208 else if (errno != EEXIST) {
1209 mutt_perror (ctx->path);
1214 mh_sequences_add_one (ctx, hi, !msg->flags.read, msg->flags.flagged,
1215 msg->flags.replied);
1219 int mh_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr)
1221 return _mh_commit_message (ctx, msg, hdr, 1);
1225 /* Sync a message in an MH folder.
1227 * This code is also used for attachment deletion in maildir
1231 static int mh_rewrite_message (CONTEXT * ctx, int msgno)
1233 HEADER *h = ctx->hdrs[msgno];
1238 char oldpath[_POSIX_PATH_MAX];
1239 char newpath[_POSIX_PATH_MAX];
1240 char partpath[_POSIX_PATH_MAX];
1242 long old_body_offset = h->content->offset;
1243 long old_body_length = h->content->length;
1244 long old_hdr_lines = h->lines;
1246 if ((dest = mx_open_new_message (ctx, h, 0)) == NULL)
1249 if ((rc = mutt_copy_message (dest->fp, ctx, h,
1250 M_CM_UPDATE, CH_UPDATE | CH_UPDATE_LEN)) == 0)
1252 snprintf (oldpath, _POSIX_PATH_MAX, "%s/%s", ctx->path, h->path);
1253 strfcpy (partpath, h->path, _POSIX_PATH_MAX);
1255 if (ctx->magic == M_MAILDIR)
1256 rc = maildir_commit_message (ctx, dest, h);
1258 rc = _mh_commit_message (ctx, dest, h, 0);
1260 mx_close_message (&dest);
1268 * Try to move the new message to the old place.
1271 * This is important when we are just updating flags.
1273 * Note that there is a race condition against programs which
1274 * use the first free slot instead of the maximum message
1275 * number. Mutt does _not_ behave like this.
1277 * Anyway, if this fails, the message is in the folder, so
1278 * all what happens is that a concurrently runnung mutt will
1279 * lose flag modifications.
1282 if (ctx->magic == M_MH && rc == 0) {
1283 snprintf (newpath, _POSIX_PATH_MAX, "%s/%s", ctx->path, h->path);
1284 if ((rc = safe_rename (newpath, oldpath)) == 0)
1285 mutt_str_replace (&h->path, partpath);
1289 mx_close_message (&dest);
1291 if (rc == -1 && restore) {
1292 h->content->offset = old_body_offset;
1293 h->content->length = old_body_length;
1294 h->lines = old_hdr_lines;
1297 mutt_free_body (&h->content->parts);
1301 static int mh_sync_message (CONTEXT * ctx, int msgno)
1303 HEADER *h = ctx->hdrs[msgno];
1305 if (h->attach_del || h->refs_changed || h->irt_changed)
1306 if (mh_rewrite_message (ctx, msgno) != 0)
1312 static int maildir_sync_message (CONTEXT * ctx, int msgno)
1314 HEADER *h = ctx->hdrs[msgno];
1316 if (h->attach_del || h->refs_changed || h->irt_changed) {
1317 /* when doing attachment deletion/rethreading, fall back to the MH case. */
1318 if (mh_rewrite_message (ctx, msgno) != 0)
1322 /* we just have to rename the file. */
1324 char newpath[_POSIX_PATH_MAX];
1325 char partpath[_POSIX_PATH_MAX];
1326 char fullpath[_POSIX_PATH_MAX];
1327 char oldpath[_POSIX_PATH_MAX];
1331 if ((p = strrchr (h->path, '/')) == NULL) {
1334 "maildir_sync_message: %s: unable to find subdir!\n",
1339 strfcpy (newpath, p, sizeof (newpath));
1341 /* kill the previous flags */
1342 if ((p = strchr (newpath, ':')) != NULL)
1345 maildir_flags (suffix, sizeof (suffix), h);
1347 snprintf (partpath, sizeof (partpath), "%s/%s%s",
1348 (h->read || h->old) ? "cur" : "new", newpath, suffix);
1349 snprintf (fullpath, sizeof (fullpath), "%s/%s", ctx->path, partpath);
1350 snprintf (oldpath, sizeof (oldpath), "%s/%s", ctx->path, h->path);
1352 if (mutt_strcmp (fullpath, oldpath) == 0) {
1353 /* message hasn't really changed */
1357 /* record that the message is possibly marked as trashed on disk */
1358 h->trash = h->deleted;
1360 if (rename (oldpath, fullpath) != 0) {
1361 mutt_perror ("rename");
1364 mutt_str_replace (&h->path, partpath);
1369 int mh_sync_mailbox (CONTEXT * ctx, int *index_hint)
1371 char path[_POSIX_PATH_MAX], tmp[_POSIX_PATH_MAX];
1376 #endif /* USE_HCACHE */
1378 if (ctx->magic == M_MH)
1379 i = mh_check_mailbox (ctx, index_hint);
1381 i = maildir_check_mailbox (ctx, index_hint);
1387 if (ctx->magic == M_MAILDIR)
1388 hc = mutt_hcache_open (HeaderCache, ctx->path);
1389 #endif /* USE_HCACHE */
1391 for (i = 0; i < ctx->msgcount; i++) {
1392 if (ctx->hdrs[i]->deleted
1393 && (ctx->magic != M_MAILDIR || !option (OPTMAILDIRTRASH))) {
1394 snprintf (path, sizeof (path), "%s/%s", ctx->path, ctx->hdrs[i]->path);
1395 if (ctx->magic == M_MAILDIR
1396 || (option (OPTMHPURGE) && ctx->magic == M_MH)) {
1398 if (ctx->magic == M_MAILDIR)
1399 mutt_hcache_delete (hc, ctx->hdrs[i]->path + 3,
1400 &maildir_hcache_keylen);
1401 #endif /* USE_HCACHE */
1404 else if (ctx->magic == M_MH) {
1405 /* MH just moves files out of the way when you delete them */
1406 if (*ctx->hdrs[i]->path != ',') {
1407 snprintf (tmp, sizeof (tmp), "%s/,%s", ctx->path,
1408 ctx->hdrs[i]->path);
1415 else if (ctx->hdrs[i]->changed || ctx->hdrs[i]->attach_del ||
1416 (ctx->magic == M_MAILDIR
1417 && (option (OPTMAILDIRTRASH) || ctx->hdrs[i]->trash)
1418 && (ctx->hdrs[i]->deleted != ctx->hdrs[i]->trash))) {
1419 if (ctx->magic == M_MAILDIR) {
1420 if (maildir_sync_message (ctx, i) == -1)
1424 if (mh_sync_message (ctx, i) == -1)
1431 if (ctx->magic == M_MAILDIR)
1432 mutt_hcache_close (hc);
1433 #endif /* USE_HCACHE */
1435 if (ctx->magic == M_MH)
1436 mh_update_sequences (ctx);
1438 /* XXX race condition? */
1440 maildir_update_mtime (ctx);
1442 /* adjust indices */
1445 for (i = 0, j = 0; i < ctx->msgcount; i++) {
1446 if (!ctx->hdrs[i]->deleted
1447 || (ctx->magic == M_MAILDIR && option (OPTMAILDIRTRASH)))
1448 ctx->hdrs[i]->index = j++;
1456 if (ctx->magic == M_MAILDIR)
1457 mutt_hcache_close (hc);
1458 #endif /* USE_HCACHE */
1462 static char *maildir_canon_filename (char *dest, const char *src, size_t l)
1466 if ((t = strrchr (src, '/')))
1469 strfcpy (dest, src, l);
1470 if ((u = strrchr (dest, ':')))
1476 static void maildir_update_tables (CONTEXT * ctx, int *index_hint)
1482 if (Sort != SORT_ORDER) {
1485 mutt_sort_headers (ctx, 1);
1489 old_count = ctx->msgcount;
1490 for (i = 0, j = 0; i < old_count; i++) {
1491 if (ctx->hdrs[i]->active && index_hint && *index_hint == i)
1494 if (ctx->hdrs[i]->active)
1495 ctx->hdrs[i]->index = j++;
1498 mx_update_tables (ctx, 0);
1499 mutt_clear_threads (ctx);
1502 static void maildir_update_flags (CONTEXT * ctx, HEADER * o, HEADER * n)
1504 /* save the global state here so we can reset it at the
1505 * end of list block if required.
1507 int context_changed = ctx->changed;
1509 /* user didn't modify this message. alter the flags to
1510 * match the current state on disk. This may not actually
1511 * do anything, but we can't tell right now. mutt_set_flag()
1512 * will just ignore the call if the status bits are
1513 * already properly set.
1515 mutt_set_flag (ctx, o, M_FLAG, n->flagged);
1516 mutt_set_flag (ctx, o, M_REPLIED, n->replied);
1517 mutt_set_flag (ctx, o, M_READ, n->read);
1518 mutt_set_flag (ctx, o, M_OLD, n->old);
1520 /* mutt_set_flag() will set this, but we don't need to
1521 * sync the changes we made because we just updated the
1522 * context to match the current on-disk state of the
1527 /* if the mailbox was not modified before we made these
1528 * changes, unset the changed flag since nothing needs to
1531 if (!context_changed)
1536 /* This function handles arrival of new mail and reopening of
1537 * maildir folders. The basic idea here is we check to see if either
1538 * the new or cur subdirectories have changed, and if so, we scan them
1539 * for the list of files. We check for newly added messages, and
1540 * then merge the flags messages we already knew about. We don't treat
1541 * either subdirectory differently, as mail could be copied directly into
1542 * the cur directory from another agent.
1544 int maildir_check_mailbox (CONTEXT * ctx, int *index_hint)
1546 struct stat st_new; /* status of the "new" subdirectory */
1547 struct stat st_cur; /* status of the "cur" subdirectory */
1548 char buf[_POSIX_PATH_MAX];
1549 int changed = 0; /* bitmask representing which subdirectories
1550 have changed. 0x1 = new, 0x2 = cur */
1551 int occult = 0; /* messages were removed from the mailbox */
1552 int have_new = 0; /* messages were added to the mailbox */
1553 struct maildir *md; /* list of messages in the mailbox */
1554 struct maildir **last, *p;
1556 HASH *fnames; /* hash table for quickly looking up the base filename
1557 for a maildir message */
1559 /* XXX seems like this check belongs in mx_check_mailbox()
1562 if (!option (OPTCHECKNEW))
1565 snprintf (buf, sizeof (buf), "%s/new", ctx->path);
1566 if (stat (buf, &st_new) == -1)
1569 snprintf (buf, sizeof (buf), "%s/cur", ctx->path);
1570 if (stat (buf, &st_cur) == -1)
1573 /* determine which subdirectories need to be scanned */
1574 if (st_new.st_mtime > ctx->mtime)
1576 if (st_cur.st_mtime > ctx->mtime_cur)
1580 return 0; /* nothing to do */
1582 /* update the modification times on the mailbox */
1583 ctx->mtime_cur = st_cur.st_mtime;
1584 ctx->mtime = st_new.st_mtime;
1586 /* do a fast scan of just the filenames in
1587 * the subdirectories that have changed.
1592 maildir_parse_dir (ctx, &last, "new", NULL);
1594 maildir_parse_dir (ctx, &last, "cur", NULL);
1596 /* we create a hash table keyed off the canonical (sans flags) filename
1597 * of each message we scanned. This is used in the loop over the
1598 * existing messages below to do some correlation.
1600 fnames = hash_create (1031);
1602 for (p = md; p; p = p->next) {
1603 maildir_canon_filename (buf, p->h->path, sizeof (buf));
1604 p->canon_fname = safe_strdup (buf);
1605 hash_insert (fnames, p->canon_fname, p, 0);
1608 /* check for modifications and adjust flags */
1609 for (i = 0; i < ctx->msgcount; i++) {
1610 ctx->hdrs[i]->active = 0;
1611 maildir_canon_filename (buf, ctx->hdrs[i]->path, sizeof (buf));
1612 p = hash_find (fnames, buf);
1614 /* message already exists, merge flags */
1615 ctx->hdrs[i]->active = 1;
1617 /* check to see if the message has moved to a different
1618 * subdirectory. If so, update the associated filename.
1620 if (mutt_strcmp (ctx->hdrs[i]->path, p->h->path))
1621 mutt_str_replace (&ctx->hdrs[i]->path, p->h->path);
1623 /* if the user hasn't modified the flags on this message, update
1624 * the flags we just detected.
1626 if (!ctx->hdrs[i]->changed)
1627 maildir_update_flags (ctx, ctx->hdrs[i], p->h);
1629 if (ctx->hdrs[i]->deleted == ctx->hdrs[i]->trash)
1630 ctx->hdrs[i]->deleted = p->h->deleted;
1631 ctx->hdrs[i]->trash = p->h->trash;
1633 /* this is a duplicate of an existing header, so remove it */
1634 mutt_free_header (&p->h);
1636 /* This message was not in the list of messages we just scanned.
1637 * Check to see if we have enough information to know if the
1638 * message has disappeared out from underneath us.
1640 else if (((changed & 1) && (!strncmp (ctx->hdrs[i]->path, "new/", 4))) ||
1641 ((changed & 2) && (!strncmp (ctx->hdrs[i]->path, "cur/", 4)))) {
1642 /* This message disappeared, so we need to simulate a "reopen"
1643 * event. We know it disappeared because we just scanned the
1644 * subdirectory it used to reside in.
1649 /* This message resides in a subdirectory which was not
1650 * modified, so we assume that it is still present and
1653 ctx->hdrs[i]->active = 1;
1657 /* destroy the file name hash */
1658 hash_destroy (&fnames, NULL);
1660 /* If we didn't just get new mail, update the tables. */
1662 maildir_update_tables (ctx, index_hint);
1664 /* do any delayed parsing we need to do. */
1665 maildir_delayed_parsing (ctx, md);
1667 /* Incorporate new messages */
1668 have_new = maildir_move_to_context (ctx, &md);
1670 return occult ? M_REOPENED : (have_new ? M_NEW_MAIL : 0);
1674 * This function handles arrival of new mail and reopening of
1675 * mh/maildir folders. Things are getting rather complex because we
1676 * don't have a well-defined "mailbox order", so the tricks from
1677 * mbox.c and mx.c won't work here.
1679 * Don't change this code unless you _really_ understand what
1684 int mh_check_mailbox (CONTEXT * ctx, int *index_hint)
1686 char buf[_POSIX_PATH_MAX];
1687 struct stat st, st_cur;
1688 short modified = 0, have_new = 0, occult = 0;
1689 struct maildir *md, *p;
1690 struct maildir **last = NULL;
1691 struct mh_sequences mhs;
1695 if (!option (OPTCHECKNEW))
1698 strfcpy (buf, ctx->path, sizeof (buf));
1699 if (stat (buf, &st) == -1)
1702 /* create .mh_sequences when there isn't one. */
1703 snprintf (buf, sizeof (buf), "%s/.mh_sequences", ctx->path);
1704 if ((i = stat (buf, &st_cur) == -1) && errno == ENOENT) {
1708 if (mh_mkstemp (ctx, &fp, &tmp) == 0) {
1710 if (safe_rename (tmp, buf) == -1)
1716 if (i == -1 && stat (buf, &st_cur) == -1)
1719 if (st.st_mtime > ctx->mtime || st_cur.st_mtime > ctx->mtime_cur)
1725 ctx->mtime_cur = st_cur.st_mtime;
1726 ctx->mtime = st.st_mtime;
1728 memset (&mhs, 0, sizeof (mhs));
1732 maildir_parse_dir (ctx, &last, NULL, NULL);
1733 mh_read_sequences (&mhs, ctx->path);
1734 mh_update_maildir (md, &mhs);
1735 mhs_free_sequences (&mhs);
1737 /* check for modifications and adjust flags */
1738 fnames = hash_create (1031);
1740 for (p = md; p; p = p->next)
1741 hash_insert (fnames, p->h->path, p, 0);
1743 for (i = 0; i < ctx->msgcount; i++) {
1744 ctx->hdrs[i]->active = 0;
1746 if ((p = hash_find (fnames, ctx->hdrs[i]->path)) && p->h &&
1747 (mbox_strict_cmp_headers (ctx->hdrs[i], p->h))) {
1748 ctx->hdrs[i]->active = 1;
1749 /* found the right message */
1750 if (!ctx->hdrs[i]->changed)
1751 maildir_update_flags (ctx, ctx->hdrs[i], p->h);
1753 mutt_free_header (&p->h);
1755 else /* message has disappeared */
1759 /* destroy the file name hash */
1761 hash_destroy (&fnames, NULL);
1763 /* If we didn't just get new mail, update the tables. */
1765 maildir_update_tables (ctx, index_hint);
1767 /* Incorporate new messages */
1768 have_new = maildir_move_to_context (ctx, &md);
1770 return occult ? M_REOPENED : (have_new ? M_NEW_MAIL : 0);
1777 * These functions try to find a message in a maildir folder when it
1778 * has moved under our feet. Note that this code is rather expensive, but
1779 * then again, it's called rarely.
1782 FILE *_maildir_open_find_message (const char *folder, const char *unique,
1783 const char *subfolder)
1785 char dir[_POSIX_PATH_MAX];
1786 char tunique[_POSIX_PATH_MAX];
1787 char fname[_POSIX_PATH_MAX];
1795 snprintf (dir, sizeof (dir), "%s/%s", folder, subfolder);
1797 if ((dp = opendir (dir)) == NULL) {
1802 while ((de = readdir (dp))) {
1803 maildir_canon_filename (tunique, de->d_name, sizeof (tunique));
1805 if (!mutt_strcmp (tunique, unique)) {
1806 snprintf (fname, sizeof (fname), "%s/%s/%s", folder, subfolder,
1808 fp = fopen (fname, "r"); /* __FOPEN_CHECKED__ */
1820 FILE *maildir_open_find_message (const char *folder, const char *msg)
1822 char unique[_POSIX_PATH_MAX];
1825 static unsigned int new_hits = 0, cur_hits = 0; /* simple dynamic optimization */
1827 maildir_canon_filename (unique, msg, sizeof (unique));
1830 _maildir_open_find_message (folder, unique,
1831 new_hits > cur_hits ? "new" : "cur"))
1832 || errno != ENOENT) {
1833 if (new_hits < UINT_MAX && cur_hits < UINT_MAX) {
1834 new_hits += (new_hits > cur_hits ? 1 : 0);
1835 cur_hits += (new_hits > cur_hits ? 0 : 1);
1841 _maildir_open_find_message (folder, unique,
1842 new_hits > cur_hits ? "cur" : "new"))
1843 || errno != ENOENT) {
1844 if (new_hits < UINT_MAX && cur_hits < UINT_MAX) {
1845 new_hits += (new_hits > cur_hits ? 0 : 1);
1846 cur_hits += (new_hits > cur_hits ? 1 : 0);
1858 * 1 if there are no messages in the mailbox
1859 * 0 if there are messages in the mailbox
1862 int maildir_check_empty (const char *path)
1866 int r = 1; /* assume empty until we find a message */
1867 char realpath[_POSIX_PATH_MAX];
1870 /* Strategy here is to look for any file not beginning with a period */
1873 /* we do "cur" on the first iteration since its more likely that we'll
1874 * find old messages without having to scan both subdirs
1876 snprintf (realpath, sizeof (realpath), "%s/%s", path,
1877 iter == 0 ? "cur" : "new");
1878 if ((dp = opendir (realpath)) == NULL)
1880 while ((de = readdir (dp))) {
1881 if (*de->d_name != '.') {
1888 } while (r && iter < 2);
1895 * 1 if there are no messages in the mailbox
1896 * 0 if there are messages in the mailbox
1899 int mh_check_empty (const char *path)
1903 int r = 1; /* assume empty until we find a message */
1905 if ((dp = opendir (path)) == NULL)
1907 while ((de = readdir (dp))) {
1908 if (mh_valid_message (de->d_name)) {