cbc7b8b62f75a6a43b7ddfc62dea1054611cbaba
[apps/madmutt.git] / mh.c
1 /*
2  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
3  * Copyright (C) 1999-2002 Thomas Roessler <roessler@does-not-exist.org>
4  * 
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.
9  * 
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.
14  * 
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.
18  */
19
20 /*
21  * This file contains routines specific to MH and ``maildir'' style
22  * mailboxes.
23  */
24
25 #if HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include "mutt.h"
30 #include "mailbox.h"
31 #include "mx.h"
32 #include "copy.h"
33 #include "buffy.h"
34 #include "sort.h"
35
36 #include <sys/stat.h>
37 #include <sys/types.h>
38 #include <dirent.h>
39 #include <limits.h>
40 #include <unistd.h>
41 #include <fcntl.h>
42
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <ctype.h>
46 #include <errno.h>
47 #include <string.h>
48 #include <utime.h>
49
50 struct maildir {
51   HEADER *h;
52   char *canon_fname;
53   unsigned header_parsed:1;
54   ino_t inode;
55   struct maildir *next;
56 };
57
58 struct mh_sequences {
59   int max;
60   short *flags;
61 };
62
63 /* mh_sequences support */
64
65 #define MH_SEQ_UNSEEN  (1 << 0)
66 #define MH_SEQ_REPLIED (1 << 1)
67 #define MH_SEQ_FLAGGED (1 << 2)
68
69 static void mhs_alloc (struct mh_sequences *mhs, int i)
70 {
71   int j;
72   int newmax;
73
74   if (i > mhs->max || !mhs->flags) {
75     newmax = i + 128;
76     safe_realloc (&mhs->flags, sizeof (mhs->flags[0]) * (newmax + 1));
77     for (j = mhs->max + 1; j <= newmax; j++)
78       mhs->flags[j] = 0;
79
80     mhs->max = newmax;
81   }
82 }
83
84 static void mhs_free_sequences (struct mh_sequences *mhs)
85 {
86   FREE (&mhs->flags);
87 }
88
89 static short mhs_check (struct mh_sequences *mhs, int i)
90 {
91   if (!mhs->flags || i > mhs->max)
92     return 0;
93   else
94     return mhs->flags[i];
95 }
96
97 static short mhs_set (struct mh_sequences *mhs, int i, short f)
98 {
99   mhs_alloc (mhs, i);
100   mhs->flags[i] |= f;
101   return mhs->flags[i];
102 }
103
104 #if 0
105
106 /* unused */
107
108 static short mhs_unset (struct mh_sequences *mhs, int i, short f)
109 {
110   mhs_alloc (mhs, i);
111   mhs->flags[i] &= ~f;
112   return mhs->flags[i];
113 }
114
115 #endif
116
117 static void mh_read_token (char *t, int *first, int *last)
118 {
119   char *p;
120
121   if ((p = strchr (t, '-'))) {
122     *p++ = '\0';
123     *first = atoi (t);
124     *last = atoi (p);
125   }
126   else
127     *first = *last = atoi (t);
128 }
129
130 static void mh_read_sequences (struct mh_sequences *mhs, const char *path)
131 {
132   FILE *fp;
133   int line = 1;
134   char *buff = NULL;
135   char *t;
136   size_t sz = 0;
137
138   short f;
139   int first, last;
140
141   char pathname[_POSIX_PATH_MAX];
142
143   snprintf (pathname, sizeof (pathname), "%s/.mh_sequences", path);
144
145   if (!(fp = fopen (pathname, "r")))
146     return;
147
148   while ((buff = mutt_read_line (buff, &sz, fp, &line))) {
149     if (!(t = strtok (buff, " \t:")))
150       continue;
151
152     if (!mutt_strcmp (t, MhUnseen))
153       f = MH_SEQ_UNSEEN;
154     else if (!mutt_strcmp (t, MhFlagged))
155       f = MH_SEQ_FLAGGED;
156     else if (!mutt_strcmp (t, MhReplied))
157       f = MH_SEQ_REPLIED;
158     else                        /* unknown sequence */
159       continue;
160
161     while ((t = strtok (NULL, " \t:"))) {
162       mh_read_token (t, &first, &last);
163       for (; first <= last; first++)
164         mhs_set (mhs, first, f);
165     }
166   }
167
168   FREE (&buff);
169   safe_fclose (&fp);
170 }
171
172 int mh_buffy (const char *path)
173 {
174   int i, r = 0;
175   struct mh_sequences mhs;
176
177   memset (&mhs, 0, sizeof (mhs));
178
179   mh_read_sequences (&mhs, path);
180   for (i = 0; !r && i <= mhs.max; i++)
181     if (mhs_check (&mhs, i) & MH_SEQ_UNSEEN)
182       r = 1;
183   mhs_free_sequences (&mhs);
184   return r;
185 }
186
187 static int mh_mkstemp (CONTEXT * dest, FILE ** fp, char **tgt)
188 {
189   int fd;
190   char path[_POSIX_PATH_MAX];
191
192   FOREVER {
193     snprintf (path, _POSIX_PATH_MAX, "%s/.mutt-%s-%d-%d",
194               dest->path, NONULL (Hostname), (int) getpid (), Counter++);
195     umask (Umask);
196     if ((fd = open (path, O_WRONLY | O_EXCL | O_CREAT, 0666)) == -1) {
197       if (errno != EEXIST) {
198         mutt_perror (path);
199         return -1;
200       }
201     }
202     else {
203       *tgt = safe_strdup (path);
204       break;
205     }
206   }
207
208   if ((*fp = fdopen (fd, "w")) == NULL) {
209     FREE (tgt);
210     close (fd);
211     unlink (path);
212     return (-1);
213   }
214
215   return 0;
216 }
217
218 static void mhs_write_one_sequence (FILE * fp, struct mh_sequences *mhs,
219                                     short f, const char *tag)
220 {
221   int i;
222   int first, last;
223
224   fprintf (fp, "%s:", tag);
225
226   first = -1;
227   last = -1;
228
229   for (i = 0; i <= mhs->max; i++) {
230     if ((mhs_check (mhs, i) & f)) {
231       if (first < 0)
232         first = i;
233       else
234         last = i;
235     }
236     else if (first >= 0) {
237       if (last < 0)
238         fprintf (fp, " %d", first);
239       else
240         fprintf (fp, " %d-%d", first, last);
241
242       first = -1;
243       last = -1;
244     }
245   }
246
247   if (first >= 0) {
248     if (last < 0)
249       fprintf (fp, " %d", first);
250     else
251       fprintf (fp, " %d-%d", first, last);
252   }
253
254   fputc ('\n', fp);
255 }
256
257 /* XXX - we don't currently remove deleted messages from sequences we don't know.  Should we? */
258
259 void mh_update_sequences (CONTEXT * ctx)
260 {
261   FILE *ofp, *nfp;
262
263   char sequences[_POSIX_PATH_MAX];
264   char *tmpfname;
265   char *buff = NULL;
266   char *p;
267   size_t s;
268   int l = 0;
269   int i;
270
271   int unseen = 0;
272   int flagged = 0;
273   int replied = 0;
274
275   char seq_unseen[STRING];
276   char seq_replied[STRING];
277   char seq_flagged[STRING];
278
279
280   struct mh_sequences mhs;
281
282   memset (&mhs, 0, sizeof (mhs));
283
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));
287
288   if (mh_mkstemp (ctx, &nfp, &tmpfname) != 0) {
289     /* error message? */
290     return;
291   }
292
293   snprintf (sequences, sizeof (sequences), "%s/.mh_sequences", ctx->path);
294
295
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)))
300         continue;
301       if (!mutt_strncmp (buff, seq_flagged, mutt_strlen (seq_flagged)))
302         continue;
303       if (!mutt_strncmp (buff, seq_replied, mutt_strlen (seq_replied)))
304         continue;
305
306       fprintf (nfp, "%s\n", buff);
307     }
308   }
309   safe_fclose (&ofp);
310
311   /* now, update our unseen, flagged, and replied sequences */
312   for (l = 0; l < ctx->msgcount; l++) {
313     if (ctx->hdrs[l]->deleted)
314       continue;
315
316     if ((p = strrchr (ctx->hdrs[l]->path, '/')))
317       p++;
318     else
319       p = ctx->hdrs[l]->path;
320
321     i = atoi (p);
322
323     if (!ctx->hdrs[l]->read) {
324       mhs_set (&mhs, i, MH_SEQ_UNSEEN);
325       unseen++;
326     }
327     if (ctx->hdrs[l]->flagged) {
328       mhs_set (&mhs, i, MH_SEQ_FLAGGED);
329       flagged++;
330     }
331     if (ctx->hdrs[l]->replied) {
332       mhs_set (&mhs, i, MH_SEQ_REPLIED);
333       replied++;
334     }
335   }
336
337   /* write out the new sequences */
338   if (unseen)
339     mhs_write_one_sequence (nfp, &mhs, MH_SEQ_UNSEEN, NONULL (MhUnseen));
340   if (flagged)
341     mhs_write_one_sequence (nfp, &mhs, MH_SEQ_FLAGGED, NONULL (MhFlagged));
342   if (replied)
343     mhs_write_one_sequence (nfp, &mhs, MH_SEQ_REPLIED, NONULL (MhReplied));
344
345   mhs_free_sequences (&mhs);
346
347
348   /* try to commit the changes - no guarantee here */
349   safe_fclose (&nfp);
350
351   unlink (sequences);
352   if (safe_rename (tmpfname, sequences) != 0) {
353     /* report an error? */
354     unlink (tmpfname);
355   }
356
357   FREE (&tmpfname);
358 }
359
360 static void mh_sequences_add_one (CONTEXT * ctx, int n, short unseen,
361                                   short flagged, short replied)
362 {
363   short unseen_done = 0;
364   short flagged_done = 0;
365   short replied_done = 0;
366
367   FILE *ofp = NULL, *nfp = NULL;
368
369   char *tmpfname;
370   char sequences[_POSIX_PATH_MAX];
371
372   char seq_unseen[STRING];
373   char seq_replied[STRING];
374   char seq_flagged[STRING];
375
376   char *buff = NULL;
377   int line;
378   size_t sz;
379
380   if (mh_mkstemp (ctx, &nfp, &tmpfname) == -1)
381     return;
382
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));
386
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);
392         unseen_done = 1;
393       }
394       else if (flagged
395                && !strncmp (buff, seq_flagged, mutt_strlen (seq_flagged))) {
396         fprintf (nfp, "%s %d\n", buff, n);
397         flagged_done = 1;
398       }
399       else if (replied
400                && !strncmp (buff, seq_replied, mutt_strlen (seq_replied))) {
401         fprintf (nfp, "%s %d\n", buff, n);
402         replied_done = 1;
403       }
404       else
405         fprintf (nfp, "%s\n", buff);
406     }
407   }
408   safe_fclose (&ofp);
409   FREE (&buff);
410
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);
417
418   safe_fclose (&nfp);
419
420   unlink (sequences);
421   if (safe_rename (tmpfname, sequences) != 0)
422     unlink (tmpfname);
423
424   FREE (&tmpfname);
425 }
426
427 static void mh_update_maildir (struct maildir *md, struct mh_sequences *mhs)
428 {
429   int i;
430   short f;
431   char *p;
432
433   for (; md; md = md->next) {
434     if ((p = strrchr (md->h->path, '/')))
435       p++;
436     else
437       p = md->h->path;
438
439     i = atoi (p);
440     f = mhs_check (mhs, i);
441
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;
445   }
446 }
447
448 /* maildir support */
449
450 static void maildir_free_entry (struct maildir **md)
451 {
452   if (!md || !*md)
453     return;
454
455   FREE (&(*md)->canon_fname);
456   if ((*md)->h)
457     mutt_free_header (&(*md)->h);
458
459   FREE (md);
460 }
461
462 static void maildir_free_maildir (struct maildir **md)
463 {
464   struct maildir *p, *q;
465
466   if (!md || !*md)
467     return;
468
469   for (p = *md; p; p = q) {
470     q = p->next;
471     maildir_free_entry (&p);
472   }
473 }
474
475 static void maildir_parse_flags (HEADER * h, const char *path)
476 {
477   char *p, *q = NULL;
478
479   h->flagged = 0;
480   h->read = 0;
481   h->replied = 0;
482
483   if ((p = strrchr (path, ':')) != NULL && mutt_strncmp (p + 1, "2,", 2) == 0) {
484     p += 3;
485
486     mutt_str_replace (&h->maildir_flags, p);
487     q = h->maildir_flags;
488
489     while (*p) {
490       switch (*p) {
491       case 'F':
492
493         h->flagged = 1;
494         break;
495
496       case 'S':                /* seen */
497
498         h->read = 1;
499         break;
500
501       case 'R':                /* replied */
502
503         h->replied = 1;
504         break;
505
506       case 'T':                /* trashed */
507         h->trash = 1;
508         h->deleted = 1;
509         break;
510
511       default:
512         *q++ = *p;
513         break;
514       }
515       p++;
516     }
517   }
518
519   if (q == h->maildir_flags)
520     FREE (&h->maildir_flags);
521   else if (q)
522     *q = '\0';
523 }
524
525 static void maildir_update_mtime (CONTEXT * ctx)
526 {
527   char buf[_POSIX_PATH_MAX];
528   struct stat st;
529
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");
535   }
536   else {
537     snprintf (buf, sizeof (buf), "%s/.mh_sequences", ctx->path);
538     if (stat (buf, &st) == 0)
539       ctx->mtime_cur = st.st_mtime;
540
541     strfcpy (buf, ctx->path, sizeof (buf));
542   }
543
544   if (stat (buf, &st) == 0)
545     ctx->mtime = st.st_mtime;
546 }
547
548 /* 
549  * Actually parse a maildir message.  This may also be used to fill
550  * out a fake header structure generated by lazy maildir parsing.
551  */
552 static HEADER *maildir_parse_message (int magic, const char *fname,
553                                       int is_old, HEADER * _h)
554 {
555   FILE *f;
556   HEADER *h = _h;
557   struct stat st;
558
559   if ((f = fopen (fname, "r")) != NULL) {
560     if (!h)
561       h = mutt_new_header ();
562     h->env = mutt_read_rfc822_header (f, h, 0, 0);
563
564     fstat (fileno (f), &st);
565     fclose (f);
566
567     if (!h->received)
568       h->received = h->date_sent;
569
570     if (h->content->length <= 0)
571       h->content->length = st.st_size - h->content->offset;
572
573     h->index = -1;
574
575     if (magic == M_MAILDIR) {
576       /* 
577        * maildir stores its flags in the filename, so ignore the
578        * flags in the header of the message 
579        */
580
581       h->old = is_old;
582       maildir_parse_flags (h, fname);
583     }
584     return h;
585   }
586   return NULL;
587 }
588
589 /* 
590  * Note that this routine will _not_ modify the context given by
591  * ctx. 
592  *
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().
599  * 
600  */
601
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)
605 {
606   struct maildir *entry;
607   HEADER *h = NULL;
608   char buf[_POSIX_PATH_MAX];
609
610   if (subdir)
611     snprintf (buf, sizeof (buf), "%s/%s/%s", ctx->path, subdir, fname);
612   else
613     snprintf (buf, sizeof (buf), "%s/%s", ctx->path, fname);
614
615   if (ctx->magic == M_MH)
616     h = maildir_parse_message (ctx->magic, buf, is_old, NULL);
617   else {
618     h = mutt_new_header ();
619     h->old = is_old;
620     maildir_parse_flags (h, buf);
621   }
622
623   if (h != NULL) {
624     if (count) {
625       (*count)++;
626       if (!ctx->quiet && ReadInc && ((*count % ReadInc) == 0 || *count == 1))
627         mutt_message (_("Reading %s... %d"), ctx->path, *count);
628     }
629
630     if (subdir) {
631       snprintf (buf, sizeof (buf), "%s/%s", subdir, fname);
632       h->path = safe_strdup (buf);
633     }
634     else
635       h->path = safe_strdup (fname);
636
637     entry = safe_calloc (sizeof (struct maildir), 1);
638     entry->h = h;
639     entry->header_parsed = (ctx->magic == M_MH);
640     entry->inode = inode;
641     **last = entry;
642     *last = &entry->next;
643
644     return 0;
645   }
646
647   return -1;
648 }
649
650
651
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
654  * it.
655  */
656
657 int mh_valid_message (const char *s)
658 {
659   for (; *s; s++) {
660     if (!isdigit ((unsigned char) *s))
661       return 0;
662   }
663   return 1;
664 }
665
666 static int maildir_parse_dir (CONTEXT * ctx, struct maildir ***last,
667                               const char *subdir, int *count)
668 {
669   DIR *dirp;
670   struct dirent *de;
671   char buf[_POSIX_PATH_MAX];
672   int is_old = 0;
673
674   if (subdir) {
675     snprintf (buf, sizeof (buf), "%s/%s", ctx->path, subdir);
676     is_old = (mutt_strcmp ("cur", subdir) == 0);
677   }
678   else
679     strfcpy (buf, ctx->path, sizeof (buf));
680
681   if ((dirp = opendir (buf)) == NULL)
682     return -1;
683
684   while ((de = readdir (dirp)) != NULL) {
685
686     if ((ctx->magic == M_MH && !mh_valid_message (de->d_name))
687         || (ctx->magic == M_MAILDIR && *de->d_name == '.'))
688       continue;
689
690     /* FOO - really ignore the return value? */
691
692     dprint (2,
693             (debugfile, "%s:%d: parsing %s\n", __FILE__, __LINE__,
694              de->d_name));
695     maildir_parse_entry (ctx, last, subdir, de->d_name, count, is_old,
696                          de->d_ino);
697   }
698
699   closedir (dirp);
700   return 0;
701 }
702
703 static int maildir_add_to_context (CONTEXT * ctx, struct maildir *md)
704 {
705   int oldmsgcount = ctx->msgcount;
706
707   while (md) {
708
709     dprint (2, (debugfile, "%s:%d maildir_add_to_context(): Considering %s\n",
710                 __FILE__, __LINE__, NONULL (md->canon_fname)));
711
712     if (md->h) {
713       dprint (2,
714               (debugfile,
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);
721
722       ctx->hdrs[ctx->msgcount] = md->h;
723       ctx->hdrs[ctx->msgcount]->index = ctx->msgcount;
724       ctx->size +=
725         md->h->content->length + md->h->content->offset -
726         md->h->content->hdr_offset;
727
728       md->h = NULL;
729       ctx->msgcount++;
730     }
731     md = md->next;
732   }
733
734   if (ctx->msgcount > oldmsgcount) {
735     mx_update_context (ctx, ctx->msgcount - oldmsgcount);
736     return 1;
737   }
738   return 0;
739 }
740
741 static int maildir_move_to_context (CONTEXT * ctx, struct maildir **md)
742 {
743   int r;
744
745   r = maildir_add_to_context (ctx, *md);
746   maildir_free_maildir (md);
747   return r;
748 }
749
750 /*
751  * Merge two maildir lists according to the inode numbers.
752  */
753 static struct maildir *maildir_merge_inode (struct maildir *left,
754                                             struct maildir *right)
755 {
756   struct maildir *head;
757   struct maildir *tail;
758
759   if (left && right) {
760     if (left->inode < right->inode) {
761       head = left;
762       left = left->next;
763     }
764     else {
765       head = right;
766       right = right->next;
767     }
768   }
769   else {
770     if (left)
771       return left;
772     else
773       return right;
774   }
775
776   tail = head;
777
778   while (left && right) {
779     if (left->inode < right->inode) {
780       tail->next = left;
781       left = left->next;
782     }
783     else {
784       tail->next = right;
785       right = right->next;
786     }
787     tail = tail->next;
788   }
789
790   if (left) {
791     tail->next = left;
792   }
793   else {
794     tail->next = right;
795   }
796
797   return head;
798 }
799
800 /*
801  * Sort maildir list according to inode.
802  */
803 static struct maildir *maildir_sort_inode (struct maildir *list)
804 {
805   struct maildir *left = list;
806   struct maildir *right = list;
807
808   if (!list || !list->next) {
809     return list;
810   }
811
812   list = list->next;
813   while (list && list->next) {
814     right = right->next;
815     list = list->next->next;
816   }
817
818   list = right;
819   right = right->next;
820   list->next = 0;
821
822   left = maildir_sort_inode (left);
823   right = maildir_sort_inode (right);
824   return maildir_merge_inode (left, right);
825 }
826
827 #if USE_HCACHE
828 static size_t maildir_hcache_keylen (const char *fn)
829 {
830   const char *p = strchr (fn, ':');
831
832   return p ? (size_t) (p - fn) : mutt_strlen (fn);
833 }
834 #endif
835
836 /* 
837  * This function does the second parsing pass for a maildir-style
838  * folder.
839  */
840 void maildir_delayed_parsing (CONTEXT * ctx, struct maildir *md)
841 {
842   struct maildir *p;
843   char fn[_POSIX_PATH_MAX];
844   int count;
845
846 #if USE_HCACHE
847   void *hc = NULL;
848   void *data;
849   struct timeval *when = NULL;
850   struct stat lastchanged;
851   int ret;
852
853   hc = mutt_hcache_open (HeaderCache, ctx->path);
854 #endif
855
856   for (p = md, count = 0; p; p = p->next, count++) {
857     if (!(p && p->h && !p->header_parsed))
858       continue;
859
860 #if USE_HCACHE
861     data = mutt_hcache_fetch (hc, p->h->path + 3, &maildir_hcache_keylen);
862     when = (struct timeval *) data;
863 #endif
864
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);
868
869 #if USE_HCACHE
870     if (option (OPTHCACHEVERIFY)) {
871       ret = stat (fn, &lastchanged);
872     }
873     else {
874       lastchanged.st_mtime = 0;
875       ret = 0;
876     }
877
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);
881     }
882     else
883 #endif
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);
887 #if USE_HCACHE
888       mutt_hcache_store (hc, p->h->path + 3, p->h, 0, &maildir_hcache_keylen);
889 #endif
890     }
891     else
892       mutt_free_header (&p->h);
893 #if USE_HCACHE
894     FREE (&data);
895 #endif
896   }
897 #if USE_HCACHE
898   mutt_hcache_close (hc);
899 #endif
900 }
901
902 /* Read a MH/maildir style mailbox.
903  *
904  * args:
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
908  */
909 int mh_read_dir (CONTEXT * ctx, const char *subdir)
910 {
911   struct maildir *md;
912   struct mh_sequences mhs;
913   struct maildir **last;
914   int count;
915
916
917   memset (&mhs, 0, sizeof (mhs));
918
919   maildir_update_mtime (ctx);
920
921   md = NULL;
922   last = &md;
923   count = 0;
924   if (maildir_parse_dir (ctx, &last, subdir, &count) == -1)
925     return -1;
926
927   if (ctx->magic == M_MH) {
928     mh_read_sequences (&mhs, ctx->path);
929     mh_update_maildir (md, &mhs);
930     mhs_free_sequences (&mhs);
931   }
932
933   md = maildir_sort_inode (md);
934
935   if (ctx->magic == M_MAILDIR)
936     maildir_delayed_parsing (ctx, md);
937
938   maildir_move_to_context (ctx, &md);
939   return 0;
940 }
941
942 /* read a maildir style mailbox */
943 int maildir_read_dir (CONTEXT * ctx)
944 {
945   /* maildir looks sort of like MH, except that there are two subdirectories
946    * of the main folder path from which to read messages
947    */
948   if (mh_read_dir (ctx, "new") == -1 || mh_read_dir (ctx, "cur") == -1)
949     return (-1);
950
951   return 0;
952 }
953
954 /*
955  * Open a new (temporary) message in an MH folder.
956  */
957
958 int mh_open_new_message (MESSAGE * msg, CONTEXT * dest, HEADER * hdr)
959 {
960   return mh_mkstemp (dest, &msg->fp, &msg->path);
961 }
962
963 int ch_compar (const void *a, const void *b)
964 {
965   return (int) (*((const char *) a) - *((const char *) b));
966 }
967
968 static void maildir_flags (char *dest, size_t destlen, HEADER * hdr)
969 {
970   *dest = '\0';
971
972   /*
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.
978    */
979
980   if (hdr
981       && (hdr->flagged || hdr->replied || hdr->read || hdr->deleted
982           || hdr->old || hdr->maildir_flags)) {
983     char tmp[LONG_STRING];
984
985     snprintf (tmp, sizeof (tmp),
986               "%s%s%s%s%s",
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);
994   }
995 }
996
997
998 /*
999  * Open a new (temporary) message in a maildir folder.
1000  * 
1001  * Note that this uses _almost_ the maildir file name format, but
1002  * with a {cur,new} prefix.
1003  *
1004  */
1005
1006 int maildir_open_new_message (MESSAGE * msg, CONTEXT * dest, HEADER * hdr)
1007 {
1008   int fd;
1009   char path[_POSIX_PATH_MAX];
1010   char suffix[16];
1011   char subdir[16];
1012
1013   if (hdr) {
1014     short deleted = hdr->deleted;
1015
1016     hdr->deleted = 0;
1017
1018     maildir_flags (suffix, sizeof (suffix), hdr);
1019
1020     hdr->deleted = deleted;
1021   }
1022   else
1023     *suffix = '\0';
1024
1025   if (hdr && (hdr->read || hdr->old))
1026     strfcpy (subdir, "cur", sizeof (subdir));
1027   else
1028     strfcpy (subdir, "new", sizeof (subdir));
1029
1030   FOREVER {
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);
1034
1035     dprint (2, (debugfile, "maildir_open_new_message (): Trying %s.\n",
1036                 path));
1037
1038     umask (Umask);
1039     if ((fd = open (path, O_WRONLY | O_EXCL | O_CREAT, 0666)) == -1) {
1040       if (errno != EEXIST) {
1041         mutt_perror (path);
1042         return -1;
1043       }
1044     }
1045     else {
1046       dprint (2, (debugfile, "maildir_open_new_message (): Success.\n"));
1047       msg->path = safe_strdup (path);
1048       break;
1049     }
1050   }
1051
1052   if ((msg->fp = fdopen (fd, "w")) == NULL) {
1053     FREE (&msg->path);
1054     close (fd);
1055     unlink (path);
1056     return (-1);
1057   }
1058
1059   return 0;
1060 }
1061
1062
1063
1064 /*
1065  * Commit a message to a maildir folder.
1066  * 
1067  * msg->path contains the file name of a file in tmp/. We take the
1068  * flags from this file's name. 
1069  *
1070  * ctx is the mail folder we commit to.
1071  * 
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,
1075  * hdr is NULL. 
1076  *
1077  * msg->path looks like this:
1078  * 
1079  *    tmp/{cur,new}.mutt-HOSTNAME-PID-COUNTER:flags
1080  * 
1081  * See also maildir_open_new_message().
1082  * 
1083  */
1084
1085 int maildir_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr)
1086 {
1087   char subdir[4];
1088   char suffix[16];
1089   char path[_POSIX_PATH_MAX];
1090   char full[_POSIX_PATH_MAX];
1091   char *s;
1092
1093   if (safe_fclose (&msg->fp) != 0)
1094     return -1;
1095
1096   /* extract the subdir */
1097   s = strrchr (msg->path, '/') + 1;
1098   strfcpy (subdir, s, 4);
1099
1100   /* extract the flags */
1101   if ((s = strchr (s, ':')))
1102     strfcpy (suffix, s, sizeof (suffix));
1103   else
1104     suffix[0] = '\0';
1105
1106   /* construct a new file name. */
1107   FOREVER {
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);
1112
1113     dprint (2, (debugfile, "maildir_commit_message (): renaming %s to %s.\n",
1114                 msg->path, full));
1115
1116     if (safe_rename (msg->path, full) == 0) {
1117       if (hdr)
1118         mutt_str_replace (&hdr->path, path);
1119       FREE (&msg->path);
1120
1121       /*
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
1125        * actually set.
1126        */
1127       if (msg->received) {
1128         struct utimbuf ut;
1129
1130         ut.actime = msg->received;
1131         ut.modtime = msg->received;
1132         if (utime (full, &ut)) {
1133           mutt_perror (_
1134                        ("maildir_commit_message(): unable to set time on file"));
1135           return -1;
1136         }
1137       }
1138
1139       return 0;
1140     }
1141     else if (errno != EEXIST) {
1142       mutt_perror (ctx->path);
1143       return -1;
1144     }
1145   }
1146 }
1147
1148 /* 
1149  * commit a message to an MH folder.
1150  * 
1151  */
1152
1153
1154 static int _mh_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr,
1155                                short updseq)
1156 {
1157   DIR *dirp;
1158   struct dirent *de;
1159   char *cp, *dep;
1160   unsigned int n, hi = 0;
1161   char path[_POSIX_PATH_MAX];
1162   char tmp[16];
1163
1164   if (safe_fclose (&msg->fp) != 0)
1165     return -1;
1166
1167   if ((dirp = opendir (ctx->path)) == NULL) {
1168     mutt_perror (ctx->path);
1169     return (-1);
1170   }
1171
1172   /* figure out what the next message number is */
1173   while ((de = readdir (dirp)) != NULL) {
1174     dep = de->d_name;
1175     if (*dep == ',')
1176       dep++;
1177     cp = dep;
1178     while (*cp) {
1179       if (!isdigit ((unsigned char) *cp))
1180         break;
1181       cp++;
1182     }
1183     if (!*cp) {
1184       n = atoi (dep);
1185       if (n > hi)
1186         hi = n;
1187     }
1188   }
1189   closedir (dirp);
1190
1191   /* 
1192    * Now try to rename the file to the proper name.
1193    * 
1194    * Note: We may have to try multiple times, until we find a free
1195    * slot.
1196    */
1197
1198   FOREVER {
1199     hi++;
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) {
1203       if (hdr)
1204         mutt_str_replace (&hdr->path, tmp);
1205       FREE (&msg->path);
1206       break;
1207     }
1208     else if (errno != EEXIST) {
1209       mutt_perror (ctx->path);
1210       return -1;
1211     }
1212   }
1213   if (updseq)
1214     mh_sequences_add_one (ctx, hi, !msg->flags.read, msg->flags.flagged,
1215                           msg->flags.replied);
1216   return 0;
1217 }
1218
1219 int mh_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr)
1220 {
1221   return _mh_commit_message (ctx, msg, hdr, 1);
1222 }
1223
1224
1225 /* Sync a message in an MH folder.
1226  * 
1227  * This code is also used for attachment deletion in maildir
1228  * folders.
1229  */
1230
1231 static int mh_rewrite_message (CONTEXT * ctx, int msgno)
1232 {
1233   HEADER *h = ctx->hdrs[msgno];
1234   MESSAGE *dest;
1235
1236   int rc;
1237   short restore = 1;
1238   char oldpath[_POSIX_PATH_MAX];
1239   char newpath[_POSIX_PATH_MAX];
1240   char partpath[_POSIX_PATH_MAX];
1241
1242   long old_body_offset = h->content->offset;
1243   long old_body_length = h->content->length;
1244   long old_hdr_lines = h->lines;
1245
1246   if ((dest = mx_open_new_message (ctx, h, 0)) == NULL)
1247     return -1;
1248
1249   if ((rc = mutt_copy_message (dest->fp, ctx, h,
1250                                M_CM_UPDATE, CH_UPDATE | CH_UPDATE_LEN)) == 0)
1251   {
1252     snprintf (oldpath, _POSIX_PATH_MAX, "%s/%s", ctx->path, h->path);
1253     strfcpy (partpath, h->path, _POSIX_PATH_MAX);
1254
1255     if (ctx->magic == M_MAILDIR)
1256       rc = maildir_commit_message (ctx, dest, h);
1257     else
1258       rc = _mh_commit_message (ctx, dest, h, 0);
1259
1260     mx_close_message (&dest);
1261
1262     if (rc == 0) {
1263       unlink (oldpath);
1264       restore = 0;
1265     }
1266
1267     /* 
1268      * Try to move the new message to the old place.
1269      * (MH only.)
1270      *
1271      * This is important when we are just updating flags.
1272      *
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.
1276      * 
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.
1280      */
1281
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);
1286     }
1287   }
1288   else
1289     mx_close_message (&dest);
1290
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;
1295   }
1296
1297   mutt_free_body (&h->content->parts);
1298   return rc;
1299 }
1300
1301 static int mh_sync_message (CONTEXT * ctx, int msgno)
1302 {
1303   HEADER *h = ctx->hdrs[msgno];
1304
1305   if (h->attach_del || h->refs_changed || h->irt_changed)
1306     if (mh_rewrite_message (ctx, msgno) != 0)
1307       return -1;
1308
1309   return 0;
1310 }
1311
1312 static int maildir_sync_message (CONTEXT * ctx, int msgno)
1313 {
1314   HEADER *h = ctx->hdrs[msgno];
1315
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)
1319       return (-1);
1320   }
1321   else {
1322     /* we just have to rename the file. */
1323
1324     char newpath[_POSIX_PATH_MAX];
1325     char partpath[_POSIX_PATH_MAX];
1326     char fullpath[_POSIX_PATH_MAX];
1327     char oldpath[_POSIX_PATH_MAX];
1328     char suffix[16];
1329     char *p;
1330
1331     if ((p = strrchr (h->path, '/')) == NULL) {
1332       dprint (1,
1333               (debugfile,
1334                "maildir_sync_message: %s: unable to find subdir!\n",
1335                h->path));
1336       return (-1);
1337     }
1338     p++;
1339     strfcpy (newpath, p, sizeof (newpath));
1340
1341     /* kill the previous flags */
1342     if ((p = strchr (newpath, ':')) != NULL)
1343       *p = 0;
1344
1345     maildir_flags (suffix, sizeof (suffix), h);
1346
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);
1351
1352     if (mutt_strcmp (fullpath, oldpath) == 0) {
1353       /* message hasn't really changed */
1354       return 0;
1355     }
1356
1357     /* record that the message is possibly marked as trashed on disk */
1358     h->trash = h->deleted;
1359
1360     if (rename (oldpath, fullpath) != 0) {
1361       mutt_perror ("rename");
1362       return (-1);
1363     }
1364     mutt_str_replace (&h->path, partpath);
1365   }
1366   return (0);
1367 }
1368
1369 int mh_sync_mailbox (CONTEXT * ctx, int *index_hint)
1370 {
1371   char path[_POSIX_PATH_MAX], tmp[_POSIX_PATH_MAX];
1372   int i, j;
1373
1374 #if USE_HCACHE
1375   void *hc = NULL;
1376 #endif /* USE_HCACHE */
1377
1378   if (ctx->magic == M_MH)
1379     i = mh_check_mailbox (ctx, index_hint);
1380   else
1381     i = maildir_check_mailbox (ctx, index_hint);
1382
1383   if (i != 0)
1384     return i;
1385
1386 #if USE_HCACHE
1387   if (ctx->magic == M_MAILDIR)
1388     hc = mutt_hcache_open (HeaderCache, ctx->path);
1389 #endif /* USE_HCACHE */
1390
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)) {
1397 #if USE_HCACHE
1398         if (ctx->magic == M_MAILDIR)
1399           mutt_hcache_delete (hc, ctx->hdrs[i]->path + 3,
1400                               &maildir_hcache_keylen);
1401 #endif /* USE_HCACHE */
1402         unlink (path);
1403       }
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);
1409           unlink (tmp);
1410           rename (path, tmp);
1411         }
1412
1413       }
1414     }
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)
1421           goto err;
1422       }
1423       else {
1424         if (mh_sync_message (ctx, i) == -1)
1425           goto err;
1426       }
1427     }
1428   }
1429
1430 #if USE_HCACHE
1431   if (ctx->magic == M_MAILDIR)
1432     mutt_hcache_close (hc);
1433 #endif /* USE_HCACHE */
1434
1435   if (ctx->magic == M_MH)
1436     mh_update_sequences (ctx);
1437
1438   /* XXX race condition? */
1439
1440   maildir_update_mtime (ctx);
1441
1442   /* adjust indices */
1443
1444   if (ctx->deleted) {
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++;
1449     }
1450   }
1451
1452   return 0;
1453
1454 err:
1455 #if USE_HCACHE
1456   if (ctx->magic == M_MAILDIR)
1457     mutt_hcache_close (hc);
1458 #endif /* USE_HCACHE */
1459   return -1;
1460 }
1461
1462 static char *maildir_canon_filename (char *dest, const char *src, size_t l)
1463 {
1464   char *t, *u;
1465
1466   if ((t = strrchr (src, '/')))
1467     src = t + 1;
1468
1469   strfcpy (dest, src, l);
1470   if ((u = strrchr (dest, ':')))
1471     *u = '\0';
1472
1473   return dest;
1474 }
1475
1476 static void maildir_update_tables (CONTEXT * ctx, int *index_hint)
1477 {
1478   short old_sort;
1479   int old_count;
1480   int i, j;
1481
1482   if (Sort != SORT_ORDER) {
1483     old_sort = Sort;
1484     Sort = SORT_ORDER;
1485     mutt_sort_headers (ctx, 1);
1486     Sort = old_sort;
1487   }
1488
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)
1492       *index_hint = j;
1493
1494     if (ctx->hdrs[i]->active)
1495       ctx->hdrs[i]->index = j++;
1496   }
1497
1498   mx_update_tables (ctx, 0);
1499   mutt_clear_threads (ctx);
1500 }
1501
1502 static void maildir_update_flags (CONTEXT * ctx, HEADER * o, HEADER * n)
1503 {
1504   /* save the global state here so we can reset it at the
1505    * end of list block if required.
1506    */
1507   int context_changed = ctx->changed;
1508
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.
1514    */
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);
1519
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
1523    * message.
1524    */
1525   o->changed = 0;
1526
1527   /* if the mailbox was not modified before we made these
1528    * changes, unset the changed flag since nothing needs to
1529    * be synchronized.
1530    */
1531   if (!context_changed)
1532     ctx->changed = 0;
1533 }
1534
1535
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.
1543  */
1544 int maildir_check_mailbox (CONTEXT * ctx, int *index_hint)
1545 {
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;
1555   int i;
1556   HASH *fnames;                 /* hash table for quickly looking up the base filename
1557                                    for a maildir message */
1558
1559   /* XXX seems like this check belongs in mx_check_mailbox()
1560    * rather than here.
1561    */
1562   if (!option (OPTCHECKNEW))
1563     return 0;
1564
1565   snprintf (buf, sizeof (buf), "%s/new", ctx->path);
1566   if (stat (buf, &st_new) == -1)
1567     return -1;
1568
1569   snprintf (buf, sizeof (buf), "%s/cur", ctx->path);
1570   if (stat (buf, &st_cur) == -1)
1571     return -1;
1572
1573   /* determine which subdirectories need to be scanned */
1574   if (st_new.st_mtime > ctx->mtime)
1575     changed = 1;
1576   if (st_cur.st_mtime > ctx->mtime_cur)
1577     changed |= 2;
1578
1579   if (!changed)
1580     return 0;                   /* nothing to do */
1581
1582   /* update the modification times on the mailbox */
1583   ctx->mtime_cur = st_cur.st_mtime;
1584   ctx->mtime = st_new.st_mtime;
1585
1586   /* do a fast scan of just the filenames in
1587    * the subdirectories that have changed.
1588    */
1589   md = NULL;
1590   last = &md;
1591   if (changed & 1)
1592     maildir_parse_dir (ctx, &last, "new", NULL);
1593   if (changed & 2)
1594     maildir_parse_dir (ctx, &last, "cur", NULL);
1595
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.
1599    */
1600   fnames = hash_create (1031);
1601
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);
1606   }
1607
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);
1613     if (p && p->h) {
1614       /* message already exists, merge flags */
1615       ctx->hdrs[i]->active = 1;
1616
1617       /* check to see if the message has moved to a different
1618        * subdirectory.  If so, update the associated filename.
1619        */
1620       if (mutt_strcmp (ctx->hdrs[i]->path, p->h->path))
1621         mutt_str_replace (&ctx->hdrs[i]->path, p->h->path);
1622
1623       /* if the user hasn't modified the flags on this message, update
1624        * the flags we just detected.
1625        */
1626       if (!ctx->hdrs[i]->changed)
1627         maildir_update_flags (ctx, ctx->hdrs[i], p->h);
1628
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;
1632
1633       /* this is a duplicate of an existing header, so remove it */
1634       mutt_free_header (&p->h);
1635     }
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.
1639      */
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.
1645        */
1646       occult = 1;
1647     }
1648     else {
1649       /* This message resides in a subdirectory which was not
1650        * modified, so we assume that it is still present and
1651        * unchanged.
1652        */
1653       ctx->hdrs[i]->active = 1;
1654     }
1655   }
1656
1657   /* destroy the file name hash */
1658   hash_destroy (&fnames, NULL);
1659
1660   /* If we didn't just get new mail, update the tables. */
1661   if (occult)
1662     maildir_update_tables (ctx, index_hint);
1663
1664   /* do any delayed parsing we need to do. */
1665   maildir_delayed_parsing (ctx, md);
1666
1667   /* Incorporate new messages */
1668   have_new = maildir_move_to_context (ctx, &md);
1669
1670   return occult ? M_REOPENED : (have_new ? M_NEW_MAIL : 0);
1671 }
1672
1673 /* 
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.
1678  *
1679  * Don't change this code unless you _really_ understand what
1680  * happens.
1681  *
1682  */
1683
1684 int mh_check_mailbox (CONTEXT * ctx, int *index_hint)
1685 {
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;
1692   HASH *fnames;
1693   int i;
1694
1695   if (!option (OPTCHECKNEW))
1696     return 0;
1697
1698   strfcpy (buf, ctx->path, sizeof (buf));
1699   if (stat (buf, &st) == -1)
1700     return -1;
1701
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) {
1705     char *tmp;
1706     FILE *fp = NULL;
1707
1708     if (mh_mkstemp (ctx, &fp, &tmp) == 0) {
1709       safe_fclose (&fp);
1710       if (safe_rename (tmp, buf) == -1)
1711         unlink (tmp);
1712       FREE (&tmp);
1713     }
1714   }
1715
1716   if (i == -1 && stat (buf, &st_cur) == -1)
1717     modified = 1;
1718
1719   if (st.st_mtime > ctx->mtime || st_cur.st_mtime > ctx->mtime_cur)
1720     modified = 1;
1721
1722   if (!modified)
1723     return 0;
1724
1725   ctx->mtime_cur = st_cur.st_mtime;
1726   ctx->mtime = st.st_mtime;
1727
1728   memset (&mhs, 0, sizeof (mhs));
1729
1730   md = NULL;
1731   last = &md;
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);
1736
1737   /* check for modifications and adjust flags */
1738   fnames = hash_create (1031);
1739
1740   for (p = md; p; p = p->next)
1741     hash_insert (fnames, p->h->path, p, 0);
1742
1743   for (i = 0; i < ctx->msgcount; i++) {
1744     ctx->hdrs[i]->active = 0;
1745
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);
1752
1753       mutt_free_header (&p->h);
1754     }
1755     else                        /* message has disappeared */
1756       occult = 1;
1757   }
1758
1759   /* destroy the file name hash */
1760
1761   hash_destroy (&fnames, NULL);
1762
1763   /* If we didn't just get new mail, update the tables. */
1764   if (occult)
1765     maildir_update_tables (ctx, index_hint);
1766
1767   /* Incorporate new messages */
1768   have_new = maildir_move_to_context (ctx, &md);
1769
1770   return occult ? M_REOPENED : (have_new ? M_NEW_MAIL : 0);
1771 }
1772
1773
1774
1775
1776 /*
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.
1780  */
1781
1782 FILE *_maildir_open_find_message (const char *folder, const char *unique,
1783                                   const char *subfolder)
1784 {
1785   char dir[_POSIX_PATH_MAX];
1786   char tunique[_POSIX_PATH_MAX];
1787   char fname[_POSIX_PATH_MAX];
1788
1789   DIR *dp;
1790   struct dirent *de;
1791
1792   FILE *fp = NULL;
1793   int oe = ENOENT;
1794
1795   snprintf (dir, sizeof (dir), "%s/%s", folder, subfolder);
1796
1797   if ((dp = opendir (dir)) == NULL) {
1798     errno = ENOENT;
1799     return NULL;
1800   }
1801
1802   while ((de = readdir (dp))) {
1803     maildir_canon_filename (tunique, de->d_name, sizeof (tunique));
1804
1805     if (!mutt_strcmp (tunique, unique)) {
1806       snprintf (fname, sizeof (fname), "%s/%s/%s", folder, subfolder,
1807                 de->d_name);
1808       fp = fopen (fname, "r");  /* __FOPEN_CHECKED__ */
1809       oe = errno;
1810       break;
1811     }
1812   }
1813
1814   closedir (dp);
1815
1816   errno = oe;
1817   return fp;
1818 }
1819
1820 FILE *maildir_open_find_message (const char *folder, const char *msg)
1821 {
1822   char unique[_POSIX_PATH_MAX];
1823   FILE *fp;
1824
1825   static unsigned int new_hits = 0, cur_hits = 0;       /* simple dynamic optimization */
1826
1827   maildir_canon_filename (unique, msg, sizeof (unique));
1828
1829   if ((fp =
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);
1836     }
1837
1838     return fp;
1839   }
1840   if ((fp =
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);
1847     }
1848
1849     return fp;
1850   }
1851
1852   return NULL;
1853 }
1854
1855
1856 /*
1857  * Returns:
1858  * 1 if there are no messages in the mailbox
1859  * 0 if there are messages in the mailbox
1860  * -1 on error
1861  */
1862 int maildir_check_empty (const char *path)
1863 {
1864   DIR *dp;
1865   struct dirent *de;
1866   int r = 1;                    /* assume empty until we find a message */
1867   char realpath[_POSIX_PATH_MAX];
1868   int iter = 0;
1869
1870   /* Strategy here is to look for any file not beginning with a period */
1871
1872   do {
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
1875      */
1876     snprintf (realpath, sizeof (realpath), "%s/%s", path,
1877               iter == 0 ? "cur" : "new");
1878     if ((dp = opendir (realpath)) == NULL)
1879       return -1;
1880     while ((de = readdir (dp))) {
1881       if (*de->d_name != '.') {
1882         r = 0;
1883         break;
1884       }
1885     }
1886     closedir (dp);
1887     iter++;
1888   } while (r && iter < 2);
1889
1890   return r;
1891 }
1892
1893 /*
1894  * Returns:
1895  * 1 if there are no messages in the mailbox
1896  * 0 if there are messages in the mailbox
1897  * -1 on error
1898  */
1899 int mh_check_empty (const char *path)
1900 {
1901   DIR *dp;
1902   struct dirent *de;
1903   int r = 1;                    /* assume empty until we find a message */
1904
1905   if ((dp = opendir (path)) == NULL)
1906     return -1;
1907   while ((de = readdir (dp))) {
1908     if (mh_valid_message (de->d_name)) {
1909       r = 0;
1910       break;
1911     }
1912   }
1913   closedir (dp);
1914
1915   return r;
1916 }