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