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