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