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