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