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