dc900e4139b742969df91e59e8f7a5d3bc8b2469
[apps/madmutt.git] / mbox.c
1 /*
2  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
3  * 
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  * 
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  * 
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */ 
18
19 /* This file contains code to parse ``mbox'' and ``mmdf'' style mailboxes */
20
21 #include "mutt.h"
22 #include "mailbox.h"
23 #include "mx.h"
24 #include "sort.h"
25 #include "copy.h"
26
27 #include <sys/stat.h>
28 #include <dirent.h>
29 #include <string.h>
30 #include <utime.h>
31 #include <sys/file.h>
32 #include <errno.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35
36 /* struct used by mutt_sync_mailbox() to store new offsets */
37 struct m_update_t
38 {
39   short valid;
40   long hdr;
41   long body;
42   long lines;
43   long length;
44 };
45
46 /* parameters:
47  * ctx - context to lock
48  * excl - exclusive lock?
49  * retry - should retry if unable to lock?
50  */
51 int mbox_lock_mailbox (CONTEXT *ctx, int excl, int retry)
52 {
53   int r;
54
55   if ((r = mx_lock_file (ctx->path, fileno (ctx->fp), excl, 1, retry)) == 0)
56     ctx->locked = 1;
57   else if (retry && !excl)
58   {
59     ctx->readonly = 1;
60     return 0;
61   }
62   
63   return (r);
64 }
65
66 void mbox_unlock_mailbox (CONTEXT *ctx)
67 {
68   if (ctx->locked)
69   {
70     fflush (ctx->fp);
71
72     mx_unlock_file (ctx->path, fileno (ctx->fp), 1);
73     ctx->locked = 0;
74   }
75 }
76
77 int mmdf_parse_mailbox (CONTEXT *ctx)
78 {
79   char buf[HUGE_STRING];
80   char return_path[LONG_STRING];
81   int count = 0, oldmsgcount = ctx->msgcount;
82   int lines;
83   time_t t, tz;
84   long loc, tmploc;
85   HEADER *hdr;
86   struct stat sb;
87 #ifdef NFS_ATTRIBUTE_HACK
88   struct utimbuf newtime;
89 #endif
90
91   if (stat (ctx->path, &sb) == -1)
92   {
93     mutt_perror (ctx->path);
94     return (-1);
95   }
96   ctx->mtime = sb.st_mtime;
97   ctx->size = sb.st_size;
98
99 #ifdef NFS_ATTRIBUTE_HACK
100   if (sb.st_mtime > sb.st_atime)
101   {
102     newtime.modtime = sb.st_mtime;
103     newtime.actime = time (NULL);
104     utime (ctx->path, &newtime);
105   }
106 #endif
107
108   /* precompute the local timezone to speed up calculation of the
109      received time */
110   tz = mutt_local_tz (0);
111
112   buf[sizeof (buf) - 1] = 0;
113   
114   FOREVER
115   {
116     if (fgets (buf, sizeof (buf) - 1, ctx->fp) == NULL)
117       break;
118
119     if (mutt_strcmp (buf, MMDF_SEP) == 0)
120     {
121       loc = ftell (ctx->fp);
122       
123       count++;
124       if (!ctx->quiet && ReadInc && ((count % ReadInc == 0) || count == 1))
125         mutt_message (_("Reading %s... %d (%d%%)"), ctx->path, count,
126                       loc / (ctx->size / 100 + 1));
127
128
129       if (ctx->msgcount == ctx->hdrmax)
130         mx_alloc_memory (ctx);
131       ctx->hdrs[ctx->msgcount] = hdr = mutt_new_header ();
132       hdr->offset = loc;
133       hdr->index = ctx->msgcount;
134
135       if (fgets (buf, sizeof (buf) - 1, ctx->fp) == NULL)
136       {
137         /* TODO: memory leak??? */
138         dprint (1, (debugfile, "mmdf_parse_mailbox: unexpected EOF\n"));
139         break;
140       }
141
142       return_path[0] = 0;
143
144       if (!is_from (buf, return_path, sizeof (return_path), &t))
145       {
146         if (fseek (ctx->fp, loc, SEEK_SET) != 0)
147         {
148           dprint (1, (debugfile, "mmdf_parse_mailbox: fseek() failed\n"));
149           mutt_error _("Mailbox is corrupt!");
150           return (-1);
151         }
152       } 
153       else
154         hdr->received = t - tz;
155
156       hdr->env = mutt_read_rfc822_header (ctx->fp, hdr, 0, 0);
157
158       loc = ftell (ctx->fp);
159
160       if (hdr->content->length > 0 && hdr->lines > 0)
161       {
162         tmploc = loc + hdr->content->length;
163
164         if (0 < tmploc && tmploc < ctx->size)
165         {
166           if (fseek (ctx->fp, tmploc, SEEK_SET) != 0 ||
167               fgets (buf, sizeof (buf) - 1, ctx->fp) == NULL ||
168               mutt_strcmp (MMDF_SEP, buf) != 0)
169           {
170             if (fseek (ctx->fp, loc, SEEK_SET) != 0)
171               dprint (1, (debugfile, "mmdf_parse_mailbox: fseek() failed\n"));
172             hdr->content->length = -1;
173           }
174         }
175         else
176           hdr->content->length = -1;
177       }
178       else
179         hdr->content->length = -1;
180
181       if (hdr->content->length < 0)
182       {
183         lines = -1;
184         do {
185           loc = ftell (ctx->fp);
186           if (fgets (buf, sizeof (buf) - 1, ctx->fp) == NULL)
187             break;
188           lines++;
189         } while (mutt_strcmp (buf, MMDF_SEP) != 0);
190
191         hdr->lines = lines;
192         hdr->content->length = loc - hdr->content->offset;
193       }
194
195       if (!hdr->env->return_path && return_path[0])
196         hdr->env->return_path = rfc822_parse_adrlist (hdr->env->return_path, return_path);
197
198       if (!hdr->env->from)
199         hdr->env->from = rfc822_cpy_adr (hdr->env->return_path);
200
201       ctx->msgcount++;
202     }
203     else
204     {
205       dprint (1, (debugfile, "mmdf_parse_mailbox: corrupt mailbox!\n"));
206       mutt_error _("Mailbox is corrupt!");
207       return (-1);
208     }
209   }
210
211   if (ctx->msgcount > oldmsgcount)
212     mx_update_context (ctx, ctx->msgcount - oldmsgcount);
213
214   return (0);
215 }
216
217 /* Note that this function is also called when new mail is appended to the
218  * currently open folder, and NOT just when the mailbox is initially read.
219  *
220  * NOTE: it is assumed that the mailbox being read has been locked before
221  * this routine gets called.  Strange things could happen if it's not!
222  */
223 int mbox_parse_mailbox (CONTEXT *ctx)
224 {
225   struct stat sb;
226   char buf[HUGE_STRING], return_path[STRING];
227   HEADER *curhdr;
228   time_t t, tz;
229   int count = 0, lines = 0;
230   long loc;
231 #ifdef NFS_ATTRIBUTE_HACK
232   struct utimbuf newtime;
233 #endif
234
235   /* Save information about the folder at the time we opened it. */
236   if (stat (ctx->path, &sb) == -1)
237   {
238     mutt_perror (ctx->path);
239     return (-1);
240   }
241
242   ctx->size = sb.st_size;
243   ctx->mtime = sb.st_mtime;
244
245 #ifdef NFS_ATTRIBUTE_HACK
246   if (sb.st_mtime > sb.st_atime)
247   {
248     newtime.modtime = sb.st_mtime;
249     newtime.actime = time (NULL);
250     utime (ctx->path, &newtime);
251   }
252 #endif
253
254   if (!ctx->readonly)
255     ctx->readonly = access (ctx->path, W_OK) ? 1 : 0;
256
257   /* precompute the local timezone to speed up calculation of the
258      date received */
259   tz = mutt_local_tz (0);
260
261   loc = ftell (ctx->fp);
262   while (fgets (buf, sizeof (buf), ctx->fp) != NULL)
263   {
264     if (is_from (buf, return_path, sizeof (return_path), &t))
265     {
266       /* Save the Content-Length of the previous message */
267       if (count > 0)
268       {
269 #define PREV ctx->hdrs[ctx->msgcount-1]
270
271         if (PREV->content->length < 0)
272         {
273           PREV->content->length = loc - PREV->content->offset - 1;
274           if (PREV->content->length < 0)
275             PREV->content->length = 0;
276         }
277         if (!PREV->lines)
278           PREV->lines = lines ? lines - 1 : 0;
279       }
280
281       count++;
282
283       if (!ctx->quiet && ReadInc && ((count % ReadInc == 0) || count == 1))
284         mutt_message (_("Reading %s... %d (%d%%)"), ctx->path, count,
285                       ftell (ctx->fp) / (ctx->size / 100 + 1));
286
287       if (ctx->msgcount == ctx->hdrmax)
288         mx_alloc_memory (ctx);
289       
290       curhdr = ctx->hdrs[ctx->msgcount] = mutt_new_header ();
291       curhdr->received = t - tz;
292       curhdr->offset = loc;
293       curhdr->index = ctx->msgcount;
294         
295       curhdr->env = mutt_read_rfc822_header (ctx->fp, curhdr, 0, 0);
296
297       /* if we know how long this message is, either just skip over the body,
298        * or if we don't know how many lines there are, count them now (this will
299        * save time by not having to search for the next message marker).
300        */
301       if (curhdr->content->length > 0)
302       {
303         long tmploc;
304
305         loc = ftell (ctx->fp);
306         tmploc = loc + curhdr->content->length + 1;
307
308         if (0 < tmploc && tmploc < ctx->size)
309         {
310           /*
311            * check to see if the content-length looks valid.  we expect to
312            * to see a valid message separator at this point in the stream
313            */
314           if (fseek (ctx->fp, tmploc, SEEK_SET) != 0 ||
315               fgets (buf, sizeof (buf), ctx->fp) == NULL ||
316               mutt_strncmp ("From ", buf, 5) != 0)
317           {
318             dprint (1, (debugfile, "mbox_parse_mailbox: bad content-length in message %d (cl=%ld)\n", curhdr->index, curhdr->content->length));
319             dprint (1, (debugfile, "\tLINE: %s", buf));
320             if (fseek (ctx->fp, loc, SEEK_SET) != 0) /* nope, return the previous position */
321             {
322               dprint (1, (debugfile, "mbox_parse_mailbox: fseek() failed\n"));
323             }
324             curhdr->content->length = -1;
325           }
326         }
327         else if (tmploc != ctx->size)
328         {
329           /* content-length would put us past the end of the file, so it
330            * must be wrong
331            */
332           curhdr->content->length = -1;
333         }
334
335         if (curhdr->content->length != -1)
336         {
337           /* good content-length.  check to see if we know how many lines
338            * are in this message.
339            */
340           if (curhdr->lines == 0)
341           {
342             int cl = curhdr->content->length;
343
344             /* count the number of lines in this message */
345             if (fseek (ctx->fp, loc, SEEK_SET) != 0)
346               dprint (1, (debugfile, "mbox_parse_mailbox: fseek() failed\n"));
347             while (cl-- > 0)
348             {
349               if (fgetc (ctx->fp) == '\n')
350                 curhdr->lines++;
351             }
352           }
353
354           /* return to the offset of the next message separator */
355           if (fseek (ctx->fp, tmploc, SEEK_SET) != 0)
356             dprint (1, (debugfile, "mbox_parse_mailbox: fseek() failed\n"));
357         }
358       }
359
360       ctx->msgcount++;
361
362       if (!curhdr->env->return_path && return_path[0])
363         curhdr->env->return_path = rfc822_parse_adrlist (curhdr->env->return_path, return_path);
364
365       if (!curhdr->env->from)
366         curhdr->env->from = rfc822_cpy_adr (curhdr->env->return_path);
367
368       lines = 0;
369     }
370     else
371       lines++;
372     
373     loc = ftell (ctx->fp);
374   }
375   
376   /*
377    * Only set the content-length of the previous message if we have read more
378    * than one message during _this_ invocation.  If this routine is called
379    * when new mail is received, we need to make sure not to clobber what
380    * previously was the last message since the headers may be sorted.
381    */
382   if (count > 0)
383   {
384     if (PREV->content->length < 0)
385     {
386       PREV->content->length = ftell (ctx->fp) - PREV->content->offset - 1;
387       if (PREV->content->length < 0)
388         PREV->content->length = 0;
389     }
390
391     if (!PREV->lines)
392       PREV->lines = lines ? lines - 1 : 0;
393
394     mx_update_context (ctx, count);
395   }
396
397   return (0);
398 }
399
400 #undef PREV
401
402 /* open a mbox or mmdf style mailbox */
403 int mbox_open_mailbox (CONTEXT *ctx)
404 {
405   int rc;
406
407   if ((ctx->fp = fopen (ctx->path, "r")) == NULL)
408   {
409     mutt_perror (ctx->path);
410     return (-1);
411   }
412   mutt_block_signals ();
413   if (mbox_lock_mailbox (ctx, 0, 1) == -1)
414   {
415     mutt_unblock_signals ();
416     return (-1);
417   }
418
419   if (ctx->magic == M_MBOX)
420     rc = mbox_parse_mailbox (ctx);
421   else if (ctx->magic == M_MMDF)
422     rc = mmdf_parse_mailbox (ctx);
423   else
424     rc = -1;
425
426   mbox_unlock_mailbox (ctx);
427   mutt_unblock_signals ();
428   return (rc);
429 }
430
431 /* return 1 if address lists are strictly identical */
432 static int strict_addrcmp (const ADDRESS *a, const ADDRESS *b)
433 {
434   while (a && b)
435   {
436     if (mutt_strcmp (a->mailbox, b->mailbox) ||
437         mutt_strcmp (a->personal, b->personal))
438       return (0);
439
440     a = a->next;
441     b = b->next;
442   }
443   if (a || b)
444     return (0);
445
446   return (1);
447 }
448
449 static int strict_cmp_lists (const LIST *a, const LIST *b)
450 {
451   while (a && b)
452   {
453     if (mutt_strcmp (a->data, b->data))
454       return (0);
455
456     a = a->next;
457     b = b->next;
458   }
459   if (a || b)
460     return (0);
461
462   return (1);
463 }
464
465 static int strict_cmp_envelopes (const ENVELOPE *e1, const ENVELOPE *e2)
466 {
467   if (e1 && e2)
468   {
469     if (mutt_strcmp (e1->message_id, e2->message_id) ||
470         mutt_strcmp (e1->subject, e2->subject) ||
471         !strict_cmp_lists (e1->references, e2->references) ||
472         !strict_addrcmp (e1->from, e2->from) ||
473         !strict_addrcmp (e1->sender, e2->sender) ||
474         !strict_addrcmp (e1->reply_to, e2->reply_to) ||
475         !strict_addrcmp (e1->to, e2->to) ||
476         !strict_addrcmp (e1->cc, e2->cc) ||
477         !strict_addrcmp (e1->return_path, e2->return_path))
478       return (0);
479     else
480       return (1);
481   }
482   else
483   {
484     if (e1 == NULL && e2 == NULL)
485       return (1);
486     else
487       return (0);
488   }
489 }
490
491 static int strict_cmp_parameters (const PARAMETER *p1, const PARAMETER *p2)
492 {
493   while (p1 && p2)
494   {
495     if (mutt_strcmp (p1->attribute, p2->attribute) ||
496         mutt_strcmp (p1->value, p2->value))
497       return (0);
498
499     p1 = p1->next;
500     p2 = p2->next;
501   }
502   if (p1 || p2)
503     return (0);
504
505   return (1);
506 }
507
508 static int strict_cmp_bodies (const BODY *b1, const BODY *b2)
509 {
510   if (b1->type != b2->type ||
511       b1->encoding != b2->encoding ||
512       mutt_strcmp (b1->subtype, b2->subtype) ||
513       mutt_strcmp (b1->description, b2->description) ||
514       !strict_cmp_parameters (b1->parameter, b2->parameter) ||
515       b1->length != b2->length)
516     return (0);
517   return (1);
518 }
519
520 /* return 1 if headers are strictly identical */
521 int mbox_strict_cmp_headers (const HEADER *h1, const HEADER *h2)
522 {
523   if (h1 && h2)
524   {
525     if (h1->received != h2->received ||
526         h1->date_sent != h2->date_sent ||
527         h1->content->length != h2->content->length ||
528         h1->lines != h2->lines ||
529         h1->zhours != h2->zhours ||
530         h1->zminutes != h2->zminutes ||
531         h1->zoccident != h2->zoccident ||
532         h1->mime != h2->mime ||
533         !strict_cmp_envelopes (h1->env, h2->env) ||
534         !strict_cmp_bodies (h1->content, h2->content))
535       return (0);
536     else
537       return (1);
538   }
539   else
540   {
541     if (h1 == NULL && h2 == NULL)
542       return (1);
543     else
544       return (0);
545   }
546 }
547
548 /* check to see if the mailbox has changed on disk.
549  *
550  * return values:
551  *      M_REOPENED      mailbox has been reopened
552  *      M_NEW_MAIL      new mail has arrived!
553  *      M_LOCKED        couldn't lock the file
554  *      0               no change
555  *      -1              error
556  */
557 int mbox_check_mailbox (CONTEXT *ctx, int *index_hint)
558 {
559   struct stat st;
560   char buffer[LONG_STRING];
561   int unlock = 0;
562   int modified = 0;
563
564   if (stat (ctx->path, &st) == 0)
565   {
566     if (st.st_mtime == ctx->mtime && st.st_size == ctx->size)
567       return (0);
568
569     if (st.st_size == ctx->size)
570     {
571       /* the file was touched, but it is still the same length, so just exit */
572       ctx->mtime = st.st_mtime;
573       return (0);
574     }
575
576     if (st.st_size > ctx->size)
577     {
578       /* lock the file if it isn't already */
579       if (!ctx->locked)
580       {
581         mutt_block_signals ();
582         if (mbox_lock_mailbox (ctx, 0, 0) == -1)
583         {
584           mutt_unblock_signals ();
585           /* we couldn't lock the mailbox, but nothing serious happened:
586            * probably the new mail arrived: no reason to wait till we can
587            * parse it: we'll get it on the next pass
588            */
589           return (M_LOCKED);
590         }
591         unlock = 1;
592       }
593
594       /*
595        * Check to make sure that the only change to the mailbox is that 
596        * message(s) were appended to this file.  My heuristic is that we should
597        * see the message separator at *exactly* what used to be the end of the
598        * folder.
599        */
600       if (fseek (ctx->fp, ctx->size, SEEK_SET) != 0)
601         dprint (1, (debugfile, "mbox_check_mailbox: fseek() failed\n"));
602       if (fgets (buffer, sizeof (buffer), ctx->fp) != NULL)
603       {
604         if ((ctx->magic == M_MBOX && mutt_strncmp ("From ", buffer, 5) == 0) ||
605             (ctx->magic == M_MMDF && mutt_strcmp (MMDF_SEP, buffer) == 0))
606         {
607           if (fseek (ctx->fp, ctx->size, SEEK_SET) != 0)
608             dprint (1, (debugfile, "mbox_check_mailbox: fseek() failed\n"));
609           if (ctx->magic == M_MBOX)
610             mbox_parse_mailbox (ctx);
611           else
612             mmdf_parse_mailbox (ctx);
613
614           /* Only unlock the folder if it was locked inside of this routine.
615            * It may have been locked elsewhere, like in
616            * mutt_checkpoint_mailbox().
617            */
618
619           if (unlock)
620           {
621             mbox_unlock_mailbox (ctx);
622             mutt_unblock_signals ();
623           }
624
625           return (M_NEW_MAIL); /* signal that new mail arrived */
626         }
627         else
628           modified = 1;
629       }
630       else
631       {
632         dprint (1, (debugfile, "mbox_check_mailbox: fgets returned NULL.\n"));
633         modified = 1;
634       }
635     }
636     else
637       modified = 1;
638   }
639
640   if (modified)
641   {
642     if (mutt_reopen_mailbox (ctx, index_hint) != -1)
643     {
644       if (unlock)
645       {
646         mbox_unlock_mailbox (ctx);
647         mutt_unblock_signals ();
648       }
649       return (M_REOPENED);
650     }
651   }
652
653   /* fatal error */
654
655   mbox_unlock_mailbox (ctx);
656   mx_fastclose_mailbox (ctx);
657   mutt_unblock_signals ();
658   mutt_error _("Mailbox was corrupted!");
659   return (-1);
660 }
661
662 /* return values:
663  *      0       success
664  *      -1      failure
665  */
666 int mbox_sync_mailbox (CONTEXT *ctx, int *index_hint)
667 {
668   char tempfile[_POSIX_PATH_MAX];
669   char buf[32];
670   int i, j, save_sort = SORT_ORDER;
671   int rc = -1;
672   int need_sort = 0; /* flag to resort mailbox if new mail arrives */
673   int first = -1;       /* first message to be written */
674   long offset;  /* location in mailbox to write changed messages */
675   struct stat statbuf;
676   struct utimbuf utimebuf;
677   struct m_update_t *newOffset = NULL;
678   struct m_update_t *oldOffset = NULL;
679   FILE *fp = NULL;
680
681   /* sort message by their position in the mailbox on disk */
682   if (Sort != SORT_ORDER)
683   {
684     save_sort = Sort;
685     Sort = SORT_ORDER;
686     mutt_sort_headers (ctx, 0);
687   }
688
689   /* need to open the file for writing in such a way that it does not truncate
690    * the file, so use read-write mode.
691    */
692   if ((ctx->fp = freopen (ctx->path, "r+", ctx->fp)) == NULL)
693   {
694     mx_fastclose_mailbox (ctx);
695     mutt_error _("Fatal error!  Could not reopen mailbox!");
696     return (-1);
697   }
698
699   mutt_block_signals ();
700
701   if (mbox_lock_mailbox (ctx, 1, 1) == -1)
702   {
703     mutt_unblock_signals ();
704     mutt_error _("Unable to lock mailbox!");
705     goto bail;
706   }
707
708   /* Check to make sure that the file hasn't changed on disk */
709   if ((i = mbox_check_mailbox (ctx, index_hint)) == M_NEW_MAIL ||  i == M_REOPENED)
710   {
711     /* new mail arrived, or mailbox reopened */
712     need_sort = i;
713     rc = i;
714     goto bail;
715   }
716   else if (i < 0)
717   {
718     /* fatal error */
719     Sort = save_sort;
720     return (-1);
721   }
722
723   /* Create a temporary file to write the new version of the mailbox in. */
724   mutt_mktemp (tempfile);
725   if ((i = open (tempfile, O_WRONLY | O_EXCL | O_CREAT, 0600)) == -1 ||
726       (fp = fdopen (i, "w")) == NULL)
727   {
728     if (-1 != i)
729     {
730       close (i);
731       unlink (tempfile);
732     }
733     mutt_error _("Could not create temporary file!");
734     mutt_sleep (5);
735     goto bail;
736   }
737
738   /* find the first deleted/changed message.  we save a lot of time by only
739    * rewriting the mailbox from the point where it has actually changed.
740    */
741   for (i = 0 ; i < ctx->msgcount && !ctx->hdrs[i]->deleted && 
742                !ctx->hdrs[i]->changed && !ctx->hdrs[i]->attach_del; i++)
743     ;
744   if (i == ctx->msgcount)
745   { 
746     /* this means ctx->changed or ctx->deleted was set, but no
747      * messages were found to be changed or deleted.  This should
748      * never happen, is we presume it is a bug in mutt.
749      */
750     mutt_error _("sync: mbox modified, but no modified messages! (report this bug)");
751     mutt_sleep(5); /* the mutt_error /will/ get cleared! */
752     dprint(1, (debugfile, "mbox_sync_mailbox(): no modified messages.\n"));
753     unlink (tempfile);
754     goto bail;
755   }
756
757     /* save the index of the first changed/deleted message */
758   first = i; 
759   /* where to start overwriting */
760   offset = ctx->hdrs[i]->offset; 
761
762   /* the offset stored in the header does not include the MMDF_SEP, so make
763    * sure we seek to the correct location
764    */
765   if (ctx->magic == M_MMDF)
766     offset -= (sizeof MMDF_SEP - 1);
767   
768   /* allocate space for the new offsets */
769   newOffset = safe_calloc (ctx->msgcount - first, sizeof (struct m_update_t));
770   oldOffset = safe_calloc (ctx->msgcount - first, sizeof (struct m_update_t));
771
772   for (i = first, j = 0; i < ctx->msgcount; i++)
773   {
774     /*
775      * back up some information which is needed to restore offsets when
776      * something fails.
777      */
778     
779     oldOffset[i-first].valid  = 1;
780     oldOffset[i-first].hdr    = ctx->hdrs[i]->offset;
781     oldOffset[i-first].body   = ctx->hdrs[i]->content->offset;
782     oldOffset[i-first].lines  = ctx->hdrs[i]->lines;
783     oldOffset[i-first].length = ctx->hdrs[i]->content->length;
784     
785     if (! ctx->hdrs[i]->deleted)
786     {
787       j++;
788       if (!ctx->quiet && WriteInc && ((i % WriteInc) == 0 || j == 1))
789         mutt_message (_("Writing messages... %d (%d%%)"), i,
790                       ftell (ctx->fp) / (ctx->size / 100 + 1));
791
792       if (ctx->magic == M_MMDF)
793       {
794         if (fputs (MMDF_SEP, fp) == EOF)
795         {
796           mutt_perror (tempfile);
797           mutt_sleep (5);
798           unlink (tempfile);
799           goto bail;
800         }
801           
802       }
803
804       /* save the new offset for this message.  we add `offset' because the
805        * temporary file only contains saved message which are located after
806        * `offset' in the real mailbox
807        */
808       newOffset[i - first].hdr = ftell (fp) + offset;
809
810       if (mutt_copy_message (fp, ctx, ctx->hdrs[i], M_CM_UPDATE, CH_FROM | CH_UPDATE | CH_UPDATE_LEN) == -1)
811       {
812         mutt_perror (tempfile);
813         mutt_sleep (5);
814         unlink (tempfile);
815         goto bail;
816       }
817
818       /* Since messages could have been deleted, the offsets stored in memory
819        * will be wrong, so update what we can, which is the offset of this
820        * message, and the offset of the body.  If this is a multipart message,
821        * we just flush the in memory cache so that the message will be reparsed
822        * if the user accesses it later.
823        */
824       newOffset[i - first].body = ftell (fp) - ctx->hdrs[i]->content->length + offset;
825       mutt_free_body (&ctx->hdrs[i]->content->parts);
826
827       switch(ctx->magic)
828       {
829         case M_MMDF: 
830           if(fputs(MMDF_SEP, fp) == EOF) 
831           {
832             mutt_perror (tempfile);
833             mutt_sleep (5);
834             unlink (tempfile);
835             goto bail; 
836           }
837           break;
838         default:
839           if(fputs("\n", fp) == EOF) 
840           {
841             mutt_perror (tempfile);
842             mutt_sleep (5);
843             unlink (tempfile);
844             goto bail;
845           }
846       }
847     }
848   }
849   
850   if (fclose (fp) != 0)
851   {
852     fp = NULL;
853     dprint(1, (debugfile, "mbox_sync_mailbox: fclose() returned non-zero.\n"));
854     unlink (tempfile);
855     mutt_perror (tempfile);
856     mutt_sleep (5);
857     goto bail;
858   }
859   fp = NULL;
860
861   /* Save the state of this folder. */
862   if (stat (ctx->path, &statbuf) == -1)
863   {
864     mutt_perror (ctx->path);
865     mutt_sleep (5);
866     unlink (tempfile);
867     goto bail;
868   }
869
870   if ((fp = fopen (tempfile, "r")) == NULL)
871   {
872     mutt_unblock_signals ();
873     mx_fastclose_mailbox (ctx);
874     dprint (1, (debugfile, "mbox_sync_mailbox: unable to reopen temp copy of mailbox!\n"));
875     mutt_perror (tempfile);
876     mutt_sleep (5);
877     return (-1);
878   }
879
880   if (fseek (ctx->fp, offset, SEEK_SET) != 0 ||  /* seek the append location */
881       /* do a sanity check to make sure the mailbox looks ok */
882       fgets (buf, sizeof (buf), ctx->fp) == NULL ||
883       (ctx->magic == M_MBOX && mutt_strncmp ("From ", buf, 5) != 0) ||
884       (ctx->magic == M_MMDF && mutt_strcmp (MMDF_SEP, buf) != 0))
885   {
886     dprint (1, (debugfile, "mbox_sync_mailbox: message not in expected position."));
887     dprint (1, (debugfile, "\tLINE: %s\n", buf));
888     i = -1;
889   }
890   else
891   {
892     if (fseek (ctx->fp, offset, SEEK_SET) != 0) /* return to proper offset */
893     {
894       i = -1;
895       dprint (1, (debugfile, "mbox_sync_mailbox: fseek() failed\n"));
896     }
897     else
898     {
899       /* copy the temp mailbox back into place starting at the first
900        * change/deleted message
901        */
902       mutt_message _("Committing changes...");
903       i = mutt_copy_stream (fp, ctx->fp);
904
905       if (ferror (ctx->fp))
906         i = -1;
907     }
908     if (i == 0)
909     {
910       ctx->size = ftell (ctx->fp); /* update the size of the mailbox */
911       ftruncate (fileno (ctx->fp), ctx->size);
912     }
913   }
914
915   fclose (fp);
916   fp = NULL;
917   mbox_unlock_mailbox (ctx);
918
919   if (fclose (ctx->fp) != 0 || i == -1)
920   {
921     /* error occured while writing the mailbox back, so keep the temp copy
922      * around
923      */
924     
925     char savefile[_POSIX_PATH_MAX];
926     
927     snprintf (savefile, sizeof (savefile), "%s/mutt.%s-%s-%d",
928               NONULL (Tempdir), NONULL(Username), NONULL(Hostname), getpid ());
929     rename (tempfile, savefile);
930     mutt_unblock_signals ();
931     mx_fastclose_mailbox (ctx);
932     mutt_pretty_mailbox (savefile);
933     mutt_error (_("Write failed!  Saved partial mailbox to %s"), savefile);
934     mutt_sleep (5);
935     return (-1);
936   }
937
938   /* Restore the previous access/modification times */
939   utimebuf.actime = statbuf.st_atime;
940   utimebuf.modtime = statbuf.st_mtime;
941   utime (ctx->path, &utimebuf);
942
943   /* reopen the mailbox in read-only mode */
944   if ((ctx->fp = fopen (ctx->path, "r")) == NULL)
945   {
946     unlink (tempfile);
947     mutt_unblock_signals ();
948     mx_fastclose_mailbox (ctx);
949     mutt_error _("Fatal error!  Could not reopen mailbox!");
950     Sort = save_sort;
951     return (-1);
952   }
953
954   /* update the offsets of the rewritten messages */
955   for (i = first, j = first; i < ctx->msgcount; i++)
956   {
957     if (!ctx->hdrs[i]->deleted)
958     {
959       ctx->hdrs[i]->offset = newOffset[i - first].hdr;
960       ctx->hdrs[i]->content->hdr_offset = newOffset[i - first].hdr;
961       ctx->hdrs[i]->content->offset = newOffset[i - first].body;
962       ctx->hdrs[i]->index = j++;
963     }
964   }
965   FREE (&newOffset);
966   FREE (&oldOffset);
967   unlink (tempfile); /* remove partial copy of the mailbox */
968   mutt_unblock_signals ();
969   Sort = save_sort; /* Restore the default value. */
970
971   return (0); /* signal success */
972
973 bail:  /* Come here in case of disaster */
974
975   safe_fclose (&fp);
976
977   /* restore offsets, as far as they are valid */
978   if (first >= 0 && oldOffset)
979   {
980     for (i = first; i < ctx->msgcount && oldOffset[i-first].valid; i++)
981     {
982       ctx->hdrs[i]->offset = oldOffset[i-first].hdr;
983       ctx->hdrs[i]->content->hdr_offset = oldOffset[i-first].hdr;
984       ctx->hdrs[i]->content->offset = oldOffset[i-first].body;
985       ctx->hdrs[i]->lines = oldOffset[i-first].lines;
986       ctx->hdrs[i]->content->length = oldOffset[i-first].length;
987     }
988   }
989   
990   /* this is ok to call even if we haven't locked anything */
991   mbox_unlock_mailbox (ctx);
992
993   mutt_unblock_signals ();
994   FREE (&newOffset);
995   FREE (&oldOffset);
996
997   if ((ctx->fp = freopen (ctx->path, "r", ctx->fp)) == NULL)
998   {
999     mutt_error _("Could not reopen mailbox!");
1000     mx_fastclose_mailbox (ctx);
1001     return (-1);
1002   }
1003
1004   if (need_sort || save_sort != Sort)
1005   {
1006     Sort = save_sort;
1007     /* if the mailbox was reopened, the thread tree will be invalid so make
1008      * sure to start threading from scratch.  */
1009     mutt_sort_headers (ctx, (need_sort == M_REOPENED));
1010   }
1011
1012   return rc;
1013 }
1014
1015 /* close a mailbox opened in write-mode */
1016 int mbox_close_mailbox (CONTEXT *ctx)
1017 {
1018   mx_unlock_file (ctx->path, fileno (ctx->fp), 1);
1019   mutt_unblock_signals ();
1020   mx_fastclose_mailbox (ctx);
1021   return 0;
1022 }
1023
1024 int mutt_reopen_mailbox (CONTEXT *ctx, int *index_hint)
1025 {
1026   int (*cmp_headers) (const HEADER *, const HEADER *) = NULL;
1027   HEADER **old_hdrs;
1028   int old_msgcount;
1029   int msg_mod = 0;
1030   int index_hint_set;
1031   int i, j;
1032   int rc = -1;
1033
1034   /* silent operations */
1035   ctx->quiet = 1;
1036   
1037   mutt_message _("Reopening mailbox...");
1038   
1039   /* our heuristics require the old mailbox to be unsorted */
1040   if (Sort != SORT_ORDER)
1041   {
1042     short old_sort;
1043
1044     old_sort = Sort;
1045     Sort = SORT_ORDER;
1046     mutt_sort_headers (ctx, 1);
1047     Sort = old_sort;
1048   }
1049
1050   old_hdrs = NULL;
1051   old_msgcount = 0;
1052   
1053   /* simulate a close */
1054   if (ctx->id_hash)
1055     hash_destroy (&ctx->id_hash, NULL);
1056   if (ctx->subj_hash)
1057     hash_destroy (&ctx->subj_hash, NULL);
1058   mutt_clear_threads (ctx);
1059   FREE (&ctx->v2r);
1060   if (ctx->readonly)
1061   {
1062     for (i = 0; i < ctx->msgcount; i++)
1063       mutt_free_header (&(ctx->hdrs[i])); /* nothing to do! */
1064     FREE (&ctx->hdrs);
1065   }
1066   else
1067   {
1068       /* save the old headers */
1069     old_msgcount = ctx->msgcount;
1070     old_hdrs = ctx->hdrs;
1071     ctx->hdrs = NULL;
1072   }
1073
1074   ctx->hdrmax = 0;      /* force allocation of new headers */
1075   ctx->msgcount = 0;
1076   ctx->vcount = 0;
1077   ctx->tagged = 0;
1078   ctx->deleted = 0;
1079   ctx->new = 0;
1080   ctx->unread = 0;
1081   ctx->flagged = 0;
1082   ctx->changed = 0;
1083   ctx->id_hash = NULL;
1084   ctx->subj_hash = NULL;
1085
1086   switch (ctx->magic)
1087   {
1088     case M_MBOX:
1089     case M_MMDF:
1090       if (fseek (ctx->fp, 0, SEEK_SET) != 0)
1091       {
1092         dprint (1, (debugfile, "mutt_reopen_mailbox: fseek() failed\n"));
1093         rc = -1;
1094       } 
1095       else 
1096       {
1097         cmp_headers = mbox_strict_cmp_headers;
1098         rc = ((ctx->magic == M_MBOX) ? mbox_parse_mailbox
1099                                      : mmdf_parse_mailbox) (ctx);
1100       }
1101       break;
1102
1103     default:
1104       rc = -1;
1105       break;
1106   }
1107   
1108   if (rc == -1)
1109   {
1110     /* free the old headers */
1111     for (j = 0; j < old_msgcount; j++)
1112       mutt_free_header (&(old_hdrs[j]));
1113     FREE (&old_hdrs);
1114
1115     ctx->quiet = 0;
1116     return (-1);
1117   }
1118
1119   /* now try to recover the old flags */
1120
1121   index_hint_set = (index_hint == NULL);
1122
1123   if (!ctx->readonly)
1124   {
1125     for (i = 0; i < ctx->msgcount; i++)
1126     {
1127       int found = 0;
1128
1129       /* some messages have been deleted, and new  messages have been
1130        * appended at the end; the heuristic is that old messages have then
1131        * "advanced" towards the beginning of the folder, so we begin the
1132        * search at index "i"
1133        */
1134       for (j = i; j < old_msgcount; j++)
1135       {
1136         if (old_hdrs[j] == NULL)
1137           continue;
1138         if (cmp_headers (ctx->hdrs[i], old_hdrs[j]))
1139         {
1140           found = 1;
1141           break;
1142         }
1143       }
1144       if (!found)
1145       {
1146         for (j = 0; j < i && j < old_msgcount; j++)
1147         {
1148           if (old_hdrs[j] == NULL)
1149             continue;
1150           if (cmp_headers (ctx->hdrs[i], old_hdrs[j]))
1151           {
1152             found = 1;
1153             break;
1154           }
1155         }
1156       }
1157
1158       if (found)
1159       {
1160         /* this is best done here */
1161         if (!index_hint_set && *index_hint == j)
1162           *index_hint = i;
1163
1164         if (old_hdrs[j]->changed)
1165         {
1166           /* Only update the flags if the old header was changed;
1167            * otherwise, the header may have been modified externally,
1168            * and we don't want to lose _those_ changes
1169            */
1170           mutt_set_flag (ctx, ctx->hdrs[i], M_FLAG, old_hdrs[j]->flagged);
1171           mutt_set_flag (ctx, ctx->hdrs[i], M_REPLIED, old_hdrs[j]->replied);
1172           mutt_set_flag (ctx, ctx->hdrs[i], M_OLD, old_hdrs[j]->old);
1173           mutt_set_flag (ctx, ctx->hdrs[i], M_READ, old_hdrs[j]->read);
1174         }
1175         mutt_set_flag (ctx, ctx->hdrs[i], M_DELETE, old_hdrs[j]->deleted);
1176         mutt_set_flag (ctx, ctx->hdrs[i], M_TAG, old_hdrs[j]->tagged);
1177
1178         /* we don't need this header any more */
1179         mutt_free_header (&(old_hdrs[j]));
1180       }
1181     }
1182
1183     /* free the remaining old headers */
1184     for (j = 0; j < old_msgcount; j++)
1185     {
1186       if (old_hdrs[j])
1187       {
1188         mutt_free_header (&(old_hdrs[j]));
1189         msg_mod = 1;
1190       }
1191     }
1192     FREE (&old_hdrs);
1193   }
1194
1195   ctx->quiet = 0;
1196
1197   return ((ctx->changed || msg_mod) ? M_REOPENED : M_NEW_MAIL);
1198 }
1199
1200 /*
1201  * Returns:
1202  * 1 if the mailbox is not empty
1203  * 0 if the mailbox is empty
1204  * -1 on error
1205  */
1206 int mbox_check_empty (const char *path)
1207 {
1208   struct stat st;
1209
1210   if (stat (path, &st) == -1)
1211     return -1;
1212
1213   return ((st.st_size == 0));
1214 }