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