2 * Copyright notice from original mutt:
3 * Copyright (C) 1996-8 Michael R. Elkins <me@mutt.org>
4 * Copyright (C) 1996-9 Brandon Long <blong@fiction.net>
5 * Copyright (C) 1999-2005 Brendan Cully <brendan@kublai.com>
7 * This file is part of mutt-ng, see http://www.muttng.org/.
8 * It's licensed under the GNU General Public License,
9 * please see the file GPL in the top level source directory.
12 /* Support for IMAP4rev1, with the occasional nod to IMAP 4. */
18 #include <lib-lib/mem.h>
19 #include <lib-lib/ascii.h>
20 #include <lib-lib/str.h>
21 #include <lib-lib/buffer.h>
29 #include "imap_private.h"
30 #if defined(USE_SSL) || defined(USE_GNUTLS)
31 # include <lib-sys/mutt_ssl.h>
35 #include <lib-lib/macros.h>
41 #include <sys/types.h>
44 /* imap forward declarations */
45 static int imap_get_delim (IMAP_DATA * idata);
46 static char *imap_get_flags (string_list_t ** hflags, char *s);
47 static int imap_check_acl (IMAP_DATA * idata);
48 static int imap_check_capabilities (IMAP_DATA * idata);
49 static void imap_set_flag (IMAP_DATA * idata, int aclbit, int flag,
50 const char *str, char *flags, size_t flsize);
52 /* imap_access: Check permissions on an IMAP mailbox.
53 * TODO: ACL checks. Right now we assume if it exists we can
55 int imap_access (const char *path, int flags __attribute__ ((unused)))
59 char buf[LONG_STRING];
60 char mailbox[LONG_STRING];
61 char mbox[LONG_STRING];
63 if (imap_parse_path (path, &mx))
66 if (!(idata = imap_conn_find (&mx.account,
67 option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW :
73 imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
75 /* we may already be in the folder we're checking */
76 if (!ascii_strcmp(idata->mailbox, mx.mbox)) {
82 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
84 if (mutt_bit_isset (idata->capabilities, IMAP4REV1))
85 snprintf (buf, sizeof (buf), "STATUS %s (UIDVALIDITY)", mbox);
86 else if (mutt_bit_isset (idata->capabilities, STATUS))
87 snprintf (buf, sizeof (buf), "STATUS %s (UID-VALIDITY)", mbox);
92 if (imap_exec (idata, buf, IMAP_CMD_FAIL_OK) < 0) {
99 int imap_create_mailbox (IMAP_DATA * idata, char *mailbox)
101 char buf[LONG_STRING], mbox[LONG_STRING];
103 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
104 snprintf (buf, sizeof (buf), "CREATE %s", mbox);
106 if (imap_exec (idata, buf, 0) != 0)
112 int imap_rename_mailbox (IMAP_DATA * idata, IMAP_MBOX * mx,
115 char oldmbox[LONG_STRING];
116 char newmbox[LONG_STRING];
117 char buf[LONG_STRING];
119 imap_munge_mbox_name (oldmbox, sizeof (oldmbox), mx->mbox);
120 imap_munge_mbox_name (newmbox, sizeof (newmbox), newname);
122 snprintf (buf, sizeof (buf), "RENAME %s %s", oldmbox, newmbox);
124 if (imap_exec (idata, buf, 0) != 0)
130 int imap_delete_mailbox (CONTEXT * ctx, IMAP_MBOX mx)
132 char buf[LONG_STRING], mbox[LONG_STRING];
135 if (!ctx || !ctx->data) {
136 if (!(idata = imap_conn_find (&mx.account,
137 option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW
147 imap_munge_mbox_name (mbox, sizeof (mbox), mx.mbox);
148 snprintf (buf, sizeof (buf), "DELETE %s", mbox);
150 if (imap_exec ((IMAP_DATA *) idata, buf, 0) != 0)
156 /* imap_logout_all: close all open connections. Quick and dirty until we can
157 * make sure we've got all the context we need. */
158 void imap_logout_all (void)
163 conn = mutt_socket_head ();
168 if (conn->account.type == M_ACCT_TYPE_IMAP && conn->fd >= 0) {
169 mutt_message (_("Closing connection to %s..."), conn->account.host);
170 imap_logout ((IMAP_DATA *) conn->data);
172 mutt_socket_close (conn);
173 mutt_socket_free (conn);
180 /* imap_read_literal: read bytes bytes from server into file. Not explicitly
181 * buffered, relies on FILE buffering. NOTE: strips \r from \r\n.
182 * Apparently even literals use \r\n-terminated strings ?! */
183 int imap_read_literal (FILE * fp, IMAP_DATA * idata, long bytes, progress_t* bar)
190 for (pos = 0; pos < bytes; pos++) {
191 if (mutt_socket_readchar (idata->conn, &c) != 1) {
192 idata->status = IMAP_FATAL;
198 if (r == 1 && c != '\n')
209 if (bar && !(pos % 1024))
210 mutt_progress_bar (bar, pos);
216 /* imap_expunge_mailbox: Purge IMAP portion of expunged messages from the
217 * context. Must not be done while something has a handle on any headers
218 * (eg inside pager or editor). That is, check IMAP_REOPEN_ALLOW. */
219 void imap_expunge_mailbox (IMAP_DATA * idata)
224 for (i = 0; i < idata->ctx->msgcount; i++) {
225 h = idata->ctx->hdrs[i];
227 if (h->index == -1) {
230 /* free cached body from disk, if neccessary */
231 cacheno = HEADER_DATA (h)->uid % IMAP_CACHE_LEN;
232 if (idata->cache[cacheno].uid == HEADER_DATA (h)->uid &&
233 idata->cache[cacheno].path) {
234 unlink (idata->cache[cacheno].path);
235 p_delete(&idata->cache[cacheno].path);
238 imap_free_header_data (&h->data);
242 /* We may be called on to expunge at any time. We can't rely on the caller
243 * to always know to rethread */
244 mx_update_tables (idata->ctx, 0);
245 mutt_sort_headers (idata->ctx, 1);
248 static int imap_get_delim (IMAP_DATA * idata)
253 /* assume that the delim is /. If this fails, we're in bigger trouble
254 * than getting the delim wrong */
257 imap_cmd_start (idata, "string_list_t \"\" \"\"");
260 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
263 s = imap_next_word (idata->cmd.buf);
264 if (ascii_strncasecmp ("string_list_t", s, 4) == 0) {
265 s = imap_next_word (s);
266 s = imap_next_word (s);
267 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
269 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
274 while (rc == IMAP_CMD_CONTINUE);
279 /* get rights for folder, let imap_handle_untagged do the rest */
280 static int imap_check_acl (IMAP_DATA * idata)
282 char buf[LONG_STRING];
283 char mbox[LONG_STRING];
285 imap_munge_mbox_name (mbox, sizeof (mbox), idata->mailbox);
286 snprintf (buf, sizeof (buf), "MYRIGHTS %s", mbox);
287 if (imap_exec (idata, buf, 0) != 0) {
288 imap_error ("imap_check_acl", buf);
294 /* imap_check_capabilities: make sure we can log in to this server. */
295 static int imap_check_capabilities (IMAP_DATA * idata)
297 if (imap_exec (idata, "CAPABILITY", 0) != 0) {
298 imap_error ("imap_check_capabilities", idata->cmd.buf);
302 if (!(mutt_bit_isset (idata->capabilities, IMAP4)
303 || mutt_bit_isset (idata->capabilities, IMAP4REV1))) {
304 mutt_error _("This IMAP server is ancient. Mutt does not work with it.");
306 mutt_sleep (2); /* pause a moment to let the user see the error */
314 /* imap_conn_find: Find an open IMAP connection matching account, or open
315 * a new one if none can be found. */
316 IMAP_DATA *imap_conn_find (const ACCOUNT * account, int flags)
323 if (!(conn = mutt_conn_find (NULL, account)))
326 /* if opening a new UNSELECTED connection, preserve existing creds */
327 creds = &(conn->account);
329 /* make sure this connection is not in SELECTED state, if neccessary */
330 if (flags & M_IMAP_CONN_NOSELECT)
331 while (conn->data && ((IMAP_DATA *) conn->data)->state == IMAP_SELECTED) {
332 if (!(conn = mutt_conn_find (conn, account)))
334 memcpy (&(conn->account), creds, sizeof (ACCOUNT));
337 idata = (IMAP_DATA *) conn->data;
339 /* don't open a new connection if one isn't wanted */
340 if (flags & M_IMAP_CONN_NONEW) {
342 mutt_socket_free (conn);
345 if (idata->state < IMAP_AUTHENTICATED)
350 /* The current connection is a new connection */
351 if (!(idata = imap_new_idata ())) {
352 mutt_socket_free (conn);
361 if (idata->state == IMAP_DISCONNECTED)
362 imap_open_connection (idata);
363 if (idata->state == IMAP_CONNECTED) {
364 if (!imap_authenticate (idata)) {
365 idata->state = IMAP_AUTHENTICATED;
368 mutt_account_unsetpass (&idata->conn->account);
370 p_delete(&idata->capstr);
372 if (new && idata->state == IMAP_AUTHENTICATED) {
373 imap_get_delim (idata);
374 if (option (OPTIMAPCHECKSUBSCRIBED)) {
375 mutt_message _("Checking mailbox subscriptions");
376 imap_exec (idata, "LSUB \"\" \"*\"", 0);
383 int imap_open_connection (IMAP_DATA * idata)
385 char buf[LONG_STRING];
387 if (mutt_socket_open (idata->conn) < 0)
390 idata->state = IMAP_CONNECTED;
392 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE) {
393 mutt_socket_close (idata->conn);
394 idata->state = IMAP_DISCONNECTED;
398 if (ascii_strncasecmp ("* OK", idata->cmd.buf, 4) == 0) {
399 /* TODO: Parse new tagged CAPABILITY data (* OK [CAPABILITY...]) */
400 if (imap_check_capabilities (idata))
402 #if defined(USE_SSL) || defined(USE_GNUTLS)
403 /* Attempt STARTTLS if available and desired. */
404 if (!idata->conn->ssf && (option(OPTSSLFORCETLS) ||
405 mutt_bit_isset (idata->capabilities, STARTTLS))) {
408 if (option (OPTSSLFORCETLS))
410 else if ((rc = query_quadoption (OPT_SSLSTARTTLS,
411 _("Secure connection with TLS?"))) == -1)
414 if ((rc = imap_exec (idata, "STARTTLS", IMAP_CMD_FAIL_OK)) == -1)
417 #if defined (USE_SSL) || defined (USE_GNUTLS)
418 if (mutt_ssl_starttls (idata->conn))
421 mutt_error (_("Could not negotiate TLS connection"));
426 /* RFC 2595 demands we recheck CAPABILITY after TLS completes. */
427 if (imap_exec (idata, "CAPABILITY", 0))
434 if (option(OPTSSLFORCETLS) && ! idata->conn->ssf) {
435 mutt_error _("Encrypted connection unavailable");
441 else if (ascii_strncasecmp ("* PREAUTH", idata->cmd.buf, 9) == 0) {
442 idata->state = IMAP_AUTHENTICATED;
443 if (imap_check_capabilities (idata) != 0)
445 p_delete(&idata->capstr);
448 imap_error ("imap_open_connection()", buf);
455 mutt_socket_close (idata->conn);
456 idata->state = IMAP_DISCONNECTED;
458 p_delete(&idata->capstr);
462 /* imap_get_flags: Make a simple list out of a FLAGS response.
463 * return stream following FLAGS response */
464 static char *imap_get_flags (string_list_t ** hflags, char *s)
466 string_list_t *flags;
470 /* sanity-check string */
471 if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
474 s = vskipspaces(s + 5);
479 /* create list, update caller's flags handle */
480 flags = string_item_new();
483 while (*s && *s != ')') {
484 s = vskipspaces(s + 1);
486 while (*s && (*s != ')') && !ISSPACE (*s))
491 mutt_add_list (flags, flag_word);
495 /* note bad flags response */
497 string_list_wipe(hflags);
507 int imap_open_mailbox (CONTEXT * ctx)
511 char buf[LONG_STRING];
512 char bufout[LONG_STRING];
517 if (imap_parse_path (ctx->path, &mx)) {
518 mutt_error (_("%s is an invalid IMAP path"), ctx->path);
522 /* we require a connection which isn't currently in IMAP_SELECTED state */
523 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NOSELECT)))
525 if (idata->state < IMAP_AUTHENTICATED)
530 /* once again the context is new */
533 /* Clean up path and replace the one in the ctx */
534 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
535 p_delete(&(idata->mailbox));
536 idata->mailbox = m_strdup(buf);
537 imap_qualify_path (buf, sizeof (buf), &mx, idata->mailbox);
539 p_delete(&(ctx->path));
540 ctx->path = m_strdup(buf);
544 /* clear mailbox status */
546 memset (idata->rights, 0, (RIGHTSMAX + 7) / 8);
547 idata->newMailCount = 0;
549 mutt_message (_("Selecting %s..."), idata->mailbox);
550 imap_munge_mbox_name (buf, sizeof (buf), idata->mailbox);
551 snprintf (bufout, sizeof (bufout), "%s %s",
552 ctx->readonly ? "EXAMINE" : "SELECT", buf);
554 idata->state = IMAP_SELECTED;
556 imap_cmd_start (idata, bufout);
561 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
564 pc = idata->cmd.buf + 2;
566 /* Obtain list of available flags here, may be overridden by a
567 * PERMANENTFLAGS tag in the OK response */
568 if (ascii_strncasecmp ("FLAGS", pc, 5) == 0) {
569 /* don't override PERMANENTFLAGS */
571 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
575 /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
576 else if (ascii_strncasecmp ("OK [PERMANENTFLAGS", pc, 18) == 0) {
577 /* safe to call on NULL */
578 string_list_wipe(&(idata->flags));
579 /* skip "OK [PERMANENT" so syntax is the same as FLAGS */
581 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
585 /* save UIDVALIDITY for the header cache */
586 else if (ascii_strncasecmp ("OK [UIDVALIDITY", pc, 14) == 0) {
588 pc = imap_next_word (pc);
590 sscanf (pc, "%lu", &(idata->uid_validity));
594 pc = imap_next_word (pc);
595 if (!ascii_strncasecmp ("EXISTS", pc, 6)) {
596 count = idata->newMailCount;
597 idata->newMailCount = 0;
601 while (rc == IMAP_CMD_CONTINUE);
603 if (rc == IMAP_CMD_NO) {
606 s = imap_next_word (idata->cmd.buf); /* skip seq */
607 s = imap_next_word (s); /* Skip response */
608 mutt_error ("%s", s);
613 if (rc != IMAP_CMD_OK)
616 /* check for READ-ONLY notification */
617 if (!ascii_strncasecmp
618 (imap_get_qualifier (idata->cmd.buf), "[READ-ONLY]", 11)
619 && !mutt_bit_isset (idata->capabilities, ACL)) {
623 if (mutt_bit_isset (idata->capabilities, ACL)) {
624 if (imap_check_acl (idata))
626 if (!(mutt_bit_isset (idata->rights, ACL_DELETE) ||
627 mutt_bit_isset (idata->rights, ACL_SEEN) ||
628 mutt_bit_isset (idata->rights, ACL_WRITE) ||
629 mutt_bit_isset (idata->rights, ACL_INSERT)))
632 /* assume we have all rights if ACL is unavailable */
634 mutt_bit_set (idata->rights, ACL_LOOKUP);
635 mutt_bit_set (idata->rights, ACL_READ);
636 mutt_bit_set (idata->rights, ACL_SEEN);
637 mutt_bit_set (idata->rights, ACL_WRITE);
638 mutt_bit_set (idata->rights, ACL_INSERT);
639 mutt_bit_set (idata->rights, ACL_POST);
640 mutt_bit_set (idata->rights, ACL_CREATE);
641 mutt_bit_set (idata->rights, ACL_DELETE);
645 ctx->hdrs = p_new(HEADER *, count);
646 ctx->v2r = p_new(int, count);
648 if (count && (imap_read_headers (idata, 0, count - 1) < 0)) {
649 mutt_error _("Error opening mailbox");
659 if (idata->state == IMAP_SELECTED)
660 idata->state = IMAP_AUTHENTICATED;
666 int imap_open_mailbox_append (CONTEXT * ctx)
670 char buf[LONG_STRING];
671 char mailbox[LONG_STRING];
674 if (imap_parse_path (ctx->path, &mx))
677 /* in APPEND mode, we appear to hijack an existing IMAP connection -
678 * ctx is brand new and mostly empty */
680 if (!(idata = imap_conn_find (&(mx.account), 0))) {
689 imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
693 /* really we should also check for W_OK */
694 if (!imap_access (ctx->path, F_OK))
697 snprintf (buf, sizeof (buf), _("Create %s?"), mailbox);
698 if (option (OPTCONFIRMCREATE) && mutt_yesorno (buf, 1) < 1)
701 if (imap_create_mailbox (idata, mailbox) < 0)
707 /* imap_logout: Gracefully log out of server. */
708 void imap_logout (IMAP_DATA * idata)
710 /* we set status here to let imap_handle_untagged know we _expect_ to
711 * receive a bye response (so it doesn't freak out and close the conn) */
712 idata->status = IMAP_BYE;
713 imap_cmd_start (idata, "LOGOUT");
714 while (imap_cmd_step (idata) == IMAP_CMD_CONTINUE);
715 p_delete(&idata->cmd.buf);
720 int imap_close_connection (CONTEXT *ctx)
722 if (CTX_DATA->status != IMAP_BYE)
724 mutt_message _("Closing connection to IMAP server...");
725 imap_logout (CTX_DATA);
728 mutt_socket_close (CTX_DATA->conn);
729 CTX_DATA->state = IMAP_DISCONNECTED;
730 CTX_DATA->conn->data = NULL;
735 /* imap_set_flag: append str to flags if we currently have permission
736 * according to aclbit */
737 static void imap_set_flag(IMAP_DATA *idata, int aclbit, int flag,
738 const char *str, char *flags, size_t flsize)
740 if (mutt_bit_isset(idata->rights, aclbit)) {
742 m_strcat(flags, flsize, str);
746 /* imap_make_msg_set: make an IMAP4rev1 UID message set out of a set of
747 * headers, given a flag enum to filter on.
748 * Params: idata: IMAP_DATA containing context containing header set
749 * buf: to write message set into
750 * buflen: length of buffer
751 * flag: enum of flag type on which to filter
752 * changed: include only changed messages in message set
753 * Returns: number of messages in message set (0 if no matches) */
754 int imap_make_msg_set (IMAP_DATA * idata, BUFFER * buf, int flag, int changed)
756 HEADER **hdrs; /* sorted local copy */
757 int count = 0; /* number of messages in message set */
758 int match = 0; /* whether current message matches flag condition */
759 int setstart = 0; /* start of current message range */
761 short oldsort; /* we clobber reverse, must restore it */
763 /* assuming 32-bit UIDs */
767 /* make copy of header pointers to sort in natural order */
768 hdrs = p_dup(idata->ctx->hdrs, idata->ctx->msgcount);
770 if (Sort != SORT_ORDER) {
773 qsort ((void *) hdrs, idata->ctx->msgcount, sizeof (HEADER *),
774 mutt_get_sort_func (SORT_ORDER));
778 for (n = 0; n < idata->ctx->msgcount; n++) {
780 /* don't include pending expunged messages */
784 if (hdrs[n]->deleted)
793 if (match && (!changed || hdrs[n]->changed)) {
796 setstart = HEADER_DATA (hdrs[n])->uid;
798 snprintf (uid, sizeof (uid), "%u", HEADER_DATA (hdrs[n])->uid);
799 mutt_buffer_addstr (buf, uid);
803 snprintf (uid, sizeof (uid), ",%u", HEADER_DATA (hdrs[n])->uid);
804 mutt_buffer_addstr (buf, uid);
807 /* tie up if the last message also matches */
808 else if (n == idata->ctx->msgcount - 1) {
809 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n])->uid);
810 mutt_buffer_addstr (buf, uid);
813 /* this message is not expunged and doesn't match. End current set. */
814 else if (setstart && hdrs[n]->active) {
815 if (HEADER_DATA (hdrs[n - 1])->uid > setstart) {
816 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n - 1])->uid);
817 mutt_buffer_addstr (buf, uid);
828 /* Update the IMAP server to reflect the flags a single message. */
830 int imap_sync_message (IMAP_DATA *idata, HEADER *hdr, BUFFER *cmd,
833 char flags[LONG_STRING];
838 snprintf (uid, sizeof (uid), "%u", HEADER_DATA(hdr)->uid);
839 cmd->dptr = cmd->data;
840 mutt_buffer_addstr (cmd, "UID STORE ");
841 mutt_buffer_addstr (cmd, uid);
845 imap_set_flag (idata, ACL_SEEN, hdr->read, "\\Seen ",
846 flags, sizeof (flags));
847 imap_set_flag (idata, ACL_WRITE, hdr->flagged,
848 "\\Flagged ", flags, sizeof (flags));
849 imap_set_flag (idata, ACL_WRITE, hdr->replied,
850 "\\Answered ", flags, sizeof (flags));
851 imap_set_flag (idata, ACL_DELETE, hdr->deleted,
852 "\\Deleted ", flags, sizeof (flags));
854 /* now make sure we don't lose custom tags */
855 if (mutt_bit_isset (idata->rights, ACL_WRITE))
856 imap_add_keywords (flags, hdr, idata->flags, sizeof (flags));
860 /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to
861 * explicitly revoke all system flags (if we have permission) */
864 imap_set_flag (idata, ACL_SEEN, 1, "\\Seen ", flags, sizeof (flags));
865 imap_set_flag (idata, ACL_WRITE, 1, "\\Flagged ", flags, sizeof (flags));
866 imap_set_flag (idata, ACL_WRITE, 1, "\\Answered ", flags, sizeof (flags));
867 imap_set_flag (idata, ACL_DELETE, 1, "\\Deleted ", flags, sizeof (flags));
871 mutt_buffer_addstr (cmd, " -FLAGS.SILENT (");
873 mutt_buffer_addstr (cmd, " FLAGS.SILENT (");
875 mutt_buffer_addstr (cmd, flags);
876 mutt_buffer_addstr (cmd, ")");
878 /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */
881 /* after all this it's still possible to have no flags, if you
882 * have no ACL rights */
883 if (*flags && (imap_exec (idata, cmd->data, 0) != 0) &&
884 err_continue && (*err_continue != M_YES))
886 *err_continue = imap_continue ("imap_sync_message: STORE failed",
888 if (*err_continue != M_YES)
893 idata->ctx->changed--;
898 /* update the IMAP server to reflect message changes done within mutt.
900 * ctx: the current context
901 * expunge: 0 or 1 - do expunge?
904 int imap_sync_mailbox (CONTEXT * ctx, int expunge, int *index_hint)
907 CONTEXT *appendctx = NULL;
911 int err_continue = M_NO; /* continue on error? */
914 idata = (IMAP_DATA *) ctx->data;
916 if (idata->state != IMAP_SELECTED) {
920 /* This function is only called when the calling code expects the context
922 imap_allow_reopen (ctx);
924 if ((rc = imap_check_mailbox (ctx, index_hint, 0)) != 0)
929 /* if we are expunging anyway, we can do deleted messages very quickly... */
930 if (expunge && mutt_bit_isset (idata->rights, ACL_DELETE)) {
931 mutt_buffer_addstr (&cmd, "UID STORE ");
932 deleted = imap_make_msg_set (idata, &cmd, M_DELETE, 1);
934 /* if we have a message set, then let's delete */
936 mutt_message (_("Marking %d messages deleted..."), deleted);
937 mutt_buffer_addstr (&cmd, " +FLAGS.SILENT (\\Deleted)");
938 /* mark these messages as unchanged so second pass ignores them. Done
939 * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */
940 for (n = 0; n < ctx->msgcount; n++)
941 if (ctx->hdrs[n]->deleted && ctx->hdrs[n]->changed)
942 ctx->hdrs[n]->active = 0;
943 if (imap_exec (idata, cmd.data, 0) != 0) {
944 mutt_error (_("Expunge failed"));
952 /* save status changes */
953 for (n = 0; n < ctx->msgcount; n++) {
954 if (ctx->hdrs[n]->active && ctx->hdrs[n]->changed) {
956 mutt_message (_("Saving message status flags... [%d/%d]"), n + 1,
959 /* if the message has been rethreaded or attachments have been deleted
960 * we delete the message and reupload it.
961 * This works better if we're expunging, of course. */
962 if ((ctx->hdrs[n]->env && (ctx->hdrs[n]->env->refs_changed || ctx->hdrs[n]->env->irt_changed)) ||
963 ctx->hdrs[n]->attach_del) {
965 appendctx = mx_open_mailbox (ctx->path, M_APPEND | M_QUIET, NULL);
967 _mutt_save_message (ctx->hdrs[n], appendctx, 1, 0, 0);
971 if (imap_sync_message (idata, ctx->hdrs[n], &cmd, &err_continue) < 0) {
979 /* We must send an EXPUNGE command if we're not closing. */
980 if (expunge && !(ctx->closing) &&
981 mutt_bit_isset (idata->rights, ACL_DELETE)) {
982 mutt_message _("Expunging messages from server...");
984 /* Set expunge bit so we don't get spurious reopened messages */
985 idata->reopen |= IMAP_EXPUNGE_EXPECTED;
986 if (imap_exec (idata, "EXPUNGE", 0) != 0) {
987 imap_error (_("imap_sync_mailbox: EXPUNGE failed"), idata->cmd.buf);
988 rc = imap_reconnect (ctx);
993 if (expunge && ctx->closing) {
994 if (imap_exec (idata, "CLOSE", 0))
995 mutt_error (_("CLOSE failed"));
996 idata->state = IMAP_AUTHENTICATED;
1002 p_delete(&cmd.data);
1004 mx_fastclose_mailbox (appendctx);
1005 p_delete(&appendctx);
1010 /* imap_close_mailbox: clean up IMAP data in CONTEXT */
1011 void imap_close_mailbox (CONTEXT * ctx)
1016 idata = (IMAP_DATA *) ctx->data;
1017 /* Check to see if the mailbox is actually open */
1021 if (ctx == idata->ctx) {
1022 if (idata->state != IMAP_FATAL && idata->state == IMAP_SELECTED) {
1023 /* mx_close_mailbox won't sync if there are no deleted messages
1024 * and the mailbox is unchanged, so we may have to close here */
1025 if (!ctx->deleted && imap_exec (idata, "CLOSE", 0))
1026 mutt_error (_("CLOSE failed"));
1027 idata->state = IMAP_AUTHENTICATED;
1030 idata->reopen &= IMAP_REOPEN_ALLOW;
1031 p_delete(&(idata->mailbox));
1032 string_list_wipe(&idata->flags);
1036 /* free IMAP part of headers */
1037 for (i = 0; i < ctx->msgcount; i++)
1038 imap_free_header_data (&(ctx->hdrs[i]->data));
1040 for (i = 0; i < IMAP_CACHE_LEN; i++) {
1041 if (idata->cache[i].path) {
1042 unlink (idata->cache[i].path);
1043 p_delete(&idata->cache[i].path);
1048 /* use the NOOP command to poll for new mail
1051 * M_REOPENED mailbox has been externally modified
1052 * M_NEW_MAIL new mail has arrived!
1056 int imap_check_mailbox (CONTEXT * ctx, int *index_hint __attribute__ ((unused)), int force)
1058 /* overload keyboard timeout to avoid many mailbox checks in a row.
1059 * Most users don't like having to wait exactly when they press a key. */
1063 idata = (IMAP_DATA *) ctx->data;
1065 if ((force || time (NULL) >= idata->lastread + Timeout)
1066 && imap_exec (idata, "NOOP", 0) != 0)
1069 /* We call this even when we haven't run NOOP in case we have pending
1070 * changes to process, since we can reopen here. */
1071 imap_cmd_finish (idata);
1073 if (idata->check_status & IMAP_EXPUNGE_PENDING)
1074 result = M_REOPENED;
1075 else if (idata->check_status & IMAP_NEWMAIL_PENDING)
1076 result = M_NEW_MAIL;
1077 else if (idata->check_status & IMAP_FLAGS_PENDING)
1080 idata->check_status = 0;
1091 * 0+ number of messages in mailbox
1092 * -1 error while polling mailboxes
1094 int imap_mailbox_check (char *path, int new)
1098 char buf[LONG_STRING];
1099 char mbox[LONG_STRING];
1100 char mbox_unquoted[LONG_STRING];
1107 if (imap_parse_path (path, &mx))
1110 /* If imap_passive is set, don't open a connection to check for new mail */
1111 if (option (OPTIMAPPASSIVE))
1112 connflags = M_IMAP_CONN_NONEW;
1114 if (!(idata = imap_conn_find (&(mx.account), connflags))) {
1120 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1123 imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1124 m_strcpy(mbox_unquoted, sizeof(mbox_unquoted), buf);
1126 /* The draft IMAP implementor's guide warns againts using the STATUS
1127 * command on a mailbox that you have selected
1130 if (m_strcmp(mbox_unquoted, idata->mailbox) == 0
1131 || (ascii_strcasecmp (mbox_unquoted, "INBOX") == 0
1132 && m_strcasecmp(mbox_unquoted, idata->mailbox) == 0)) {
1133 m_strcpy(buf, sizeof(buf), "NOOP");
1135 else if (mutt_bit_isset (idata->capabilities, IMAP4REV1) ||
1136 mutt_bit_isset (idata->capabilities, STATUS)) {
1137 snprintf (buf, sizeof (buf), "STATUS %s (%s)", mbox,
1138 new == 1 ? "RECENT" : (new == 2 ? "UNSEEN" : "MESSAGES"));
1141 /* Server does not support STATUS, and this is not the current mailbox.
1142 * There is no lightweight way to check recent arrivals */
1145 imap_cmd_start (idata, buf);
1148 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
1151 s = imap_next_word (idata->cmd.buf);
1152 if (ascii_strncasecmp ("STATUS", s, 6) == 0) {
1153 s = imap_next_word (s);
1154 /* The mailbox name may or may not be quoted here. We could try to
1155 * munge the server response and compare with quoted (or vise versa)
1156 * but it is probably more efficient to just strncmp against both. */
1157 if (m_strncmp(mbox_unquoted, s, m_strlen(mbox_unquoted)) == 0
1158 || m_strncmp(mbox, s, m_strlen(mbox)) == 0) {
1159 s = imap_next_word (s);
1160 s = imap_next_word (s);
1161 if (isdigit ((unsigned char) *s)) {
1163 msgcount = atoi (s);
1169 while (rc == IMAP_CMD_CONTINUE);
1174 /* returns number of patterns in the search that should be done server-side
1175 * (eg are full-text) */
1176 static int do_search (const pattern_t* search, int allpats)
1179 const pattern_t* pat;
1181 for (pat = search; pat; pat = pat->next) {
1186 if (pat->stringmatch)
1190 if (pat->child && do_search (pat->child, 1))
1201 /* convert mutt pattern_t to IMAP SEARCH command containing only elements
1202 * that require full-text search (mutt already has what it needs for most
1203 * match types, and does a better job (eg server doesn't support regexps). */
1204 static int imap_compile_search (const pattern_t* pat, BUFFER* buf)
1206 if (! do_search (pat, 0))
1210 mutt_buffer_addstr (buf, "NOT ");
1215 if ((clauses = do_search (pat->child, 1)) > 0) {
1216 const pattern_t* clause = pat->child;
1218 mutt_buffer_addch (buf, '(');
1221 if (do_search (clause, 0)) {
1222 if (pat->op == M_OR && clauses > 1)
1223 mutt_buffer_addstr (buf, "OR ");
1225 if (imap_compile_search (clause, buf) < 0)
1229 mutt_buffer_addch (buf, ' ');
1231 clause = clause->next;
1235 mutt_buffer_addch (buf, ')');
1243 mutt_buffer_addstr (buf, "HEADER ");
1245 /* extract header name */
1246 if (! (delim = strchr (pat->str, ':'))) {
1247 mutt_error (_("Header search without header name: %s"), pat->str);
1251 imap_quote_string (term, sizeof (term), pat->str);
1252 mutt_buffer_addstr (buf, term);
1253 mutt_buffer_addch (buf, ' ');
1257 delim = vskipspaces(delim);
1258 imap_quote_string (term, sizeof (term), delim);
1259 mutt_buffer_addstr (buf, term);
1263 mutt_buffer_addstr (buf, "BODY ");
1264 imap_quote_string (term, sizeof (term), pat->str);
1265 mutt_buffer_addstr (buf, term);
1269 mutt_buffer_addstr (buf, "TEXT ");
1270 imap_quote_string (term, sizeof (term), pat->str);
1271 mutt_buffer_addstr (buf, term);
1279 int imap_search (CONTEXT* ctx, const pattern_t* pat) {
1281 IMAP_DATA* idata = (IMAP_DATA*)ctx->data;
1284 for (i = 0; i < ctx->msgcount; i++)
1285 ctx->hdrs[i]->matched = 0;
1287 if (!do_search (pat, 1))
1291 mutt_buffer_addstr (&buf, "UID SEARCH ");
1292 if (imap_compile_search (pat, &buf) < 0) {
1293 p_delete(&buf.data);
1296 if (imap_exec (idata, buf.data, 0) < 0) {
1297 p_delete(&buf.data);
1301 p_delete(&buf.data);
1305 /* all this listing/browsing is a mess. I don't like that name is a pointer
1306 * into idata->buf (used to be a pointer into the passed in buffer, just
1307 * as bad), nor do I like the fact that the fetch is done here. This
1308 * code can't possibly handle non-string_list_t untagged responses properly.
1310 int imap_parse_list_response (IMAP_DATA * idata, char **name, int *noselect,
1311 int *noinferiors, char *delim)
1319 rc = imap_cmd_step (idata);
1320 if (rc == IMAP_CMD_OK)
1322 if (rc != IMAP_CMD_CONTINUE)
1325 s = imap_next_word (idata->cmd.buf);
1326 if ((ascii_strncasecmp ("string_list_t", s, 4) == 0) ||
1327 (ascii_strncasecmp ("LSUB", s, 4) == 0)) {
1331 s = imap_next_word (s); /* flags */
1337 while (*ep && *ep != ')')
1340 if (!ascii_strncasecmp (s, "\\NoSelect", 9))
1342 if (!ascii_strncasecmp (s, "\\NoInferiors", 12))
1344 /* See draft-gahrns-imap-child-mailbox-?? */
1345 if (!ascii_strncasecmp (s, "\\HasNoChildren", 14))
1349 while (*s && *s != '\\' && *s != ')')
1355 s = imap_next_word (s); /* delim */
1356 /* Reset the delimiter, this can change */
1357 if (ascii_strncasecmp (s, "NIL", 3)) {
1358 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
1360 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
1364 s = imap_next_word (s); /* name */
1365 if (s && *s == '{') { /* Literal */
1366 if (imap_get_literal_count (idata->cmd.buf, &bytes) < 0)
1368 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
1370 *name = idata->cmd.buf;
1379 int imap_subscribe (char *path, int subscribe)
1383 char buf[LONG_STRING];
1384 char mbox[LONG_STRING];
1385 char errstr[STRING];
1389 if (mx_get_magic (path) != M_IMAP || imap_parse_path (path, &mx) < 0) {
1390 mutt_error (_("Bad mailbox name"));
1394 if (!(idata = imap_conn_find (&(mx.account), 0)))
1399 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1401 if (option (OPTIMAPCHECKSUBSCRIBED)) {
1404 err.dsize = sizeof (errstr);
1405 snprintf (mbox, sizeof (mbox), "%smailboxes \"%s\"",
1406 subscribe ? "" : "un", path);
1407 mutt_parse_rc_line (mbox, &token, &err);
1408 p_delete(&token.data);
1412 mutt_message (_("Subscribing to %s..."), buf);
1414 mutt_message (_("Unsubscribing to %s..."), buf);
1415 imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1417 snprintf (buf, sizeof (buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);
1419 if (imap_exec (idata, buf, 0) < 0)
1430 /* trim dest to the length of the longest prefix it shares with src,
1431 * returning the length of the trimmed string */
1432 static int longest_common_prefix (char *dest, const char* src,
1433 int start, ssize_t dlen) {
1436 while (pos < dlen && dest[pos] && dest[pos] == src[pos])
1443 /* look for IMAP URLs to complete from defined mailboxes. Could be extended
1444 * to complete over open connections and account/folder hooks too. */
1445 static int imap_complete_hosts (char *dest, ssize_t len) {
1452 matchlen = m_strlen(dest);
1453 if (list_empty (Incoming))
1455 for (i = 0; i < Incoming->length; i++) {
1456 mailbox = (BUFFY*) Incoming->data[i];
1457 if (!m_strncmp(dest, mailbox->path, matchlen)) {
1459 m_strcpy(dest, len, mailbox->path);
1462 longest_common_prefix (dest, mailbox->path, matchlen, len);
1466 for (conn = mutt_socket_head (); conn && conn->next; conn = conn->next) {
1468 char urlstr[LONG_STRING];
1470 if (conn->account.type != M_ACCT_TYPE_IMAP)
1473 mutt_account_tourl (&conn->account, &url);
1474 /* FIXME: how to handle multiple users on the same host? */
1477 url_ciss_tostring (&url, urlstr, sizeof (urlstr), 0);
1478 if (!m_strncmp(dest, urlstr, matchlen)) {
1480 m_strcpy(dest, len, urlstr);
1483 longest_common_prefix (dest, urlstr, matchlen, len);
1490 /* imap_complete: given a partial IMAP folder path, return a string which
1491 * adds as much to the path as is unique */
1492 int imap_complete (char *dest, size_t dlen, char *path) {
1495 char list[LONG_STRING];
1496 char buf[LONG_STRING];
1497 char *list_word = NULL;
1498 int noselect, noinferiors;
1500 char completion[LONG_STRING];
1501 int clen, matchlen = 0;
1502 int completions = 0;
1505 if (imap_parse_path (path, &mx) || !mx.mbox) {
1506 m_strcpy(dest, dlen, path);
1507 return imap_complete_hosts (dest, dlen);
1510 /* don't open a new socket just for completion. Instead complete over
1511 * known mailboxes/hooks/etc */
1512 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NONEW))) {
1514 m_strcpy(dest, dlen, path);
1515 return imap_complete_hosts (dest, dlen);
1519 /* reformat path for IMAP list, and append wildcard */
1520 /* don't use INBOX in place of "" */
1521 if (mx.mbox && mx.mbox[0])
1522 imap_fix_path (idata, mx.mbox, list, sizeof (list));
1526 /* fire off command */
1527 snprintf (buf, sizeof (buf), "%s \"\" \"%s%%\"",
1528 option (OPTIMAPLSUB) ? "LSUB" : "string_list_t", list);
1530 imap_cmd_start (idata, buf);
1532 /* and see what the results are */
1533 m_strcpy(completion, sizeof(completion), NONULL(mx.mbox));
1535 if (imap_parse_list_response (idata, &list_word, &noselect, &noinferiors,
1540 /* store unquoted */
1541 imap_unmunge_mbox_name (list_word);
1543 /* if the folder isn't selectable, append delimiter to force browse
1544 * to enter it on second tab. */
1546 clen = m_strlen(list_word);
1547 list_word[clen++] = delim;
1548 list_word[clen] = '\0';
1550 /* copy in first word */
1552 m_strcpy(completion, sizeof(completion), list_word);
1553 matchlen = m_strlen(completion);
1558 matchlen = longest_common_prefix (completion, list_word, 0, matchlen);
1562 while (ascii_strncmp (idata->cmd.seq, idata->cmd.buf, SEQLEN));
1565 /* reformat output */
1566 imap_qualify_path (dest, dlen, &mx, completion);
1567 mutt_pretty_mailbox (dest);
1576 /* reconnect if connection was lost */
1577 int imap_reconnect (CONTEXT * ctx)
1579 IMAP_DATA *imap_data;
1584 imap_data = (IMAP_DATA *) ctx->data;
1587 if (imap_data->status == IMAP_CONNECTED)
1591 if (query_quadoption
1593 _("Connection lost. Reconnect to IMAP server?")) != M_YES)
1596 mx_open_mailbox (ctx->path, 0, ctx);