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