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