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