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