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