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