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