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