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 (str_cmp (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               str_cmp (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 (str_cmp (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               str_ncmp ("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 && str_ncmp ("From ", buffer, 5) == 0)
471             || (ctx->magic == M_MMDF && str_cmp (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     Sort = save_sort;
568     need_sort = 1;
569   }
570
571   /* need to open the file for writing in such a way that it does not truncate
572    * the file, so use read-write mode.
573    */
574   if ((ctx->fp = freopen (ctx->path, "r+", ctx->fp)) == NULL) {
575     mx_fastclose_mailbox (ctx);
576     mutt_error _("Fatal error!  Could not reopen mailbox!");
577
578     return (-1);
579   }
580
581   mutt_block_signals ();
582
583   if (mbox_lock_mailbox (ctx, 1, 1) == -1) {
584     mutt_unblock_signals ();
585     mutt_error _("Unable to lock mailbox!");
586
587     goto bail;
588   }
589
590   /* Check to make sure that the file hasn't changed on disk */
591   if ((i = _mbox_check_mailbox (ctx, index_hint)) == M_NEW_MAIL
592       || i == M_REOPENED) {
593     /* new mail arrived, or mailbox reopened */
594     need_sort = i;
595     rc = i;
596     goto bail;
597   }
598   else if (i < 0)
599     /* fatal error */
600     return (-1);
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 = mem_calloc (ctx->msgcount - first, sizeof (struct m_update_t));
647   oldOffset = mem_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 && str_ncmp ("From ", buf, 5) != 0) ||
753       (ctx->magic == M_MMDF && str_cmp (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     return (-1);
815   }
816
817   /* update the offsets of the rewritten messages */
818   for (i = first, j = first; i < ctx->msgcount; i++) {
819     if (!ctx->hdrs[i]->deleted) {
820       ctx->hdrs[i]->offset = newOffset[i - first].hdr;
821       ctx->hdrs[i]->content->hdr_offset = newOffset[i - first].hdr;
822       ctx->hdrs[i]->content->offset = newOffset[i - first].body;
823       ctx->hdrs[i]->index = j++;
824     }
825   }
826   mem_free (&newOffset);
827   mem_free (&oldOffset);
828   unlink (tempfile);            /* remove partial copy of the mailbox */
829   mutt_unblock_signals ();
830
831   return (0);                   /* signal success */
832
833 bail:                          /* Come here in case of disaster */
834
835   safe_fclose (&fp);
836
837   /* restore offsets, as far as they are valid */
838   if (first >= 0 && oldOffset) {
839     for (i = first; i < ctx->msgcount && oldOffset[i - first].valid; i++) {
840       ctx->hdrs[i]->offset = oldOffset[i - first].hdr;
841       ctx->hdrs[i]->content->hdr_offset = oldOffset[i - first].hdr;
842       ctx->hdrs[i]->content->offset = oldOffset[i - first].body;
843       ctx->hdrs[i]->lines = oldOffset[i - first].lines;
844       ctx->hdrs[i]->content->length = oldOffset[i - first].length;
845     }
846   }
847
848   /* this is ok to call even if we haven't locked anything */
849   mbox_unlock_mailbox (ctx);
850
851   mutt_unblock_signals ();
852   mem_free (&newOffset);
853   mem_free (&oldOffset);
854
855   if ((ctx->fp = freopen (ctx->path, "r", ctx->fp)) == NULL) {
856     mutt_error _("Could not reopen mailbox!");
857
858     mx_fastclose_mailbox (ctx);
859     return (-1);
860   }
861
862   if (need_sort)
863     /* if the mailbox was reopened, the thread tree will be invalid so make
864      * sure to start threading from scratch.  */
865     mutt_sort_headers (ctx, (need_sort == M_REOPENED));
866
867   return rc;
868 }
869
870 static int mbox_sync_mailbox (CONTEXT * ctx, int unused, int *index_hint) {
871 #ifdef BUFFY_SIZE
872   BUFFY* tmp = NULL;
873 #endif
874   int rc = _mbox_sync_mailbox (ctx, unused, index_hint);
875
876 #ifdef BUFFY_SIZE
877   if ((tmp = buffy_find_mailbox (ctx->path)) && tmp->new == 0)
878     buffy_update_mailbox (tmp);
879 #endif
880   return (rc);
881 }
882
883 /* close a mailbox opened in write-mode */
884 int mbox_close_mailbox (CONTEXT * ctx)
885 {
886   mx_unlock_file (ctx->path, fileno (ctx->fp), 1);
887
888 #ifdef USE_COMPRESSED
889   if (ctx->compressinfo)
890     mutt_slow_close_compressed (ctx);
891 #endif
892
893   mutt_unblock_signals ();
894   mx_fastclose_mailbox (ctx);
895   return 0;
896 }
897
898 static int mbox_reopen_mailbox (CONTEXT * ctx, int *index_hint)
899 {
900   int (*cmp_headers) (const HEADER *, const HEADER *) = NULL;
901   HEADER **old_hdrs;
902   int old_msgcount;
903   int msg_mod = 0;
904   int index_hint_set;
905   int i, j;
906   int rc = -1;
907
908   /* silent operations */
909   ctx->quiet = 1;
910
911   mutt_message _("Reopening mailbox...");
912
913   /* our heuristics require the old mailbox to be unsorted */
914   if (Sort != SORT_ORDER) {
915     short old_sort;
916
917     old_sort = Sort;
918     Sort = SORT_ORDER;
919     mutt_sort_headers (ctx, 1);
920     Sort = old_sort;
921   }
922
923   old_hdrs = NULL;
924   old_msgcount = 0;
925
926   /* simulate a close */
927   if (ctx->id_hash)
928     hash_destroy (&ctx->id_hash, NULL);
929   if (ctx->subj_hash)
930     hash_destroy (&ctx->subj_hash, NULL);
931   mutt_clear_threads (ctx);
932   mem_free (&ctx->v2r);
933   if (ctx->readonly) {
934     for (i = 0; i < ctx->msgcount; i++)
935       mutt_free_header (&(ctx->hdrs[i]));       /* nothing to do! */
936     mem_free (&ctx->hdrs);
937   }
938   else {
939     /* save the old headers */
940     old_msgcount = ctx->msgcount;
941     old_hdrs = ctx->hdrs;
942     ctx->hdrs = NULL;
943   }
944
945   ctx->hdrmax = 0;              /* force allocation of new headers */
946   ctx->msgcount = 0;
947   ctx->vcount = 0;
948   ctx->tagged = 0;
949   ctx->deleted = 0;
950   ctx->new = 0;
951   ctx->unread = 0;
952   ctx->flagged = 0;
953   ctx->changed = 0;
954   ctx->id_hash = NULL;
955   ctx->subj_hash = NULL;
956
957   switch (ctx->magic) {
958   case M_MBOX:
959   case M_MMDF:
960     if (fseek (ctx->fp, 0, SEEK_SET) != 0) {
961       debug_print (1, ("fseek() failed\n"));
962       rc = -1;
963     }
964     else {
965       cmp_headers = mutt_cmp_header;
966       if (ctx->magic == M_MBOX)
967         rc = mbox_parse_mailbox (ctx);
968       else
969         rc = mmdf_parse_mailbox (ctx);
970     }
971     break;
972
973   default:
974     rc = -1;
975     break;
976   }
977
978   if (rc == -1) {
979     /* free the old headers */
980     for (j = 0; j < old_msgcount; j++)
981       mutt_free_header (&(old_hdrs[j]));
982     mem_free (&old_hdrs);
983
984     ctx->quiet = 0;
985     return (-1);
986   }
987
988   /* now try to recover the old flags */
989
990   index_hint_set = (index_hint == NULL);
991
992   if (!ctx->readonly) {
993     for (i = 0; i < ctx->msgcount; i++) {
994       int found = 0;
995
996       /* some messages have been deleted, and new  messages have been
997        * appended at the end; the heuristic is that old messages have then
998        * "advanced" towards the beginning of the folder, so we begin the
999        * search at index "i"
1000        */
1001       for (j = i; j < old_msgcount; j++) {
1002         if (old_hdrs[j] == NULL)
1003           continue;
1004         if (cmp_headers (ctx->hdrs[i], old_hdrs[j])) {
1005           found = 1;
1006           break;
1007         }
1008       }
1009       if (!found) {
1010         for (j = 0; j < i && j < old_msgcount; j++) {
1011           if (old_hdrs[j] == NULL)
1012             continue;
1013           if (cmp_headers (ctx->hdrs[i], old_hdrs[j])) {
1014             found = 1;
1015             break;
1016           }
1017         }
1018       }
1019
1020       if (found) {
1021         /* this is best done here */
1022         if (!index_hint_set && *index_hint == j)
1023           *index_hint = i;
1024
1025         if (old_hdrs[j]->changed) {
1026           /* Only update the flags if the old header was changed;
1027            * otherwise, the header may have been modified externally,
1028            * and we don't want to lose _those_ changes
1029            */
1030           mutt_set_flag (ctx, ctx->hdrs[i], M_FLAG, old_hdrs[j]->flagged);
1031           mutt_set_flag (ctx, ctx->hdrs[i], M_REPLIED, old_hdrs[j]->replied);
1032           mutt_set_flag (ctx, ctx->hdrs[i], M_OLD, old_hdrs[j]->old);
1033           mutt_set_flag (ctx, ctx->hdrs[i], M_READ, old_hdrs[j]->read);
1034         }
1035         mutt_set_flag (ctx, ctx->hdrs[i], M_DELETE, old_hdrs[j]->deleted);
1036         mutt_set_flag (ctx, ctx->hdrs[i], M_TAG, old_hdrs[j]->tagged);
1037
1038         /* we don't need this header any more */
1039         mutt_free_header (&(old_hdrs[j]));
1040       }
1041     }
1042
1043     /* free the remaining old headers */
1044     for (j = 0; j < old_msgcount; j++) {
1045       if (old_hdrs[j]) {
1046         mutt_free_header (&(old_hdrs[j]));
1047         msg_mod = 1;
1048       }
1049     }
1050     mem_free (&old_hdrs);
1051   }
1052
1053   ctx->quiet = 0;
1054
1055   return ((ctx->changed || msg_mod) ? M_REOPENED : M_NEW_MAIL);
1056 }
1057
1058 /*
1059  * Returns:
1060  * 1 if the mailbox is not empty
1061  * 0 if the mailbox is empty
1062  * -1 on error
1063  */
1064 int mbox_check_empty (const char *path)
1065 {
1066   struct stat st;
1067
1068   if (stat (path, &st) == -1)
1069     return -1;
1070
1071   return ((st.st_size == 0));
1072 }
1073
1074 int mbox_is_magic (const char* path, struct stat* st) {
1075   int magic = -1;
1076   FILE* f;
1077   char tmp[_POSIX_PATH_MAX];
1078
1079   if (S_ISDIR(st->st_mode))
1080     return (-1);
1081
1082   if (st->st_size == 0) {
1083     /* hard to tell what zero-length files are, so assume the default magic */
1084     if (DefaultMagic == M_MBOX || DefaultMagic == M_MMDF)
1085       return (DefaultMagic);
1086     else
1087       return (M_MBOX);
1088   }
1089   else if ((f = fopen (path, "r")) != NULL) {
1090 #ifndef BUFFY_SIZE
1091     struct utimbuf times;
1092 #endif
1093     fgets (tmp, sizeof (tmp), f);
1094     if (str_ncmp ("From ", tmp, 5) == 0)
1095       magic = M_MBOX;
1096     else if (str_cmp (MMDF_SEP, tmp) == 0)
1097       magic = M_MMDF;
1098     safe_fclose (&f);
1099 #ifndef BUFFY_SIZE
1100     /* need to restore the times here, the file was not really accessed,
1101      * only the type was accessed.  This is important, because detection
1102      * of "new mail" depends on those times set correctly.
1103      */
1104     times.actime = st->st_atime;
1105     times.modtime = st->st_mtime;
1106     utime (path, &times);
1107 #endif
1108   } else {
1109     mutt_perror (path);
1110     return (-1);         /* fopen failed */
1111   }
1112
1113 #ifdef USE_COMPRESSED
1114   if (magic == -1 && mutt_can_read_compressed (path))
1115     return (M_COMPRESSED);
1116 #endif
1117   return (magic);
1118 }
1119
1120 static int commit_message (MESSAGE* msg, CONTEXT* ctx, int mbox) {
1121   if ((mbox && fputc ('\n', msg->fp) == EOF) ||
1122       (!mbox && fputs (MMDF_SEP, msg->fp) == EOF))
1123     return (-1);
1124   if ((fflush (msg->fp) == EOF || fsync (fileno (msg->fp)) == -1)) {
1125     mutt_perror (_("Can't write message"));
1126     return (-1);
1127   }
1128   return (0);
1129 }
1130
1131 static int mbox_commit_message (MESSAGE* msg, CONTEXT* ctx) {
1132   return (commit_message (msg, ctx, 1));
1133 }
1134
1135 static int mmdf_commit_message (MESSAGE* msg, CONTEXT* ctx) {
1136   return (commit_message (msg, ctx, 0));
1137 }
1138
1139 static mx_t* reg_mx (void) {
1140   mx_t* fmt = mem_calloc (1, sizeof (mx_t));
1141   fmt->local = 1;
1142   fmt->mx_check_empty = mbox_check_empty;
1143   fmt->mx_is_magic = mbox_is_magic;
1144   fmt->mx_access = access;
1145   fmt->mx_open_mailbox = mbox_open_mailbox;
1146   fmt->mx_open_new_message = mbox_open_new_message;
1147   fmt->mx_sync_mailbox = mbox_sync_mailbox;
1148   fmt->mx_check_mailbox = mbox_check_mailbox;
1149   return (fmt);
1150 }
1151
1152 mx_t* mbox_reg_mx (void) {
1153   mx_t* fmt = reg_mx ();
1154   fmt->type = M_MBOX;
1155   fmt->mx_commit_message = mbox_commit_message;
1156   return (fmt);
1157 }
1158 mx_t* mmdf_reg_mx (void) {
1159   mx_t* fmt = reg_mx ();
1160   fmt->type = M_MMDF;
1161   fmt->mx_commit_message = mmdf_commit_message;
1162   return (fmt);
1163 }