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