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