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