05c9e8a3d9af3ccdb51bf86889350ecf8f2b5a94
[apps/madmutt.git] / lib-mx / mx.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 #include <lib-lib/lib-lib.h>
12
13 #include <utime.h>
14
15 #include <lib-lua/lib-lua.h>
16 #include <lib-sys/unix.h>
17 #include <lib-mime/mime.h>
18 #include <lib-ui/sidebar.h>
19
20 #include "mutt.h"
21 #include "crypt.h"
22 #include "pattern.h"
23 #include "buffy.h"
24 #include "mx.h"
25 #include "mbox.h"
26 #include "mh.h"
27 #include "sort.h"
28 #include "thread.h"
29 #include "copy.h"
30 #include "keymap.h"
31 #include "compress.h"
32 #include "dotlock.h"
33
34 #include <imap/imap.h>
35 #include <pop/pop.h>
36
37 #ifdef USE_NNTP
38 #include <nntp/nntp.h>
39 #endif
40
41 static mx_t const *mxfmts[] = {
42     &mbox_mx,
43     &mh_mx,
44     &maildir_mx,
45     &imap_mx,
46     &pop_mx,
47 #ifdef USE_NNTP
48     &nntp_mx,
49 #endif
50     &compress_mx,
51 };
52
53 #define MX_IDX(idx)          (idx >= 0 && idx < countof(mxfmts))
54 #define mutt_is_spool(s)     (m_strcmp(Spoolfile, s) == 0)
55
56 /* parameters: 
57  * path - file to lock
58  * retry - should retry if unable to lock?
59  */
60 static int invoke_dotlock (const char *path, int flags, int retry)
61 {
62   char cmd[LONG_STRING + _POSIX_PATH_MAX];
63   char f[STRING + _POSIX_PATH_MAX];
64   char r[STRING];
65
66   if (flags & DL_FL_RETRY)
67     snprintf (r, sizeof (r), "-r %d ", retry ? MAXLOCKATTEMPT : 0);
68
69   mutt_quote_filename (f, sizeof (f), path);
70
71   snprintf(cmd, sizeof(cmd), "%s %s%s%s%s%s%s%s",
72            MCore.dotlock,
73            flags & DL_FL_TRY ? "-t " : "",
74            flags & DL_FL_UNLOCK ? "-u " : "",
75            flags & DL_FL_USEPRIV ? "-p " : "",
76            flags & DL_FL_FORCE ? "-f " : "",
77            flags & DL_FL_UNLINK ? "-d " : "",
78            flags & DL_FL_RETRY ? r : "", f);
79
80   return mutt_system (cmd);
81 }
82
83 static int dotlock_file (const char *path, int retry)
84 {
85   int r;
86   int flags = DL_FL_USEPRIV | DL_FL_RETRY;
87
88   if (retry)
89     retry = 1;
90
91 retry_lock:
92   if ((r = invoke_dotlock (path, flags, retry)) == DL_EX_EXIST) {
93     if (!option (OPTNOCURSES)) {
94       char msg[LONG_STRING];
95
96       snprintf (msg, sizeof (msg),
97                 _("Lock count exceeded, remove lock for %s?"), path);
98       if (retry && mutt_yesorno (msg, M_YES) == M_YES) {
99         flags |= DL_FL_FORCE;
100         retry--;
101         mutt_clear_error ();
102         goto retry_lock;
103       }
104     }
105     else {
106       mutt_error (_("Can't dotlock %s.\n"), path);
107     }
108   }
109   return (r == DL_EX_OK ? 0 : -1);
110 }
111
112 static int undotlock_file (const char *path)
113 {
114   return (invoke_dotlock (path,  DL_FL_USEPRIV | DL_FL_UNLOCK, 0) ==
115           DL_EX_OK ? 0 : -1);
116 }
117
118 /* looks up index of type for path in mxfmts */
119 static int mx_get_idx (const char* path) {
120     int i = 0, t = 0;
121     struct stat st;
122
123     /* first, test all non-local folders to avoid stat() call */
124     for (i = 0; i < countof(mxfmts); i++) {
125         if (!mxfmts[i]->local)
126             t = mxfmts[i]->mx_is_magic(path, NULL);
127         if (t >= 1)
128             return (t-1);
129     }
130     if (stat (path, &st) == 0) {
131         /* if stat() succeeded, keep testing until success and
132          * pass stat() info so that we only need to do it once */
133         for (i = 0; i < countof(mxfmts); i++) {
134             if (mxfmts[i]->local)
135                 t = mxfmts[i]->mx_is_magic(path, &st);
136             if (t >= 1)
137                 return (t-1);
138         }
139     }
140     return (-1);
141 }
142
143 /* Args:
144  *      excl            if excl != 0, request an exclusive lock
145  *      dot             if dot != 0, try to dotlock the file
146  *      time_out        should retry locking?
147  */
148 int mx_lock_file (const char *path, int fd, int excl, int dot, int time_out)
149 {
150 #if defined (USE_FCNTL) || defined (USE_FLOCK)
151     int count;
152     int attempt;
153     struct stat prev_sb;
154 #endif
155     int r = 0;
156
157 #ifdef USE_FCNTL
158     struct flock lck;
159
160
161     p_clear(&lck, 1);
162     lck.l_type = excl ? F_WRLCK : F_RDLCK;
163     lck.l_whence = SEEK_SET;
164
165     count = 0;
166     attempt = 0;
167     prev_sb.st_size = 0;
168     while (fcntl (fd, F_SETLK, &lck) == -1) {
169         struct stat sb;
170
171         if (errno != EAGAIN && errno != EACCES) {
172             mutt_perror ("fcntl");
173             return (-1);
174         }
175
176         if (fstat (fd, &sb) != 0)
177             sb.st_size = 0;
178
179         if (count == 0)
180             prev_sb = sb;
181
182         /* only unlock file if it is unchanged */
183         if (prev_sb.st_size == sb.st_size
184             && ++count >= (time_out ? MAXLOCKATTEMPT : 0)) {
185             if (time_out)
186                 mutt_error _("Timeout exceeded while attempting fcntl lock!");
187
188             return (-1);
189         }
190
191         prev_sb = sb;
192
193         mutt_message (_("Waiting for fcntl lock... %d"), ++attempt);
194         sleep (1);
195     }
196 #endif /* USE_FCNTL */
197
198 #ifdef USE_FLOCK
199     count = 0;
200     attempt = 0;
201     while (flock (fd, (excl ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
202         struct stat sb;
203
204         if (errno != EWOULDBLOCK) {
205             mutt_perror ("flock");
206             r = -1;
207             break;
208         }
209
210         if (fstat (fd, &sb) != 0)
211             sb.st_size = 0;
212
213         if (count == 0)
214             prev_sb = sb;
215
216         /* only unlock file if it is unchanged */
217         if (prev_sb.st_size == sb.st_size
218             && ++count >= (time_out ? MAXLOCKATTEMPT : 0)) {
219             if (time_out)
220                 mutt_error _("Timeout exceeded while attempting flock lock!");
221
222             r = -1;
223             break;
224         }
225
226         prev_sb = sb;
227
228         mutt_message (_("Waiting for flock attempt... %d"), ++attempt);
229         sleep (1);
230     }
231 #endif /* USE_FLOCK */
232
233     if (r == 0 && dot)
234         r = dotlock_file (path, time_out);
235
236     if (r == -1) {
237         /* release any other locks obtained in this routine */
238
239 #ifdef USE_FCNTL
240         lck.l_type = F_UNLCK;
241         fcntl (fd, F_SETLK, &lck);
242 #endif /* USE_FCNTL */
243
244 #ifdef USE_FLOCK
245         flock (fd, LOCK_UN);
246 #endif /* USE_FLOCK */
247
248         return (-1);
249     }
250
251     return 0;
252 }
253
254 int mx_unlock_file (const char *path, int fd, int dot)
255 {
256 #ifdef USE_FCNTL
257     struct flock unlockit;
258
259     p_clear(&unlockit, 1);
260     unlockit.l_type = F_UNLCK;
261     unlockit.l_whence = SEEK_SET;
262     fcntl (fd, F_SETLK, &unlockit);
263 #endif
264
265 #ifdef USE_FLOCK
266     flock (fd, LOCK_UN);
267 #endif
268
269     if (dot)
270         undotlock_file (path);
271
272     return 0;
273 }
274
275 static void mx_unlink_empty (const char *path)
276 {
277     int fd;
278
279     if ((fd = open (path, O_RDWR)) == -1)
280         return;
281
282     if (mx_lock_file (path, fd, 1, 0, 1) == -1) {
283     close (fd);
284     return;
285   }
286
287   invoke_dotlock(path, DL_FL_UNLINK, 1);
288
289   mx_unlock_file (path, fd, 0);
290   close (fd);
291 }
292
293 /* try to figure out what type of mailbox ``path'' is */
294 int mx_get_magic (const char *path) {
295   int i = 0;
296
297   if (m_strlen(path) == 0)
298     return (-1);
299   if ((i = mx_get_idx (path)) >= 0)
300     return (mxfmts[i]->type);
301   return (-1);
302 }
303
304 int mx_is_local (int m) {
305   if (!MX_IDX(m))
306     return (0);
307   return (mxfmts[m]->local);
308 }
309
310 /*
311  * set DefaultMagic to the given value
312  */
313 int mx_set_magic (const char *s)
314 {
315   if (ascii_strcasecmp (s, "mbox") == 0)
316     DefaultMagic = M_MBOX;
317   else if (ascii_strcasecmp (s, "mh") == 0)
318     DefaultMagic = M_MH;
319   else if (ascii_strcasecmp (s, "maildir") == 0)
320     DefaultMagic = M_MAILDIR;
321   else
322     return (-1);
323
324   return 0;
325 }
326
327 /* mx_access: Wrapper for access, checks permissions on a given mailbox.
328  *   We may be interested in using ACL-style flags at some point, currently
329  *   we use the normal access() flags. */
330 int mx_access (const char *path, int flags)
331 {
332   int i = 0;
333
334   if ((i = mx_get_idx (path)) >= 0 && mxfmts[i]->mx_access)
335     return (mxfmts[i]->mx_access(path,flags));
336   return (0);
337 }
338
339 static int mx_open_mailbox_append (CONTEXT * ctx, int flags)
340 {
341   struct stat sb;
342
343   /* special case for appending to compressed folders -
344    * even if we can not open them for reading */
345   if (mutt_can_append_compressed (ctx->path))
346     mutt_open_append_compressed (ctx);
347
348   ctx->append = 1;
349
350   if (mx_get_magic (ctx->path) == M_IMAP)
351     return imap_open_mailbox_append (ctx);
352
353   if (stat (ctx->path, &sb) == 0) {
354     ctx->magic = mx_get_magic (ctx->path);
355
356     switch (ctx->magic) {
357     case 0:
358       mutt_error (_("%s is not a mailbox."), ctx->path);
359       /* fall through */
360     case -1:
361       return (-1);
362     }
363   }
364   else if (errno == ENOENT) {
365     ctx->magic = DefaultMagic;
366
367     if (ctx->magic == M_MH || ctx->magic == M_MAILDIR) {
368       char tmp[_POSIX_PATH_MAX];
369
370       if (mkdir (ctx->path, S_IRWXU)) {
371         mutt_perror (ctx->path);
372         return (-1);
373       }
374
375       if (ctx->magic == M_MAILDIR) {
376         snprintf (tmp, sizeof (tmp), "%s/cur", ctx->path);
377         if (mkdir (tmp, S_IRWXU)) {
378           mutt_perror (tmp);
379           rmdir (ctx->path);
380           return (-1);
381         }
382
383         snprintf (tmp, sizeof (tmp), "%s/new", ctx->path);
384         if (mkdir (tmp, S_IRWXU)) {
385           mutt_perror (tmp);
386           snprintf (tmp, sizeof (tmp), "%s/cur", ctx->path);
387           rmdir (tmp);
388           rmdir (ctx->path);
389           return (-1);
390         }
391         snprintf (tmp, sizeof (tmp), "%s/tmp", ctx->path);
392         if (mkdir (tmp, S_IRWXU)) {
393           mutt_perror (tmp);
394           snprintf (tmp, sizeof (tmp), "%s/cur", ctx->path);
395           rmdir (tmp);
396           snprintf (tmp, sizeof (tmp), "%s/new", ctx->path);
397           rmdir (tmp);
398           rmdir (ctx->path);
399           return (-1);
400         }
401       }
402       else {
403         int i;
404
405         snprintf (tmp, sizeof (tmp), "%s/.mh_sequences", ctx->path);
406         if ((i = creat (tmp, S_IRWXU)) == -1) {
407           mutt_perror (tmp);
408           rmdir (ctx->path);
409           return (-1);
410         }
411         close (i);
412       }
413     }
414   }
415   else {
416     mutt_perror (ctx->path);
417     return (-1);
418   }
419
420   switch (ctx->magic) {
421   case M_MBOX:
422     if ((ctx->fp =
423          safe_fopen (ctx->path, flags & M_NEWFOLDER ? "w" : "a")) == NULL
424         || mbox_lock_mailbox (ctx, 1, 1) != 0) {
425       if (!ctx->fp)
426         mutt_perror (ctx->path);
427       else {
428         mutt_error (_("Couldn't lock %s\n"), ctx->path);
429         m_fclose(&ctx->fp);
430       }
431       return (-1);
432     }
433     fseeko (ctx->fp, 0, 2);
434     break;
435
436   case M_MH:
437   case M_MAILDIR:
438     /* nothing to do */
439     break;
440
441   default:
442     return (-1);
443   }
444
445   return 0;
446 }
447
448 /*
449  * open a mailbox and parse it
450  *
451  * Args:
452  *      flags   M_NOSORT        do not sort mailbox
453  *              M_APPEND        open mailbox for appending
454  *              M_READONLY      open mailbox in read-only mode
455  *              M_QUIET         only print error messages
456  *      ctx     if non-null, context struct to use
457  */
458 CONTEXT *mx_open_mailbox (const char *path, int flags, CONTEXT * pctx)
459 {
460   CONTEXT *ctx = pctx;
461   int rc;
462
463   if (!ctx)
464     ctx = p_new(CONTEXT, 1);
465   p_clear(ctx, 1);
466   ctx->path = m_strdup(path);
467
468   ctx->msgnotreadyet = -1;
469   ctx->collapsed = 0;
470
471   if (flags & M_QUIET)
472     ctx->quiet = 1;
473   if (flags & M_READONLY)
474     ctx->readonly = 1;
475   if (flags & M_COUNT)
476     ctx->counting = 1;
477
478   if (flags & (M_APPEND | M_NEWFOLDER)) {
479     if (mx_open_mailbox_append (ctx, flags) != 0) {
480       mx_fastclose_mailbox (ctx);
481       if (!pctx)
482         p_delete(&ctx);
483       return NULL;
484     }
485     return ctx;
486   }
487
488   if (!MX_IDX(ctx->magic-1))
489     ctx->magic = mx_get_magic (path);
490
491   if (ctx->magic == M_COMPRESSED)
492     mutt_open_read_compressed (ctx);
493
494   if (ctx->magic == 0)
495     mutt_error (_("%s is not a mailbox."), path);
496
497   if (ctx->magic == -1)
498     mutt_perror (path);
499
500   if (ctx->magic <= 0) {
501     mx_fastclose_mailbox (ctx);
502     if (!pctx)
503       p_delete(&ctx);
504     return (NULL);
505   }
506
507   /* if the user has a `push' command in their .muttrc, or in a folder-hook,
508    * it will cause the progress messages not to be displayed because
509    * mutt_refresh() will think we are in the middle of a macro.  so set a
510    * flag to indicate that we should really refresh the screen.
511    */
512   set_option (OPTFORCEREFRESH);
513
514   if (!ctx->quiet)
515     mutt_message (_("Reading %s..."), ctx->path);
516
517   rc = mxfmts[ctx->magic-1]->mx_open_mailbox(ctx);
518
519   if (rc == 0) {
520     if ((flags & M_NOSORT) == 0) {
521       /* avoid unnecessary work since the mailbox is completely unthreaded
522          to begin with */
523       unset_option (OPTSORTSUBTHREADS);
524       unset_option (OPTNEEDRESCORE);
525       mutt_sort_headers (ctx, 1);
526     }
527     if (!ctx->quiet)
528       mutt_clear_error ();
529   }
530   else {
531     mx_fastclose_mailbox (ctx);
532     if (!pctx)
533       p_delete(&ctx);
534   }
535
536   unset_option (OPTFORCEREFRESH);
537   return (ctx);
538 }
539
540 /* free up memory associated with the mailbox context */
541 void mx_fastclose_mailbox (CONTEXT * ctx)
542 {
543   int i;
544
545   if (!ctx)
546     return;
547
548   if (MX_IDX(ctx->magic-1) && mxfmts[ctx->magic-1]->mx_fastclose_mailbox)
549     mxfmts[ctx->magic-1]->mx_fastclose_mailbox(ctx);
550   if (ctx->subj_hash)
551     hash_delete (&ctx->subj_hash, NULL);
552   if (ctx->id_hash)
553     hash_delete (&ctx->id_hash, NULL);
554   mutt_clear_threads (ctx);
555   for (i = 0; i < ctx->msgcount; i++)
556     header_delete(&ctx->hdrs[i]);
557   p_delete(&ctx->hdrs);
558   p_delete(&ctx->v2r);
559
560   if (ctx->cinfo)
561     mutt_fast_close_compressed (ctx);
562
563   p_delete(&ctx->path);
564   p_delete(&ctx->pattern);
565   pattern_list_wipe(&ctx->limit_pattern);
566   m_fclose(&ctx->fp);
567   p_clear(ctx, 1);
568 }
569
570 /* save changes to disk */
571 static int sync_mailbox (CONTEXT * ctx, int *index_hint)
572 {
573   int rc = -1;
574
575   if (!ctx->quiet)
576     mutt_message (_("Writing %s..."), ctx->path);
577
578   if (MX_IDX(ctx->magic-1))
579     /* the 1 is only of interest for IMAP and means EXPUNGE */
580     rc = mxfmts[ctx->magic-1]->mx_sync_mailbox(ctx,1,index_hint);
581
582   if (rc == 0 && ctx->cinfo)
583     return mutt_sync_compressed (ctx);
584
585   return rc;
586 }
587
588 /* move deleted mails to the trash folder */
589 static int trash_append (CONTEXT * ctx)
590 {
591   CONTEXT *ctx_trash;
592   int i = 0;
593   struct stat st, stc;
594
595   if (!TrashPath || !ctx->deleted ||
596       (ctx->magic == M_MAILDIR && option (OPTMAILDIRTRASH)))
597     return 0;
598
599   for (; i < ctx->msgcount && (!ctx->hdrs[i]->deleted ||
600                                ctx->hdrs[i]->appended); i++);
601   if (i == ctx->msgcount)
602     return 0;                   /* nothing to be done */
603
604   if (mutt_save_confirm (TrashPath, &st) != 0) {
605     mutt_error _("message(s) not deleted");
606
607     return -1;
608   }
609
610   if (lstat (ctx->path, &stc) == 0 && stc.st_ino == st.st_ino
611       && stc.st_dev == st.st_dev && stc.st_rdev == st.st_rdev)
612     return 0;                   /* we are in the trash folder: simple sync */
613
614   if ((ctx_trash = mx_open_mailbox (TrashPath, M_APPEND, NULL)) != NULL) {
615     for (i = 0; i < ctx->msgcount; i++)
616       if (ctx->hdrs[i]->deleted && !ctx->hdrs[i]->appended
617           && !ctx->hdrs[i]->purged
618           && mutt_append_message (ctx_trash, ctx, ctx->hdrs[i], 0, 0) == -1) {
619         mx_close_mailbox (ctx_trash, NULL);
620         return -1;
621       }
622
623     mx_close_mailbox (ctx_trash, NULL);
624   }
625   else {
626     mutt_error _("Can't open trash folder");
627
628     return -1;
629   }
630
631   return 0;
632 }
633
634 /* save changes and close mailbox */
635 static int _mx_close_mailbox (CONTEXT * ctx, int *index_hint)
636 {
637   int i, move_messages = 0, purge = 1, read_msgs = 0;
638   int check;
639   int isSpool = 0;
640   CONTEXT f;
641   char mbox[_POSIX_PATH_MAX];
642   char buf[STRING];
643
644   if (!ctx)
645     return 0;
646
647   ctx->closing = 1;
648
649 #ifdef USE_NNTP
650   if (ctx->magic == M_NNTP) {
651     int ret;
652
653     ret = nntp_close_mailbox (ctx);
654     mx_fastclose_mailbox (ctx);
655     return ret;
656   }
657 #endif
658   if (ctx->readonly || ctx->dontwrite) {
659     /* mailbox is readonly or we don't want to write */
660     mx_fastclose_mailbox (ctx);
661     return 0;
662   }
663
664   if (ctx->append) {
665     /* mailbox was opened in write-mode */
666     if (ctx->magic == M_MBOX)
667       mbox_close_mailbox (ctx);
668     else
669       mx_fastclose_mailbox (ctx);
670     return 0;
671   }
672
673   for (i = 0; i < ctx->msgcount; i++) {
674     if (!ctx->hdrs[i]->deleted && ctx->hdrs[i]->read
675         && !(ctx->hdrs[i]->flagged && option (OPTKEEPFLAGGED)))
676       read_msgs++;
677   }
678
679   if (read_msgs && quadoption (OPT_MOVE) != M_NO) {
680     char *p;
681
682     if ((p = mutt_find_hook (M_MBOXHOOK, ctx->path))) {
683       isSpool = 1;
684       m_strcpy(mbox, sizeof(mbox), p);
685     }
686     else {
687       m_strcpy(mbox, sizeof(mbox), NONULL(Inbox));
688       isSpool = mutt_is_spool (ctx->path) && !mutt_is_spool (mbox);
689     }
690     mutt_expand_path (mbox, sizeof (mbox));
691
692     if (isSpool) {
693       snprintf (buf, sizeof (buf), _("Move read messages to %s?"), mbox);
694       if ((move_messages = query_quadoption (OPT_MOVE, buf)) == -1) {
695         ctx->closing = 0;
696         return (-1);
697       }
698     }
699   }
700
701   /* 
702    * There is no point in asking whether or not to purge if we are
703    * just marking messages as "trash".
704    */
705   if (ctx->deleted && !(ctx->magic == M_MAILDIR && option (OPTMAILDIRTRASH))) {
706     snprintf (buf, sizeof (buf), ctx->deleted == 1
707               ? _("Purge %d deleted message?") :
708               _("Purge %d deleted messages?"), ctx->deleted);
709     if ((purge = query_quadoption (OPT_DELETE, buf)) < 0) {
710       ctx->closing = 0;
711       return (-1);
712     }
713   }
714
715   /* IMAP servers manage the OLD flag themselves */
716   if (ctx->magic != M_IMAP)
717     if (option (OPTMARKOLD)) {
718       for (i = 0; i < ctx->msgcount; i++) {
719         if (!ctx->hdrs[i]->deleted && !ctx->hdrs[i]->old)
720           mutt_set_flag (ctx, ctx->hdrs[i], M_OLD, 1);
721       }
722     }
723
724   if (move_messages) {
725     mutt_message (_("Moving read messages to %s..."), mbox);
726
727     /* try to use server-side copy first */
728     i = 1;
729
730     if (ctx->magic == M_IMAP && imap_is_magic (mbox, NULL) == M_IMAP) {
731       /* tag messages for moving, and clear old tags, if any */
732       for (i = 0; i < ctx->msgcount; i++)
733         if (ctx->hdrs[i]->read && !ctx->hdrs[i]->deleted
734             && !(ctx->hdrs[i]->flagged && option (OPTKEEPFLAGGED)))
735           ctx->hdrs[i]->tagged = 1;
736         else
737           ctx->hdrs[i]->tagged = 0;
738
739       i = imap_copy_messages (ctx, NULL, mbox, 1);
740     }
741
742     if (i == 0)                 /* success */
743       mutt_clear_error ();
744     else if (i == -1) {         /* horrible error, bail */
745       ctx->closing = 0;
746       return -1;
747     }
748     else                        /* use regular append-copy mode */
749     {
750       if (mx_open_mailbox (mbox, M_APPEND, &f) == NULL) {
751         ctx->closing = 0;
752         return -1;
753       }
754
755       for (i = 0; i < ctx->msgcount; i++) {
756         if (ctx->hdrs[i]->read && !ctx->hdrs[i]->deleted
757             && !(ctx->hdrs[i]->flagged && option (OPTKEEPFLAGGED))) {
758           if (mutt_append_message (&f, ctx, ctx->hdrs[i], 0, CH_UPDATE_LEN) ==
759               0) {
760             mutt_set_flag (ctx, ctx->hdrs[i], M_DELETE, 1);
761             mutt_set_flag (ctx, ctx->hdrs[i], M_APPENDED, 1);
762           }
763           else {
764             mx_close_mailbox (&f, NULL);
765             ctx->closing = 0;
766             return -1;
767           }
768         }
769       }
770
771       mx_close_mailbox (&f, NULL);
772     }
773
774   }
775   else if (!ctx->changed && ctx->deleted == 0) {
776     mutt_message _("Mailbox is unchanged.");
777
778     mx_fastclose_mailbox (ctx);
779     return 0;
780   }
781
782   /* copy mails to the trash before expunging */
783   if (purge && ctx->deleted)
784     if (trash_append (ctx) != 0) {
785       ctx->closing = 0;
786       return -1;
787     }
788
789   /* allow IMAP to preserve the deleted flag across sessions */
790   if (ctx->magic == M_IMAP) {
791     if ((check = imap_sync_mailbox (ctx, purge, index_hint)) != 0) {
792       ctx->closing = 0;
793       return check;
794     }
795   }
796   else
797   {
798     if (!purge) {
799       for (i = 0; i < ctx->msgcount; i++)
800         ctx->hdrs[i]->deleted = 0;
801       ctx->deleted = 0;
802     }
803
804     if (ctx->changed || ctx->deleted) {
805       if ((check = sync_mailbox (ctx, index_hint)) != 0) {
806         ctx->closing = 0;
807         return check;
808       }
809     }
810   }
811
812   if (move_messages)
813     mutt_message (_("%d kept, %d moved, %d deleted."),
814                   ctx->msgcount - ctx->deleted, read_msgs, ctx->deleted);
815   else
816     mutt_message (_("%d kept, %d deleted."),
817                   ctx->msgcount - ctx->deleted, ctx->deleted);
818
819   if (ctx->msgcount == ctx->deleted && ctx->magic == M_MBOX
820   &&  !mutt_is_spool (ctx->path) && !option (OPTSAVEEMPTY))
821   {
822     mx_unlink_empty (ctx->path);
823   }
824
825   if (ctx->cinfo && mutt_slow_close_compressed (ctx))
826     return (-1);
827
828   mx_fastclose_mailbox (ctx);
829
830   return 0;
831 }
832
833 int mx_close_mailbox (CONTEXT * ctx, int *index_hint) {
834   int ret = 0;
835   if (!ctx)
836     return (0);
837   ret = _mx_close_mailbox (ctx, index_hint);
838   sidebar_set_buffystats (ctx);
839   return (ret);
840 }
841
842 /* update a Context structure's internal tables. */
843
844 void mx_update_tables (CONTEXT * ctx, int committing)
845 {
846   int i, j;
847
848   /* update memory to reflect the new state of the mailbox */
849   ctx->vcount = 0;
850   ctx->vsize = 0;
851   ctx->tagged = 0;
852   ctx->deleted = 0;
853   ctx->new = 0;
854   ctx->unread = 0;
855   ctx->changed = 0;
856   ctx->flagged = 0;
857 #define this_body ctx->hdrs[j]->content
858   for (i = 0, j = 0; i < ctx->msgcount; i++) {
859     if ((committing && (!ctx->hdrs[i]->deleted ||
860                         (ctx->magic == M_MAILDIR
861                          && option (OPTMAILDIRTRASH)))) || (!committing
862                                                             && ctx->hdrs[i]->
863                                                             active)) {
864       if (i != j) {
865         ctx->hdrs[j] = ctx->hdrs[i];
866         ctx->hdrs[i] = NULL;
867       }
868       ctx->hdrs[j]->msgno = j;
869       if (ctx->hdrs[j]->virtual != -1) {
870         ctx->v2r[ctx->vcount] = j;
871         ctx->hdrs[j]->virtual = ctx->vcount++;
872         ctx->vsize += this_body->length + this_body->offset -
873           this_body->hdr_offset;
874       }
875
876       if (committing)
877         ctx->hdrs[j]->changed = 0;
878       else if (ctx->hdrs[j]->changed)
879         ctx->changed++;
880
881       if (!committing
882           || (ctx->magic == M_MAILDIR && option (OPTMAILDIRTRASH))) {
883         if (ctx->hdrs[j]->deleted)
884           ctx->deleted++;
885       }
886
887       if (ctx->hdrs[j]->tagged)
888         ctx->tagged++;
889       if (ctx->hdrs[j]->flagged)
890         ctx->flagged++;
891       if (!ctx->hdrs[j]->read) {
892         ctx->unread++;
893         if (!ctx->hdrs[j]->old)
894           ctx->new++;
895       }
896
897       j++;
898     }
899     else {
900       if (ctx->magic == M_MH || ctx->magic == M_MAILDIR)
901         ctx->size -= (ctx->hdrs[i]->content->length +
902                       ctx->hdrs[i]->content->offset -
903                       ctx->hdrs[i]->content->hdr_offset);
904       /* remove message from the hash tables */
905       if (ctx->subj_hash && ctx->hdrs[i]->env->real_subj)
906         hash_remove (ctx->subj_hash, ctx->hdrs[i]->env->real_subj,
907                      ctx->hdrs[i], NULL);
908       if (ctx->id_hash && ctx->hdrs[i]->env->message_id)
909         hash_remove (ctx->id_hash, ctx->hdrs[i]->env->message_id,
910                      ctx->hdrs[i], NULL);
911       header_delete(&ctx->hdrs[i]);
912     }
913   }
914 #undef this_body
915   ctx->msgcount = j;
916
917   /* update sidebar count */
918   sidebar_set_buffystats (ctx);
919 }
920
921
922 /* save changes to mailbox
923  *
924  * return values:
925  *      0               success
926  *      -1              error
927  */
928 static int _mx_sync_mailbox (CONTEXT * ctx, int *index_hint)
929 {
930   int rc, i;
931   int purge = 1;
932   int msgcount, deleted;
933
934   if (ctx->dontwrite) {
935     char buf[STRING], tmp[STRING];
936
937     if (km_expand_key (buf, sizeof (buf),
938                        km_find_func (MENU_MAIN, OP_TOGGLE_WRITE)))
939       snprintf (tmp, sizeof (tmp), _(" Press '%s' to toggle write"), buf);
940     else
941       m_strcpy(tmp, sizeof(tmp), _("Use 'toggle-write' to re-enable write!"));
942
943     mutt_error (_("Mailbox is marked unwritable. %s"), tmp);
944     return -1;
945   }
946   else if (ctx->readonly) {
947     mutt_error _("Mailbox is read-only.");
948
949     return -1;
950   }
951
952   if (!ctx->changed && !ctx->deleted) {
953     mutt_message _("Mailbox is unchanged.");
954
955     return (0);
956   }
957
958   if (ctx->deleted) {
959     char buf[STRING];
960
961     snprintf (buf, sizeof (buf), ctx->deleted == 1
962               ? _("Purge %d deleted message?") :
963               _("Purge %d deleted messages?"), ctx->deleted);
964     if ((purge = query_quadoption (OPT_DELETE, buf)) < 0)
965       return (-1);
966     else if (purge == M_NO) {
967       if (!ctx->changed)
968         return 0;               /* nothing to do! */
969       /* let IMAP servers hold on to D flags */
970       if (ctx->magic != M_IMAP)
971       {
972         for (i = 0; i < ctx->msgcount; i++)
973           ctx->hdrs[i]->deleted = 0;
974         ctx->deleted = 0;
975       }
976     }
977     else if (ctx->last_tag && ctx->last_tag->deleted)
978       ctx->last_tag = NULL;     /* reset last tagged msg now useless */
979   }
980
981   /* really only for IMAP - imap_sync_mailbox results in a call to
982    * mx_update_tables, so ctx->deleted is 0 when it comes back */
983   msgcount = ctx->msgcount;
984   deleted = ctx->deleted;
985
986   if (purge && ctx->deleted) {
987     if (trash_append (ctx) == -1)
988       return -1;
989   }
990
991   if (ctx->magic == M_IMAP)
992     rc = imap_sync_mailbox (ctx, purge, index_hint);
993   else
994     rc = sync_mailbox (ctx, index_hint);
995   if (rc == 0) {
996     if (ctx->magic == M_IMAP && !purge)
997       mutt_message (_("Mailbox checkpointed."));
998
999     else
1000       mutt_message (_("%d kept, %d deleted."), msgcount - deleted, deleted);
1001
1002     mutt_sleep (0);
1003
1004     if (ctx->msgcount == ctx->deleted && ctx->magic == M_MBOX
1005     &&  !mutt_is_spool (ctx->path) && !option (OPTSAVEEMPTY))
1006     {
1007       unlink (ctx->path);
1008       mx_fastclose_mailbox (ctx);
1009       return 0;
1010     }
1011
1012     /* if we haven't deleted any messages, we don't need to resort */
1013     /* ... except for certain folder formats which need "unsorted" 
1014      * sort order in order to synchronize folders.
1015      * 
1016      * MH and maildir are safe.  mbox-style seems to need re-sorting,
1017      * at least with the new threading code.
1018      */
1019     if (purge || (ctx->magic != M_MAILDIR && ctx->magic != M_MH)) {
1020       /* IMAP does this automatically after handling EXPUNGE */
1021       if (ctx->magic != M_IMAP)
1022       {
1023         mx_update_tables (ctx, 1);
1024         mutt_sort_headers (ctx, 1);     /* rethread from scratch */
1025       }
1026     }
1027   }
1028
1029   return (rc);
1030 }
1031
1032 int mx_sync_mailbox (CONTEXT* ctx, int* index_hint) {
1033   int ret = _mx_sync_mailbox (ctx, index_hint);
1034   sidebar_set_buffystats (ctx);
1035   return (ret);
1036 }
1037
1038 /* args:
1039  *      dest    destintation mailbox
1040  *      hdr     message being copied (required for maildir support, because
1041  *              the filename depends on the message flags)
1042  */
1043 MESSAGE *mx_open_new_message (CONTEXT * dest, HEADER * hdr, int flags)
1044 {
1045   MESSAGE *msg;
1046   address_t *p = NULL;
1047
1048   if (!MX_IDX(dest->magic-1)) {
1049     return (NULL);
1050   }
1051
1052   msg = p_new(MESSAGE, 1);
1053   msg->magic = dest->magic;
1054   msg->write = 1;
1055
1056   if (hdr) {
1057     msg->flags.flagged = hdr->flagged;
1058     msg->flags.replied = hdr->replied;
1059     msg->flags.read = hdr->read;
1060     msg->received = hdr->received;
1061   }
1062
1063   if (msg->received == 0)
1064     time (&msg->received);
1065
1066   if (mxfmts[dest->magic-1]->mx_open_new_message(msg, dest, hdr) == 0) {
1067     if (msg->magic == M_MBOX && flags & M_ADD_FROM) {
1068       if (hdr) {
1069         if (hdr->env->return_path)
1070           p = hdr->env->return_path;
1071         else if (hdr->env->sender)
1072           p = hdr->env->sender;
1073         else
1074           p = hdr->env->from;
1075       }
1076
1077       fprintf (msg->fp, "From %s %s", p ? p->mailbox : NONULL(MCore.username),
1078                ctime (&msg->received));
1079     }
1080   }
1081   else
1082     p_delete(&msg);
1083
1084   return msg;
1085 }
1086
1087 /* check for new mail */
1088 int mx_check_mailbox (CONTEXT * ctx, int *index_hint, int lock) {
1089   if (ctx->cinfo)
1090     return mutt_check_mailbox_compressed (ctx);
1091
1092   if (ctx) {
1093     if (ctx->locked)
1094       lock = 0;
1095     if (MX_IDX(ctx->magic-1) && mxfmts[ctx->magic-1]->mx_check_mailbox)
1096       return (mxfmts[ctx->magic-1]->mx_check_mailbox(ctx, index_hint, lock));
1097   }
1098
1099   return (-1);
1100 }
1101
1102 /* return a stream pointer for a message */
1103 MESSAGE *mx_open_message (CONTEXT * ctx, int msgno)
1104 {
1105   MESSAGE *msg;
1106
1107   msg = p_new(MESSAGE, 1);
1108   switch (msg->magic = ctx->magic) {
1109   case M_MBOX:
1110     msg->fp = ctx->fp;
1111     break;
1112
1113   case M_MH:
1114   case M_MAILDIR:
1115     {
1116       HEADER *cur = ctx->hdrs[msgno];
1117       char path[_POSIX_PATH_MAX];
1118
1119       snprintf (path, sizeof (path), "%s/%s", ctx->path, cur->path);
1120
1121       if ((msg->fp = fopen (path, "r")) == NULL && errno == ENOENT &&
1122           ctx->magic == M_MAILDIR)
1123         msg->fp = maildir_open_find_message (ctx->path, cur->path);
1124
1125       if (msg->fp == NULL) {
1126         mutt_perror (path);
1127         p_delete(&msg);
1128       }
1129     }
1130     break;
1131
1132   case M_IMAP:
1133     {
1134       if (imap_fetch_message (msg, ctx, msgno) != 0)
1135         p_delete(&msg);
1136       break;
1137     }
1138
1139   case M_POP:
1140     {
1141       if (pop_fetch_message (msg, ctx, msgno) != 0)
1142         p_delete(&msg);
1143       break;
1144     }
1145
1146 #ifdef USE_NNTP
1147   case M_NNTP:
1148     {
1149       if (nntp_fetch_message (msg, ctx, msgno) != 0)
1150         p_delete(&msg);
1151       break;
1152     }
1153 #endif /* USE_NNTP */
1154
1155   default:
1156     p_delete(&msg);
1157     break;
1158   }
1159   return (msg);
1160 }
1161
1162 /* commit a message to a folder */
1163
1164 int mx_commit_message (MESSAGE * msg, CONTEXT * ctx) {
1165   if (!(msg->write && ctx->append)) {
1166     return -1;
1167   }
1168   if (!ctx || !MX_IDX(ctx->magic-1) || !mxfmts[ctx->magic-1]->mx_commit_message)
1169     return (-1);
1170   return (mxfmts[ctx->magic-1]->mx_commit_message (msg, ctx));
1171 }
1172
1173 /* close a pointer to a message */
1174 int mx_close_message (MESSAGE ** msg)
1175 {
1176   int r = 0;
1177
1178   if ((*msg)->magic == M_MH || (*msg)->magic == M_MAILDIR
1179       || (*msg)->magic == M_IMAP
1180       || (*msg)->magic == M_POP
1181 #ifdef USE_NNTP
1182       || (*msg)->magic == M_NNTP
1183 #endif
1184     ) {
1185     r = m_fclose(&(*msg)->fp);
1186   }
1187   else
1188     (*msg)->fp = NULL;
1189
1190   if ((*msg)->path) {
1191     unlink ((*msg)->path);
1192     p_delete(&(*msg)->path);
1193   }
1194
1195   p_delete(msg);
1196   return (r);
1197 }
1198
1199 void mx_alloc_memory (CONTEXT * ctx)
1200 {
1201     ctx->hdrmax += 25;
1202
1203     p_realloc(&ctx->hdrs, ctx->hdrmax);
1204     p_realloc(&ctx->v2r, ctx->hdrmax);
1205     p_clear(ctx->hdrs + ctx->msgcount, ctx->hdrmax - ctx->msgcount);
1206     p_clear(ctx->v2r + ctx->msgcount, ctx->hdrmax - ctx->msgcount);
1207 }
1208
1209 /* this routine is called to update the counts in the context structure for
1210  * the last message header parsed.
1211  */
1212 void mx_update_context (CONTEXT * ctx, int new_messages)
1213 {
1214   HEADER *h;
1215   int msgno;
1216
1217   for (msgno = ctx->msgcount - new_messages; msgno < ctx->msgcount; msgno++) {
1218     h = ctx->hdrs[msgno];
1219
1220     /* NOTE: this _must_ be done before the check for mailcap! */
1221     h->security = crypt_query (h->content);
1222
1223     if (!ctx->pattern) {
1224       ctx->v2r[ctx->vcount] = msgno;
1225       h->virtual = ctx->vcount++;
1226     }
1227     else
1228       h->virtual = -1;
1229     h->msgno = msgno;
1230
1231     if (h->env->supersedes) {
1232       HEADER *h2;
1233
1234       if (!ctx->id_hash)
1235         ctx->id_hash = mutt_make_id_hash (ctx);
1236
1237       h2 = hash_find (ctx->id_hash, h->env->supersedes);
1238
1239       /* p_delete(&h->env->supersedes); should I ? */
1240       if (h2) {
1241         h2->superseded = 1;
1242         if (!ctx->counting && option (OPTSCORE))
1243           mutt_score_message (ctx, h2, 1);
1244       }
1245     }
1246
1247     /* add this message to the hash tables */
1248     if (ctx->id_hash && h->env->message_id)
1249       hash_insert (ctx->id_hash, h->env->message_id, h);
1250     if (!ctx->counting) {
1251       if (ctx->subj_hash && h->env->real_subj)
1252         hash_insert (ctx->subj_hash, h->env->real_subj, h);
1253
1254       if (option (OPTSCORE))
1255         mutt_score_message (ctx, h, 0);
1256     }
1257
1258     if (h->changed)
1259       ctx->changed = 1;
1260     if (h->flagged)
1261       ctx->flagged++;
1262     if (h->deleted)
1263       ctx->deleted++;
1264     if (!h->read) {
1265       ctx->unread++;
1266       if (!h->old)
1267         ctx->new++;
1268     }
1269   }
1270   /* update sidebar count */
1271   sidebar_set_buffystats (ctx);
1272 }
1273
1274 /*
1275  * Return:
1276  * 1 if the specified mailbox contains 0 messages.
1277  * 0 if the mailbox contains messages
1278  * -1 on error
1279  */
1280 int mx_check_empty (const char *path)
1281 {
1282   int i = 0;
1283   if ((i = mx_get_idx (path)) >= 0 && mxfmts[i]->mx_check_empty)
1284     return (mxfmts[i]->mx_check_empty(path));
1285   errno = EINVAL;
1286   return (-1);
1287 }
1288
1289 int mx_acl_check(CONTEXT *ctx, int flag)
1290 {
1291     if (!mxfmts[ctx->magic-1]->mx_acl_check)
1292         return 1;
1293     return mxfmts[ctx->magic-1]->mx_acl_check(ctx,flag);
1294 }
1295
1296 void mutt_parse_mime_message (CONTEXT * ctx, HEADER * cur)
1297 {
1298   MESSAGE *msg;
1299   int flags = 0;
1300
1301   do {
1302     if (cur->content->type != TYPEMESSAGE
1303         && cur->content->type != TYPEMULTIPART)
1304       break;                     /* nothing to do */
1305
1306     if (cur->content->parts)
1307       break;                     /* The message was parsed earlier. */
1308
1309     if ((msg = mx_open_message (ctx, cur->msgno))) {
1310       mutt_parse_part (msg->fp, cur->content);
1311
1312       cur->security = crypt_query (cur->content);
1313
1314       mx_close_message (&msg);
1315     }
1316   } while (0);
1317   mutt_count_body_parts (cur, flags | M_PARTS_RECOUNT);
1318 }