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-2003 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. */
19 #include "mutt_curses.h"
26 #include "imap_private.h"
27 #if defined(USE_SSL) || defined(USE_GNUTLS)
28 # include "mutt_ssl.h"
39 #include <sys/types.h>
42 /* imap forward declarations */
43 static int imap_get_delim (IMAP_DATA * idata);
44 static char *imap_get_flags (LIST ** hflags, char *s);
45 static int imap_check_acl (IMAP_DATA * idata);
46 static int imap_check_capabilities (IMAP_DATA * idata);
47 static void imap_set_flag (IMAP_DATA * idata, int aclbit, int flag,
48 const char *str, char *flags, size_t flsize);
50 /* imap_access: Check permissions on an IMAP mailbox. */
51 int imap_access (const char *path, int flags)
55 char buf[LONG_STRING];
56 char mailbox[LONG_STRING];
57 char mbox[LONG_STRING];
59 if (imap_parse_path (path, &mx))
62 if (!(idata = imap_conn_find (&mx.account,
63 option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW :
69 imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
71 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
73 /* TODO: ACL checks. Right now we assume if it exists we can mess with it. */
74 if (mutt_bit_isset (idata->capabilities, IMAP4REV1))
75 snprintf (buf, sizeof (buf), "STATUS %s (UIDVALIDITY)", mbox);
76 else if (mutt_bit_isset (idata->capabilities, STATUS))
77 snprintf (buf, sizeof (buf), "STATUS %s (UID-VALIDITY)", mbox);
79 dprint (2, (debugfile, "imap_access: STATUS not supported?\n"));
83 if (imap_exec (idata, buf, IMAP_CMD_FAIL_OK) < 0) {
84 dprint (1, (debugfile, "imap_access: Can't check STATUS of %s\n", mbox));
91 int imap_create_mailbox (IMAP_DATA * idata, char *mailbox)
93 char buf[LONG_STRING], mbox[LONG_STRING];
95 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
96 snprintf (buf, sizeof (buf), "CREATE %s", mbox);
98 if (imap_exec (idata, buf, 0) != 0)
104 int imap_rename_mailbox (IMAP_DATA * idata, IMAP_MBOX * mx,
107 char oldmbox[LONG_STRING];
108 char newmbox[LONG_STRING];
109 char buf[LONG_STRING];
111 imap_munge_mbox_name (oldmbox, sizeof (oldmbox), mx->mbox);
112 imap_munge_mbox_name (newmbox, sizeof (newmbox), newname);
114 snprintf (buf, sizeof (buf), "RENAME %s %s", oldmbox, newmbox);
116 if (imap_exec (idata, buf, 0) != 0)
122 int imap_delete_mailbox (CONTEXT * ctx, IMAP_MBOX mx)
124 char buf[LONG_STRING], mbox[LONG_STRING];
127 if (!ctx || !ctx->data) {
128 if (!(idata = imap_conn_find (&mx.account,
129 option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW
139 imap_munge_mbox_name (mbox, sizeof (mbox), mx.mbox);
140 snprintf (buf, sizeof (buf), "DELETE %s", mbox);
142 if (imap_exec ((IMAP_DATA *) idata, buf, 0) != 0)
148 /* imap_logout_all: close all open connections. Quick and dirty until we can
149 * make sure we've got all the context we need. */
150 void imap_logout_all (void)
155 conn = mutt_socket_head ();
160 if (conn->account.type == M_ACCT_TYPE_IMAP && conn->fd >= 0) {
161 mutt_message (_("Closing connection to %s..."), conn->account.host);
162 imap_logout ((IMAP_DATA *) conn->data);
164 mutt_socket_close (conn);
165 mutt_socket_free (conn);
172 /* imap_read_literal: read bytes bytes from server into file. Not explicitly
173 * buffered, relies on FILE buffering. NOTE: strips \r from \r\n.
174 * Apparently even literals use \r\n-terminated strings ?! */
175 int imap_read_literal (FILE * fp, IMAP_DATA * idata, long bytes)
182 dprint (2, (debugfile, "imap_read_literal: reading %ld bytes\n", bytes));
184 for (pos = 0; pos < bytes; pos++) {
185 if (mutt_socket_readchar (idata->conn, &c) != 1) {
188 "imap_read_literal: error during read, %ld bytes read\n",
190 idata->status = IMAP_FATAL;
196 if (r == 1 && c != '\n')
208 if (debuglevel >= IMAP_LOG_LTRL)
209 fputc (c, debugfile);
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) {
229 (debugfile, "Expunging message UID %d.\n",
230 HEADER_DATA (h)->uid));
234 /* free cached body from disk, if neccessary */
235 cacheno = HEADER_DATA (h)->uid % IMAP_CACHE_LEN;
236 if (idata->cache[cacheno].uid == HEADER_DATA (h)->uid &&
237 idata->cache[cacheno].path) {
238 unlink (idata->cache[cacheno].path);
239 FREE (&idata->cache[cacheno].path);
242 imap_free_header_data (&h->data);
246 /* We may be called on to expunge at any time. We can't rely on the caller
247 * to always know to rethread */
248 mx_update_tables (idata->ctx, 0);
249 mutt_sort_headers (idata->ctx, 1);
252 static int imap_get_delim (IMAP_DATA * idata)
257 /* assume that the delim is /. If this fails, we're in bigger trouble
258 * than getting the delim wrong */
261 imap_cmd_start (idata, "LIST \"\" \"\"");
264 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
267 s = imap_next_word (idata->cmd.buf);
268 if (ascii_strncasecmp ("LIST", s, 4) == 0) {
269 s = imap_next_word (s);
270 s = imap_next_word (s);
271 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
273 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
278 while (rc == IMAP_CMD_CONTINUE);
280 if (rc != IMAP_CMD_OK) {
281 dprint (1, (debugfile, "imap_get_delim: failed.\n"));
285 dprint (2, (debugfile, "Delimiter: %c\n", idata->delim));
290 /* get rights for folder, let imap_handle_untagged do the rest */
291 static int imap_check_acl (IMAP_DATA * idata)
293 char buf[LONG_STRING];
294 char mbox[LONG_STRING];
296 imap_munge_mbox_name (mbox, sizeof (mbox), idata->mailbox);
297 snprintf (buf, sizeof (buf), "MYRIGHTS %s", mbox);
298 if (imap_exec (idata, buf, 0) != 0) {
299 imap_error ("imap_check_acl", buf);
305 /* imap_check_capabilities: make sure we can log in to this server. */
306 static int imap_check_capabilities (IMAP_DATA * idata)
308 if (imap_exec (idata, "CAPABILITY", 0) != 0) {
309 imap_error ("imap_check_capabilities", idata->cmd.buf);
313 if (!(mutt_bit_isset (idata->capabilities, IMAP4)
314 || mutt_bit_isset (idata->capabilities, IMAP4REV1))) {
315 mutt_error _("This IMAP server is ancient. Mutt does not work with it.");
317 mutt_sleep (2); /* pause a moment to let the user see the error */
325 /* imap_conn_find: Find an open IMAP connection matching account, or open
326 * a new one if none can be found. */
327 IMAP_DATA *imap_conn_find (const ACCOUNT * account, int flags)
333 if (!(conn = mutt_conn_find (NULL, account)))
336 /* if opening a new UNSELECTED connection, preserve existing creds */
337 creds = &(conn->account);
339 /* make sure this connection is not in SELECTED state, if neccessary */
340 if (flags & M_IMAP_CONN_NOSELECT)
341 while (conn->data && ((IMAP_DATA *) conn->data)->state == IMAP_SELECTED) {
342 if (!(conn = mutt_conn_find (conn, account)))
344 memcpy (&(conn->account), creds, sizeof (ACCOUNT));
347 idata = (IMAP_DATA *) conn->data;
349 /* don't open a new connection if one isn't wanted */
350 if (flags & M_IMAP_CONN_NONEW) {
352 mutt_socket_free (conn);
355 if (idata->state < IMAP_AUTHENTICATED)
360 /* The current connection is a new connection */
361 if (!(idata = imap_new_idata ())) {
362 mutt_socket_free (conn);
370 if (idata->state == IMAP_DISCONNECTED)
371 imap_open_connection (idata);
372 if (idata->state == IMAP_CONNECTED) {
373 if (!imap_authenticate (idata)) {
374 idata->state = IMAP_AUTHENTICATED;
375 if (idata->conn->ssf)
376 dprint (2, (debugfile, "Communication encrypted at %d bits\n",
380 mutt_account_unsetpass (&idata->conn->account);
382 FREE (&idata->capstr);
384 if (idata->state == IMAP_AUTHENTICATED)
385 imap_get_delim (idata);
390 int imap_open_connection (IMAP_DATA * idata)
392 char buf[LONG_STRING];
394 if (mutt_socket_open (idata->conn) < 0)
397 idata->state = IMAP_CONNECTED;
399 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE) {
400 mutt_error (_("Unexpected response received from server: %s"),
404 mutt_socket_close (idata->conn);
405 idata->state = IMAP_DISCONNECTED;
409 if (ascii_strncasecmp ("* OK", idata->cmd.buf, 4) == 0) {
410 /* TODO: Parse new tagged CAPABILITY data (* OK [CAPABILITY...]) */
411 if (imap_check_capabilities (idata))
413 #if defined(USE_SSL) || defined(USE_GNUTLS)
414 /* Attempt STARTTLS if available and desired. */
415 if (mutt_bit_isset (idata->capabilities, STARTTLS) && !idata->conn->ssf) {
418 if ((rc = query_quadoption (OPT_SSLSTARTTLS,
419 _("Secure connection with TLS?"))) == -1)
422 if ((rc = imap_exec (idata, "STARTTLS", IMAP_CMD_FAIL_OK)) == -1)
426 if (mutt_ssl_starttls (idata->conn))
428 if (mutt_gnutls_starttls (idata->conn))
431 mutt_error (_("Could not negotiate TLS connection"));
436 /* RFC 2595 demands we recheck CAPABILITY after TLS completes. */
437 if (imap_exec (idata, "CAPABILITY", 0))
445 else if (ascii_strncasecmp ("* PREAUTH", idata->cmd.buf, 9) == 0) {
446 idata->state = IMAP_AUTHENTICATED;
447 if (imap_check_capabilities (idata) != 0)
449 FREE (&idata->capstr);
452 imap_error ("imap_open_connection()", buf);
459 mutt_socket_close (idata->conn);
460 idata->state = IMAP_DISCONNECTED;
462 FREE (&idata->capstr);
466 /* imap_get_flags: Make a simple list out of a FLAGS response.
467 * return stream following FLAGS response */
468 static char *imap_get_flags (LIST ** hflags, char *s)
474 /* sanity-check string */
475 if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
476 dprint (1, (debugfile, "imap_get_flags: not a FLAGS response: %s\n", s));
482 dprint (1, (debugfile, "imap_get_flags: bogus FLAGS response: %s\n", s));
486 /* create list, update caller's flags handle */
487 flags = mutt_new_list ();
490 while (*s && *s != ')') {
494 while (*s && (*s != ')') && !ISSPACE (*s))
499 mutt_add_list (flags, flag_word);
503 /* note bad flags response */
505 dprint (1, (debugfile,
506 "imap_get_flags: Unterminated FLAGS response: %s\n", s));
507 mutt_free_list (hflags);
517 int imap_open_mailbox (CONTEXT * ctx)
521 char buf[LONG_STRING];
522 char bufout[LONG_STRING];
527 if (imap_parse_path (ctx->path, &mx)) {
528 mutt_error (_("%s is an invalid IMAP path"), ctx->path);
532 /* we require a connection which isn't currently in IMAP_SELECTED state */
533 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NOSELECT)))
535 if (idata->state < IMAP_AUTHENTICATED)
540 /* once again the context is new */
543 /* Clean up path and replace the one in the ctx */
544 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
545 FREE (&(idata->mailbox));
546 idata->mailbox = safe_strdup (buf);
547 imap_qualify_path (buf, sizeof (buf), &mx, idata->mailbox);
550 ctx->path = safe_strdup (buf);
554 /* clear mailbox status */
556 memset (idata->rights, 0, (RIGHTSMAX + 7) / 8);
557 idata->newMailCount = 0;
559 mutt_message (_("Selecting %s..."), idata->mailbox);
560 imap_munge_mbox_name (buf, sizeof (buf), idata->mailbox);
561 snprintf (bufout, sizeof (bufout), "%s %s",
562 ctx->readonly ? "EXAMINE" : "SELECT", buf);
564 idata->state = IMAP_SELECTED;
566 imap_cmd_start (idata, bufout);
571 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
574 pc = idata->cmd.buf + 2;
576 /* Obtain list of available flags here, may be overridden by a
577 * PERMANENTFLAGS tag in the OK response */
578 if (ascii_strncasecmp ("FLAGS", pc, 5) == 0) {
579 /* don't override PERMANENTFLAGS */
581 dprint (2, (debugfile, "Getting mailbox FLAGS\n"));
582 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
586 /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
587 else if (ascii_strncasecmp ("OK [PERMANENTFLAGS", pc, 18) == 0) {
588 dprint (2, (debugfile, "Getting mailbox PERMANENTFLAGS\n"));
589 /* safe to call on NULL */
590 mutt_free_list (&(idata->flags));
591 /* skip "OK [PERMANENT" so syntax is the same as FLAGS */
593 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
597 /* save UIDVALIDITY for the header cache */
598 else if (ascii_strncasecmp ("OK [UIDVALIDITY", pc, 14) == 0) {
599 dprint (2, (debugfile, "Getting mailbox UIDVALIDITY\n"));
601 pc = imap_next_word (pc);
603 sscanf (pc, "%u", &(idata->uid_validity));
607 pc = imap_next_word (pc);
608 if (!ascii_strncasecmp ("EXISTS", pc, 6)) {
609 count = idata->newMailCount;
610 idata->newMailCount = 0;
614 while (rc == IMAP_CMD_CONTINUE);
616 if (rc == IMAP_CMD_NO) {
619 s = imap_next_word (idata->cmd.buf); /* skip seq */
620 s = imap_next_word (s); /* Skip response */
621 mutt_error ("%s", s);
626 if (rc != IMAP_CMD_OK)
629 /* check for READ-ONLY notification */
630 if (!ascii_strncasecmp
631 (imap_get_qualifier (idata->cmd.buf), "[READ-ONLY]", 11)
632 && !mutt_bit_isset (idata->capabilities, ACL)) {
633 dprint (2, (debugfile, "Mailbox is read-only.\n"));
638 /* dump the mailbox flags we've found */
639 if (debuglevel > 2) {
641 dprint (3, (debugfile, "No folder flags found\n"));
643 LIST *t = idata->flags;
645 dprint (3, (debugfile, "Mailbox flags: "));
649 dprint (3, (debugfile, "[%s] ", t->data));
652 dprint (3, (debugfile, "\n"));
657 if (mutt_bit_isset (idata->capabilities, ACL)) {
658 if (imap_check_acl (idata))
660 if (!(mutt_bit_isset (idata->rights, IMAP_ACL_DELETE) ||
661 mutt_bit_isset (idata->rights, IMAP_ACL_SEEN) ||
662 mutt_bit_isset (idata->rights, IMAP_ACL_WRITE) ||
663 mutt_bit_isset (idata->rights, IMAP_ACL_INSERT)))
666 /* assume we have all rights if ACL is unavailable */
668 mutt_bit_set (idata->rights, IMAP_ACL_LOOKUP);
669 mutt_bit_set (idata->rights, IMAP_ACL_READ);
670 mutt_bit_set (idata->rights, IMAP_ACL_SEEN);
671 mutt_bit_set (idata->rights, IMAP_ACL_WRITE);
672 mutt_bit_set (idata->rights, IMAP_ACL_INSERT);
673 mutt_bit_set (idata->rights, IMAP_ACL_POST);
674 mutt_bit_set (idata->rights, IMAP_ACL_CREATE);
675 mutt_bit_set (idata->rights, IMAP_ACL_DELETE);
679 ctx->hdrs = safe_calloc (count, sizeof (HEADER *));
680 ctx->v2r = safe_calloc (count, sizeof (int));
682 if (count && (imap_read_headers (idata, 0, count - 1) < 0)) {
683 mutt_error _("Error opening mailbox");
690 (debugfile, "imap_open_mailbox: msgcount is %d\n", ctx->msgcount));
695 if (idata->state == IMAP_SELECTED)
696 idata->state = IMAP_AUTHENTICATED;
702 int imap_open_mailbox_append (CONTEXT * ctx)
706 char buf[LONG_STRING], mbox[LONG_STRING];
707 char mailbox[LONG_STRING];
711 if (imap_parse_path (ctx->path, &mx))
714 /* in APPEND mode, we appear to hijack an existing IMAP connection -
715 * ctx is brand new and mostly empty */
717 if (!(idata = imap_conn_find (&(mx.account), 0)))
724 /* check mailbox existance */
726 imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
728 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
730 if (mutt_bit_isset (idata->capabilities, IMAP4REV1))
731 snprintf (buf, sizeof (buf), "STATUS %s (UIDVALIDITY)", mbox);
732 else if (mutt_bit_isset (idata->capabilities, STATUS))
733 /* We have no idea what the other guy wants. UW imapd 8.3 wants this
734 * (but it does not work if another mailbox is selected) */
735 snprintf (buf, sizeof (buf), "STATUS %s (UID-VALIDITY)", mbox);
737 /* STATUS not supported */
738 mutt_message _("Unable to append to IMAP mailboxes at this server");
743 r = imap_exec (idata, buf, IMAP_CMD_FAIL_OK);
745 /* command failed cause folder doesn't exist */
746 snprintf (buf, sizeof (buf), _("Create %s?"), mailbox);
747 if (option (OPTCONFIRMCREATE) && mutt_yesorno (buf, 1) < 1)
750 if (imap_create_mailbox (idata, mailbox) < 0)
754 /* Hmm, some other failure */
765 /* imap_logout: Gracefully log out of server. */
766 void imap_logout (IMAP_DATA * idata)
768 /* we set status here to let imap_handle_untagged know we _expect_ to
769 * receive a bye response (so it doesn't freak out and close the conn) */
770 idata->status = IMAP_BYE;
771 imap_cmd_start (idata, "LOGOUT");
772 while (imap_cmd_step (idata) == IMAP_CMD_CONTINUE);
773 FREE (&idata->cmd.buf);
778 int imap_close_connection (CONTEXT *ctx)
780 dprint (1, (debugfile, "imap_close_connection(): closing connection\n"));
781 if (CTX_DATA->status != IMAP_BYE)
783 mutt_message _("Closing connection to IMAP server...");
784 imap_logout (CTX_DATA);
787 mutt_socket_close (CTX_DATA->conn);
788 CTX_DATA->state = IMAP_DISCONNECTED;
789 CTX_DATA->conn->data = NULL;
794 /* imap_set_flag: append str to flags if we currently have permission
795 * according to aclbit */
796 static void imap_set_flag (IMAP_DATA * idata, int aclbit, int flag,
797 const char *str, char *flags, size_t flsize)
799 if (mutt_bit_isset (idata->rights, aclbit))
801 safe_strcat (flags, flsize, str);
804 /* imap_make_msg_set: make an IMAP4rev1 UID message set out of a set of
805 * headers, given a flag enum to filter on.
806 * Params: idata: IMAP_DATA containing context containing header set
807 * buf: to write message set into
808 * buflen: length of buffer
809 * flag: enum of flag type on which to filter
810 * changed: include only changed messages in message set
811 * Returns: number of messages in message set (0 if no matches) */
812 int imap_make_msg_set (IMAP_DATA * idata, BUFFER * buf, int flag, int changed)
814 HEADER **hdrs; /* sorted local copy */
815 int count = 0; /* number of messages in message set */
816 int match = 0; /* whether current message matches flag condition */
817 unsigned int setstart = 0; /* start of current message range */
819 short oldsort; /* we clobber reverse, must restore it */
821 /* assuming 32-bit UIDs */
825 /* make copy of header pointers to sort in natural order */
826 hdrs = safe_calloc (idata->ctx->msgcount, sizeof (HEADER *));
827 memcpy (hdrs, idata->ctx->hdrs, idata->ctx->msgcount * sizeof (HEADER *));
829 if (Sort != SORT_ORDER) {
832 qsort ((void *) hdrs, idata->ctx->msgcount, sizeof (HEADER *),
833 mutt_get_sort_func (SORT_ORDER));
837 for (n = 0; n < idata->ctx->msgcount; n++) {
839 /* don't include pending expunged messages */
843 if (hdrs[n]->deleted)
852 if (match && (!changed || hdrs[n]->changed)) {
855 setstart = HEADER_DATA (hdrs[n])->uid;
857 snprintf (uid, sizeof (uid), "%u", HEADER_DATA (hdrs[n])->uid);
858 mutt_buffer_addstr (buf, uid);
862 snprintf (uid, sizeof (uid), ",%u", HEADER_DATA (hdrs[n])->uid);
863 mutt_buffer_addstr (buf, uid);
866 /* tie up if the last message also matches */
867 else if (n == idata->ctx->msgcount - 1) {
868 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n])->uid);
869 mutt_buffer_addstr (buf, uid);
872 /* this message is not expunged and doesn't match. End current set. */
873 else if (setstart && hdrs[n]->active) {
874 if (HEADER_DATA (hdrs[n - 1])->uid > setstart) {
875 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n - 1])->uid);
876 mutt_buffer_addstr (buf, uid);
887 /* update the IMAP server to reflect message changes done within mutt.
889 * ctx: the current context
890 * expunge: 0 or 1 - do expunge?
893 int imap_sync_mailbox (CONTEXT * ctx, int expunge, int *index_hint)
896 CONTEXT *appendctx = NULL;
898 char flags[LONG_STRING];
902 int err_continue = M_NO; /* continue on error? */
905 idata = (IMAP_DATA *) ctx->data;
907 if (idata->state != IMAP_SELECTED) {
908 dprint (2, (debugfile, "imap_sync_mailbox: no mailbox selected\n"));
912 /* CLOSE purges deleted messages. If we don't want to purge them, we must
913 * tell imap_close_mailbox not to issue the CLOSE command */
919 /* This function is only called when the calling code expects the context
921 imap_allow_reopen (ctx);
923 if ((rc = imap_check_mailbox (ctx, index_hint, 0)) != 0)
926 memset (&cmd, 0, sizeof (cmd));
928 /* if we are expunging anyway, we can do deleted messages very quickly... */
929 if (expunge && mutt_bit_isset (idata->rights, IMAP_ACL_DELETE)) {
930 mutt_buffer_addstr (&cmd, "UID STORE ");
931 deleted = imap_make_msg_set (idata, &cmd, M_DELETE, 1);
933 /* if we have a message set, then let's delete */
935 mutt_message (_("Marking %d messages deleted..."), deleted);
936 mutt_buffer_addstr (&cmd, " +FLAGS.SILENT (\\Deleted)");
937 /* mark these messages as unchanged so second pass ignores them. Done
938 * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */
939 for (n = 0; n < ctx->msgcount; n++)
940 if (ctx->hdrs[n]->deleted && ctx->hdrs[n]->changed)
941 ctx->hdrs[n]->active = 0;
942 if (imap_exec (idata, cmd.data, 0) != 0) {
943 mutt_error (_("Expunge failed"));
951 /* save status changes */
952 for (n = 0; n < ctx->msgcount; n++) {
953 if (ctx->hdrs[n]->active && ctx->hdrs[n]->changed) {
954 ctx->hdrs[n]->changed = 0;
956 mutt_message (_("Saving message status flags... [%d/%d]"), n + 1,
959 snprintf (uid, sizeof (uid), "%u", HEADER_DATA (ctx->hdrs[n])->uid);
961 mutt_buffer_addstr (&cmd, "UID STORE ");
962 mutt_buffer_addstr (&cmd, uid);
964 /* if the message has been rethreaded or attachments have been deleted
965 * we delete the message and reupload it.
966 * This works better if we're expunging, of course. */
967 if (ctx->hdrs[n]->refs_changed || ctx->hdrs[n]->irt_changed ||
968 ctx->hdrs[n]->attach_del) {
971 "imap_sync_mailbox: Attachments to be deleted, falling back to _mutt_save_message\n"));
973 appendctx = mx_open_mailbox (ctx->path, M_APPEND | M_QUIET, NULL);
977 "imap_sync_mailbox: Error opening mailbox in append mode\n"));
980 _mutt_save_message (ctx->hdrs[n], appendctx, 1, 0, 0);
984 imap_set_flag (idata, IMAP_ACL_SEEN, ctx->hdrs[n]->read, "\\Seen ",
985 flags, sizeof (flags));
986 imap_set_flag (idata, IMAP_ACL_WRITE, ctx->hdrs[n]->flagged,
987 "\\Flagged ", flags, sizeof (flags));
988 imap_set_flag (idata, IMAP_ACL_WRITE, ctx->hdrs[n]->replied,
989 "\\Answered ", flags, sizeof (flags));
990 imap_set_flag (idata, IMAP_ACL_DELETE, ctx->hdrs[n]->deleted,
991 "\\Deleted ", flags, sizeof (flags));
993 /* now make sure we don't lose custom tags */
994 if (mutt_bit_isset (idata->rights, IMAP_ACL_WRITE))
995 imap_add_keywords (flags, ctx->hdrs[n], idata->flags, sizeof (flags));
997 mutt_remove_trailing_ws (flags);
999 /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to
1000 * explicitly revoke all system flags (if we have permission) */
1002 imap_set_flag (idata, IMAP_ACL_SEEN, 1, "\\Seen ", flags,
1004 imap_set_flag (idata, IMAP_ACL_WRITE, 1, "\\Flagged ", flags,
1006 imap_set_flag (idata, IMAP_ACL_WRITE, 1, "\\Answered ", flags,
1008 imap_set_flag (idata, IMAP_ACL_DELETE, 1, "\\Deleted ", flags,
1011 mutt_remove_trailing_ws (flags);
1013 mutt_buffer_addstr (&cmd, " -FLAGS.SILENT (");
1016 mutt_buffer_addstr (&cmd, " FLAGS.SILENT (");
1018 mutt_buffer_addstr (&cmd, flags);
1019 mutt_buffer_addstr (&cmd, ")");
1021 /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */
1022 ctx->hdrs[n]->active = 0;
1024 /* after all this it's still possible to have no flags, if you
1025 * have no ACL rights */
1026 if (*flags && (imap_exec (idata, cmd.data, 0) != 0) &&
1027 (err_continue != M_YES)) {
1028 err_continue = imap_continue ("imap_sync_mailbox: STORE failed",
1030 if (err_continue != M_YES) {
1036 ctx->hdrs[n]->active = 1;
1041 /* We must send an EXPUNGE command if we're not closing. */
1042 if (expunge && !(ctx->closing) &&
1043 mutt_bit_isset (idata->rights, IMAP_ACL_DELETE)) {
1044 mutt_message _("Expunging messages from server...");
1046 /* Set expunge bit so we don't get spurious reopened messages */
1047 idata->reopen |= IMAP_EXPUNGE_EXPECTED;
1048 if (imap_exec (idata, "EXPUNGE", 0) != 0) {
1049 imap_error (_("imap_sync_mailbox: EXPUNGE failed"), idata->cmd.buf);
1060 mx_fastclose_mailbox (appendctx);
1066 /* imap_close_mailbox: issue close command if neccessary, reset IMAP_DATA */
1067 void imap_close_mailbox (CONTEXT * ctx)
1072 idata = (IMAP_DATA *) ctx->data;
1073 /* Check to see if the mailbox is actually open */
1077 if ((idata->status != IMAP_FATAL) &&
1078 (idata->state == IMAP_SELECTED) && (ctx == idata->ctx)) {
1079 if (!(idata->noclose) && imap_exec (idata, "CLOSE", 0))
1080 mutt_error (_("CLOSE failed"));
1082 idata->reopen &= IMAP_REOPEN_ALLOW;
1083 idata->state = IMAP_AUTHENTICATED;
1084 FREE (&(idata->mailbox));
1085 mutt_free_list (&idata->flags);
1089 /* free IMAP part of headers */
1090 for (i = 0; i < ctx->msgcount; i++)
1091 imap_free_header_data (&(ctx->hdrs[i]->data));
1093 for (i = 0; i < IMAP_CACHE_LEN; i++) {
1094 if (idata->cache[i].path) {
1095 unlink (idata->cache[i].path);
1096 FREE (&idata->cache[i].path);
1101 /* use the NOOP command to poll for new mail
1104 * M_REOPENED mailbox has been externally modified
1105 * M_NEW_MAIL new mail has arrived!
1109 int imap_check_mailbox (CONTEXT * ctx, int *index_hint, int force)
1111 /* overload keyboard timeout to avoid many mailbox checks in a row.
1112 * Most users don't like having to wait exactly when they press a key. */
1116 idata = (IMAP_DATA *) ctx->data;
1118 if ((force || time (NULL) > idata->lastread + Timeout)
1119 && imap_exec (idata, "NOOP", 0) != 0)
1122 /* We call this even when we haven't run NOOP in case we have pending
1123 * changes to process, since we can reopen here. */
1124 imap_cmd_finish (idata);
1126 if (idata->check_status & IMAP_EXPUNGE_PENDING)
1127 result = M_REOPENED;
1128 else if (idata->check_status & IMAP_NEWMAIL_PENDING)
1129 result = M_NEW_MAIL;
1130 else if (idata->check_status & IMAP_FLAGS_PENDING)
1133 idata->check_status = 0;
1138 /* returns count of recent messages if new = 1, else count of total messages.
1139 * (useful for at least postponed function)
1140 * Question of taste: use RECENT or UNSEEN for new?
1141 * 0+ number of messages in mailbox
1142 * -1 error while polling mailboxes
1144 int imap_mailbox_check (char *path, int new)
1148 char buf[LONG_STRING];
1149 char mbox[LONG_STRING];
1150 char mbox_unquoted[LONG_STRING];
1157 if (imap_parse_path (path, &mx))
1160 /* If imap_passive is set, don't open a connection to check for new mail */
1161 if (option (OPTIMAPPASSIVE))
1162 connflags = M_IMAP_CONN_NONEW;
1164 if (!(idata = imap_conn_find (&(mx.account), connflags))) {
1170 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1173 imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1174 strfcpy (mbox_unquoted, buf, sizeof (mbox_unquoted));
1176 /* The draft IMAP implementor's guide warns againts using the STATUS
1177 * command on a mailbox that you have selected
1180 if (mutt_strcmp (mbox_unquoted, idata->mailbox) == 0
1181 || (ascii_strcasecmp (mbox_unquoted, "INBOX") == 0
1182 && mutt_strcasecmp (mbox_unquoted, idata->mailbox) == 0)) {
1183 strfcpy (buf, "NOOP", sizeof (buf));
1185 else if (mutt_bit_isset (idata->capabilities, IMAP4REV1) ||
1186 mutt_bit_isset (idata->capabilities, STATUS)) {
1187 snprintf (buf, sizeof (buf), "STATUS %s (%s)", mbox,
1188 new ? "RECENT" : "MESSAGES");
1191 /* Server does not support STATUS, and this is not the current mailbox.
1192 * There is no lightweight way to check recent arrivals */
1195 imap_cmd_start (idata, buf);
1198 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
1201 s = imap_next_word (idata->cmd.buf);
1202 if (ascii_strncasecmp ("STATUS", s, 6) == 0) {
1203 s = imap_next_word (s);
1204 /* The mailbox name may or may not be quoted here. We could try to
1205 * munge the server response and compare with quoted (or vise versa)
1206 * but it is probably more efficient to just strncmp against both. */
1207 if (mutt_strncmp (mbox_unquoted, s, mutt_strlen (mbox_unquoted)) == 0
1208 || mutt_strncmp (mbox, s, mutt_strlen (mbox)) == 0) {
1209 s = imap_next_word (s);
1210 s = imap_next_word (s);
1211 if (isdigit ((unsigned char) *s)) {
1213 msgcount = atoi (s);
1215 (debugfile, "%d new messages in %s\n", msgcount, path));
1222 "imap_mailbox_check: STATUS response doesn't match requested mailbox.\n"));
1225 while (rc == IMAP_CMD_CONTINUE);
1230 /* all this listing/browsing is a mess. I don't like that name is a pointer
1231 * into idata->buf (used to be a pointer into the passed in buffer, just
1232 * as bad), nor do I like the fact that the fetch is done here. This
1233 * code can't possibly handle non-LIST untagged responses properly.
1235 int imap_parse_list_response (IMAP_DATA * idata, char **name, int *noselect,
1236 int *noinferiors, char *delim)
1244 rc = imap_cmd_step (idata);
1245 if (rc == IMAP_CMD_OK)
1247 if (rc != IMAP_CMD_CONTINUE)
1250 s = imap_next_word (idata->cmd.buf);
1251 if ((ascii_strncasecmp ("LIST", s, 4) == 0) ||
1252 (ascii_strncasecmp ("LSUB", s, 4) == 0)) {
1256 s = imap_next_word (s); /* flags */
1262 while (*ep && *ep != ')')
1265 if (!ascii_strncasecmp (s, "\\NoSelect", 9))
1267 if (!ascii_strncasecmp (s, "\\NoInferiors", 12))
1269 /* See draft-gahrns-imap-child-mailbox-?? */
1270 if (!ascii_strncasecmp (s, "\\HasNoChildren", 14))
1274 while (*s && *s != '\\' && *s != ')')
1280 s = imap_next_word (s); /* delim */
1281 /* Reset the delimiter, this can change */
1282 if (ascii_strncasecmp (s, "NIL", 3)) {
1283 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
1285 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
1289 s = imap_next_word (s); /* name */
1290 if (s && *s == '{') { /* Literal */
1291 if (imap_get_literal_count (idata->cmd.buf, &bytes) < 0)
1293 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
1295 *name = idata->cmd.buf;
1304 int imap_subscribe (char *path, int subscribe)
1308 char buf[LONG_STRING];
1309 char mbox[LONG_STRING];
1312 if (!mx_is_imap (path) || imap_parse_path (path, &mx)) {
1313 mutt_error (_("Bad mailbox name"));
1318 if (!(idata = imap_conn_find (&(mx.account), 0)))
1323 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1325 mutt_message (_("Subscribing to %s..."), buf);
1327 mutt_message (_("Unsubscribing to %s..."), buf);
1328 imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1330 snprintf (buf, sizeof (buf), "%s %s", subscribe ? "SUBSCRIBE" :
1331 "UNSUBSCRIBE", mbox);
1333 if (imap_exec (idata, buf, 0) < 0)
1344 /* imap_complete: given a partial IMAP folder path, return a string which
1345 * adds as much to the path as is unique */
1346 int imap_complete (char *dest, size_t dlen, char *path)
1350 char list[LONG_STRING];
1351 char buf[LONG_STRING];
1352 char *list_word = NULL;
1353 int noselect, noinferiors;
1355 char completion[LONG_STRING];
1356 int clen, matchlen = 0;
1357 int completions = 0;
1361 /* verify passed in path is an IMAP path */
1362 if (imap_parse_path (path, &mx)) {
1363 dprint (2, (debugfile, "imap_complete: bad path %s\n", path));
1367 /* don't open a new socket just for completion */
1368 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NONEW)))
1372 /* reformat path for IMAP list, and append wildcard */
1373 /* don't use INBOX in place of "" */
1374 if (mx.mbox && mx.mbox[0])
1375 imap_fix_path (idata, mx.mbox, list, sizeof (list));
1379 /* fire off command */
1380 snprintf (buf, sizeof (buf), "%s \"\" \"%s%%\"",
1381 option (OPTIMAPLSUB) ? "LSUB" : "LIST", list);
1383 imap_cmd_start (idata, buf);
1385 /* and see what the results are */
1386 strfcpy (completion, NONULL (mx.mbox), sizeof (completion));
1388 if (imap_parse_list_response (idata, &list_word, &noselect, &noinferiors,
1393 /* store unquoted */
1394 imap_unmunge_mbox_name (list_word);
1396 /* if the folder isn't selectable, append delimiter to force browse
1397 * to enter it on second tab. */
1399 clen = mutt_strlen (list_word);
1400 list_word[clen++] = delim;
1401 list_word[clen] = '\0';
1403 /* copy in first word */
1405 strfcpy (completion, list_word, sizeof (completion));
1406 matchlen = mutt_strlen (completion);
1412 while (pos < matchlen && list_word[pos] &&
1413 completion[pos] == list_word[pos])
1415 completion[pos] = '\0';
1421 while (ascii_strncmp (idata->cmd.seq, idata->cmd.buf, SEQLEN));
1424 /* reformat output */
1425 imap_qualify_path (dest, dlen, &mx, completion);
1426 mutt_pretty_mailbox (dest);
1437 /* reconnect if connection was lost */
1438 int imap_reconnect (CONTEXT * ctx)
1440 IMAP_DATA *imap_data = (IMAP_DATA *) ctx->data;
1443 if (imap_data->status == IMAP_CONNECTED)
1447 if (query_quadoption
1449 _("Connection lost. Reconnect to IMAP server?")) != M_YES)
1452 mx_open_mailbox (ctx->path, 0, ctx);