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"
34 #include "lib/debug.h"
40 #include <sys/types.h>
43 /* imap forward declarations */
44 static int imap_get_delim (IMAP_DATA * idata);
45 static char *imap_get_flags (LIST ** hflags, char *s);
46 static int imap_check_acl (IMAP_DATA * idata);
47 static int imap_check_capabilities (IMAP_DATA * idata);
48 static void imap_set_flag (IMAP_DATA * idata, int aclbit, int flag,
49 const char *str, char *flags, size_t flsize);
51 /* imap_access: Check permissions on an IMAP mailbox.
52 * TODO: ACL checks. Right now we assume if it exists we can
54 int imap_access (const char *path, int flags)
58 char buf[LONG_STRING];
59 char mailbox[LONG_STRING];
60 char mbox[LONG_STRING];
62 if (imap_parse_path (path, &mx))
65 if (!(idata = imap_conn_find (&mx.account,
66 option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW :
72 imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
74 /* we may already be in the folder we're checking */
75 if (!ascii_strcmp(idata->mailbox, mx.mbox)) {
81 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
83 if (mutt_bit_isset (idata->capabilities, IMAP4REV1))
84 snprintf (buf, sizeof (buf), "STATUS %s (UIDVALIDITY)", mbox);
85 else if (mutt_bit_isset (idata->capabilities, STATUS))
86 snprintf (buf, sizeof (buf), "STATUS %s (UID-VALIDITY)", mbox);
88 debug_print (2, ("STATUS not supported?\n"));
92 if (imap_exec (idata, buf, IMAP_CMD_FAIL_OK) < 0) {
93 debug_print (1, ("Can't check STATUS of %s\n", mbox));
100 int imap_create_mailbox (IMAP_DATA * idata, char *mailbox)
102 char buf[LONG_STRING], mbox[LONG_STRING];
104 imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
105 snprintf (buf, sizeof (buf), "CREATE %s", mbox);
107 if (imap_exec (idata, buf, 0) != 0)
113 int imap_rename_mailbox (IMAP_DATA * idata, IMAP_MBOX * mx,
116 char oldmbox[LONG_STRING];
117 char newmbox[LONG_STRING];
118 char buf[LONG_STRING];
120 imap_munge_mbox_name (oldmbox, sizeof (oldmbox), mx->mbox);
121 imap_munge_mbox_name (newmbox, sizeof (newmbox), newname);
123 snprintf (buf, sizeof (buf), "RENAME %s %s", oldmbox, newmbox);
125 if (imap_exec (idata, buf, 0) != 0)
131 int imap_delete_mailbox (CONTEXT * ctx, IMAP_MBOX mx)
133 char buf[LONG_STRING], mbox[LONG_STRING];
136 if (!ctx || !ctx->data) {
137 if (!(idata = imap_conn_find (&mx.account,
138 option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW
148 imap_munge_mbox_name (mbox, sizeof (mbox), mx.mbox);
149 snprintf (buf, sizeof (buf), "DELETE %s", mbox);
151 if (imap_exec ((IMAP_DATA *) idata, buf, 0) != 0)
157 /* imap_logout_all: close all open connections. Quick and dirty until we can
158 * make sure we've got all the context we need. */
159 void imap_logout_all (void)
164 conn = mutt_socket_head ();
169 if (conn->account.type == M_ACCT_TYPE_IMAP && conn->fd >= 0) {
170 mutt_message (_("Closing connection to %s..."), conn->account.host);
171 imap_logout ((IMAP_DATA *) conn->data);
173 mutt_socket_close (conn);
174 mutt_socket_free (conn);
181 /* imap_read_literal: read bytes bytes from server into file. Not explicitly
182 * buffered, relies on FILE buffering. NOTE: strips \r from \r\n.
183 * Apparently even literals use \r\n-terminated strings ?! */
184 int imap_read_literal (FILE * fp, IMAP_DATA * idata, long bytes)
191 debug_print (2, ("reading %ld bytes\n", bytes));
193 for (pos = 0; pos < bytes; pos++) {
194 if (mutt_socket_readchar (idata->conn, &c) != 1) {
195 debug_print (1, ("error during read, %ld bytes read\n", pos));
196 idata->status = IMAP_FATAL;
202 if (r == 1 && c != '\n')
214 if (DebugLevel >= IMAP_LOG_LTRL)
215 fputc (c, DebugFile);
222 /* imap_expunge_mailbox: Purge IMAP portion of expunged messages from the
223 * context. Must not be done while something has a handle on any headers
224 * (eg inside pager or editor). That is, check IMAP_REOPEN_ALLOW. */
225 void imap_expunge_mailbox (IMAP_DATA * idata)
230 for (i = 0; i < idata->ctx->msgcount; i++) {
231 h = idata->ctx->hdrs[i];
233 if (h->index == -1) {
234 debug_print (2, ("Expunging message UID %d.\n", HEADER_DATA (h)->uid));
238 /* free cached body from disk, if neccessary */
239 cacheno = HEADER_DATA (h)->uid % IMAP_CACHE_LEN;
240 if (idata->cache[cacheno].uid == HEADER_DATA (h)->uid &&
241 idata->cache[cacheno].path) {
242 unlink (idata->cache[cacheno].path);
243 mem_free (&idata->cache[cacheno].path);
246 imap_free_header_data (&h->data);
250 /* We may be called on to expunge at any time. We can't rely on the caller
251 * to always know to rethread */
252 mx_update_tables (idata->ctx, 0);
253 mutt_sort_headers (idata->ctx, 1);
256 static int imap_get_delim (IMAP_DATA * idata)
261 /* assume that the delim is /. If this fails, we're in bigger trouble
262 * than getting the delim wrong */
265 imap_cmd_start (idata, "LIST \"\" \"\"");
268 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
271 s = imap_next_word (idata->cmd.buf);
272 if (ascii_strncasecmp ("LIST", s, 4) == 0) {
273 s = imap_next_word (s);
274 s = imap_next_word (s);
275 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
277 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
282 while (rc == IMAP_CMD_CONTINUE);
284 if (rc != IMAP_CMD_OK) {
285 debug_print (1, ("failed.\n"));
289 debug_print (2, ("Delimiter: %c\n", idata->delim));
294 /* get rights for folder, let imap_handle_untagged do the rest */
295 static int imap_check_acl (IMAP_DATA * idata)
297 char buf[LONG_STRING];
298 char mbox[LONG_STRING];
300 imap_munge_mbox_name (mbox, sizeof (mbox), idata->mailbox);
301 snprintf (buf, sizeof (buf), "MYRIGHTS %s", mbox);
302 if (imap_exec (idata, buf, 0) != 0) {
303 imap_error ("imap_check_acl", buf);
309 /* imap_check_capabilities: make sure we can log in to this server. */
310 static int imap_check_capabilities (IMAP_DATA * idata)
312 if (imap_exec (idata, "CAPABILITY", 0) != 0) {
313 imap_error ("imap_check_capabilities", idata->cmd.buf);
317 if (!(mutt_bit_isset (idata->capabilities, IMAP4)
318 || mutt_bit_isset (idata->capabilities, IMAP4REV1))) {
319 mutt_error _("This IMAP server is ancient. Mutt does not work with it.");
321 mutt_sleep (2); /* pause a moment to let the user see the error */
329 /* imap_conn_find: Find an open IMAP connection matching account, or open
330 * a new one if none can be found. */
331 IMAP_DATA *imap_conn_find (const ACCOUNT * account, int flags)
338 if (!(conn = mutt_conn_find (NULL, account)))
341 /* if opening a new UNSELECTED connection, preserve existing creds */
342 creds = &(conn->account);
344 /* make sure this connection is not in SELECTED state, if neccessary */
345 if (flags & M_IMAP_CONN_NOSELECT)
346 while (conn->data && ((IMAP_DATA *) conn->data)->state == IMAP_SELECTED) {
347 if (!(conn = mutt_conn_find (conn, account)))
349 memcpy (&(conn->account), creds, sizeof (ACCOUNT));
352 idata = (IMAP_DATA *) conn->data;
354 /* don't open a new connection if one isn't wanted */
355 if (flags & M_IMAP_CONN_NONEW) {
357 mutt_socket_free (conn);
360 if (idata->state < IMAP_AUTHENTICATED)
365 /* The current connection is a new connection */
366 if (!(idata = imap_new_idata ())) {
367 mutt_socket_free (conn);
376 if (idata->state == IMAP_DISCONNECTED)
377 imap_open_connection (idata);
378 if (idata->state == IMAP_CONNECTED) {
379 if (!imap_authenticate (idata)) {
380 idata->state = IMAP_AUTHENTICATED;
381 if (idata->conn->ssf)
382 debug_print (2, ("Communication encrypted at %d bits\n", idata->conn->ssf));
385 mutt_account_unsetpass (&idata->conn->account);
387 mem_free (&idata->capstr);
389 if (new && idata->state == IMAP_AUTHENTICATED) {
390 imap_get_delim (idata);
391 if (option (OPTIMAPCHECKSUBSCRIBED)) {
392 mutt_message _("Checking mailbox subscriptions");
393 imap_exec (idata, "LSUB \"\" \"*\"", 0);
400 int imap_open_connection (IMAP_DATA * idata)
402 char buf[LONG_STRING];
404 if (mutt_socket_open (idata->conn) < 0)
407 idata->state = IMAP_CONNECTED;
409 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE) {
410 mutt_socket_close (idata->conn);
411 idata->state = IMAP_DISCONNECTED;
415 if (ascii_strncasecmp ("* OK", idata->cmd.buf, 4) == 0) {
416 /* TODO: Parse new tagged CAPABILITY data (* OK [CAPABILITY...]) */
417 if (imap_check_capabilities (idata))
419 #if defined(USE_SSL) || defined(USE_GNUTLS)
420 /* Attempt STARTTLS if available and desired. */
421 if (!idata->conn->ssf && (option(OPTSSLFORCETLS) ||
422 mutt_bit_isset (idata->capabilities, STARTTLS))) {
425 if (option (OPTSSLFORCETLS))
427 else if ((rc = query_quadoption (OPT_SSLSTARTTLS,
428 _("Secure connection with TLS?"))) == -1)
431 if ((rc = imap_exec (idata, "STARTTLS", IMAP_CMD_FAIL_OK)) == -1)
435 if (mutt_ssl_starttls (idata->conn))
437 if (mutt_gnutls_starttls (idata->conn))
440 mutt_error (_("Could not negotiate TLS connection"));
445 /* RFC 2595 demands we recheck CAPABILITY after TLS completes. */
446 if (imap_exec (idata, "CAPABILITY", 0))
453 if (option(OPTSSLFORCETLS) && ! idata->conn->ssf) {
454 mutt_error _("Encrypted connection unavailable");
460 else if (ascii_strncasecmp ("* PREAUTH", idata->cmd.buf, 9) == 0) {
461 idata->state = IMAP_AUTHENTICATED;
462 if (imap_check_capabilities (idata) != 0)
464 mem_free (&idata->capstr);
467 imap_error ("imap_open_connection()", buf);
474 mutt_socket_close (idata->conn);
475 idata->state = IMAP_DISCONNECTED;
477 mem_free (&idata->capstr);
481 /* imap_get_flags: Make a simple list out of a FLAGS response.
482 * return stream following FLAGS response */
483 static char *imap_get_flags (LIST ** hflags, char *s)
489 /* sanity-check string */
490 if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
491 debug_print (1, ("not a FLAGS response: %s\n", s));
497 debug_print (1, ("bogus FLAGS response: %s\n", s));
501 /* create list, update caller's flags handle */
502 flags = mutt_new_list ();
505 while (*s && *s != ')') {
509 while (*s && (*s != ')') && !ISSPACE (*s))
514 mutt_add_list (flags, flag_word);
518 /* note bad flags response */
520 debug_print (1, ("Unterminated FLAGS response: %s\n", s));
521 mutt_free_list (hflags);
531 int imap_open_mailbox (CONTEXT * ctx)
535 char buf[LONG_STRING];
536 char bufout[LONG_STRING];
541 if (imap_parse_path (ctx->path, &mx)) {
542 mutt_error (_("%s is an invalid IMAP path"), ctx->path);
546 /* we require a connection which isn't currently in IMAP_SELECTED state */
547 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NOSELECT)))
549 if (idata->state < IMAP_AUTHENTICATED)
554 /* once again the context is new */
557 /* Clean up path and replace the one in the ctx */
558 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
559 mem_free (&(idata->mailbox));
560 idata->mailbox = str_dup (buf);
561 imap_qualify_path (buf, sizeof (buf), &mx, idata->mailbox);
563 mem_free (&(ctx->path));
564 ctx->path = str_dup (buf);
568 /* clear mailbox status */
570 memset (idata->rights, 0, (RIGHTSMAX + 7) / 8);
571 idata->newMailCount = 0;
573 mutt_message (_("Selecting %s..."), idata->mailbox);
574 imap_munge_mbox_name (buf, sizeof (buf), idata->mailbox);
575 snprintf (bufout, sizeof (bufout), "%s %s",
576 ctx->readonly ? "EXAMINE" : "SELECT", buf);
578 idata->state = IMAP_SELECTED;
580 imap_cmd_start (idata, bufout);
585 if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
588 pc = idata->cmd.buf + 2;
590 /* Obtain list of available flags here, may be overridden by a
591 * PERMANENTFLAGS tag in the OK response */
592 if (ascii_strncasecmp ("FLAGS", pc, 5) == 0) {
593 /* don't override PERMANENTFLAGS */
595 debug_print (2, ("Getting mailbox FLAGS\n"));
596 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
600 /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
601 else if (ascii_strncasecmp ("OK [PERMANENTFLAGS", pc, 18) == 0) {
602 debug_print (2, ("Getting mailbox PERMANENTFLAGS\n"));
603 /* safe to call on NULL */
604 mutt_free_list (&(idata->flags));
605 /* skip "OK [PERMANENT" so syntax is the same as FLAGS */
607 if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
611 /* save UIDVALIDITY for the header cache */
612 else if (ascii_strncasecmp ("OK [UIDVALIDITY", pc, 14) == 0) {
613 debug_print (2, ("Getting mailbox UIDVALIDITY\n"));
615 pc = imap_next_word (pc);
617 sscanf (pc, "%lu", &(idata->uid_validity));
621 pc = imap_next_word (pc);
622 if (!ascii_strncasecmp ("EXISTS", pc, 6)) {
623 count = idata->newMailCount;
624 idata->newMailCount = 0;
628 while (rc == IMAP_CMD_CONTINUE);
630 if (rc == IMAP_CMD_NO) {
633 s = imap_next_word (idata->cmd.buf); /* skip seq */
634 s = imap_next_word (s); /* Skip response */
635 mutt_error ("%s", s);
640 if (rc != IMAP_CMD_OK)
643 /* check for READ-ONLY notification */
644 if (!ascii_strncasecmp
645 (imap_get_qualifier (idata->cmd.buf), "[READ-ONLY]", 11)
646 && !mutt_bit_isset (idata->capabilities, ACL)) {
647 debug_print (2, ("Mailbox is read-only.\n"));
652 /* dump the mailbox flags we've found */
653 if (DebugLevel > 2) {
655 debug_print (3, ("No folder flags found\n"));
657 LIST *t = idata->flags;
659 debug_print (3, ("Mailbox flags:\n"));
663 debug_print (3, ("[%s]\n", t->data));
670 if (mutt_bit_isset (idata->capabilities, ACL)) {
671 if (imap_check_acl (idata))
673 if (!(mutt_bit_isset (idata->rights, ACL_DELETE) ||
674 mutt_bit_isset (idata->rights, ACL_SEEN) ||
675 mutt_bit_isset (idata->rights, ACL_WRITE) ||
676 mutt_bit_isset (idata->rights, ACL_INSERT)))
679 /* assume we have all rights if ACL is unavailable */
681 mutt_bit_set (idata->rights, ACL_LOOKUP);
682 mutt_bit_set (idata->rights, ACL_READ);
683 mutt_bit_set (idata->rights, ACL_SEEN);
684 mutt_bit_set (idata->rights, ACL_WRITE);
685 mutt_bit_set (idata->rights, ACL_INSERT);
686 mutt_bit_set (idata->rights, ACL_POST);
687 mutt_bit_set (idata->rights, ACL_CREATE);
688 mutt_bit_set (idata->rights, ACL_DELETE);
692 ctx->hdrs = mem_calloc (count, sizeof (HEADER *));
693 ctx->v2r = mem_calloc (count, sizeof (int));
695 if (count && (imap_read_headers (idata, 0, count - 1) < 0)) {
696 mutt_error _("Error opening mailbox");
702 debug_print (2, ("msgcount is %d\n", ctx->msgcount));
707 if (idata->state == IMAP_SELECTED)
708 idata->state = IMAP_AUTHENTICATED;
714 int imap_open_mailbox_append (CONTEXT * ctx)
718 char buf[LONG_STRING];
719 char mailbox[LONG_STRING];
722 if (imap_parse_path (ctx->path, &mx))
725 /* in APPEND mode, we appear to hijack an existing IMAP connection -
726 * ctx is brand new and mostly empty */
728 if (!(idata = imap_conn_find (&(mx.account), 0))) {
737 imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
741 /* really we should also check for W_OK */
742 if (!imap_access (ctx->path, F_OK))
745 snprintf (buf, sizeof (buf), _("Create %s?"), mailbox);
746 if (option (OPTCONFIRMCREATE) && mutt_yesorno (buf, 1) < 1)
749 if (imap_create_mailbox (idata, mailbox) < 0)
755 /* imap_logout: Gracefully log out of server. */
756 void imap_logout (IMAP_DATA * idata)
758 /* we set status here to let imap_handle_untagged know we _expect_ to
759 * receive a bye response (so it doesn't freak out and close the conn) */
760 idata->status = IMAP_BYE;
761 imap_cmd_start (idata, "LOGOUT");
762 while (imap_cmd_step (idata) == IMAP_CMD_CONTINUE);
763 mem_free (&idata->cmd.buf);
768 int imap_close_connection (CONTEXT *ctx)
770 debug_print (1, (debugfile, "imap_close_connection(): closing connection\n"));
771 if (CTX_DATA->status != IMAP_BYE)
773 mutt_message _("Closing connection to IMAP server...");
774 imap_logout (CTX_DATA);
777 mutt_socket_close (CTX_DATA->conn);
778 CTX_DATA->state = IMAP_DISCONNECTED;
779 CTX_DATA->conn->data = NULL;
784 /* imap_set_flag: append str to flags if we currently have permission
785 * according to aclbit */
786 static void imap_set_flag (IMAP_DATA * idata, int aclbit, int flag,
787 const char *str, char *flags, size_t flsize)
789 if (mutt_bit_isset (idata->rights, aclbit))
791 str_cat (flags, flsize, str);
794 /* imap_make_msg_set: make an IMAP4rev1 UID message set out of a set of
795 * headers, given a flag enum to filter on.
796 * Params: idata: IMAP_DATA containing context containing header set
797 * buf: to write message set into
798 * buflen: length of buffer
799 * flag: enum of flag type on which to filter
800 * changed: include only changed messages in message set
801 * Returns: number of messages in message set (0 if no matches) */
802 int imap_make_msg_set (IMAP_DATA * idata, BUFFER * buf, int flag, int changed)
804 HEADER **hdrs; /* sorted local copy */
805 int count = 0; /* number of messages in message set */
806 int match = 0; /* whether current message matches flag condition */
807 unsigned int setstart = 0; /* start of current message range */
809 short oldsort; /* we clobber reverse, must restore it */
811 /* assuming 32-bit UIDs */
815 /* make copy of header pointers to sort in natural order */
816 hdrs = mem_calloc (idata->ctx->msgcount, sizeof (HEADER *));
817 memcpy (hdrs, idata->ctx->hdrs, idata->ctx->msgcount * sizeof (HEADER *));
819 if (Sort != SORT_ORDER) {
822 qsort ((void *) hdrs, idata->ctx->msgcount, sizeof (HEADER *),
823 mutt_get_sort_func (SORT_ORDER));
827 for (n = 0; n < idata->ctx->msgcount; n++) {
829 /* don't include pending expunged messages */
833 if (hdrs[n]->deleted)
842 if (match && (!changed || hdrs[n]->changed)) {
845 setstart = HEADER_DATA (hdrs[n])->uid;
847 snprintf (uid, sizeof (uid), "%u", HEADER_DATA (hdrs[n])->uid);
848 mutt_buffer_addstr (buf, uid);
852 snprintf (uid, sizeof (uid), ",%u", HEADER_DATA (hdrs[n])->uid);
853 mutt_buffer_addstr (buf, uid);
856 /* tie up if the last message also matches */
857 else if (n == idata->ctx->msgcount - 1) {
858 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n])->uid);
859 mutt_buffer_addstr (buf, uid);
862 /* this message is not expunged and doesn't match. End current set. */
863 else if (setstart && hdrs[n]->active) {
864 if (HEADER_DATA (hdrs[n - 1])->uid > setstart) {
865 snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n - 1])->uid);
866 mutt_buffer_addstr (buf, uid);
877 /* Update the IMAP server to reflect the flags a single message. */
879 int imap_sync_message (IMAP_DATA *idata, HEADER *hdr, BUFFER *cmd,
882 char flags[LONG_STRING];
887 snprintf (uid, sizeof (uid), "%u", HEADER_DATA(hdr)->uid);
888 cmd->dptr = cmd->data;
889 mutt_buffer_addstr (cmd, "UID STORE ");
890 mutt_buffer_addstr (cmd, uid);
894 imap_set_flag (idata, ACL_SEEN, hdr->read, "\\Seen ",
895 flags, sizeof (flags));
896 imap_set_flag (idata, ACL_WRITE, hdr->flagged,
897 "\\Flagged ", flags, sizeof (flags));
898 imap_set_flag (idata, ACL_WRITE, hdr->replied,
899 "\\Answered ", flags, sizeof (flags));
900 imap_set_flag (idata, ACL_DELETE, hdr->deleted,
901 "\\Deleted ", flags, sizeof (flags));
903 /* now make sure we don't lose custom tags */
904 if (mutt_bit_isset (idata->rights, ACL_WRITE))
905 imap_add_keywords (flags, hdr, idata->flags, sizeof (flags));
907 str_skip_trailws (flags);
909 /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to
910 * explicitly revoke all system flags (if we have permission) */
913 imap_set_flag (idata, ACL_SEEN, 1, "\\Seen ", flags, sizeof (flags));
914 imap_set_flag (idata, ACL_WRITE, 1, "\\Flagged ", flags, sizeof (flags));
915 imap_set_flag (idata, ACL_WRITE, 1, "\\Answered ", flags, sizeof (flags));
916 imap_set_flag (idata, ACL_DELETE, 1, "\\Deleted ", flags, sizeof (flags));
918 str_skip_trailws (flags);
920 mutt_buffer_addstr (cmd, " -FLAGS.SILENT (");
922 mutt_buffer_addstr (cmd, " FLAGS.SILENT (");
924 mutt_buffer_addstr (cmd, flags);
925 mutt_buffer_addstr (cmd, ")");
927 /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */
930 /* after all this it's still possible to have no flags, if you
931 * have no ACL rights */
932 if (*flags && (imap_exec (idata, cmd->data, 0) != 0) &&
933 err_continue && (*err_continue != M_YES))
935 *err_continue = imap_continue ("imap_sync_message: STORE failed",
937 if (*err_continue != M_YES)
942 idata->ctx->changed--;
947 /* update the IMAP server to reflect message changes done within mutt.
949 * ctx: the current context
950 * expunge: 0 or 1 - do expunge?
953 int imap_sync_mailbox (CONTEXT * ctx, int expunge, int *index_hint)
956 CONTEXT *appendctx = NULL;
960 int err_continue = M_NO; /* continue on error? */
963 idata = (IMAP_DATA *) ctx->data;
965 if (idata->state != IMAP_SELECTED) {
966 debug_print (2, ("no mailbox selected\n"));
970 /* This function is only called when the calling code expects the context
972 imap_allow_reopen (ctx);
974 if ((rc = imap_check_mailbox (ctx, index_hint, 0)) != 0)
977 memset (&cmd, 0, sizeof (cmd));
979 /* if we are expunging anyway, we can do deleted messages very quickly... */
980 if (expunge && mutt_bit_isset (idata->rights, ACL_DELETE)) {
981 mutt_buffer_addstr (&cmd, "UID STORE ");
982 deleted = imap_make_msg_set (idata, &cmd, M_DELETE, 1);
984 /* if we have a message set, then let's delete */
986 mutt_message (_("Marking %d messages deleted..."), deleted);
987 mutt_buffer_addstr (&cmd, " +FLAGS.SILENT (\\Deleted)");
988 /* mark these messages as unchanged so second pass ignores them. Done
989 * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */
990 for (n = 0; n < ctx->msgcount; n++)
991 if (ctx->hdrs[n]->deleted && ctx->hdrs[n]->changed)
992 ctx->hdrs[n]->active = 0;
993 if (imap_exec (idata, cmd.data, 0) != 0) {
994 mutt_error (_("Expunge failed"));
1002 /* save status changes */
1003 for (n = 0; n < ctx->msgcount; n++) {
1004 if (ctx->hdrs[n]->active && ctx->hdrs[n]->changed) {
1006 mutt_message (_("Saving message status flags... [%d/%d]"), n + 1,
1009 /* if the message has been rethreaded or attachments have been deleted
1010 * we delete the message and reupload it.
1011 * This works better if we're expunging, of course. */
1012 if ((ctx->hdrs[n]->env && (ctx->hdrs[n]->env->refs_changed || ctx->hdrs[n]->env->irt_changed)) ||
1013 ctx->hdrs[n]->attach_del) {
1014 debug_print (3, ("Attachments to be deleted, falling back to _mutt_save_message\n"));
1016 appendctx = mx_open_mailbox (ctx->path, M_APPEND | M_QUIET, NULL);
1018 debug_print (1, ("Error opening mailbox in append mode\n"));
1021 _mutt_save_message (ctx->hdrs[n], appendctx, 1, 0, 0);
1024 if (imap_sync_message (idata, ctx->hdrs[n], &cmd, &err_continue) < 0) {
1032 /* We must send an EXPUNGE command if we're not closing. */
1033 if (expunge && !(ctx->closing) &&
1034 mutt_bit_isset (idata->rights, ACL_DELETE)) {
1035 mutt_message _("Expunging messages from server...");
1037 /* Set expunge bit so we don't get spurious reopened messages */
1038 idata->reopen |= IMAP_EXPUNGE_EXPECTED;
1039 if (imap_exec (idata, "EXPUNGE", 0) != 0) {
1040 imap_error (_("imap_sync_mailbox: EXPUNGE failed"), idata->cmd.buf);
1041 rc = imap_reconnect (ctx);
1046 if (expunge && ctx->closing) {
1047 if (imap_exec (idata, "CLOSE", 0))
1048 mutt_error (_("CLOSE failed"));
1049 idata->state = IMAP_AUTHENTICATED;
1055 mem_free (&cmd.data);
1057 mx_fastclose_mailbox (appendctx);
1058 mem_free (&appendctx);
1063 /* imap_close_mailbox: clean up IMAP data in CONTEXT */
1064 void imap_close_mailbox (CONTEXT * ctx)
1069 idata = (IMAP_DATA *) ctx->data;
1070 /* Check to see if the mailbox is actually open */
1074 if (ctx == idata->ctx) {
1075 if (idata->state != IMAP_FATAL && idata->state == IMAP_SELECTED) {
1076 /* mx_close_mailbox won't sync if there are no deleted messages
1077 * and the mailbox is unchanged, so we may have to close here */
1078 if (!ctx->deleted && imap_exec (idata, "CLOSE", 0))
1079 mutt_error (_("CLOSE failed"));
1080 idata->state = IMAP_AUTHENTICATED;
1083 idata->reopen &= IMAP_REOPEN_ALLOW;
1084 mem_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 mem_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))) {
1165 mem_free (&mx.mbox);
1170 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1171 mem_free (&mx.mbox);
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 (str_cmp (mbox_unquoted, idata->mailbox) == 0
1181 || (ascii_strcasecmp (mbox_unquoted, "INBOX") == 0
1182 && str_casecmp (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 (str_ncmp (mbox_unquoted, s, str_len (mbox_unquoted)) == 0
1208 || str_ncmp (mbox, s, str_len (mbox)) == 0) {
1209 s = imap_next_word (s);
1210 s = imap_next_word (s);
1211 if (isdigit ((unsigned char) *s)) {
1213 msgcount = atoi (s);
1214 debug_print (2, ("%d new messages in %s\n", msgcount, path));
1219 debug_print (1, ("STATUS response doesn't match requested mailbox.\n"));
1222 while (rc == IMAP_CMD_CONTINUE);
1227 /* all this listing/browsing is a mess. I don't like that name is a pointer
1228 * into idata->buf (used to be a pointer into the passed in buffer, just
1229 * as bad), nor do I like the fact that the fetch is done here. This
1230 * code can't possibly handle non-LIST untagged responses properly.
1232 int imap_parse_list_response (IMAP_DATA * idata, char **name, int *noselect,
1233 int *noinferiors, char *delim)
1241 rc = imap_cmd_step (idata);
1242 if (rc == IMAP_CMD_OK)
1244 if (rc != IMAP_CMD_CONTINUE)
1247 s = imap_next_word (idata->cmd.buf);
1248 if ((ascii_strncasecmp ("LIST", s, 4) == 0) ||
1249 (ascii_strncasecmp ("LSUB", s, 4) == 0)) {
1253 s = imap_next_word (s); /* flags */
1259 while (*ep && *ep != ')')
1262 if (!ascii_strncasecmp (s, "\\NoSelect", 9))
1264 if (!ascii_strncasecmp (s, "\\NoInferiors", 12))
1266 /* See draft-gahrns-imap-child-mailbox-?? */
1267 if (!ascii_strncasecmp (s, "\\HasNoChildren", 14))
1271 while (*s && *s != '\\' && *s != ')')
1277 s = imap_next_word (s); /* delim */
1278 /* Reset the delimiter, this can change */
1279 if (ascii_strncasecmp (s, "NIL", 3)) {
1280 if (s && s[0] == '\"' && s[1] && s[2] == '\"')
1282 else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
1286 s = imap_next_word (s); /* name */
1287 if (s && *s == '{') { /* Literal */
1288 if (imap_get_literal_count (idata->cmd.buf, &bytes) < 0)
1290 if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
1292 *name = idata->cmd.buf;
1301 int imap_subscribe (char *path, int subscribe)
1305 char buf[LONG_STRING];
1306 char mbox[LONG_STRING];
1307 char errstr[STRING];
1311 if (mx_get_magic (path) == M_IMAP || imap_parse_path (path, &mx)) {
1312 mutt_error (_("Bad mailbox name"));
1316 if (!(idata = imap_conn_find (&(mx.account), 0)))
1321 imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1323 if (option (OPTIMAPCHECKSUBSCRIBED)) {
1324 memset (&token, 0, sizeof (token));
1326 err.dsize = sizeof (errstr);
1327 snprintf (mbox, sizeof (mbox), "%smailboxes \"%s\"",
1328 subscribe ? "" : "un", path);
1329 if (mutt_parse_rc_line (mbox, &token, &err))
1330 debug_print (1, ("Error adding subscribed mailbox: %s\n", errstr));
1331 mem_free (&token.data);
1335 mutt_message (_("Subscribing to %s..."), buf);
1337 mutt_message (_("Unsubscribing to %s..."), buf);
1338 imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1340 snprintf (buf, sizeof (buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);
1342 if (imap_exec (idata, buf, 0) < 0)
1345 mem_free (&mx.mbox);
1349 mem_free (&mx.mbox);
1353 /* trim dest to the length of the longest prefix it shares with src,
1354 * returning the length of the trimmed string */
1355 static int longest_common_prefix (char *dest, const char* src,
1356 int start, size_t dlen) {
1359 while (pos < dlen && dest[pos] && dest[pos] == src[pos])
1366 /* look for IMAP URLs to complete from defined mailboxes. Could be extended
1367 * to complete over open connections and account/folder hooks too. */
1368 static int imap_complete_hosts (char *dest, size_t len) {
1375 matchlen = str_len (dest);
1376 if (list_empty (Incoming))
1378 for (i = 0; i < Incoming->length; i++) {
1379 mailbox = (BUFFY*) Incoming->data[i];
1380 if (!str_ncmp (dest, mailbox->path, matchlen)) {
1382 strfcpy (dest, mailbox->path, len);
1385 longest_common_prefix (dest, mailbox->path, matchlen, len);
1389 for (conn = mutt_socket_head (); conn->next; conn = conn->next) {
1391 char urlstr[LONG_STRING];
1393 if (conn->account.type != M_ACCT_TYPE_IMAP)
1396 mutt_account_tourl (&conn->account, &url);
1397 /* FIXME: how to handle multiple users on the same host? */
1400 url_ciss_tostring (&url, urlstr, sizeof (urlstr), 0);
1401 if (!str_ncmp (dest, urlstr, matchlen)) {
1403 strfcpy (dest, urlstr, len);
1406 longest_common_prefix (dest, urlstr, matchlen, len);
1413 /* imap_complete: given a partial IMAP folder path, return a string which
1414 * adds as much to the path as is unique */
1415 int imap_complete (char *dest, size_t dlen, char *path) {
1418 char list[LONG_STRING];
1419 char buf[LONG_STRING];
1420 char *list_word = NULL;
1421 int noselect, noinferiors;
1423 char completion[LONG_STRING];
1424 int clen, matchlen = 0;
1425 int completions = 0;
1428 if (imap_parse_path (path, &mx) || !mx.mbox) {
1429 strfcpy (dest, path, dlen);
1430 return imap_complete_hosts (dest, dlen);
1433 /* don't open a new socket just for completion. Instead complete over
1434 * known mailboxes/hooks/etc */
1435 if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NONEW))) {
1436 mem_free (&mx.mbox);
1437 strfcpy (dest, path, dlen);
1438 return imap_complete_hosts (dest, dlen);
1442 /* reformat path for IMAP list, and append wildcard */
1443 /* don't use INBOX in place of "" */
1444 if (mx.mbox && mx.mbox[0])
1445 imap_fix_path (idata, mx.mbox, list, sizeof (list));
1449 /* fire off command */
1450 snprintf (buf, sizeof (buf), "%s \"\" \"%s%%\"",
1451 option (OPTIMAPLSUB) ? "LSUB" : "LIST", list);
1453 imap_cmd_start (idata, buf);
1455 /* and see what the results are */
1456 strfcpy (completion, NONULL (mx.mbox), sizeof (completion));
1458 if (imap_parse_list_response (idata, &list_word, &noselect, &noinferiors,
1463 /* store unquoted */
1464 imap_unmunge_mbox_name (list_word);
1466 /* if the folder isn't selectable, append delimiter to force browse
1467 * to enter it on second tab. */
1469 clen = str_len (list_word);
1470 list_word[clen++] = delim;
1471 list_word[clen] = '\0';
1473 /* copy in first word */
1475 strfcpy (completion, list_word, sizeof (completion));
1476 matchlen = str_len (completion);
1481 matchlen = longest_common_prefix (completion, list_word, 0, matchlen);
1485 while (ascii_strncmp (idata->cmd.seq, idata->cmd.buf, SEQLEN));
1488 /* reformat output */
1489 imap_qualify_path (dest, dlen, &mx, completion);
1490 mutt_pretty_mailbox (dest);
1492 mem_free (&mx.mbox);
1499 /* reconnect if connection was lost */
1500 int imap_reconnect (CONTEXT * ctx)
1502 IMAP_DATA *imap_data;
1507 imap_data = (IMAP_DATA *) ctx->data;
1510 if (imap_data->status == IMAP_CONNECTED)
1514 if (query_quadoption
1516 _("Connection lost. Reconnect to IMAP server?")) != M_YES)
1519 mx_open_mailbox (ctx->path, 0, ctx);