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