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. */
21 #include "mutt_curses.h"
27 #include "imap_private.h"
28 #if defined(USE_SSL) || defined(USE_GNUTLS)
29 # include "mutt_ssl.h"
36 #include "lib/debug.h"
42 #include <sys/types.h>
45 /* imap forward declarations */
46 static int imap_get_delim (IMAP_DATA * idata);
47 static char *imap_get_flags (LIST ** hflags, char *s);
48 static int imap_check_acl (IMAP_DATA * idata);
49 static int imap_check_capabilities (IMAP_DATA * idata);
50 static void imap_set_flag (IMAP_DATA * idata, int aclbit, int flag,
51 const char *str, char *flags, size_t flsize);
53 /* imap_access: Check permissions on an IMAP mailbox.
54 * TODO: ACL checks. Right now we assume if it exists we can
56 int imap_access (const char *path, int flags)
60 char buf[LONG_STRING];
61 char mailbox[LONG_STRING];
62 char mbox[LONG_STRING];
64 if (imap_parse_path (path, &mx))
67 if (!(idata = imap_conn_find (&mx.account,
68 option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW :
74 imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
76 /* we may already be in the folder we're checking */
77 if (!ascii_strcmp(idata->mailbox, mx.mbox)) {
83 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
85 if (mutt_bit_isset (idata->capabilities, IMAP4REV1))
86 snprintf (buf, sizeof (buf), "STATUS %s (UIDVALIDITY)", mbox);
87 else if (mutt_bit_isset (idata->capabilities, STATUS))
88 snprintf (buf, sizeof (buf), "STATUS %s (UID-VALIDITY)", mbox);
90 debug_print (2, ("STATUS not supported?\n"));
94 if (imap_exec (idata, buf, IMAP_CMD_FAIL_OK) < 0) {
95 debug_print (1, ("Can't check STATUS of %s\n", mbox));
102 int imap_create_mailbox (IMAP_DATA * idata, char *mailbox)
104 char buf[LONG_STRING], mbox[LONG_STRING];
106 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
107 snprintf (buf, sizeof (buf), "CREATE %s", mbox);
109 if (imap_exec (idata, buf, 0) != 0)
115 int imap_rename_mailbox (IMAP_DATA * idata, IMAP_MBOX * mx,
118 char oldmbox[LONG_STRING];
119 char newmbox[LONG_STRING];
120 char buf[LONG_STRING];
122 imap_munge_mbox_name (oldmbox, sizeof (oldmbox), mx->mbox);
123 imap_munge_mbox_name (newmbox, sizeof (newmbox), newname);
125 snprintf (buf, sizeof (buf), "RENAME %s %s", oldmbox, newmbox);
127 if (imap_exec (idata, buf, 0) != 0)
133 int imap_delete_mailbox (CONTEXT * ctx, IMAP_MBOX mx)
135 char buf[LONG_STRING], mbox[LONG_STRING];
138 if (!ctx || !ctx->data) {
139 if (!(idata = imap_conn_find (&mx.account,
140 option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW
150 imap_munge_mbox_name (mbox, sizeof (mbox), mx.mbox);
151 snprintf (buf, sizeof (buf), "DELETE %s", mbox);
153 if (imap_exec ((IMAP_DATA *) idata, buf, 0) != 0)
159 /* imap_logout_all: close all open connections. Quick and dirty until we can
160 * make sure we've got all the context we need. */
161 void imap_logout_all (void)
166 conn = mutt_socket_head ();
171 if (conn->account.type == M_ACCT_TYPE_IMAP && conn->fd >= 0) {
172 mutt_message (_("Closing connection to %s..."), conn->account.host);
173 imap_logout ((IMAP_DATA *) conn->data);
175 mutt_socket_close (conn);
176 mutt_socket_free (conn);
183 /* imap_read_literal: read bytes bytes from server into file. Not explicitly
184 * buffered, relies on FILE buffering. NOTE: strips \r from \r\n.
185 * Apparently even literals use \r\n-terminated strings ?! */
186 int imap_read_literal (FILE * fp, IMAP_DATA * idata, long bytes)
193 debug_print (2, ("reading %ld bytes\n", bytes));
195 for (pos = 0; pos < bytes; pos++) {
196 if (mutt_socket_readchar (idata->conn, &c) != 1) {
197 debug_print (1, ("error during read, %ld bytes read\n", pos));
198 idata->status = IMAP_FATAL;
204 if (r == 1 && c != '\n')
216 if (DebugLevel >= IMAP_LOG_LTRL)
217 fputc (c, DebugFile);
224 /* imap_expunge_mailbox: Purge IMAP portion of expunged messages from the
225 * context. Must not be done while something has a handle on any headers
226 * (eg inside pager or editor). That is, check IMAP_REOPEN_ALLOW. */
227 void imap_expunge_mailbox (IMAP_DATA * idata)
232 for (i = 0; i < idata->ctx->msgcount; i++) {
233 h = idata->ctx->hdrs[i];
235 if (h->index == -1) {
236 debug_print (2, ("Expunging message UID %d.\n", HEADER_DATA (h)->uid));
240 /* free cached body from disk, if neccessary */
241 cacheno = HEADER_DATA (h)->uid % IMAP_CACHE_LEN;
242 if (idata->cache[cacheno].uid == HEADER_DATA (h)->uid &&
243 idata->cache[cacheno].path) {
244 unlink (idata->cache[cacheno].path);
245 mem_free (&idata->cache[cacheno].path);
248 imap_free_header_data (&h->data);
252 /* We may be called on to expunge at any time. We can't rely on the caller
253 * to always know to rethread */
254 mx_update_tables (idata->ctx, 0);
255 mutt_sort_headers (idata->ctx, 1);
258 static int imap_get_delim (IMAP_DATA * idata)
263 /* assume that the delim is /. If this fails, we're in bigger trouble
264 * than getting the delim wrong */
267 imap_cmd_start (idata, "LIST \"\" \"\"");
270 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
273 s = imap_next_word (idata->cmd.buf);
274 if (ascii_strncasecmp ("LIST", s, 4) == 0) {
275 s = imap_next_word (s);
276 s = imap_next_word (s);
277 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
279 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
284 while (rc == IMAP_CMD_CONTINUE);
286 if (rc != IMAP_CMD_OK) {
287 debug_print (1, ("failed.\n"));
291 debug_print (2, ("Delimiter: %c\n", idata->delim));
296 /* get rights for folder, let imap_handle_untagged do the rest */
297 static int imap_check_acl (IMAP_DATA * idata)
299 char buf[LONG_STRING];
300 char mbox[LONG_STRING];
302 imap_munge_mbox_name (mbox, sizeof (mbox), idata->mailbox);
303 snprintf (buf, sizeof (buf), "MYRIGHTS %s", mbox);
304 if (imap_exec (idata, buf, 0) != 0) {
305 imap_error ("imap_check_acl", buf);
311 /* imap_check_capabilities: make sure we can log in to this server. */
312 static int imap_check_capabilities (IMAP_DATA * idata)
314 if (imap_exec (idata, "CAPABILITY", 0) != 0) {
315 imap_error ("imap_check_capabilities", idata->cmd.buf);
319 if (!(mutt_bit_isset (idata->capabilities, IMAP4)
320 || mutt_bit_isset (idata->capabilities, IMAP4REV1))) {
321 mutt_error _("This IMAP server is ancient. Mutt does not work with it.");
323 mutt_sleep (2); /* pause a moment to let the user see the error */
331 /* imap_conn_find: Find an open IMAP connection matching account, or open
332 * a new one if none can be found. */
333 IMAP_DATA *imap_conn_find (const ACCOUNT * account, int flags)
340 if (!(conn = mutt_conn_find (NULL, account)))
343 /* if opening a new UNSELECTED connection, preserve existing creds */
344 creds = &(conn->account);
346 /* make sure this connection is not in SELECTED state, if neccessary */
347 if (flags & M_IMAP_CONN_NOSELECT)
348 while (conn->data && ((IMAP_DATA *) conn->data)->state == IMAP_SELECTED) {
349 if (!(conn = mutt_conn_find (conn, account)))
351 memcpy (&(conn->account), creds, sizeof (ACCOUNT));
354 idata = (IMAP_DATA *) conn->data;
356 /* don't open a new connection if one isn't wanted */
357 if (flags & M_IMAP_CONN_NONEW) {
359 mutt_socket_free (conn);
362 if (idata->state < IMAP_AUTHENTICATED)
367 /* The current connection is a new connection */
368 if (!(idata = imap_new_idata ())) {
369 mutt_socket_free (conn);
378 if (idata->state == IMAP_DISCONNECTED)
379 imap_open_connection (idata);
380 if (idata->state == IMAP_CONNECTED) {
381 if (!imap_authenticate (idata)) {
382 idata->state = IMAP_AUTHENTICATED;
383 if (idata->conn->ssf)
384 debug_print (2, ("Communication encrypted at %d bits\n", idata->conn->ssf));
387 mutt_account_unsetpass (&idata->conn->account);
389 mem_free (&idata->capstr);
391 if (new && idata->state == IMAP_AUTHENTICATED) {
392 imap_get_delim (idata);
393 if (option (OPTIMAPCHECKSUBSCRIBED)) {
394 mutt_message _("Checking mailbox subscriptions");
395 imap_exec (idata, "LSUB \"\" \"*\"", 0);
402 int imap_open_connection (IMAP_DATA * idata)
404 char buf[LONG_STRING];
406 if (mutt_socket_open (idata->conn) < 0)
409 idata->state = IMAP_CONNECTED;
411 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE) {
412 mutt_socket_close (idata->conn);
413 idata->state = IMAP_DISCONNECTED;
417 if (ascii_strncasecmp ("* OK", idata->cmd.buf, 4) == 0) {
418 /* TODO: Parse new tagged CAPABILITY data (* OK [CAPABILITY...]) */
419 if (imap_check_capabilities (idata))
421 #if defined(USE_SSL) || defined(USE_GNUTLS)
422 /* Attempt STARTTLS if available and desired. */
423 if (!idata->conn->ssf && (option(OPTSSLFORCETLS) ||
424 mutt_bit_isset (idata->capabilities, STARTTLS))) {
427 if (option (OPTSSLFORCETLS))
429 else if ((rc = query_quadoption (OPT_SSLSTARTTLS,
430 _("Secure connection with TLS?"))) == -1)
433 if ((rc = imap_exec (idata, "STARTTLS", IMAP_CMD_FAIL_OK)) == -1)
437 if (mutt_ssl_starttls (idata->conn))
439 if (mutt_gnutls_starttls (idata->conn))
442 mutt_error (_("Could not negotiate TLS connection"));
447 /* RFC 2595 demands we recheck CAPABILITY after TLS completes. */
448 if (imap_exec (idata, "CAPABILITY", 0))
455 if (option(OPTSSLFORCETLS) && ! idata->conn->ssf) {
456 mutt_error _("Encrypted connection unavailable");
462 else if (ascii_strncasecmp ("* PREAUTH", idata->cmd.buf, 9) == 0) {
463 idata->state = IMAP_AUTHENTICATED;
464 if (imap_check_capabilities (idata) != 0)
466 mem_free (&idata->capstr);
469 imap_error ("imap_open_connection()", buf);
476 mutt_socket_close (idata->conn);
477 idata->state = IMAP_DISCONNECTED;
479 mem_free (&idata->capstr);
483 /* imap_get_flags: Make a simple list out of a FLAGS response.
484 * return stream following FLAGS response */
485 static char *imap_get_flags (LIST ** hflags, char *s)
491 /* sanity-check string */
492 if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
493 debug_print (1, ("not a FLAGS response: %s\n", s));
499 debug_print (1, ("bogus FLAGS response: %s\n", s));
503 /* create list, update caller's flags handle */
504 flags = mutt_new_list ();
507 while (*s && *s != ')') {
511 while (*s && (*s != ')') && !ISSPACE (*s))
516 mutt_add_list (flags, flag_word);
520 /* note bad flags response */
522 debug_print (1, ("Unterminated FLAGS response: %s\n", s));
523 mutt_free_list (hflags);
533 int imap_open_mailbox (CONTEXT * ctx)
537 char buf[LONG_STRING];
538 char bufout[LONG_STRING];
543 if (imap_parse_path (ctx->path, &mx)) {
544 mutt_error (_("%s is an invalid IMAP path"), ctx->path);
548 /* we require a connection which isn't currently in IMAP_SELECTED state */
549 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NOSELECT)))
551 if (idata->state < IMAP_AUTHENTICATED)
556 /* once again the context is new */
559 /* Clean up path and replace the one in the ctx */
560 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
561 mem_free (&(idata->mailbox));
562 idata->mailbox = str_dup (buf);
563 imap_qualify_path (buf, sizeof (buf), &mx, idata->mailbox);
565 mem_free (&(ctx->path));
566 ctx->path = str_dup (buf);
570 /* clear mailbox status */
572 memset (idata->rights, 0, (RIGHTSMAX + 7) / 8);
573 idata->newMailCount = 0;
575 mutt_message (_("Selecting %s..."), idata->mailbox);
576 imap_munge_mbox_name (buf, sizeof (buf), idata->mailbox);
577 snprintf (bufout, sizeof (bufout), "%s %s",
578 ctx->readonly ? "EXAMINE" : "SELECT", buf);
580 idata->state = IMAP_SELECTED;
582 imap_cmd_start (idata, bufout);
587 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
590 pc = idata->cmd.buf + 2;
592 /* Obtain list of available flags here, may be overridden by a
593 * PERMANENTFLAGS tag in the OK response */
594 if (ascii_strncasecmp ("FLAGS", pc, 5) == 0) {
595 /* don't override PERMANENTFLAGS */
597 debug_print (2, ("Getting mailbox FLAGS\n"));
598 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
602 /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
603 else if (ascii_strncasecmp ("OK [PERMANENTFLAGS", pc, 18) == 0) {
604 debug_print (2, ("Getting mailbox PERMANENTFLAGS\n"));
605 /* safe to call on NULL */
606 mutt_free_list (&(idata->flags));
607 /* skip "OK [PERMANENT" so syntax is the same as FLAGS */
609 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
613 /* save UIDVALIDITY for the header cache */
614 else if (ascii_strncasecmp ("OK [UIDVALIDITY", pc, 14) == 0) {
615 debug_print (2, ("Getting mailbox UIDVALIDITY\n"));
617 pc = imap_next_word (pc);
619 sscanf (pc, "%lu", &(idata->uid_validity));
623 pc = imap_next_word (pc);
624 if (!ascii_strncasecmp ("EXISTS", pc, 6)) {
625 count = idata->newMailCount;
626 idata->newMailCount = 0;
630 while (rc == IMAP_CMD_CONTINUE);
632 if (rc == IMAP_CMD_NO) {
635 s = imap_next_word (idata->cmd.buf); /* skip seq */
636 s = imap_next_word (s); /* Skip response */
637 mutt_error ("%s", s);
642 if (rc != IMAP_CMD_OK)
645 /* check for READ-ONLY notification */
646 if (!ascii_strncasecmp
647 (imap_get_qualifier (idata->cmd.buf), "[READ-ONLY]", 11)
648 && !mutt_bit_isset (idata->capabilities, ACL)) {
649 debug_print (2, ("Mailbox is read-only.\n"));
654 /* dump the mailbox flags we've found */
655 if (DebugLevel > 2) {
657 debug_print (3, ("No folder flags found\n"));
659 LIST *t = idata->flags;
661 debug_print (3, ("Mailbox flags:\n"));
665 debug_print (3, ("[%s]\n", t->data));
672 if (mutt_bit_isset (idata->capabilities, ACL)) {
673 if (imap_check_acl (idata))
675 if (!(mutt_bit_isset (idata->rights, ACL_DELETE) ||
676 mutt_bit_isset (idata->rights, ACL_SEEN) ||
677 mutt_bit_isset (idata->rights, ACL_WRITE) ||
678 mutt_bit_isset (idata->rights, ACL_INSERT)))
681 /* assume we have all rights if ACL is unavailable */
683 mutt_bit_set (idata->rights, ACL_LOOKUP);
684 mutt_bit_set (idata->rights, ACL_READ);
685 mutt_bit_set (idata->rights, ACL_SEEN);
686 mutt_bit_set (idata->rights, ACL_WRITE);
687 mutt_bit_set (idata->rights, ACL_INSERT);
688 mutt_bit_set (idata->rights, ACL_POST);
689 mutt_bit_set (idata->rights, ACL_CREATE);
690 mutt_bit_set (idata->rights, ACL_DELETE);
694 ctx->hdrs = mem_calloc (count, sizeof (HEADER *));
695 ctx->v2r = mem_calloc (count, sizeof (int));
697 if (count && (imap_read_headers (idata, 0, count - 1) < 0)) {
698 mutt_error _("Error opening mailbox");
704 debug_print (2, ("msgcount is %d\n", ctx->msgcount));
709 if (idata->state == IMAP_SELECTED)
710 idata->state = IMAP_AUTHENTICATED;
716 int imap_open_mailbox_append (CONTEXT * ctx)
720 char buf[LONG_STRING];
721 char mailbox[LONG_STRING];
724 if (imap_parse_path (ctx->path, &mx))
727 /* in APPEND mode, we appear to hijack an existing IMAP connection -
728 * ctx is brand new and mostly empty */
730 if (!(idata = imap_conn_find (&(mx.account), 0))) {
739 imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
743 /* really we should also check for W_OK */
744 if (!imap_access (ctx->path, F_OK))
747 snprintf (buf, sizeof (buf), _("Create %s?"), mailbox);
748 if (option (OPTCONFIRMCREATE) && mutt_yesorno (buf, 1) < 1)
751 if (imap_create_mailbox (idata, mailbox) < 0)
757 /* imap_logout: Gracefully log out of server. */
758 void imap_logout (IMAP_DATA * idata)
760 /* we set status here to let imap_handle_untagged know we _expect_ to
761 * receive a bye response (so it doesn't freak out and close the conn) */
762 idata->status = IMAP_BYE;
763 imap_cmd_start (idata, "LOGOUT");
764 while (imap_cmd_step (idata) == IMAP_CMD_CONTINUE);
765 mem_free (&idata->cmd.buf);
770 int imap_close_connection (CONTEXT *ctx)
772 debug_print (1, (debugfile, "imap_close_connection(): closing connection\n"));
773 if (CTX_DATA->status != IMAP_BYE)
775 mutt_message _("Closing connection to IMAP server...");
776 imap_logout (CTX_DATA);
779 mutt_socket_close (CTX_DATA->conn);
780 CTX_DATA->state = IMAP_DISCONNECTED;
781 CTX_DATA->conn->data = NULL;
786 /* imap_set_flag: append str to flags if we currently have permission
787 * according to aclbit */
788 static void imap_set_flag (IMAP_DATA * idata, int aclbit, int flag,
789 const char *str, char *flags, size_t flsize)
791 if (mutt_bit_isset (idata->rights, aclbit))
793 str_cat (flags, flsize, str);
796 /* imap_make_msg_set: make an IMAP4rev1 UID message set out of a set of
797 * headers, given a flag enum to filter on.
798 * Params: idata: IMAP_DATA containing context containing header set
799 * buf: to write message set into
800 * buflen: length of buffer
801 * flag: enum of flag type on which to filter
802 * changed: include only changed messages in message set
803 * Returns: number of messages in message set (0 if no matches) */
804 int imap_make_msg_set (IMAP_DATA * idata, BUFFER * buf, int flag, int changed)
806 HEADER **hdrs; /* sorted local copy */
807 int count = 0; /* number of messages in message set */
808 int match = 0; /* whether current message matches flag condition */
809 unsigned int setstart = 0; /* start of current message range */
811 short oldsort; /* we clobber reverse, must restore it */
813 /* assuming 32-bit UIDs */
817 /* make copy of header pointers to sort in natural order */
818 hdrs = mem_calloc (idata->ctx->msgcount, sizeof (HEADER *));
819 memcpy (hdrs, idata->ctx->hdrs, idata->ctx->msgcount * sizeof (HEADER *));
821 if (Sort != SORT_ORDER) {
824 qsort ((void *) hdrs, idata->ctx->msgcount, sizeof (HEADER *),
825 mutt_get_sort_func (SORT_ORDER));
829 for (n = 0; n < idata->ctx->msgcount; n++) {
831 /* don't include pending expunged messages */
835 if (hdrs[n]->deleted)
844 if (match && (!changed || hdrs[n]->changed)) {
847 setstart = HEADER_DATA (hdrs[n])->uid;
849 snprintf (uid, sizeof (uid), "%u", HEADER_DATA (hdrs[n])->uid);
850 mutt_buffer_addstr (buf, uid);
854 snprintf (uid, sizeof (uid), ",%u", HEADER_DATA (hdrs[n])->uid);
855 mutt_buffer_addstr (buf, uid);
858 /* tie up if the last message also matches */
859 else if (n == idata->ctx->msgcount - 1) {
860 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n])->uid);
861 mutt_buffer_addstr (buf, uid);
864 /* this message is not expunged and doesn't match. End current set. */
865 else if (setstart && hdrs[n]->active) {
866 if (HEADER_DATA (hdrs[n - 1])->uid > setstart) {
867 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n - 1])->uid);
868 mutt_buffer_addstr (buf, uid);
879 /* Update the IMAP server to reflect the flags a single message. */
881 int imap_sync_message (IMAP_DATA *idata, HEADER *hdr, BUFFER *cmd,
884 char flags[LONG_STRING];
889 snprintf (uid, sizeof (uid), "%u", HEADER_DATA(hdr)->uid);
890 cmd->dptr = cmd->data;
891 mutt_buffer_addstr (cmd, "UID STORE ");
892 mutt_buffer_addstr (cmd, uid);
896 imap_set_flag (idata, ACL_SEEN, hdr->read, "\\Seen ",
897 flags, sizeof (flags));
898 imap_set_flag (idata, ACL_WRITE, hdr->flagged,
899 "\\Flagged ", flags, sizeof (flags));
900 imap_set_flag (idata, ACL_WRITE, hdr->replied,
901 "\\Answered ", flags, sizeof (flags));
902 imap_set_flag (idata, ACL_DELETE, hdr->deleted,
903 "\\Deleted ", flags, sizeof (flags));
905 /* now make sure we don't lose custom tags */
906 if (mutt_bit_isset (idata->rights, ACL_WRITE))
907 imap_add_keywords (flags, hdr, idata->flags, sizeof (flags));
909 str_skip_trailws (flags);
911 /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to
912 * explicitly revoke all system flags (if we have permission) */
915 imap_set_flag (idata, ACL_SEEN, 1, "\\Seen ", flags, sizeof (flags));
916 imap_set_flag (idata, ACL_WRITE, 1, "\\Flagged ", flags, sizeof (flags));
917 imap_set_flag (idata, ACL_WRITE, 1, "\\Answered ", flags, sizeof (flags));
918 imap_set_flag (idata, ACL_DELETE, 1, "\\Deleted ", flags, sizeof (flags));
920 str_skip_trailws (flags);
922 mutt_buffer_addstr (cmd, " -FLAGS.SILENT (");
924 mutt_buffer_addstr (cmd, " FLAGS.SILENT (");
926 mutt_buffer_addstr (cmd, flags);
927 mutt_buffer_addstr (cmd, ")");
929 /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */
932 /* after all this it's still possible to have no flags, if you
933 * have no ACL rights */
934 if (*flags && (imap_exec (idata, cmd->data, 0) != 0) &&
935 err_continue && (*err_continue != M_YES))
937 *err_continue = imap_continue ("imap_sync_message: STORE failed",
939 if (*err_continue != M_YES)
944 idata->ctx->changed--;
949 /* update the IMAP server to reflect message changes done within mutt.
951 * ctx: the current context
952 * expunge: 0 or 1 - do expunge?
955 int imap_sync_mailbox (CONTEXT * ctx, int expunge, int *index_hint)
958 CONTEXT *appendctx = NULL;
962 int err_continue = M_NO; /* continue on error? */
965 idata = (IMAP_DATA *) ctx->data;
967 if (idata->state != IMAP_SELECTED) {
968 debug_print (2, ("no mailbox selected\n"));
972 /* This function is only called when the calling code expects the context
974 imap_allow_reopen (ctx);
976 if ((rc = imap_check_mailbox (ctx, index_hint, 0)) != 0)
979 memset (&cmd, 0, sizeof (cmd));
981 /* if we are expunging anyway, we can do deleted messages very quickly... */
982 if (expunge && mutt_bit_isset (idata->rights, ACL_DELETE)) {
983 mutt_buffer_addstr (&cmd, "UID STORE ");
984 deleted = imap_make_msg_set (idata, &cmd, M_DELETE, 1);
986 /* if we have a message set, then let's delete */
988 mutt_message (_("Marking %d messages deleted..."), deleted);
989 mutt_buffer_addstr (&cmd, " +FLAGS.SILENT (\\Deleted)");
990 /* mark these messages as unchanged so second pass ignores them. Done
991 * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */
992 for (n = 0; n < ctx->msgcount; n++)
993 if (ctx->hdrs[n]->deleted && ctx->hdrs[n]->changed)
994 ctx->hdrs[n]->active = 0;
995 if (imap_exec (idata, cmd.data, 0) != 0) {
996 mutt_error (_("Expunge failed"));
1004 /* save status changes */
1005 for (n = 0; n < ctx->msgcount; n++) {
1006 if (ctx->hdrs[n]->active && ctx->hdrs[n]->changed) {
1008 mutt_message (_("Saving message status flags... [%d/%d]"), n + 1,
1011 /* if the message has been rethreaded or attachments have been deleted
1012 * we delete the message and reupload it.
1013 * This works better if we're expunging, of course. */
1014 if ((ctx->hdrs[n]->env && (ctx->hdrs[n]->env->refs_changed || ctx->hdrs[n]->env->irt_changed)) ||
1015 ctx->hdrs[n]->attach_del) {
1016 debug_print (3, ("Attachments to be deleted, falling back to _mutt_save_message\n"));
1018 appendctx = mx_open_mailbox (ctx->path, M_APPEND | M_QUIET, NULL);
1020 debug_print (1, ("Error opening mailbox in append mode\n"));
1023 _mutt_save_message (ctx->hdrs[n], appendctx, 1, 0, 0);
1026 if (imap_sync_message (idata, ctx->hdrs[n], &cmd, &err_continue) < 0) {
1034 /* We must send an EXPUNGE command if we're not closing. */
1035 if (expunge && !(ctx->closing) &&
1036 mutt_bit_isset (idata->rights, ACL_DELETE)) {
1037 mutt_message _("Expunging messages from server...");
1039 /* Set expunge bit so we don't get spurious reopened messages */
1040 idata->reopen |= IMAP_EXPUNGE_EXPECTED;
1041 if (imap_exec (idata, "EXPUNGE", 0) != 0) {
1042 imap_error (_("imap_sync_mailbox: EXPUNGE failed"), idata->cmd.buf);
1043 rc = imap_reconnect (ctx);
1048 if (expunge && ctx->closing) {
1049 if (imap_exec (idata, "CLOSE", 0))
1050 mutt_error (_("CLOSE failed"));
1051 idata->state = IMAP_AUTHENTICATED;
1057 mem_free (&cmd.data);
1059 mx_fastclose_mailbox (appendctx);
1060 mem_free (&appendctx);
1065 /* imap_close_mailbox: clean up IMAP data in CONTEXT */
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 (ctx == idata->ctx) {
1077 if (idata->state != IMAP_FATAL && idata->state == IMAP_SELECTED) {
1078 /* mx_close_mailbox won't sync if there are no deleted messages
1079 * and the mailbox is unchanged, so we may have to close here */
1080 if (!ctx->deleted && imap_exec (idata, "CLOSE", 0))
1081 mutt_error (_("CLOSE failed"));
1082 idata->state = IMAP_AUTHENTICATED;
1085 idata->reopen &= IMAP_REOPEN_ALLOW;
1086 mem_free (&(idata->mailbox));
1087 mutt_free_list (&idata->flags);
1091 /* free IMAP part of headers */
1092 for (i = 0; i < ctx->msgcount; i++)
1093 imap_free_header_data (&(ctx->hdrs[i]->data));
1095 for (i = 0; i < IMAP_CACHE_LEN; i++) {
1096 if (idata->cache[i].path) {
1097 unlink (idata->cache[i].path);
1098 mem_free (&idata->cache[i].path);
1103 /* use the NOOP command to poll for new mail
1106 * M_REOPENED mailbox has been externally modified
1107 * M_NEW_MAIL new mail has arrived!
1111 int imap_check_mailbox (CONTEXT * ctx, int *index_hint, int force)
1113 /* overload keyboard timeout to avoid many mailbox checks in a row.
1114 * Most users don't like having to wait exactly when they press a key. */
1118 idata = (IMAP_DATA *) ctx->data;
1120 if ((force || time (NULL) >= idata->lastread + Timeout)
1121 && imap_exec (idata, "NOOP", 0) != 0)
1124 /* We call this even when we haven't run NOOP in case we have pending
1125 * changes to process, since we can reopen here. */
1126 imap_cmd_finish (idata);
1128 if (idata->check_status & IMAP_EXPUNGE_PENDING)
1129 result = M_REOPENED;
1130 else if (idata->check_status & IMAP_NEWMAIL_PENDING)
1131 result = M_NEW_MAIL;
1132 else if (idata->check_status & IMAP_FLAGS_PENDING)
1135 idata->check_status = 0;
1140 /* returns count of recent messages if new = 1, else count of total messages.
1141 * (useful for at least postponed function)
1142 * Question of taste: use RECENT or UNSEEN for new?
1143 * 0+ number of messages in mailbox
1144 * -1 error while polling mailboxes
1146 int imap_mailbox_check (char *path, int new)
1150 char buf[LONG_STRING];
1151 char mbox[LONG_STRING];
1152 char mbox_unquoted[LONG_STRING];
1159 if (imap_parse_path (path, &mx))
1162 /* If imap_passive is set, don't open a connection to check for new mail */
1163 if (option (OPTIMAPPASSIVE))
1164 connflags = M_IMAP_CONN_NONEW;
1166 if (!(idata = imap_conn_find (&(mx.account), connflags))) {
1167 mem_free (&mx.mbox);
1172 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1173 mem_free (&mx.mbox);
1175 imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1176 strfcpy (mbox_unquoted, buf, sizeof (mbox_unquoted));
1178 /* The draft IMAP implementor's guide warns againts using the STATUS
1179 * command on a mailbox that you have selected
1182 if (str_cmp (mbox_unquoted, idata->mailbox) == 0
1183 || (ascii_strcasecmp (mbox_unquoted, "INBOX") == 0
1184 && str_casecmp (mbox_unquoted, idata->mailbox) == 0)) {
1185 strfcpy (buf, "NOOP", sizeof (buf));
1187 else if (mutt_bit_isset (idata->capabilities, IMAP4REV1) ||
1188 mutt_bit_isset (idata->capabilities, STATUS)) {
1189 snprintf (buf, sizeof (buf), "STATUS %s (%s)", mbox,
1190 new ? "RECENT" : "MESSAGES");
1193 /* Server does not support STATUS, and this is not the current mailbox.
1194 * There is no lightweight way to check recent arrivals */
1197 imap_cmd_start (idata, buf);
1200 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
1203 s = imap_next_word (idata->cmd.buf);
1204 if (ascii_strncasecmp ("STATUS", s, 6) == 0) {
1205 s = imap_next_word (s);
1206 /* The mailbox name may or may not be quoted here. We could try to
1207 * munge the server response and compare with quoted (or vise versa)
1208 * but it is probably more efficient to just strncmp against both. */
1209 if (str_ncmp (mbox_unquoted, s, str_len (mbox_unquoted)) == 0
1210 || str_ncmp (mbox, s, str_len (mbox)) == 0) {
1211 s = imap_next_word (s);
1212 s = imap_next_word (s);
1213 if (isdigit ((unsigned char) *s)) {
1215 msgcount = atoi (s);
1216 debug_print (2, ("%d new messages in %s\n", msgcount, path));
1221 debug_print (1, ("STATUS response doesn't match requested mailbox.\n"));
1224 while (rc == IMAP_CMD_CONTINUE);
1229 /* all this listing/browsing is a mess. I don't like that name is a pointer
1230 * into idata->buf (used to be a pointer into the passed in buffer, just
1231 * as bad), nor do I like the fact that the fetch is done here. This
1232 * code can't possibly handle non-LIST untagged responses properly.
1234 int imap_parse_list_response (IMAP_DATA * idata, char **name, int *noselect,
1235 int *noinferiors, char *delim)
1243 rc = imap_cmd_step (idata);
1244 if (rc == IMAP_CMD_OK)
1246 if (rc != IMAP_CMD_CONTINUE)
1249 s = imap_next_word (idata->cmd.buf);
1250 if ((ascii_strncasecmp ("LIST", s, 4) == 0) ||
1251 (ascii_strncasecmp ("LSUB", s, 4) == 0)) {
1255 s = imap_next_word (s); /* flags */
1261 while (*ep && *ep != ')')
1264 if (!ascii_strncasecmp (s, "\\NoSelect", 9))
1266 if (!ascii_strncasecmp (s, "\\NoInferiors", 12))
1268 /* See draft-gahrns-imap-child-mailbox-?? */
1269 if (!ascii_strncasecmp (s, "\\HasNoChildren", 14))
1273 while (*s && *s != '\\' && *s != ')')
1279 s = imap_next_word (s); /* delim */
1280 /* Reset the delimiter, this can change */
1281 if (ascii_strncasecmp (s, "NIL", 3)) {
1282 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
1284 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
1288 s = imap_next_word (s); /* name */
1289 if (s && *s == '{') { /* Literal */
1290 if (imap_get_literal_count (idata->cmd.buf, &bytes) < 0)
1292 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
1294 *name = idata->cmd.buf;
1303 int imap_subscribe (char *path, int subscribe)
1307 char buf[LONG_STRING];
1308 char mbox[LONG_STRING];
1309 char errstr[STRING];
1313 if (mx_get_magic (path) == M_IMAP || imap_parse_path (path, &mx)) {
1314 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 if (option (OPTIMAPCHECKSUBSCRIBED)) {
1326 memset (&token, 0, sizeof (token));
1328 err.dsize = sizeof (errstr);
1329 snprintf (mbox, sizeof (mbox), "%smailboxes \"%s\"",
1330 subscribe ? "" : "un", path);
1331 if (mutt_parse_rc_line (mbox, &token, &err))
1332 debug_print (1, ("Error adding subscribed mailbox: %s\n", errstr));
1333 mem_free (&token.data);
1337 mutt_message (_("Subscribing to %s..."), buf);
1339 mutt_message (_("Unsubscribing to %s..."), buf);
1340 imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1342 snprintf (buf, sizeof (buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);
1344 if (imap_exec (idata, buf, 0) < 0)
1347 mem_free (&mx.mbox);
1351 mem_free (&mx.mbox);
1355 /* trim dest to the length of the longest prefix it shares with src,
1356 * returning the length of the trimmed string */
1357 static int longest_common_prefix (char *dest, const char* src,
1358 int start, size_t dlen) {
1361 while (pos < dlen && dest[pos] && dest[pos] == src[pos])
1368 /* look for IMAP URLs to complete from defined mailboxes. Could be extended
1369 * to complete over open connections and account/folder hooks too. */
1370 static int imap_complete_hosts (char *dest, size_t len) {
1377 matchlen = str_len (dest);
1378 if (list_empty (Incoming))
1380 for (i = 0; i < Incoming->length; i++) {
1381 mailbox = (BUFFY*) Incoming->data[i];
1382 if (!str_ncmp (dest, mailbox->path, matchlen)) {
1384 strfcpy (dest, mailbox->path, len);
1387 longest_common_prefix (dest, mailbox->path, matchlen, len);
1391 for (conn = mutt_socket_head (); conn->next; conn = conn->next) {
1393 char urlstr[LONG_STRING];
1395 if (conn->account.type != M_ACCT_TYPE_IMAP)
1398 mutt_account_tourl (&conn->account, &url);
1399 /* FIXME: how to handle multiple users on the same host? */
1402 url_ciss_tostring (&url, urlstr, sizeof (urlstr), 0);
1403 if (!str_ncmp (dest, urlstr, matchlen)) {
1405 strfcpy (dest, urlstr, len);
1408 longest_common_prefix (dest, urlstr, matchlen, len);
1415 /* imap_complete: given a partial IMAP folder path, return a string which
1416 * adds as much to the path as is unique */
1417 int imap_complete (char *dest, size_t dlen, char *path) {
1420 char list[LONG_STRING];
1421 char buf[LONG_STRING];
1422 char *list_word = NULL;
1423 int noselect, noinferiors;
1425 char completion[LONG_STRING];
1426 int clen, matchlen = 0;
1427 int completions = 0;
1430 if (imap_parse_path (path, &mx) || !mx.mbox) {
1431 strfcpy (dest, path, dlen);
1432 return imap_complete_hosts (dest, dlen);
1435 /* don't open a new socket just for completion. Instead complete over
1436 * known mailboxes/hooks/etc */
1437 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NONEW))) {
1438 mem_free (&mx.mbox);
1439 strfcpy (dest, path, dlen);
1440 return imap_complete_hosts (dest, dlen);
1444 /* reformat path for IMAP list, and append wildcard */
1445 /* don't use INBOX in place of "" */
1446 if (mx.mbox && mx.mbox[0])
1447 imap_fix_path (idata, mx.mbox, list, sizeof (list));
1451 /* fire off command */
1452 snprintf (buf, sizeof (buf), "%s \"\" \"%s%%\"",
1453 option (OPTIMAPLSUB) ? "LSUB" : "LIST", list);
1455 imap_cmd_start (idata, buf);
1457 /* and see what the results are */
1458 strfcpy (completion, NONULL (mx.mbox), sizeof (completion));
1460 if (imap_parse_list_response (idata, &list_word, &noselect, &noinferiors,
1465 /* store unquoted */
1466 imap_unmunge_mbox_name (list_word);
1468 /* if the folder isn't selectable, append delimiter to force browse
1469 * to enter it on second tab. */
1471 clen = str_len (list_word);
1472 list_word[clen++] = delim;
1473 list_word[clen] = '\0';
1475 /* copy in first word */
1477 strfcpy (completion, list_word, sizeof (completion));
1478 matchlen = str_len (completion);
1483 matchlen = longest_common_prefix (completion, list_word, 0, matchlen);
1487 while (ascii_strncmp (idata->cmd.seq, idata->cmd.buf, SEQLEN));
1490 /* reformat output */
1491 imap_qualify_path (dest, dlen, &mx, completion);
1492 mutt_pretty_mailbox (dest);
1494 mem_free (&mx.mbox);
1501 /* reconnect if connection was lost */
1502 int imap_reconnect (CONTEXT * ctx)
1504 IMAP_DATA *imap_data;
1509 imap_data = (IMAP_DATA *) ctx->data;
1512 if (imap_data->status == IMAP_CONNECTED)
1516 if (query_quadoption
1518 _("Connection lost. Reconnect to IMAP server?")) != M_YES)
1521 mx_open_mailbox (ctx->path, 0, ctx);