Remove the time module alltogether.
[apps/madmutt.git] / lib-mx / 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'' style mailboxes */
11
12 #include <lib-lib/lib-lib.h>
13
14 #include <lib-ui/lib-ui.h>
15 #include <lib-sys/mutt_signal.h>
16
17 #include "mutt.h"
18 #include "mx.h"
19 #include "buffy.h"
20 #include "mbox.h"
21 #include "sort.h"
22 #include "thread.h"
23 #include "copy.h"
24 #include "compress.h"
25
26 /* struct used by mutt_sync_mailbox() to store new offsets */
27 struct m_update_t {
28     short valid;
29     off_t hdr;
30     off_t body;
31     long lines;
32     off_t length;
33 };
34
35 static int mbox_open_new_message(MESSAGE *msg, CONTEXT *dest, HEADER *hdr)
36 {
37     msg->fp = dest->fp;
38     return 0;
39 }
40
41 /* prototypes */
42 static int mbox_reopen_mailbox (CONTEXT*, int*);
43
44 /* parameters:
45  * ctx - context to lock
46  * excl - exclusive lock?
47  * retry - should retry if unable to lock?
48  */
49 int mbox_lock_mailbox(CONTEXT *ctx, int excl, int retry)
50 {
51   int r;
52
53   if ((r = mx_lock_file(ctx->path, fileno(ctx->fp), excl, 1, retry)) == 0)
54     ctx->locked = 1;
55   else if (retry && !excl) {
56     ctx->readonly = 1;
57     return 0;
58   }
59
60   return (r);
61 }
62
63 static void mbox_unlock_mailbox (CONTEXT * ctx)
64 {
65   if (ctx->locked) {
66     fflush (ctx->fp);
67
68     mx_unlock_file (ctx->path, fileno (ctx->fp), 1);
69     ctx->locked = 0;
70   }
71 }
72
73 /* Note that this function is also called when new mail is appended to the
74  * currently open folder, and NOT just when the mailbox is initially read.
75  *
76  * NOTE: it is assumed that the mailbox being read has been locked before
77  * this routine gets called.  Strange things could happen if it's not!
78  */
79 static int mbox_parse_mailbox (CONTEXT * ctx)
80 {
81   struct stat sb;
82   char buf[HUGE_STRING], return_path[STRING];
83   HEADER *curhdr;
84   time_t t, tz;
85   int count = 0, lines = 0;
86   off_t loc;
87
88   /* Save information about the folder at the time we opened it. */
89   if (stat (ctx->path, &sb) == -1) {
90     mutt_perror (ctx->path);
91     return (-1);
92   }
93
94   ctx->size = sb.st_size;
95   ctx->mtime = sb.st_mtime;
96
97   if (!ctx->readonly)
98     ctx->readonly = access (ctx->path, W_OK) ? 1 : 0;
99
100   /* precompute the local timezone to speed up calculation of the
101      date received */
102   {
103       time_t t = time(NULL);
104       tz = localtime(&t)->tm_gmtoff;
105   }
106
107   loc = ftello (ctx->fp);
108   while (fgets (buf, sizeof (buf), ctx->fp) != NULL) {
109     if (is_from (buf, return_path, sizeof (return_path), &t)) {
110       /* Save the Content-Length of the previous message */
111       if (count > 0) {
112 #define PREV ctx->hdrs[ctx->msgcount-1]
113
114         if (PREV->content->length < 0) {
115           PREV->content->length = loc - PREV->content->offset - 1;
116           if (PREV->content->length < 0)
117             PREV->content->length = 0;
118         }
119         if (!PREV->lines)
120           PREV->lines = lines ? lines - 1 : 0;
121       }
122
123       count++;
124
125       if (!ctx->quiet && ReadInc && ((count % ReadInc == 0) || count == 1))
126         mutt_message (_("Reading %s... %d (%d%%)"), ctx->path, count,
127                       (int) (ftello (ctx->fp) / (ctx->size / 100 + 1)));
128
129       if (ctx->msgcount == ctx->hdrmax)
130         mx_alloc_memory (ctx);
131
132       curhdr = ctx->hdrs[ctx->msgcount] = header_new();
133       curhdr->received = t - tz;
134       curhdr->offset = loc;
135       curhdr->index = ctx->msgcount;
136
137       curhdr->env = mutt_read_rfc822_header (ctx->fp, curhdr, 0, 0);
138
139       /* if we know how long this message is, either just skip over the body,
140        * or if we don't know how many lines there are, count them now (this will
141        * save time by not having to search for the next message marker).
142        */
143       if (curhdr->content->length > 0) {
144         off_t tmploc;
145
146         loc = ftello (ctx->fp);
147         tmploc = loc + curhdr->content->length + 1;
148
149         if (0 < tmploc && tmploc < ctx->size) {
150           /*
151            * check to see if the content-length looks valid.  we expect to
152            * to see a valid message separator at this point in the stream
153            */
154           if (fseeko (ctx->fp, tmploc, SEEK_SET) != 0 ||
155               fgets (buf, sizeof (buf), ctx->fp) == NULL ||
156               m_strncmp("From ", buf, 5) != 0) {
157             fseeko (ctx->fp, loc, SEEK_SET); /* nope, return the previous position */
158             curhdr->content->length = -1;
159           }
160         }
161         else if (tmploc != ctx->size) {
162           /* content-length would put us past the end of the file, so it
163            * must be wrong
164            */
165           curhdr->content->length = -1;
166         }
167
168         if (curhdr->content->length != -1) {
169           /* good content-length.  check to see if we know how many lines
170            * are in this message.
171            */
172           if (curhdr->lines == 0) {
173             int cl = curhdr->content->length;
174
175             /* count the number of lines in this message */
176             fseeko (ctx->fp, loc, SEEK_SET);
177             while (cl-- > 0) {
178               if (fgetc (ctx->fp) == '\n')
179                 curhdr->lines++;
180             }
181           }
182
183           /* return to the offset of the next message separator */
184           fseeko(ctx->fp, tmploc, SEEK_SET);
185         }
186       }
187
188       ctx->msgcount++;
189
190       if (!curhdr->env->return_path && return_path[0])
191         curhdr->env->return_path =
192           rfc822_parse_adrlist (curhdr->env->return_path, return_path);
193
194       if (!curhdr->env->from)
195         curhdr->env->from = address_list_dup (curhdr->env->return_path);
196
197       lines = 0;
198     }
199     else
200       lines++;
201
202     loc = ftello (ctx->fp);
203   }
204
205   /*
206    * Only set the content-length of the previous message if we have read more
207    * than one message during _this_ invocation.  If this routine is called
208    * when new mail is received, we need to make sure not to clobber what
209    * previously was the last message since the headers may be sorted.
210    */
211   if (count > 0) {
212     if (PREV->content->length < 0) {
213       PREV->content->length = ftello (ctx->fp) - PREV->content->offset - 1;
214       if (PREV->content->length < 0)
215         PREV->content->length = 0;
216     }
217
218     if (!PREV->lines)
219       PREV->lines = lines ? lines - 1 : 0;
220
221     mx_update_context (ctx, count);
222   }
223
224   return (0);
225 }
226
227 #undef PREV
228
229 /* open a mbox style mailbox */
230 static int mbox_open_mailbox (CONTEXT * ctx)
231 {
232     int rc;
233
234     if (!(ctx->fp = fopen(ctx->path, "r"))) {
235         mutt_perror(ctx->path);
236         return -1;
237     }
238
239     mutt_block_signals();
240     if (mbox_lock_mailbox(ctx, 0, 1) < 0) {
241         mutt_unblock_signals();
242         return -1;
243     }
244
245     rc = ctx->magic == M_MBOX ? mbox_parse_mailbox(ctx) : -1;
246
247     mbox_unlock_mailbox(ctx);
248     mutt_unblock_signals();
249     return rc;
250 }
251
252 /* check to see if the mailbox has changed on disk.
253  *
254  * return values:
255  *      M_REOPENED      mailbox has been reopened
256  *      M_NEW_MAIL      new mail has arrived!
257  *      M_LOCKED        couldn't lock the file
258  *      0               no change
259  *      -1              error
260  */
261 static int _mbox_check_mailbox (CONTEXT * ctx, int *index_hint)
262 {
263   struct stat st;
264   char buffer[LONG_STRING];
265   int unlock = 0;
266   int modified = 0;
267
268   if (stat (ctx->path, &st) == 0) {
269     if (st.st_mtime == ctx->mtime && st.st_size == ctx->size)
270       return (0);
271
272     if (st.st_size == ctx->size) {
273       /* the file was touched, but it is still the same length, so just exit */
274       ctx->mtime = st.st_mtime;
275       return (0);
276     }
277
278     if (st.st_size > ctx->size) {
279       /* lock the file if it isn't already */
280       if (!ctx->locked) {
281         mutt_block_signals ();
282         if (mbox_lock_mailbox (ctx, 0, 0) == -1) {
283           mutt_unblock_signals ();
284           /* we couldn't lock the mailbox, but nothing serious happened:
285            * probably the new mail arrived: no reason to wait till we can
286            * parse it: we'll get it on the next pass
287            */
288           return (M_LOCKED);
289         }
290         unlock = 1;
291       }
292
293       /*
294        * Check to make sure that the only change to the mailbox is that 
295        * message(s) were appended to this file.  My heuristic is that we should
296        * see the message separator at *exactly* what used to be the end of the
297        * folder.
298        */
299       fseeko (ctx->fp, ctx->size, SEEK_SET);
300       if (fgets (buffer, sizeof (buffer), ctx->fp) != NULL) {
301         if (ctx->magic == M_MBOX && m_strncmp("From ", buffer, 5) == 0) {
302           fseeko (ctx->fp, ctx->size, SEEK_SET);
303           mbox_parse_mailbox (ctx);
304
305           /* Only unlock the folder if it was locked inside of this routine.
306            * It may have been locked elsewhere, like in
307            * mutt_checkpoint_mailbox().
308            */
309
310           if (unlock) {
311             mbox_unlock_mailbox (ctx);
312             mutt_unblock_signals ();
313           }
314
315           return (M_NEW_MAIL);  /* signal that new mail arrived */
316         }
317         else
318           modified = 1;
319       } else {
320         modified = 1;
321       }
322     } else {
323       modified = 1;
324     }
325   }
326
327   if (modified) {
328     if (mbox_reopen_mailbox (ctx, index_hint) != -1) {
329       if (unlock) {
330         mbox_unlock_mailbox (ctx);
331         mutt_unblock_signals ();
332       }
333       return (M_REOPENED);
334     }
335   }
336
337   /* fatal error */
338
339   mbox_unlock_mailbox (ctx);
340   mx_fastclose_mailbox (ctx);
341   mutt_unblock_signals ();
342   mutt_error _("Mailbox was corrupted!");
343
344   return (-1);
345 }
346
347 static int mbox_check_mailbox(CONTEXT *ctx, int *index_hint, int lock)
348 {
349     int rc = 0;
350
351     if (lock) {
352         mutt_block_signals();
353         if (mbox_lock_mailbox(ctx, 0, 0) < 0) {
354             mutt_unblock_signals();
355             return M_LOCKED;
356         }
357     }
358
359     rc = _mbox_check_mailbox(ctx, index_hint);
360
361     if (lock) {
362         mutt_unblock_signals ();
363         mbox_unlock_mailbox (ctx);
364     }
365     return rc;
366 }
367
368 /* return values:
369  *      0       success
370  *      -1      failure
371  */
372 static int mbox_sync_mailbox (CONTEXT * ctx, int unused __attribute__ ((unused)), int *index_hint)
373 {
374   char tempfile[_POSIX_PATH_MAX];
375   char buf[32];
376   int i, j, save_sort = SORT_ORDER;
377   int rc = -1;
378   int need_sort = 0;            /* flag to resort mailbox if new mail arrives */
379   int first = -1;               /* first message to be written */
380   off_t offset;                /* location in mailbox to write changed messages */
381   struct stat statbuf;
382   struct utimbuf utimebuf;
383   struct m_update_t *newOffset = NULL;
384   struct m_update_t *oldOffset = NULL;
385   FILE *fp = NULL;
386
387   /* sort message by their position in the mailbox on disk */
388   if (Sort != SORT_ORDER) {
389     save_sort = Sort;
390     Sort = SORT_ORDER;
391     mutt_sort_headers (ctx, 0);
392     Sort = save_sort;
393     need_sort = 1;
394   }
395
396   /* need to open the file for writing in such a way that it does not truncate
397    * the file, so use read-write mode.
398    */
399   if ((ctx->fp = freopen (ctx->path, "r+", ctx->fp)) == NULL) {
400     mx_fastclose_mailbox (ctx);
401     mutt_error _("Fatal error!  Could not reopen mailbox!");
402
403     return (-1);
404   }
405
406   mutt_block_signals ();
407
408   if (mbox_lock_mailbox (ctx, 1, 1) == -1) {
409     mutt_unblock_signals ();
410     mutt_error _("Unable to lock mailbox!");
411
412     goto bail;
413   }
414
415   /* Check to make sure that the file hasn't changed on disk */
416   if ((i = _mbox_check_mailbox (ctx, index_hint)) == M_NEW_MAIL
417       || i == M_REOPENED) {
418     /* new mail arrived, or mailbox reopened */
419     need_sort = i;
420     rc = i;
421     goto bail;
422   }
423   else if (i < 0)
424     /* fatal error */
425     return (-1);
426
427   /* Create a temporary file to write the new version of the mailbox in. */
428   fp = m_tempfile(tempfile, _POSIX_PATH_MAX, NONULL(mod_core.tmpdir), NULL);
429   if (fp == NULL) {
430     mutt_error _("Could not create temporary file!");
431     mutt_sleep (5);
432     goto bail;
433   }
434
435   /* find the first deleted/changed message.  we save a lot of time by only
436    * rewriting the mailbox from the point where it has actually changed.
437    */
438   for (i = 0; i < ctx->msgcount && !ctx->hdrs[i]->deleted &&
439        !ctx->hdrs[i]->changed && !ctx->hdrs[i]->attach_del; i++);
440   if (i == ctx->msgcount) {
441     /* this means ctx->changed or ctx->deleted was set, but no
442      * messages were found to be changed or deleted.  This should
443      * never happen, is we presume it is a bug in mutt.
444      */
445     mutt_error
446       _("sync: mbox modified, but no modified messages! (report this bug)");
447     mutt_sleep (5);             /* the mutt_error /will/ get cleared! */
448     unlink (tempfile);
449     goto bail;
450   }
451
452   /* save the index of the first changed/deleted message */
453   first = i;
454   /* where to start overwriting */
455   offset = ctx->hdrs[i]->offset;
456
457   /* allocate space for the new offsets */
458   newOffset = p_new(struct m_update_t, ctx->msgcount - first);
459   oldOffset = p_new(struct m_update_t, ctx->msgcount - first);
460
461   for (i = first, j = 0; i < ctx->msgcount; i++) {
462     /*
463      * back up some information which is needed to restore offsets when
464      * something fails.
465      */
466
467     oldOffset[i - first].valid = 1;
468     oldOffset[i - first].hdr = ctx->hdrs[i]->offset;
469     oldOffset[i - first].body = ctx->hdrs[i]->content->offset;
470     oldOffset[i - first].lines = ctx->hdrs[i]->lines;
471     oldOffset[i - first].length = ctx->hdrs[i]->content->length;
472
473     if (!ctx->hdrs[i]->deleted) {
474       j++;
475       if (!ctx->quiet && WriteInc && ((i % WriteInc) == 0 || j == 1))
476         mutt_message (_("Writing messages... %d (%d%%)"), i,
477                       (int) (ftello (ctx->fp) / (ctx->size / 100 + 1)));
478
479       /* save the new offset for this message.  we add `offset' because the
480        * temporary file only contains saved message which are located after
481        * `offset' in the real mailbox
482        */
483       newOffset[i - first].hdr = ftello (fp) + offset;
484
485       if (mutt_copy_message
486           (fp, ctx, ctx->hdrs[i], M_CM_UPDATE,
487            CH_FROM | CH_UPDATE | CH_UPDATE_LEN) == -1) {
488         mutt_perror (_("Can't create temporary file"));
489         mutt_sleep (5);
490         unlink (tempfile);
491         goto bail;
492       }
493
494       /* Since messages could have been deleted, the offsets stored in memory
495        * will be wrong, so update what we can, which is the offset of this
496        * message, and the offset of the body.  If this is a multipart message,
497        * we just flush the in memory cache so that the message will be reparsed
498        * if the user accesses it later.
499        */
500       newOffset[i - first].body =
501         ftello (fp) - ctx->hdrs[i]->content->length + offset;
502       body_list_wipe(&ctx->hdrs[i]->content->parts);
503
504       if (fputs ("\n", fp) == EOF) {
505         mutt_perror (_("Can't create temporary file"));
506         mutt_sleep (5);
507         unlink (tempfile);
508         goto bail;
509       }
510     }
511   }
512
513   if (m_fclose(&fp) != 0) {
514     unlink (tempfile);
515     mutt_perror (_("Can't create temporary file"));
516     mutt_sleep (5);
517     goto bail;
518   }
519
520   /* Save the state of this folder. */
521   if (stat (ctx->path, &statbuf) == -1) {
522     mutt_perror (ctx->path);
523     mutt_sleep (5);
524     unlink (tempfile);
525     goto bail;
526   }
527
528   if ((fp = fopen (tempfile, "r")) == NULL) {
529     mutt_unblock_signals ();
530     mx_fastclose_mailbox (ctx);
531     mutt_perror (_("Can't create temporary file"));
532     mutt_sleep (5);
533     return (-1);
534   }
535
536   if (fseeko (ctx->fp, offset, SEEK_SET) != 0 /* seek the append location */
537       /* do a sanity check to make sure the mailbox looks ok */
538   ||  fgets (buf, sizeof (buf), ctx->fp) == NULL
539   ||  (ctx->magic == M_MBOX && m_strncmp("From ", buf, 5) != 0))
540   {
541     i = -1;
542   }
543   else {
544     if (fseeko (ctx->fp, offset, SEEK_SET) != 0) {       /* return to proper offset */
545       i = -1;
546     } else {
547       /* copy the temp mailbox back into place starting at the first
548        * change/deleted message
549        */
550       mutt_message _("Committing changes...");
551
552       i = mutt_copy_stream (fp, ctx->fp);
553
554       if (ferror (ctx->fp))
555         i = -1;
556     }
557     if (i == 0) {
558       ctx->size = ftello (ctx->fp);      /* update the size of the mailbox */
559       ftruncate (fileno (ctx->fp), ctx->size);
560     }
561   }
562
563   m_fclose(&fp);
564   mbox_unlock_mailbox (ctx);
565
566   if (m_fclose(&ctx->fp) != 0 || i == -1) {
567     /* error occured while writing the mailbox back, so keep the temp copy
568      * around
569      */
570
571     char savefile[_POSIX_PATH_MAX];
572
573     snprintf(savefile, sizeof (savefile), "%s/mutt.%s-%u",
574              NONULL(mod_core.tmpdir), NONULL(mod_core.username), (unsigned int)getpid());
575     rename (tempfile, savefile);
576     mutt_unblock_signals ();
577     mx_fastclose_mailbox (ctx);
578     mutt_pretty_mailbox (savefile);
579     mutt_error (_("Write failed!  Saved partial mailbox to %s"), savefile);
580     mutt_sleep (5);
581     return (-1);
582   }
583
584   /* Restore the previous access/modification times */
585   utimebuf.actime = statbuf.st_atime;
586   utimebuf.modtime = statbuf.st_mtime;
587   utime (ctx->path, &utimebuf);
588
589   /* reopen the mailbox in read-only mode */
590   if ((ctx->fp = fopen (ctx->path, "r")) == NULL) {
591     unlink (tempfile);
592     mutt_unblock_signals ();
593     mx_fastclose_mailbox (ctx);
594     mutt_error _("Fatal error!  Could not reopen mailbox!");
595     return (-1);
596   }
597
598   /* update the offsets of the rewritten messages */
599   for (i = first, j = first; i < ctx->msgcount; i++) {
600     if (!ctx->hdrs[i]->deleted) {
601       ctx->hdrs[i]->offset = newOffset[i - first].hdr;
602       ctx->hdrs[i]->content->hdr_offset = newOffset[i - first].hdr;
603       ctx->hdrs[i]->content->offset = newOffset[i - first].body;
604       ctx->hdrs[i]->index = j++;
605     }
606   }
607   p_delete(&newOffset);
608   p_delete(&oldOffset);
609   unlink (tempfile);            /* remove partial copy of the mailbox */
610   mutt_unblock_signals ();
611
612   return (0);                   /* signal success */
613
614 bail:                          /* Come here in case of disaster */
615
616   m_fclose(&fp);
617
618   /* restore offsets, as far as they are valid */
619   if (first >= 0 && oldOffset) {
620     for (i = first; i < ctx->msgcount && oldOffset[i - first].valid; i++) {
621       ctx->hdrs[i]->offset = oldOffset[i - first].hdr;
622       ctx->hdrs[i]->content->hdr_offset = oldOffset[i - first].hdr;
623       ctx->hdrs[i]->content->offset = oldOffset[i - first].body;
624       ctx->hdrs[i]->lines = oldOffset[i - first].lines;
625       ctx->hdrs[i]->content->length = oldOffset[i - first].length;
626     }
627   }
628
629   /* this is ok to call even if we haven't locked anything */
630   mbox_unlock_mailbox (ctx);
631
632   mutt_unblock_signals ();
633   p_delete(&newOffset);
634   p_delete(&oldOffset);
635
636   if ((ctx->fp = freopen (ctx->path, "r", ctx->fp)) == NULL) {
637     mutt_error _("Could not reopen mailbox!");
638
639     mx_fastclose_mailbox (ctx);
640     return (-1);
641   }
642
643   if (need_sort)
644     /* if the mailbox was reopened, the thread tree will be invalid so make
645      * sure to start threading from scratch.  */
646     mutt_sort_headers (ctx, (need_sort == M_REOPENED));
647
648   return rc;
649 }
650
651 /* close a mailbox opened in write-mode */
652 int mbox_close_mailbox (CONTEXT * ctx)
653 {
654   mx_unlock_file (ctx->path, fileno (ctx->fp), 1);
655
656   if (ctx->cinfo)
657     mutt_slow_close_compressed (ctx);
658
659   mutt_unblock_signals ();
660   mx_fastclose_mailbox (ctx);
661   return 0;
662 }
663
664 static int mbox_reopen_mailbox (CONTEXT * ctx, int *index_hint)
665 {
666   int (*cmp_headers) (const HEADER *, const HEADER *) = NULL;
667   HEADER **old_hdrs;
668   int old_msgcount;
669   int msg_mod = 0;
670   int index_hint_set;
671   int i, j;
672   int rc = -1;
673
674   /* silent operations */
675   ctx->quiet = 1;
676
677   mutt_message _("Reopening mailbox...");
678
679   /* our heuristics require the old mailbox to be unsorted */
680   if (Sort != SORT_ORDER) {
681     short old_sort;
682
683     old_sort = Sort;
684     Sort = SORT_ORDER;
685     mutt_sort_headers (ctx, 1);
686     Sort = old_sort;
687   }
688
689   old_hdrs = NULL;
690   old_msgcount = 0;
691
692   /* simulate a close */
693   if (ctx->id_hash)
694     hash_delete (&ctx->id_hash, NULL);
695   if (ctx->subj_hash)
696     hash_delete (&ctx->subj_hash, NULL);
697   mutt_clear_threads (ctx);
698   p_delete(&ctx->v2r);
699   if (ctx->readonly) {
700     for (i = 0; i < ctx->msgcount; i++)
701       header_delete(&(ctx->hdrs[i]));       /* nothing to do! */
702     p_delete(&ctx->hdrs);
703   }
704   else {
705     /* save the old headers */
706     old_msgcount = ctx->msgcount;
707     old_hdrs = ctx->hdrs;
708     ctx->hdrs = NULL;
709   }
710
711   ctx->hdrmax = 0;              /* force allocation of new headers */
712   ctx->msgcount = 0;
713   ctx->vcount = 0;
714   ctx->tagged = 0;
715   ctx->deleted = 0;
716   ctx->new = 0;
717   ctx->unread = 0;
718   ctx->flagged = 0;
719   ctx->changed = 0;
720   ctx->id_hash = NULL;
721   ctx->subj_hash = NULL;
722
723   if (ctx->magic == M_MBOX && !fseeko(ctx->fp, 0, SEEK_SET)) {
724     cmp_headers = mutt_cmp_header;
725     rc = mbox_parse_mailbox (ctx);
726   } else {
727     rc = -1;
728   }
729
730   if (rc == -1) {
731     /* free the old headers */
732     for (j = 0; j < old_msgcount; j++)
733       header_delete(&(old_hdrs[j]));
734     p_delete(&old_hdrs);
735
736     ctx->quiet = 0;
737     return (-1);
738   }
739
740   /* now try to recover the old flags */
741
742   index_hint_set = (index_hint == NULL);
743
744   if (!ctx->readonly) {
745     for (i = 0; i < ctx->msgcount; i++) {
746       int found = 0;
747
748       /* some messages have been deleted, and new  messages have been
749        * appended at the end; the heuristic is that old messages have then
750        * "advanced" towards the beginning of the folder, so we begin the
751        * search at index "i"
752        */
753       for (j = i; j < old_msgcount; j++) {
754         if (old_hdrs[j] == NULL)
755           continue;
756         if (cmp_headers (ctx->hdrs[i], old_hdrs[j])) {
757           found = 1;
758           break;
759         }
760       }
761       if (!found) {
762         for (j = 0; j < i && j < old_msgcount; j++) {
763           if (old_hdrs[j] == NULL)
764             continue;
765           if (cmp_headers (ctx->hdrs[i], old_hdrs[j])) {
766             found = 1;
767             break;
768           }
769         }
770       }
771
772       if (found) {
773         /* this is best done here */
774         if (!index_hint_set && *index_hint == j)
775           *index_hint = i;
776
777         if (old_hdrs[j]->changed) {
778           /* Only update the flags if the old header was changed;
779            * otherwise, the header may have been modified externally,
780            * and we don't want to lose _those_ changes
781            */
782           mutt_set_flag (ctx, ctx->hdrs[i], M_FLAG, old_hdrs[j]->flagged);
783           mutt_set_flag (ctx, ctx->hdrs[i], M_REPLIED, old_hdrs[j]->replied);
784           mutt_set_flag (ctx, ctx->hdrs[i], M_OLD, old_hdrs[j]->old);
785           mutt_set_flag (ctx, ctx->hdrs[i], M_READ, old_hdrs[j]->read);
786         }
787         mutt_set_flag (ctx, ctx->hdrs[i], M_DELETE, old_hdrs[j]->deleted);
788         mutt_set_flag (ctx, ctx->hdrs[i], M_TAG, old_hdrs[j]->tagged);
789
790         /* we don't need this header any more */
791         header_delete(&(old_hdrs[j]));
792       }
793     }
794
795     /* free the remaining old headers */
796     for (j = 0; j < old_msgcount; j++) {
797       if (old_hdrs[j]) {
798         header_delete(&(old_hdrs[j]));
799         msg_mod = 1;
800       }
801     }
802     p_delete(&old_hdrs);
803   }
804
805   ctx->quiet = 0;
806
807   return ((ctx->changed || msg_mod) ? M_REOPENED : M_NEW_MAIL);
808 }
809
810 /*
811  * Returns:
812  * 1 if the mailbox is not empty
813  * 0 if the mailbox is empty
814  * -1 on error
815  */
816 int mbox_check_empty (const char *path)
817 {
818   struct stat st;
819
820   if (stat (path, &st) == -1)
821     return -1;
822
823   return ((st.st_size == 0));
824 }
825
826 int mbox_is_magic (const char* path, struct stat* st)
827 {
828   int magic = -1;
829   FILE* f;
830   char tmp[_POSIX_PATH_MAX];
831
832   if (S_ISDIR(st->st_mode))
833     return (-1);
834
835   if (st->st_size == 0) {
836     return M_MBOX;
837   }
838   else if ((f = fopen (path, "r")) != NULL) {
839     struct utimbuf times;
840
841     fgets (tmp, sizeof (tmp), f);
842     if (m_strncmp("From ", tmp, 5) == 0)
843       magic = M_MBOX;
844     m_fclose(&f);
845
846     /* need to restore the times here, the file was not really accessed,
847      * only the type was accessed.  This is important, because detection
848      * of "new mail" depends on those times set correctly.
849      */
850     times.actime = st->st_atime;
851     times.modtime = st->st_mtime;
852     utime (path, &times);
853   } else {
854     mutt_perror (path);
855     return (-1);         /* fopen failed */
856   }
857
858   if (magic == -1 && mutt_can_read_compressed (path))
859     return (M_COMPRESSED);
860   return (magic);
861 }
862
863 static int mbox_commit_message (MESSAGE* msg, CONTEXT* ctx) {
864   if (fputc ('\n', msg->fp) == EOF)
865     return -1;
866   if ((fflush (msg->fp) == EOF || fsync (fileno (msg->fp)) == -1)) {
867     mutt_perror (_("Can't write message"));
868     return -1;
869   }
870   return 0;
871 }
872
873 mx_t const mbox_mx = {
874     M_MBOX,
875     1,
876     mbox_is_magic,
877     mbox_check_empty,
878     access,
879     mbox_open_mailbox,
880     mbox_open_new_message,
881     NULL,
882     mbox_check_mailbox,
883     NULL,
884     mbox_sync_mailbox,
885     mbox_commit_message,
886 };