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