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