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