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