Nico Golde:
[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   unsigned int size;
901   struct timeval *when = NULL;
902   struct stat lastchanged;
903   int ret;
904
905   hc = mutt_hcache_open (HeaderCache, ctx->path);
906 #endif
907
908   for (p = md, count = 0; p; p = p->next, count++)
909   {
910     if (! (p && p->h && !p->header_parsed))
911         continue;
912
913 #if USE_HCACHE
914     data      = mutt_hcache_fetch (hc, p->h->path + 3, &maildir_hcache_keylen);
915     when      = (struct timeval *) data;
916 #endif
917
918     if (!ctx->quiet && ReadInc && ((count % ReadInc) == 0 || count == 1))
919       mutt_message (_("Reading %s... %d"), ctx->path, count);
920     snprintf (fn, sizeof (fn), "%s/%s", ctx->path, p->h->path);
921
922 #if USE_HCACHE
923     if (option(OPTHCACHEVERIFY)) {
924       ret = stat(fn, &lastchanged);
925     } else {
926       lastchanged.st_mtime = 0;
927       ret = 0;
928     }
929
930     if (data != NULL && !ret && lastchanged.st_mtime <= when->tv_sec)
931     {
932       p->h = mutt_hcache_restore ((unsigned char *)data, &p->h);
933       maildir_parse_flags (p->h, fn);
934     } else
935 #endif
936     if (maildir_parse_message (ctx->magic, fn, p->h->old, p->h))
937     {
938       p->header_parsed = 1;
939       maildir_parse_flags (p->h, fn);
940 #if USE_HCACHE
941       mutt_hcache_store (hc, p->h->path + 3, p->h, 0, &maildir_hcache_keylen);
942 #endif
943     } else
944       mutt_free_header (&p->h);
945 #if USE_HCACHE
946     FREE(&data);
947 #endif
948   }
949 #if USE_HCACHE
950   mutt_hcache_close (hc);
951 #endif
952 }
953
954 /* Read a MH/maildir style mailbox.
955  *
956  * args:
957  *      ctx [IN/OUT]    context for this mailbox
958  *      subdir [IN]     NULL for MH mailboxes, otherwise the subdir of the
959  *                      maildir mailbox to read from
960  */
961 int mh_read_dir (CONTEXT * ctx, const char *subdir)
962 {
963   struct maildir *md;
964   struct mh_sequences mhs;
965   struct maildir **last;
966   int count;
967
968
969   memset (&mhs, 0, sizeof (mhs));
970
971   maildir_update_mtime (ctx);
972
973   md = NULL;
974   last = &md;
975   count = 0;
976   if (maildir_parse_dir (ctx, &last, subdir, &count) == -1)
977     return -1;
978
979   if (ctx->magic == M_MH)
980   {
981     mh_read_sequences (&mhs, ctx->path);
982     mh_update_maildir (md, &mhs);
983     mhs_free_sequences (&mhs);
984   }
985
986   md = maildir_sort_inode(md);
987
988   if (ctx->magic == M_MAILDIR)
989     maildir_delayed_parsing (ctx, md);
990
991   maildir_move_to_context (ctx, &md);
992   return 0;
993 }
994
995 /* read a maildir style mailbox */
996 int maildir_read_dir (CONTEXT * ctx)
997 {
998   /* maildir looks sort of like MH, except that there are two subdirectories
999    * of the main folder path from which to read messages
1000    */
1001   if (mh_read_dir (ctx, "new") == -1 || mh_read_dir (ctx, "cur") == -1)
1002     return (-1);
1003
1004   return 0;
1005 }
1006
1007 /*
1008  * Open a new (temporary) message in an MH folder.
1009  */
1010
1011 int mh_open_new_message (MESSAGE * msg, CONTEXT * dest, HEADER * hdr)
1012 {
1013   return mh_mkstemp (dest, &msg->fp, &msg->path);
1014 }
1015
1016 int ch_compar (const void *a, const void *b)
1017 {
1018   return (int)( *((const char *) a) - *((const char *) b));
1019 }
1020
1021 static void maildir_flags (char *dest, size_t destlen, HEADER * hdr)
1022 {
1023   *dest = '\0';
1024
1025   /*
1026    * The maildir specification requires that all files in the cur
1027    * subdirectory have the :unique string appeneded, regardless of whether
1028    * or not there are any flags.  If .old is set, we know that this message
1029    * will end up in the cur directory, so we include it in the following
1030    * test even though there is no associated flag.
1031    */
1032   
1033   if (hdr && (hdr->flagged || hdr->replied || hdr->read || hdr->deleted || hdr->old || hdr->maildir_flags))
1034   {
1035     char tmp[LONG_STRING];
1036     snprintf (tmp, sizeof (tmp),
1037               "%s%s%s%s%s",
1038               hdr->flagged ? "F" : "",
1039               hdr->replied ? "R" : "",
1040               hdr->read ? "S" : "", hdr->deleted ? "T" : "",
1041               NONULL(hdr->maildir_flags));
1042     if (hdr->maildir_flags)
1043       qsort (tmp, strlen (tmp), 1, ch_compar);
1044     snprintf (dest, destlen, ":2,%s", tmp);
1045   }
1046 }
1047
1048
1049 /*
1050  * Open a new (temporary) message in a maildir folder.
1051  * 
1052  * Note that this uses _almost_ the maildir file name format, but
1053  * with a {cur,new} prefix.
1054  *
1055  */
1056
1057 int maildir_open_new_message (MESSAGE * msg, CONTEXT * dest, HEADER * hdr)
1058 {
1059   int fd;
1060   char path[_POSIX_PATH_MAX];
1061   char suffix[16];
1062   char subdir[16];
1063
1064   if (hdr)
1065   {
1066     short deleted = hdr->deleted;
1067     hdr->deleted = 0;
1068
1069     maildir_flags (suffix, sizeof (suffix), hdr);
1070
1071     hdr->deleted = deleted;
1072   }
1073   else
1074     *suffix = '\0';
1075
1076   if (hdr && (hdr->read || hdr->old))
1077     strfcpy (subdir, "cur", sizeof (subdir));
1078   else
1079     strfcpy (subdir, "new", sizeof (subdir));
1080
1081   FOREVER
1082   {
1083     snprintf (path, _POSIX_PATH_MAX, "%s/tmp/%s.%ld.%u_%d.%s%s",
1084               dest->path, subdir, time (NULL), (unsigned int)getpid (),
1085               Counter++, NONULL (Hostname), suffix);
1086
1087     dprint (2, (debugfile, "maildir_open_new_message (): Trying %s.\n",
1088                 path));
1089
1090     umask(Umask);
1091     if ((fd = open (path, O_WRONLY | O_EXCL | O_CREAT, 0666)) == -1)
1092     {
1093       if (errno != EEXIST)
1094       {
1095         mutt_perror (path);
1096         return -1;
1097       }
1098     }
1099     else
1100     {
1101       dprint (2, (debugfile, "maildir_open_new_message (): Success.\n"));
1102       msg->path = safe_strdup (path);
1103       break;
1104     }
1105   }
1106
1107   if ((msg->fp = fdopen (fd, "w")) == NULL)
1108   {
1109     FREE (&msg->path);
1110     close (fd);
1111     unlink (path);
1112     return (-1);
1113   }
1114
1115   return 0;
1116 }
1117
1118
1119
1120 /*
1121  * Commit a message to a maildir folder.
1122  * 
1123  * msg->path contains the file name of a file in tmp/. We take the
1124  * flags from this file's name. 
1125  *
1126  * ctx is the mail folder we commit to.
1127  * 
1128  * hdr is a header structure to which we write the message's new
1129  * file name.  This is used in the mh and maildir folder synch
1130  * routines.  When this routine is invoked from mx_commit_message,
1131  * hdr is NULL. 
1132  *
1133  * msg->path looks like this:
1134  * 
1135  *    tmp/{cur,new}.mutt-HOSTNAME-PID-COUNTER:flags
1136  * 
1137  * See also maildir_open_new_message().
1138  * 
1139  */
1140
1141 int maildir_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr)
1142 {
1143   char subdir[4];
1144   char suffix[16];
1145   char path[_POSIX_PATH_MAX];
1146   char full[_POSIX_PATH_MAX];
1147   char *s;
1148
1149   if (safe_fclose (&msg->fp) != 0)
1150     return -1;
1151
1152   /* extract the subdir */
1153   s = strrchr (msg->path, '/') + 1;
1154   strfcpy (subdir, s, 4);
1155
1156   /* extract the flags */
1157   if ((s = strchr (s, ':')))
1158     strfcpy (suffix, s, sizeof (suffix));
1159   else
1160     suffix[0] = '\0';
1161
1162   /* construct a new file name. */
1163   FOREVER
1164   {
1165     snprintf (path, _POSIX_PATH_MAX, "%s/%ld.%u_%d.%s%s", subdir,
1166               time (NULL), (unsigned int)getpid (), Counter++, 
1167               NONULL (Hostname), suffix);
1168     snprintf (full, _POSIX_PATH_MAX, "%s/%s", ctx->path, path);
1169
1170     dprint (2, (debugfile, "maildir_commit_message (): renaming %s to %s.\n",
1171                 msg->path, full));
1172
1173     if (safe_rename (msg->path, full) == 0)
1174     {
1175       if (hdr)
1176         mutt_str_replace (&hdr->path, path);
1177       FREE (&msg->path);
1178
1179       /*
1180        * Adjust the mtime on the file to match the time at which this
1181        * message was received.  Currently this is only set when copying
1182        * messages between mailboxes, so we test to ensure that it is
1183        * actually set.
1184        */
1185       if (msg->received)
1186       {
1187         struct utimbuf ut;
1188
1189         ut.actime = msg->received;
1190         ut.modtime = msg->received;
1191         if (utime (full, &ut))
1192         {
1193           mutt_perror (_("maildir_commit_message(): unable to set time on file"));
1194           return -1;
1195         }
1196       }
1197
1198       return 0;
1199     }
1200     else if (errno != EEXIST)
1201     {
1202       mutt_perror (ctx->path);
1203       return -1;
1204     }
1205   }
1206 }
1207
1208 /* 
1209  * commit a message to an MH folder.
1210  * 
1211  */
1212
1213
1214 static int _mh_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr,
1215                                short updseq)
1216 {
1217   DIR *dirp;
1218   struct dirent *de;
1219   char *cp, *dep;
1220   unsigned int n, hi = 0;
1221   char path[_POSIX_PATH_MAX];
1222   char tmp[16];
1223
1224   if (safe_fclose (&msg->fp) != 0)
1225     return -1;
1226
1227   if ((dirp = opendir (ctx->path)) == NULL)
1228   {
1229     mutt_perror (ctx->path);
1230     return (-1);
1231   }
1232
1233   /* figure out what the next message number is */
1234   while ((de = readdir (dirp)) != NULL)
1235   {
1236     dep = de->d_name;
1237     if (*dep == ',')
1238       dep++;
1239     cp = dep;
1240     while (*cp)
1241     {
1242       if (!isdigit ((unsigned char) *cp))
1243         break;
1244       cp++;
1245     }
1246     if (!*cp)
1247     {
1248       n = atoi (dep);
1249       if (n > hi)
1250         hi = n;
1251     }
1252   }
1253   closedir (dirp);
1254
1255   /* 
1256    * Now try to rename the file to the proper name.
1257    * 
1258    * Note: We may have to try multiple times, until we find a free
1259    * slot.
1260    */
1261
1262   FOREVER
1263   {
1264     hi++;
1265     snprintf (tmp, sizeof (tmp), "%d", hi);
1266     snprintf (path, sizeof (path), "%s/%s", ctx->path, tmp);
1267     if (safe_rename (msg->path, path) == 0)
1268     {
1269       if (hdr)
1270         mutt_str_replace (&hdr->path, tmp);
1271       FREE (&msg->path);
1272       break;
1273     }
1274     else if (errno != EEXIST)
1275     {
1276       mutt_perror (ctx->path);
1277       return -1;
1278     }
1279   }
1280   if (updseq)
1281     mh_sequences_add_one (ctx, hi, !msg->flags.read, msg->flags.flagged,
1282                           msg->flags.replied);
1283   return 0;
1284 }
1285
1286 int mh_commit_message (CONTEXT * ctx, MESSAGE * msg, HEADER * hdr)
1287 {
1288   return _mh_commit_message (ctx, msg, hdr, 1);
1289 }
1290
1291
1292 /* Sync a message in an MH folder.
1293  * 
1294  * This code is also used for attachment deletion in maildir
1295  * folders.
1296  */
1297
1298 static int mh_rewrite_message (CONTEXT * ctx, int msgno)
1299 {
1300   HEADER *h = ctx->hdrs[msgno];
1301   MESSAGE *dest;
1302
1303   int rc;
1304   short restore = 1;
1305   char oldpath[_POSIX_PATH_MAX];
1306   char newpath[_POSIX_PATH_MAX];
1307   char partpath[_POSIX_PATH_MAX];
1308
1309   long old_body_offset = h->content->offset;
1310   long old_body_length = h->content->length;
1311   long old_hdr_lines = h->lines;
1312
1313   if ((dest = mx_open_new_message (ctx, h, 0)) == NULL)
1314     return -1;
1315
1316   if ((rc = mutt_copy_message (dest->fp, ctx, h,
1317                                M_CM_UPDATE, CH_UPDATE | CH_UPDATE_LEN)) == 0)
1318   {
1319     snprintf (oldpath, _POSIX_PATH_MAX, "%s/%s", ctx->path, h->path);
1320     strfcpy (partpath, h->path, _POSIX_PATH_MAX);
1321
1322     if (ctx->magic == M_MAILDIR)
1323       rc = maildir_commit_message (ctx, dest, h);
1324     else
1325       rc = _mh_commit_message (ctx, dest, h, 0);
1326
1327     mx_close_message (&dest);
1328
1329     if (rc == 0)
1330     {
1331       unlink (oldpath);
1332       restore = 0;
1333     }
1334
1335     /* 
1336      * Try to move the new message to the old place.
1337      * (MH only.)
1338      *
1339      * This is important when we are just updating flags.
1340      *
1341      * Note that there is a race condition against programs which
1342      * use the first free slot instead of the maximum message
1343      * number.  Mutt does _not_ behave like this.
1344      * 
1345      * Anyway, if this fails, the message is in the folder, so
1346      * all what happens is that a concurrently runnung mutt will
1347      * lose flag modifications.
1348      */
1349
1350     if (ctx->magic == M_MH && rc == 0)
1351     {
1352       snprintf (newpath, _POSIX_PATH_MAX, "%s/%s", ctx->path, h->path);
1353       if ((rc = safe_rename (newpath, oldpath)) == 0)
1354         mutt_str_replace (&h->path, partpath);
1355     }
1356   }
1357   else
1358     mx_close_message (&dest);
1359
1360   if (rc == -1 && restore)
1361   {
1362     h->content->offset = old_body_offset;
1363     h->content->length = old_body_length;
1364     h->lines = old_hdr_lines;
1365   }
1366
1367   mutt_free_body (&h->content->parts);
1368   return rc;
1369 }
1370
1371 static int mh_sync_message (CONTEXT * ctx, int msgno)
1372 {
1373   HEADER *h = ctx->hdrs[msgno];
1374
1375   if (h->attach_del || h->refs_changed || h->irt_changed)
1376     if (mh_rewrite_message (ctx, msgno) != 0)
1377       return -1;
1378
1379   return 0;
1380 }
1381
1382 static int maildir_sync_message (CONTEXT * ctx, int msgno)
1383 {
1384   HEADER *h = ctx->hdrs[msgno];
1385
1386   if (h->attach_del || h->refs_changed || h->irt_changed)
1387   {
1388     /* when doing attachment deletion/rethreading, fall back to the MH case. */
1389     if (mh_rewrite_message (ctx, msgno) != 0)
1390       return (-1);
1391   }
1392   else
1393   {
1394     /* we just have to rename the file. */
1395
1396     char newpath[_POSIX_PATH_MAX];
1397     char partpath[_POSIX_PATH_MAX];
1398     char fullpath[_POSIX_PATH_MAX];
1399     char oldpath[_POSIX_PATH_MAX];
1400     char suffix[16];
1401     char *p;
1402
1403     if ((p = strrchr (h->path, '/')) == NULL)
1404     {
1405       dprint (1,
1406               (debugfile,
1407                "maildir_sync_message: %s: unable to find subdir!\n",
1408                h->path));
1409       return (-1);
1410     }
1411     p++;
1412     strfcpy (newpath, p, sizeof (newpath));
1413
1414     /* kill the previous flags */
1415     if ((p = strchr (newpath, ':')) != NULL)
1416       *p = 0;
1417
1418     maildir_flags (suffix, sizeof (suffix), h);
1419
1420     snprintf (partpath, sizeof (partpath), "%s/%s%s",
1421               (h->read || h->old) ? "cur" : "new", newpath, suffix);
1422     snprintf (fullpath, sizeof (fullpath), "%s/%s", ctx->path, partpath);
1423     snprintf (oldpath, sizeof (oldpath), "%s/%s", ctx->path, h->path);
1424
1425     if (mutt_strcmp (fullpath, oldpath) == 0)
1426     {
1427       /* message hasn't really changed */
1428       return 0;
1429     }
1430
1431     /* record that the message is possibly marked as trashed on disk */
1432     h->trash = h->deleted;
1433
1434     if (rename (oldpath, fullpath) != 0)
1435     {
1436       mutt_perror ("rename");
1437       return (-1);
1438     }
1439     mutt_str_replace (&h->path, partpath);
1440   }
1441   return (0);
1442 }
1443
1444 int mh_sync_mailbox (CONTEXT * ctx, int *index_hint)
1445 {
1446   char path[_POSIX_PATH_MAX], tmp[_POSIX_PATH_MAX];
1447   int i, j;
1448 #if USE_HCACHE
1449   void *hc = NULL;
1450 #endif /* USE_HCACHE */
1451
1452   if (ctx->magic == M_MH)
1453     i = mh_check_mailbox (ctx, index_hint);
1454   else 
1455     i = maildir_check_mailbox (ctx, index_hint);
1456       
1457   if (i != 0)
1458     return i;
1459
1460 #if USE_HCACHE
1461   if (ctx->magic == M_MAILDIR)
1462     hc = mutt_hcache_open(HeaderCache, ctx->path);
1463 #endif /* USE_HCACHE */
1464
1465   for (i = 0; i < ctx->msgcount; i++)
1466   {
1467     if (ctx->hdrs[i]->deleted
1468         && (ctx->magic != M_MAILDIR || !option (OPTMAILDIRTRASH)))
1469     {
1470       snprintf (path, sizeof (path), "%s/%s", ctx->path, ctx->hdrs[i]->path);
1471       if (ctx->magic == M_MAILDIR
1472           || (option (OPTMHPURGE) && ctx->magic == M_MH))
1473       {
1474 #if USE_HCACHE
1475         if (ctx->magic == M_MAILDIR)
1476           mutt_hcache_delete (hc, ctx->hdrs[i]->path + 3, &maildir_hcache_keylen);
1477 #endif /* USE_HCACHE */
1478         unlink (path);
1479       }
1480       else if (ctx->magic == M_MH)
1481       {
1482         /* MH just moves files out of the way when you delete them */
1483         if (*ctx->hdrs[i]->path != ',')
1484         {
1485           snprintf (tmp, sizeof (tmp), "%s/,%s", ctx->path,
1486                     ctx->hdrs[i]->path);
1487           unlink (tmp);
1488           rename (path, tmp);
1489         }
1490
1491       }
1492     }
1493     else if (ctx->hdrs[i]->changed || ctx->hdrs[i]->attach_del ||
1494              (ctx->magic == M_MAILDIR
1495               && (option (OPTMAILDIRTRASH) || ctx->hdrs[i]->trash)
1496               && (ctx->hdrs[i]->deleted != ctx->hdrs[i]->trash)))
1497     {
1498       if (ctx->magic == M_MAILDIR)
1499       {
1500         if (maildir_sync_message (ctx, i) == -1)
1501           goto err;
1502       }
1503       else
1504       {
1505         if (mh_sync_message (ctx, i) == -1)
1506           goto err;
1507       }
1508     }
1509   }
1510
1511 #if USE_HCACHE
1512   if (ctx->magic == M_MAILDIR)
1513     mutt_hcache_close (hc);
1514 #endif /* USE_HCACHE */
1515
1516   if (ctx->magic == M_MH)
1517     mh_update_sequences (ctx);
1518
1519   /* XXX race condition? */
1520
1521   maildir_update_mtime (ctx);
1522
1523   /* adjust indices */
1524
1525   if (ctx->deleted)
1526   {
1527     for (i = 0, j = 0; i < ctx->msgcount; i++)
1528     {
1529       if (!ctx->hdrs[i]->deleted
1530           || (ctx->magic == M_MAILDIR && option (OPTMAILDIRTRASH)))
1531         ctx->hdrs[i]->index = j++;
1532     }
1533   }
1534
1535   return 0;
1536
1537 err:
1538 #if USE_HCACHE
1539   if (ctx->magic == M_MAILDIR)
1540     mutt_hcache_close (hc);
1541 #endif /* USE_HCACHE */
1542   return -1;
1543 }
1544
1545 static char *maildir_canon_filename (char *dest, const char *src, size_t l)
1546 {
1547   char *t, *u;
1548
1549   if ((t = strrchr (src, '/')))
1550     src = t + 1;
1551
1552   strfcpy (dest, src, l);
1553   if ((u = strrchr (dest, ':')))
1554     *u = '\0';
1555
1556   return dest;
1557 }
1558
1559 static void maildir_update_tables (CONTEXT *ctx, int *index_hint)
1560 {
1561   short old_sort;
1562   int old_count;
1563   int i, j;
1564   
1565   if (Sort != SORT_ORDER)
1566   {
1567     old_sort = Sort;
1568     Sort = SORT_ORDER;
1569     mutt_sort_headers (ctx, 1);
1570     Sort = old_sort;
1571   }
1572   
1573   old_count = ctx->msgcount;
1574   for (i = 0, j = 0; i < old_count; i++)
1575   {
1576     if (ctx->hdrs[i]->active && index_hint && *index_hint == i)
1577       *index_hint = j;
1578     
1579     if (ctx->hdrs[i]->active)
1580       ctx->hdrs[i]->index = j++;
1581   }
1582
1583   mx_update_tables (ctx, 0);
1584   mutt_clear_threads (ctx);
1585 }
1586
1587 static void maildir_update_flags (CONTEXT *ctx, HEADER *o, HEADER *n)
1588 {
1589   /* save the global state here so we can reset it at the
1590    * end of list block if required.
1591    */
1592   int context_changed = ctx->changed;
1593   
1594   /* user didn't modify this message.  alter the flags to
1595    * match the current state on disk.  This may not actually
1596    * do anything, but we can't tell right now.  mutt_set_flag()
1597    * will just ignore the call if the status bits are
1598    * already properly set.
1599    */
1600   mutt_set_flag (ctx, o, M_FLAG, n->flagged);
1601   mutt_set_flag (ctx, o, M_REPLIED, n->replied);
1602   mutt_set_flag (ctx, o, M_READ, n->read);
1603   mutt_set_flag (ctx, o, M_OLD, n->old);
1604
1605   /* mutt_set_flag() will set this, but we don't need to
1606    * sync the changes we made because we just updated the
1607    * context to match the current on-disk state of the
1608    * message.
1609    */
1610   o->changed = 0;
1611   
1612   /* if the mailbox was not modified before we made these
1613    * changes, unset the changed flag since nothing needs to
1614    * be synchronized.
1615    */
1616   if (!context_changed)
1617     ctx->changed = 0;
1618 }
1619
1620
1621 /* This function handles arrival of new mail and reopening of
1622  * maildir folders.  The basic idea here is we check to see if either
1623  * the new or cur subdirectories have changed, and if so, we scan them
1624  * for the list of files.  We check for newly added messages, and
1625  * then merge the flags messages we already knew about.  We don't treat
1626  * either subdirectory differently, as mail could be copied directly into
1627  * the cur directory from another agent.
1628  */
1629 int maildir_check_mailbox (CONTEXT * ctx, int *index_hint)
1630 {
1631   struct stat st_new;           /* status of the "new" subdirectory */
1632   struct stat st_cur;           /* status of the "cur" subdirectory */
1633   char buf[_POSIX_PATH_MAX];
1634   int changed = 0;              /* bitmask representing which subdirectories
1635                                    have changed.  0x1 = new, 0x2 = cur */
1636   int occult = 0;               /* messages were removed from the mailbox */
1637   int have_new = 0;             /* messages were added to the mailbox */
1638   struct maildir *md;           /* list of messages in the mailbox */
1639   struct maildir **last, *p;
1640   int i;
1641   HASH *fnames;                 /* hash table for quickly looking up the base filename
1642                                    for a maildir message */
1643
1644   /* XXX seems like this check belongs in mx_check_mailbox()
1645    * rather than here.
1646    */
1647   if (!option (OPTCHECKNEW))
1648     return 0;
1649
1650   snprintf (buf, sizeof (buf), "%s/new", ctx->path);
1651   if (stat (buf, &st_new) == -1)
1652     return -1;
1653
1654   snprintf (buf, sizeof (buf), "%s/cur", ctx->path);
1655   if (stat (buf, &st_cur) == -1)
1656     return -1;
1657
1658   /* determine which subdirectories need to be scanned */
1659   if (st_new.st_mtime > ctx->mtime)
1660     changed = 1;
1661   if (st_cur.st_mtime > ctx->mtime_cur)
1662     changed |= 2;
1663
1664   if (!changed)
1665     return 0;                   /* nothing to do */
1666
1667   /* update the modification times on the mailbox */
1668   ctx->mtime_cur = st_cur.st_mtime;
1669   ctx->mtime = st_new.st_mtime;
1670
1671   /* do a fast scan of just the filenames in
1672    * the subdirectories that have changed.
1673    */
1674   md = NULL;
1675   last = &md;
1676   if (changed & 1)
1677     maildir_parse_dir (ctx, &last, "new", NULL);
1678   if (changed & 2)
1679     maildir_parse_dir (ctx, &last, "cur", NULL);
1680
1681   /* we create a hash table keyed off the canonical (sans flags) filename
1682    * of each message we scanned.  This is used in the loop over the
1683    * existing messages below to do some correlation.
1684    */
1685   fnames = hash_create (1031);
1686
1687   for (p = md; p; p = p->next)
1688   {
1689     maildir_canon_filename (buf, p->h->path, sizeof (buf));
1690     p->canon_fname = safe_strdup (buf);
1691     hash_insert (fnames, p->canon_fname, p, 0);
1692   }
1693
1694   /* check for modifications and adjust flags */
1695   for (i = 0; i < ctx->msgcount; i++)
1696   {
1697     ctx->hdrs[i]->active = 0;
1698     maildir_canon_filename (buf, ctx->hdrs[i]->path, sizeof (buf));
1699     p = hash_find (fnames, buf);
1700     if (p && p->h)
1701     {
1702       /* message already exists, merge flags */
1703       ctx->hdrs[i]->active = 1;
1704
1705       /* check to see if the message has moved to a different
1706        * subdirectory.  If so, update the associated filename.
1707        */
1708       if (mutt_strcmp (ctx->hdrs[i]->path, p->h->path))
1709         mutt_str_replace (&ctx->hdrs[i]->path, p->h->path);
1710
1711       /* if the user hasn't modified the flags on this message, update
1712        * the flags we just detected.
1713        */
1714       if (!ctx->hdrs[i]->changed)
1715         maildir_update_flags (ctx, ctx->hdrs[i], p->h);
1716
1717       if (ctx->hdrs[i]->deleted == ctx->hdrs[i]->trash)
1718         ctx->hdrs[i]->deleted = p->h->deleted;
1719       ctx->hdrs[i]->trash = p->h->trash;
1720
1721       /* this is a duplicate of an existing header, so remove it */
1722       mutt_free_header (&p->h);
1723     }
1724     /* This message was not in the list of messages we just scanned.
1725      * Check to see if we have enough information to know if the
1726      * message has disappeared out from underneath us.
1727      */
1728     else if (((changed & 1) && (!strncmp (ctx->hdrs[i]->path, "new/", 4))) ||
1729              ((changed & 2) && (!strncmp (ctx->hdrs[i]->path, "cur/", 4))))
1730     {
1731       /* This message disappeared, so we need to simulate a "reopen"
1732        * event.  We know it disappeared because we just scanned the
1733        * subdirectory it used to reside in.
1734        */
1735       occult = 1;
1736     }
1737     else
1738     {
1739       /* This message resides in a subdirectory which was not
1740        * modified, so we assume that it is still present and
1741        * unchanged.
1742        */
1743       ctx->hdrs[i]->active = 1;
1744     }
1745   }
1746
1747   /* destroy the file name hash */
1748   hash_destroy (&fnames, NULL);
1749
1750   /* If we didn't just get new mail, update the tables. */
1751   if (occult)
1752     maildir_update_tables (ctx, index_hint);
1753   
1754   /* do any delayed parsing we need to do. */
1755   maildir_delayed_parsing (ctx, md);
1756
1757   /* Incorporate new messages */
1758   have_new = maildir_move_to_context (ctx, &md);
1759
1760   return occult ? M_REOPENED : (have_new ? M_NEW_MAIL : 0);
1761 }
1762
1763 /* 
1764  * This function handles arrival of new mail and reopening of
1765  * mh/maildir folders. Things are getting rather complex because we
1766  * don't have a well-defined "mailbox order", so the tricks from
1767  * mbox.c and mx.c won't work here.
1768  *
1769  * Don't change this code unless you _really_ understand what
1770  * happens.
1771  *
1772  */
1773
1774 int mh_check_mailbox (CONTEXT * ctx, int *index_hint)
1775 {
1776   char buf[_POSIX_PATH_MAX];
1777   struct stat st, st_cur;
1778   short modified = 0, have_new = 0, occult = 0;
1779   struct maildir *md, *p;
1780   struct maildir **last = NULL;
1781   struct mh_sequences mhs;
1782   HASH *fnames;
1783   int i;
1784
1785   if (!option (OPTCHECKNEW))
1786     return 0;
1787
1788   strfcpy (buf, ctx->path, sizeof (buf));
1789   if (stat (buf, &st) == -1)
1790     return -1;
1791   
1792   /* create .mh_sequences when there isn't one. */
1793   snprintf (buf, sizeof (buf), "%s/.mh_sequences", ctx->path);
1794   if ((i = stat (buf, &st_cur) == -1) && errno == ENOENT)
1795   {
1796     char *tmp;
1797     FILE *fp = NULL;
1798     
1799     if (mh_mkstemp (ctx, &fp, &tmp) == 0)
1800     {
1801       safe_fclose (&fp);
1802       if (safe_rename (tmp, buf) == -1)
1803         unlink (tmp);
1804       FREE (&tmp);
1805     }
1806   }
1807
1808   if (i == -1 && stat (buf, &st_cur) == -1)
1809     modified = 1;
1810
1811   if (st.st_mtime > ctx->mtime || st_cur.st_mtime > ctx->mtime_cur)
1812     modified = 1;
1813
1814   if (!modified)
1815     return 0;
1816
1817   ctx->mtime_cur = st_cur.st_mtime;
1818   ctx->mtime = st.st_mtime;
1819
1820   memset (&mhs, 0, sizeof (mhs));
1821   
1822   md   = NULL;
1823   last = &md;
1824   maildir_parse_dir (ctx, &last, NULL, NULL);
1825   mh_read_sequences (&mhs, ctx->path);
1826   mh_update_maildir (md, &mhs);
1827   mhs_free_sequences (&mhs);
1828
1829   /* check for modifications and adjust flags */
1830   fnames = hash_create (1031);
1831
1832   for (p = md; p; p = p->next)
1833     hash_insert (fnames, p->h->path, p, 0);
1834
1835   for (i = 0; i < ctx->msgcount; i++)
1836   {
1837     ctx->hdrs[i]->active = 0;
1838
1839     if ((p = hash_find (fnames, ctx->hdrs[i]->path)) && p->h &&
1840         (mbox_strict_cmp_headers (ctx->hdrs[i], p->h)))
1841     {
1842       ctx->hdrs[i]->active = 1;
1843       /* found the right message */
1844       if (!ctx->hdrs[i]->changed)
1845         maildir_update_flags (ctx, ctx->hdrs[i], p->h);
1846
1847       mutt_free_header (&p->h);
1848     }
1849     else /* message has disappeared */
1850       occult = 1;
1851   }
1852
1853   /* destroy the file name hash */
1854
1855   hash_destroy (&fnames, NULL);
1856
1857   /* If we didn't just get new mail, update the tables. */
1858   if (occult)
1859     maildir_update_tables (ctx, index_hint);
1860
1861   /* Incorporate new messages */
1862   have_new = maildir_move_to_context (ctx, &md);
1863
1864   return occult ? M_REOPENED : (have_new ? M_NEW_MAIL : 0);
1865 }
1866
1867
1868
1869
1870 /*
1871  * These functions try to find a message in a maildir folder when it
1872  * has moved under our feet.  Note that this code is rather expensive, but
1873  * then again, it's called rarely.
1874  */
1875
1876 FILE *_maildir_open_find_message (const char *folder, const char *unique,
1877                                   const char *subfolder)
1878 {
1879   char dir[_POSIX_PATH_MAX];
1880   char tunique[_POSIX_PATH_MAX];
1881   char fname[_POSIX_PATH_MAX];
1882
1883   DIR *dp;
1884   struct dirent *de;
1885
1886   FILE *fp = NULL;
1887   int oe = ENOENT;
1888
1889   snprintf (dir, sizeof (dir), "%s/%s", folder, subfolder);
1890
1891   if ((dp = opendir (dir)) == NULL)
1892   {
1893     errno = ENOENT;
1894     return NULL;
1895   }
1896
1897   while ((de = readdir (dp)))
1898   {
1899     maildir_canon_filename (tunique, de->d_name, sizeof (tunique));
1900
1901     if (!mutt_strcmp (tunique, unique))
1902     {
1903       snprintf (fname, sizeof (fname), "%s/%s/%s", folder, subfolder,
1904                 de->d_name);
1905       fp = fopen (fname, "r");  /* __FOPEN_CHECKED__ */
1906       oe = errno;
1907       break;
1908     }
1909   }
1910
1911   closedir (dp);
1912
1913   errno = oe;
1914   return fp;
1915 }
1916
1917 FILE *maildir_open_find_message (const char *folder, const char *msg)
1918 {
1919   char unique[_POSIX_PATH_MAX];
1920   FILE *fp;
1921
1922   static unsigned int new_hits = 0, cur_hits = 0;       /* simple dynamic optimization */
1923
1924   maildir_canon_filename (unique, msg, sizeof (unique));
1925
1926   if (
1927       (fp =
1928        _maildir_open_find_message (folder, unique,
1929                                    new_hits > cur_hits ? "new" : "cur"))
1930       || errno != ENOENT)
1931   {
1932     if (new_hits < UINT_MAX && cur_hits < UINT_MAX)
1933     {
1934       new_hits += (new_hits > cur_hits ? 1 : 0);
1935       cur_hits += (new_hits > cur_hits ? 0 : 1);
1936     }
1937
1938     return fp;
1939   }
1940   if (
1941       (fp =
1942        _maildir_open_find_message (folder, unique,
1943                                    new_hits > cur_hits ? "cur" : "new"))
1944       || errno != ENOENT)
1945   {
1946     if (new_hits < UINT_MAX && cur_hits < UINT_MAX)
1947     {
1948       new_hits += (new_hits > cur_hits ? 0 : 1);
1949       cur_hits += (new_hits > cur_hits ? 1 : 0);
1950     }
1951
1952     return fp;
1953   }
1954
1955   return NULL;
1956 }
1957
1958
1959 /*
1960  * Returns:
1961  * 1 if there are no messages in the mailbox
1962  * 0 if there are messages in the mailbox
1963  * -1 on error
1964  */
1965 int maildir_check_empty (const char *path)
1966 {
1967   DIR *dp;
1968   struct dirent *de;
1969   int r = 1; /* assume empty until we find a message */
1970   char realpath[_POSIX_PATH_MAX];
1971   int iter = 0;
1972
1973   /* Strategy here is to look for any file not beginning with a period */
1974
1975   do {
1976     /* we do "cur" on the first iteration since its more likely that we'll
1977      * find old messages without having to scan both subdirs
1978      */
1979     snprintf (realpath, sizeof (realpath), "%s/%s", path,
1980               iter == 0 ? "cur" : "new");
1981     if ((dp = opendir (realpath)) == NULL)
1982       return -1;
1983     while ((de = readdir (dp)))
1984     {
1985       if (*de->d_name != '.')
1986       {
1987         r = 0;
1988         break;
1989       }
1990     }
1991     closedir (dp);
1992     iter++;
1993   } while (r && iter < 2);
1994
1995   return r;
1996 }
1997
1998 /*
1999  * Returns:
2000  * 1 if there are no messages in the mailbox
2001  * 0 if there are messages in the mailbox
2002  * -1 on error
2003  */
2004 int mh_check_empty (const char *path)
2005 {
2006   DIR *dp;
2007   struct dirent *de;
2008   int r = 1; /* assume empty until we find a message */
2009   
2010   if ((dp = opendir (path)) == NULL)
2011     return -1;
2012   while ((de = readdir (dp)))
2013   {
2014     if (mh_valid_message (de->d_name))
2015     {
2016       r = 0;
2017       break;
2018     }
2019   }
2020   closedir (dp);
2021   
2022   return r;
2023 }