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. */
19 #include "mutt_curses.h"
25 #include "imap_private.h"
26 #if defined(USE_SSL) || defined(USE_GNUTLS)
27 # include "mutt_ssl.h"
33 #include "lib/debug.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 debug_print (2, ("STATUS not supported?\n"));
83 if (imap_exec (idata, buf, IMAP_CMD_FAIL_OK) < 0) {
84 debug_print (1, ("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 debug_print (2, ("reading %ld bytes\n", bytes));
184 for (pos = 0; pos < bytes; pos++) {
185 if (mutt_socket_readchar (idata->conn, &c) != 1) {
186 debug_print (1, ("error during read, %ld bytes read\n", pos));
187 idata->status = IMAP_FATAL;
193 if (r == 1 && c != '\n')
205 if (DebugLevel >= IMAP_LOG_LTRL)
206 fputc (c, DebugFile);
213 /* imap_expunge_mailbox: Purge IMAP portion of expunged messages from the
214 * context. Must not be done while something has a handle on any headers
215 * (eg inside pager or editor). That is, check IMAP_REOPEN_ALLOW. */
216 void imap_expunge_mailbox (IMAP_DATA * idata)
221 for (i = 0; i < idata->ctx->msgcount; i++) {
222 h = idata->ctx->hdrs[i];
224 if (h->index == -1) {
225 debug_print (2, ("Expunging message UID %d.\n", HEADER_DATA (h)->uid));
229 /* free cached body from disk, if neccessary */
230 cacheno = HEADER_DATA (h)->uid % IMAP_CACHE_LEN;
231 if (idata->cache[cacheno].uid == HEADER_DATA (h)->uid &&
232 idata->cache[cacheno].path) {
233 unlink (idata->cache[cacheno].path);
234 FREE (&idata->cache[cacheno].path);
237 imap_free_header_data (&h->data);
241 /* We may be called on to expunge at any time. We can't rely on the caller
242 * to always know to rethread */
243 mx_update_tables (idata->ctx, 0);
244 mutt_sort_headers (idata->ctx, 1);
247 static int imap_get_delim (IMAP_DATA * idata)
252 /* assume that the delim is /. If this fails, we're in bigger trouble
253 * than getting the delim wrong */
256 imap_cmd_start (idata, "LIST \"\" \"\"");
259 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
262 s = imap_next_word (idata->cmd.buf);
263 if (ascii_strncasecmp ("LIST", s, 4) == 0) {
264 s = imap_next_word (s);
265 s = imap_next_word (s);
266 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
268 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
273 while (rc == IMAP_CMD_CONTINUE);
275 if (rc != IMAP_CMD_OK) {
276 debug_print (1, ("failed.\n"));
280 debug_print (2, ("Delimiter: %c\n", idata->delim));
285 /* get rights for folder, let imap_handle_untagged do the rest */
286 static int imap_check_acl (IMAP_DATA * idata)
288 char buf[LONG_STRING];
289 char mbox[LONG_STRING];
291 imap_munge_mbox_name (mbox, sizeof (mbox), idata->mailbox);
292 snprintf (buf, sizeof (buf), "MYRIGHTS %s", mbox);
293 if (imap_exec (idata, buf, 0) != 0) {
294 imap_error ("imap_check_acl", buf);
300 /* imap_check_capabilities: make sure we can log in to this server. */
301 static int imap_check_capabilities (IMAP_DATA * idata)
303 if (imap_exec (idata, "CAPABILITY", 0) != 0) {
304 imap_error ("imap_check_capabilities", idata->cmd.buf);
308 if (!(mutt_bit_isset (idata->capabilities, IMAP4)
309 || mutt_bit_isset (idata->capabilities, IMAP4REV1))) {
310 mutt_error _("This IMAP server is ancient. Mutt does not work with it.");
312 mutt_sleep (2); /* pause a moment to let the user see the error */
320 /* imap_conn_find: Find an open IMAP connection matching account, or open
321 * a new one if none can be found. */
322 IMAP_DATA *imap_conn_find (const ACCOUNT * account, int flags)
328 if (!(conn = mutt_conn_find (NULL, account)))
331 /* if opening a new UNSELECTED connection, preserve existing creds */
332 creds = &(conn->account);
334 /* make sure this connection is not in SELECTED state, if neccessary */
335 if (flags & M_IMAP_CONN_NOSELECT)
336 while (conn->data && ((IMAP_DATA *) conn->data)->state == IMAP_SELECTED) {
337 if (!(conn = mutt_conn_find (conn, account)))
339 memcpy (&(conn->account), creds, sizeof (ACCOUNT));
342 idata = (IMAP_DATA *) conn->data;
344 /* don't open a new connection if one isn't wanted */
345 if (flags & M_IMAP_CONN_NONEW) {
347 mutt_socket_free (conn);
350 if (idata->state < IMAP_AUTHENTICATED)
355 /* The current connection is a new connection */
356 if (!(idata = imap_new_idata ())) {
357 mutt_socket_free (conn);
365 if (idata->state == IMAP_DISCONNECTED)
366 imap_open_connection (idata);
367 if (idata->state == IMAP_CONNECTED) {
368 if (!imap_authenticate (idata)) {
369 idata->state = IMAP_AUTHENTICATED;
370 if (idata->conn->ssf)
371 debug_print (2, ("Communication encrypted at %d bits\n", idata->conn->ssf));
374 mutt_account_unsetpass (&idata->conn->account);
376 FREE (&idata->capstr);
378 if (idata->state == IMAP_AUTHENTICATED)
379 imap_get_delim (idata);
384 int imap_open_connection (IMAP_DATA * idata)
386 char buf[LONG_STRING];
388 if (mutt_socket_open (idata->conn) < 0)
391 idata->state = IMAP_CONNECTED;
393 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE) {
394 mutt_error (_("Unexpected response received from server: %s"),
398 mutt_socket_close (idata->conn);
399 idata->state = IMAP_DISCONNECTED;
403 if (ascii_strncasecmp ("* OK", idata->cmd.buf, 4) == 0) {
404 /* TODO: Parse new tagged CAPABILITY data (* OK [CAPABILITY...]) */
405 if (imap_check_capabilities (idata))
407 #if defined(USE_SSL) || defined(USE_GNUTLS)
408 /* Attempt STARTTLS if available and desired. */
409 if (mutt_bit_isset (idata->capabilities, STARTTLS) && !idata->conn->ssf) {
412 if ((rc = query_quadoption (OPT_SSLSTARTTLS,
413 _("Secure connection with TLS?"))) == -1)
416 if ((rc = imap_exec (idata, "STARTTLS", IMAP_CMD_FAIL_OK)) == -1)
420 if (mutt_ssl_starttls (idata->conn))
422 if (mutt_gnutls_starttls (idata->conn))
425 mutt_error (_("Could not negotiate TLS connection"));
430 /* RFC 2595 demands we recheck CAPABILITY after TLS completes. */
431 if (imap_exec (idata, "CAPABILITY", 0))
439 else if (ascii_strncasecmp ("* PREAUTH", idata->cmd.buf, 9) == 0) {
440 idata->state = IMAP_AUTHENTICATED;
441 if (imap_check_capabilities (idata) != 0)
443 FREE (&idata->capstr);
446 imap_error ("imap_open_connection()", buf);
453 mutt_socket_close (idata->conn);
454 idata->state = IMAP_DISCONNECTED;
456 FREE (&idata->capstr);
460 /* imap_get_flags: Make a simple list out of a FLAGS response.
461 * return stream following FLAGS response */
462 static char *imap_get_flags (LIST ** hflags, char *s)
468 /* sanity-check string */
469 if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
470 debug_print (1, ("not a FLAGS response: %s\n", s));
476 debug_print (1, ("bogus FLAGS response: %s\n", s));
480 /* create list, update caller's flags handle */
481 flags = mutt_new_list ();
484 while (*s && *s != ')') {
488 while (*s && (*s != ')') && !ISSPACE (*s))
493 mutt_add_list (flags, flag_word);
497 /* note bad flags response */
499 debug_print (1, ("Unterminated FLAGS response: %s\n", s));
500 mutt_free_list (hflags);
510 int imap_open_mailbox (CONTEXT * ctx)
514 char buf[LONG_STRING];
515 char bufout[LONG_STRING];
520 if (imap_parse_path (ctx->path, &mx)) {
521 mutt_error (_("%s is an invalid IMAP path"), ctx->path);
525 /* we require a connection which isn't currently in IMAP_SELECTED state */
526 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NOSELECT)))
528 if (idata->state < IMAP_AUTHENTICATED)
533 /* once again the context is new */
536 /* Clean up path and replace the one in the ctx */
537 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
538 FREE (&(idata->mailbox));
539 idata->mailbox = safe_strdup (buf);
540 imap_qualify_path (buf, sizeof (buf), &mx, idata->mailbox);
543 ctx->path = safe_strdup (buf);
547 /* clear mailbox status */
549 memset (idata->rights, 0, (RIGHTSMAX + 7) / 8);
550 idata->newMailCount = 0;
552 mutt_message (_("Selecting %s..."), idata->mailbox);
553 imap_munge_mbox_name (buf, sizeof (buf), idata->mailbox);
554 snprintf (bufout, sizeof (bufout), "%s %s",
555 ctx->readonly ? "EXAMINE" : "SELECT", buf);
557 idata->state = IMAP_SELECTED;
559 imap_cmd_start (idata, bufout);
564 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
567 pc = idata->cmd.buf + 2;
569 /* Obtain list of available flags here, may be overridden by a
570 * PERMANENTFLAGS tag in the OK response */
571 if (ascii_strncasecmp ("FLAGS", pc, 5) == 0) {
572 /* don't override PERMANENTFLAGS */
574 debug_print (2, ("Getting mailbox FLAGS\n"));
575 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
579 /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
580 else if (ascii_strncasecmp ("OK [PERMANENTFLAGS", pc, 18) == 0) {
581 debug_print (2, ("Getting mailbox PERMANENTFLAGS\n"));
582 /* safe to call on NULL */
583 mutt_free_list (&(idata->flags));
584 /* skip "OK [PERMANENT" so syntax is the same as FLAGS */
586 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
590 /* save UIDVALIDITY for the header cache */
591 else if (ascii_strncasecmp ("OK [UIDVALIDITY", pc, 14) == 0) {
592 debug_print (2, ("Getting mailbox UIDVALIDITY\n"));
594 pc = imap_next_word (pc);
596 sscanf (pc, "%lu", &(idata->uid_validity));
600 pc = imap_next_word (pc);
601 if (!ascii_strncasecmp ("EXISTS", pc, 6)) {
602 count = idata->newMailCount;
603 idata->newMailCount = 0;
607 while (rc == IMAP_CMD_CONTINUE);
609 if (rc == IMAP_CMD_NO) {
612 s = imap_next_word (idata->cmd.buf); /* skip seq */
613 s = imap_next_word (s); /* Skip response */
614 mutt_error ("%s", s);
619 if (rc != IMAP_CMD_OK)
622 /* check for READ-ONLY notification */
623 if (!ascii_strncasecmp
624 (imap_get_qualifier (idata->cmd.buf), "[READ-ONLY]", 11)
625 && !mutt_bit_isset (idata->capabilities, ACL)) {
626 debug_print (2, ("Mailbox is read-only.\n"));
631 /* dump the mailbox flags we've found */
632 if (DebugLevel > 2) {
634 debug_print (3, ("No folder flags found\n"));
636 LIST *t = idata->flags;
638 debug_print (3, ("Mailbox flags:\n"));
642 debug_print (3, ("[%s]\n", t->data));
649 if (mutt_bit_isset (idata->capabilities, ACL)) {
650 if (imap_check_acl (idata))
652 if (!(mutt_bit_isset (idata->rights, ACL_DELETE) ||
653 mutt_bit_isset (idata->rights, ACL_SEEN) ||
654 mutt_bit_isset (idata->rights, ACL_WRITE) ||
655 mutt_bit_isset (idata->rights, ACL_INSERT)))
658 /* assume we have all rights if ACL is unavailable */
660 mutt_bit_set (idata->rights, ACL_LOOKUP);
661 mutt_bit_set (idata->rights, ACL_READ);
662 mutt_bit_set (idata->rights, ACL_SEEN);
663 mutt_bit_set (idata->rights, ACL_WRITE);
664 mutt_bit_set (idata->rights, ACL_INSERT);
665 mutt_bit_set (idata->rights, ACL_POST);
666 mutt_bit_set (idata->rights, ACL_CREATE);
667 mutt_bit_set (idata->rights, ACL_DELETE);
671 ctx->hdrs = safe_calloc (count, sizeof (HEADER *));
672 ctx->v2r = safe_calloc (count, sizeof (int));
674 if (count && (imap_read_headers (idata, 0, count - 1) < 0)) {
675 mutt_error _("Error opening mailbox");
681 debug_print (2, ("msgcount is %d\n", ctx->msgcount));
686 if (idata->state == IMAP_SELECTED)
687 idata->state = IMAP_AUTHENTICATED;
693 int imap_open_mailbox_append (CONTEXT * ctx)
697 char buf[LONG_STRING], mbox[LONG_STRING];
698 char mailbox[LONG_STRING];
702 if (imap_parse_path (ctx->path, &mx))
705 /* in APPEND mode, we appear to hijack an existing IMAP connection -
706 * ctx is brand new and mostly empty */
708 if (!(idata = imap_conn_find (&(mx.account), 0)))
715 /* check mailbox existance */
717 imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
719 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
721 if (mutt_bit_isset (idata->capabilities, IMAP4REV1))
722 snprintf (buf, sizeof (buf), "STATUS %s (UIDVALIDITY)", mbox);
723 else if (mutt_bit_isset (idata->capabilities, STATUS))
724 /* We have no idea what the other guy wants. UW imapd 8.3 wants this
725 * (but it does not work if another mailbox is selected) */
726 snprintf (buf, sizeof (buf), "STATUS %s (UID-VALIDITY)", mbox);
728 /* STATUS not supported */
729 mutt_message _("Unable to append to IMAP mailboxes at this server");
734 r = imap_exec (idata, buf, IMAP_CMD_FAIL_OK);
736 /* command failed cause folder doesn't exist */
737 snprintf (buf, sizeof (buf), _("Create %s?"), mailbox);
738 if (option (OPTCONFIRMCREATE) && mutt_yesorno (buf, 1) < 1)
741 if (imap_create_mailbox (idata, mailbox) < 0)
745 /* Hmm, some other failure */
756 /* imap_logout: Gracefully log out of server. */
757 void imap_logout (IMAP_DATA * idata)
759 /* we set status here to let imap_handle_untagged know we _expect_ to
760 * receive a bye response (so it doesn't freak out and close the conn) */
761 idata->status = IMAP_BYE;
762 imap_cmd_start (idata, "LOGOUT");
763 while (imap_cmd_step (idata) == IMAP_CMD_CONTINUE);
764 FREE (&idata->cmd.buf);
769 int imap_close_connection (CONTEXT *ctx)
771 debug_print (1, (debugfile, "imap_close_connection(): closing connection\n"));
772 if (CTX_DATA->status != IMAP_BYE)
774 mutt_message _("Closing connection to IMAP server...");
775 imap_logout (CTX_DATA);
778 mutt_socket_close (CTX_DATA->conn);
779 CTX_DATA->state = IMAP_DISCONNECTED;
780 CTX_DATA->conn->data = NULL;
785 /* imap_set_flag: append str to flags if we currently have permission
786 * according to aclbit */
787 static void imap_set_flag (IMAP_DATA * idata, int aclbit, int flag,
788 const char *str, char *flags, size_t flsize)
790 if (mutt_bit_isset (idata->rights, aclbit))
792 safe_strcat (flags, flsize, str);
795 /* imap_make_msg_set: make an IMAP4rev1 UID message set out of a set of
796 * headers, given a flag enum to filter on.
797 * Params: idata: IMAP_DATA containing context containing header set
798 * buf: to write message set into
799 * buflen: length of buffer
800 * flag: enum of flag type on which to filter
801 * changed: include only changed messages in message set
802 * Returns: number of messages in message set (0 if no matches) */
803 int imap_make_msg_set (IMAP_DATA * idata, BUFFER * buf, int flag, int changed)
805 HEADER **hdrs; /* sorted local copy */
806 int count = 0; /* number of messages in message set */
807 int match = 0; /* whether current message matches flag condition */
808 unsigned int setstart = 0; /* start of current message range */
810 short oldsort; /* we clobber reverse, must restore it */
812 /* assuming 32-bit UIDs */
816 /* make copy of header pointers to sort in natural order */
817 hdrs = safe_calloc (idata->ctx->msgcount, sizeof (HEADER *));
818 memcpy (hdrs, idata->ctx->hdrs, idata->ctx->msgcount * sizeof (HEADER *));
820 if (Sort != SORT_ORDER) {
823 qsort ((void *) hdrs, idata->ctx->msgcount, sizeof (HEADER *),
824 mutt_get_sort_func (SORT_ORDER));
828 for (n = 0; n < idata->ctx->msgcount; n++) {
830 /* don't include pending expunged messages */
834 if (hdrs[n]->deleted)
843 if (match && (!changed || hdrs[n]->changed)) {
846 setstart = HEADER_DATA (hdrs[n])->uid;
848 snprintf (uid, sizeof (uid), "%u", HEADER_DATA (hdrs[n])->uid);
849 mutt_buffer_addstr (buf, uid);
853 snprintf (uid, sizeof (uid), ",%u", HEADER_DATA (hdrs[n])->uid);
854 mutt_buffer_addstr (buf, uid);
857 /* tie up if the last message also matches */
858 else if (n == idata->ctx->msgcount - 1) {
859 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n])->uid);
860 mutt_buffer_addstr (buf, uid);
863 /* this message is not expunged and doesn't match. End current set. */
864 else if (setstart && hdrs[n]->active) {
865 if (HEADER_DATA (hdrs[n - 1])->uid > setstart) {
866 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n - 1])->uid);
867 mutt_buffer_addstr (buf, uid);
878 /* Update the IMAP server to reflect the flags a single message. */
880 int imap_sync_message (IMAP_DATA *idata, HEADER *hdr, BUFFER *cmd,
883 char flags[LONG_STRING];
888 snprintf (uid, sizeof (uid), "%u", HEADER_DATA(hdr)->uid);
889 cmd->dptr = cmd->data;
890 mutt_buffer_addstr (cmd, "UID STORE ");
891 mutt_buffer_addstr (cmd, uid);
895 imap_set_flag (idata, ACL_SEEN, hdr->read, "\\Seen ",
896 flags, sizeof (flags));
897 imap_set_flag (idata, ACL_WRITE, hdr->flagged,
898 "\\Flagged ", flags, sizeof (flags));
899 imap_set_flag (idata, ACL_WRITE, hdr->replied,
900 "\\Answered ", flags, sizeof (flags));
901 imap_set_flag (idata, ACL_DELETE, hdr->deleted,
902 "\\Deleted ", flags, sizeof (flags));
904 /* now make sure we don't lose custom tags */
905 if (mutt_bit_isset (idata->rights, ACL_WRITE))
906 imap_add_keywords (flags, hdr, idata->flags, sizeof (flags));
908 str_skip_trailws (flags);
910 /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to
911 * explicitly revoke all system flags (if we have permission) */
914 imap_set_flag (idata, ACL_SEEN, 1, "\\Seen ", flags, sizeof (flags));
915 imap_set_flag (idata, ACL_WRITE, 1, "\\Flagged ", flags, sizeof (flags));
916 imap_set_flag (idata, ACL_WRITE, 1, "\\Answered ", flags, sizeof (flags));
917 imap_set_flag (idata, ACL_DELETE, 1, "\\Deleted ", flags, sizeof (flags));
919 str_skip_trailws (flags);
921 mutt_buffer_addstr (cmd, " -FLAGS.SILENT (");
923 mutt_buffer_addstr (cmd, " FLAGS.SILENT (");
925 mutt_buffer_addstr (cmd, flags);
926 mutt_buffer_addstr (cmd, ")");
928 /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */
931 /* after all this it's still possible to have no flags, if you
932 * have no ACL rights */
933 if (*flags && (imap_exec (idata, cmd->data, 0) != 0) &&
934 err_continue && (*err_continue != M_YES))
936 *err_continue = imap_continue ("imap_sync_message: STORE failed",
938 if (*err_continue != M_YES)
943 idata->ctx->changed--;
948 /* update the IMAP server to reflect message changes done within mutt.
950 * ctx: the current context
951 * expunge: 0 or 1 - do expunge?
954 int imap_sync_mailbox (CONTEXT * ctx, int expunge, int *index_hint)
957 CONTEXT *appendctx = NULL;
961 int err_continue = M_NO; /* continue on error? */
964 idata = (IMAP_DATA *) ctx->data;
966 if (idata->state != IMAP_SELECTED) {
967 debug_print (2, ("no mailbox selected\n"));
971 /* CLOSE purges deleted messages. If we don't want to purge them, we must
972 * tell imap_close_mailbox not to issue the CLOSE command */
978 /* This function is only called when the calling code expects the context
980 imap_allow_reopen (ctx);
982 if ((rc = imap_check_mailbox (ctx, index_hint, 0)) != 0)
985 memset (&cmd, 0, sizeof (cmd));
987 /* if we are expunging anyway, we can do deleted messages very quickly... */
988 if (expunge && mutt_bit_isset (idata->rights, ACL_DELETE)) {
989 mutt_buffer_addstr (&cmd, "UID STORE ");
990 deleted = imap_make_msg_set (idata, &cmd, M_DELETE, 1);
992 /* if we have a message set, then let's delete */
994 mutt_message (_("Marking %d messages deleted..."), deleted);
995 mutt_buffer_addstr (&cmd, " +FLAGS.SILENT (\\Deleted)");
996 /* mark these messages as unchanged so second pass ignores them. Done
997 * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */
998 for (n = 0; n < ctx->msgcount; n++)
999 if (ctx->hdrs[n]->deleted && ctx->hdrs[n]->changed)
1000 ctx->hdrs[n]->active = 0;
1001 if (imap_exec (idata, cmd.data, 0) != 0) {
1002 mutt_error (_("Expunge failed"));
1010 /* save status changes */
1011 for (n = 0; n < ctx->msgcount; n++) {
1012 if (ctx->hdrs[n]->active && ctx->hdrs[n]->changed) {
1014 mutt_message (_("Saving message status flags... [%d/%d]"), n + 1,
1017 /* if the message has been rethreaded or attachments have been deleted
1018 * we delete the message and reupload it.
1019 * This works better if we're expunging, of course. */
1020 if (ctx->hdrs[n]->refs_changed || ctx->hdrs[n]->irt_changed ||
1021 ctx->hdrs[n]->attach_del) {
1022 debug_print (3, ("Attachments to be deleted, falling back to _mutt_save_message\n"));
1024 appendctx = mx_open_mailbox (ctx->path, M_APPEND | M_QUIET, NULL);
1026 debug_print (1, ("Error opening mailbox in append mode\n"));
1029 _mutt_save_message (ctx->hdrs[n], appendctx, 1, 0, 0);
1032 if (imap_sync_message (idata, ctx->hdrs[n], &cmd, &err_continue) < 0) {
1040 /* We must send an EXPUNGE command if we're not closing. */
1041 if (expunge && !(ctx->closing) &&
1042 mutt_bit_isset (idata->rights, ACL_DELETE)) {
1043 mutt_message _("Expunging messages from server...");
1045 /* Set expunge bit so we don't get spurious reopened messages */
1046 idata->reopen |= IMAP_EXPUNGE_EXPECTED;
1047 if (imap_exec (idata, "EXPUNGE", 0) != 0) {
1048 imap_error (_("imap_sync_mailbox: EXPUNGE failed"), idata->cmd.buf);
1059 mx_fastclose_mailbox (appendctx);
1065 /* imap_close_mailbox: issue close command if neccessary, reset IMAP_DATA */
1066 void imap_close_mailbox (CONTEXT * ctx)
1071 idata = (IMAP_DATA *) ctx->data;
1072 /* Check to see if the mailbox is actually open */
1076 if ((idata->status != IMAP_FATAL) &&
1077 (idata->state == IMAP_SELECTED) && (ctx == idata->ctx)) {
1078 if (!(idata->noclose) && imap_exec (idata, "CLOSE", 0))
1079 mutt_error (_("CLOSE failed"));
1081 idata->reopen &= IMAP_REOPEN_ALLOW;
1082 idata->state = IMAP_AUTHENTICATED;
1083 FREE (&(idata->mailbox));
1084 mutt_free_list (&idata->flags);
1088 /* free IMAP part of headers */
1089 for (i = 0; i < ctx->msgcount; i++)
1090 imap_free_header_data (&(ctx->hdrs[i]->data));
1092 for (i = 0; i < IMAP_CACHE_LEN; i++) {
1093 if (idata->cache[i].path) {
1094 unlink (idata->cache[i].path);
1095 FREE (&idata->cache[i].path);
1100 /* use the NOOP command to poll for new mail
1103 * M_REOPENED mailbox has been externally modified
1104 * M_NEW_MAIL new mail has arrived!
1108 int imap_check_mailbox (CONTEXT * ctx, int *index_hint, int force)
1110 /* overload keyboard timeout to avoid many mailbox checks in a row.
1111 * Most users don't like having to wait exactly when they press a key. */
1115 idata = (IMAP_DATA *) ctx->data;
1117 if ((force || time (NULL) > idata->lastread + Timeout)
1118 && imap_exec (idata, "NOOP", 0) != 0)
1121 /* We call this even when we haven't run NOOP in case we have pending
1122 * changes to process, since we can reopen here. */
1123 imap_cmd_finish (idata);
1125 if (idata->check_status & IMAP_EXPUNGE_PENDING)
1126 result = M_REOPENED;
1127 else if (idata->check_status & IMAP_NEWMAIL_PENDING)
1128 result = M_NEW_MAIL;
1129 else if (idata->check_status & IMAP_FLAGS_PENDING)
1132 idata->check_status = 0;
1137 /* returns count of recent messages if new = 1, else count of total messages.
1138 * (useful for at least postponed function)
1139 * Question of taste: use RECENT or UNSEEN for new?
1140 * 0+ number of messages in mailbox
1141 * -1 error while polling mailboxes
1143 int imap_mailbox_check (char *path, int new)
1147 char buf[LONG_STRING];
1148 char mbox[LONG_STRING];
1149 char mbox_unquoted[LONG_STRING];
1156 if (imap_parse_path (path, &mx))
1159 /* If imap_passive is set, don't open a connection to check for new mail */
1160 if (option (OPTIMAPPASSIVE))
1161 connflags = M_IMAP_CONN_NONEW;
1163 if (!(idata = imap_conn_find (&(mx.account), connflags))) {
1169 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1172 imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1173 strfcpy (mbox_unquoted, buf, sizeof (mbox_unquoted));
1175 /* The draft IMAP implementor's guide warns againts using the STATUS
1176 * command on a mailbox that you have selected
1179 if (safe_strcmp (mbox_unquoted, idata->mailbox) == 0
1180 || (ascii_strcasecmp (mbox_unquoted, "INBOX") == 0
1181 && safe_strcasecmp (mbox_unquoted, idata->mailbox) == 0)) {
1182 strfcpy (buf, "NOOP", sizeof (buf));
1184 else if (mutt_bit_isset (idata->capabilities, IMAP4REV1) ||
1185 mutt_bit_isset (idata->capabilities, STATUS)) {
1186 snprintf (buf, sizeof (buf), "STATUS %s (%s)", mbox,
1187 new ? "RECENT" : "MESSAGES");
1190 /* Server does not support STATUS, and this is not the current mailbox.
1191 * There is no lightweight way to check recent arrivals */
1194 imap_cmd_start (idata, buf);
1197 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
1200 s = imap_next_word (idata->cmd.buf);
1201 if (ascii_strncasecmp ("STATUS", s, 6) == 0) {
1202 s = imap_next_word (s);
1203 /* The mailbox name may or may not be quoted here. We could try to
1204 * munge the server response and compare with quoted (or vise versa)
1205 * but it is probably more efficient to just strncmp against both. */
1206 if (safe_strncmp (mbox_unquoted, s, safe_strlen (mbox_unquoted)) == 0
1207 || safe_strncmp (mbox, s, safe_strlen (mbox)) == 0) {
1208 s = imap_next_word (s);
1209 s = imap_next_word (s);
1210 if (isdigit ((unsigned char) *s)) {
1212 msgcount = atoi (s);
1213 debug_print (2, ("%d new messages in %s\n", msgcount, path));
1218 debug_print (1, ("STATUS response doesn't match requested mailbox.\n"));
1221 while (rc == IMAP_CMD_CONTINUE);
1226 /* all this listing/browsing is a mess. I don't like that name is a pointer
1227 * into idata->buf (used to be a pointer into the passed in buffer, just
1228 * as bad), nor do I like the fact that the fetch is done here. This
1229 * code can't possibly handle non-LIST untagged responses properly.
1231 int imap_parse_list_response (IMAP_DATA * idata, char **name, int *noselect,
1232 int *noinferiors, char *delim)
1240 rc = imap_cmd_step (idata);
1241 if (rc == IMAP_CMD_OK)
1243 if (rc != IMAP_CMD_CONTINUE)
1246 s = imap_next_word (idata->cmd.buf);
1247 if ((ascii_strncasecmp ("LIST", s, 4) == 0) ||
1248 (ascii_strncasecmp ("LSUB", s, 4) == 0)) {
1252 s = imap_next_word (s); /* flags */
1258 while (*ep && *ep != ')')
1261 if (!ascii_strncasecmp (s, "\\NoSelect", 9))
1263 if (!ascii_strncasecmp (s, "\\NoInferiors", 12))
1265 /* See draft-gahrns-imap-child-mailbox-?? */
1266 if (!ascii_strncasecmp (s, "\\HasNoChildren", 14))
1270 while (*s && *s != '\\' && *s != ')')
1276 s = imap_next_word (s); /* delim */
1277 /* Reset the delimiter, this can change */
1278 if (ascii_strncasecmp (s, "NIL", 3)) {
1279 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
1281 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
1285 s = imap_next_word (s); /* name */
1286 if (s && *s == '{') { /* Literal */
1287 if (imap_get_literal_count (idata->cmd.buf, &bytes) < 0)
1289 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
1291 *name = idata->cmd.buf;
1300 int imap_subscribe (char *path, int subscribe)
1304 char buf[LONG_STRING];
1305 char mbox[LONG_STRING];
1308 if (mx_get_magic (path) == M_IMAP || imap_parse_path (path, &mx)) {
1309 mutt_error (_("Bad mailbox name"));
1314 if (!(idata = imap_conn_find (&(mx.account), 0)))
1319 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1321 mutt_message (_("Subscribing to %s..."), buf);
1323 mutt_message (_("Unsubscribing to %s..."), buf);
1324 imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1326 snprintf (buf, sizeof (buf), "%s %s", subscribe ? "SUBSCRIBE" :
1327 "UNSUBSCRIBE", mbox);
1329 if (imap_exec (idata, buf, 0) < 0)
1340 /* imap_complete: given a partial IMAP folder path, return a string which
1341 * adds as much to the path as is unique */
1342 int imap_complete (char *dest, size_t dlen, char *path)
1346 char list[LONG_STRING];
1347 char buf[LONG_STRING];
1348 char *list_word = NULL;
1349 int noselect, noinferiors;
1351 char completion[LONG_STRING];
1352 int clen, matchlen = 0;
1353 int completions = 0;
1357 /* verify passed in path is an IMAP path */
1358 if (imap_parse_path (path, &mx)) {
1359 debug_print (2, ("bad path %s\n", path));
1363 /* don't open a new socket just for completion */
1364 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NONEW)))
1368 /* reformat path for IMAP list, and append wildcard */
1369 /* don't use INBOX in place of "" */
1370 if (mx.mbox && mx.mbox[0])
1371 imap_fix_path (idata, mx.mbox, list, sizeof (list));
1375 /* fire off command */
1376 snprintf (buf, sizeof (buf), "%s \"\" \"%s%%\"",
1377 option (OPTIMAPLSUB) ? "LSUB" : "LIST", list);
1379 imap_cmd_start (idata, buf);
1381 /* and see what the results are */
1382 strfcpy (completion, NONULL (mx.mbox), sizeof (completion));
1384 if (imap_parse_list_response (idata, &list_word, &noselect, &noinferiors,
1389 /* store unquoted */
1390 imap_unmunge_mbox_name (list_word);
1392 /* if the folder isn't selectable, append delimiter to force browse
1393 * to enter it on second tab. */
1395 clen = safe_strlen (list_word);
1396 list_word[clen++] = delim;
1397 list_word[clen] = '\0';
1399 /* copy in first word */
1401 strfcpy (completion, list_word, sizeof (completion));
1402 matchlen = safe_strlen (completion);
1408 while (pos < matchlen && list_word[pos] &&
1409 completion[pos] == list_word[pos])
1411 completion[pos] = '\0';
1417 while (ascii_strncmp (idata->cmd.seq, idata->cmd.buf, SEQLEN));
1420 /* reformat output */
1421 imap_qualify_path (dest, dlen, &mx, completion);
1422 mutt_pretty_mailbox (dest);
1433 /* reconnect if connection was lost */
1434 int imap_reconnect (CONTEXT * ctx)
1436 IMAP_DATA *imap_data;
1441 imap_data = (IMAP_DATA *) ctx->data;
1444 if (imap_data->status == IMAP_CONNECTED)
1448 if (query_quadoption
1450 _("Connection lost. Reconnect to IMAP server?")) != M_YES)
1453 mx_open_mailbox (ctx->path, 0, ctx);