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