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