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