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