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