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