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