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