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