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