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