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