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