NeoMutt  2025-01-09-117-gace867
Teaching an old dog new tricks
DOXYGEN
Loading...
Searching...
No Matches
imap.c File Reference

IMAP network mailbox. More...

#include "config.h"
#include <ctype.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "private.h"
#include "mutt/lib.h"
#include "config/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "conn/lib.h"
#include "mutt.h"
#include "lib.h"
#include "editor/lib.h"
#include "history/lib.h"
#include "parse/lib.h"
#include "progress/lib.h"
#include "question/lib.h"
#include "adata.h"
#include "auth.h"
#include "commands.h"
#include "edata.h"
#include "external.h"
#include "hook.h"
#include "mdata.h"
#include "msg_set.h"
#include "msn.h"
#include "mutt_logging.h"
#include "mutt_socket.h"
#include "muttlib.h"
#include "mx.h"
#include <libintl.h>
+ Include dependency graph for imap.c:

Go to the source code of this file.

Functions

void imap_init (void)
 Setup feature commands.
 
static int check_capabilities (struct ImapAccountData *adata)
 Make sure we can log in to this server.
 
static char * get_flags (struct ListHead *hflags, char *s)
 Make a simple list out of a FLAGS response.
 
static void set_flag (struct Mailbox *m, AclFlags aclflag, bool flag, const char *str, struct Buffer *flags)
 Append str to flags if we currently have permission according to aclflag.
 
static bool compare_flags_for_copy (struct Email *e)
 Compare local flags against the server.
 
static int select_email_uids (struct Email **emails, int num_emails, enum MessageType flag, bool changed, bool invert, struct UidArray *uida)
 Create a list of Email UIDs by type.
 
static int sync_helper (struct Mailbox *m, struct Email **emails, int num_emails, AclFlags right, enum MessageType flag, const char *name)
 Sync flag changes to the server.
 
static size_t longest_common_prefix (struct Buffer *buf, const char *src, size_t start)
 Find longest prefix common to two strings.
 
static int complete_hosts (struct Buffer *buf)
 Look for completion matches for mailboxes.
 
int imap_create_mailbox (struct ImapAccountData *adata, const char *mailbox)
 Create a new mailbox.
 
int imap_access (const char *path)
 Check permissions on an IMAP mailbox with a new connection.
 
int imap_rename_mailbox (struct ImapAccountData *adata, char *oldname, const char *newname)
 Rename a mailbox.
 
int imap_delete_mailbox (struct Mailbox *m, char *path)
 Delete a mailbox.
 
static void imap_logout (struct ImapAccountData *adata)
 Gracefully log out of server.
 
void imap_logout_all (void)
 Close all open connections.
 
int imap_read_literal (FILE *fp, struct ImapAccountData *adata, unsigned long bytes, struct Progress *progress)
 Read bytes bytes from server into file.
 
void imap_notify_delete_email (struct Mailbox *m, struct Email *e)
 Inform IMAP that an Email has been deleted.
 
void imap_expunge_mailbox (struct Mailbox *m, bool resort)
 Purge messages from the server.
 
int imap_open_connection (struct ImapAccountData *adata)
 Open an IMAP connection.
 
void imap_close_connection (struct ImapAccountData *adata)
 Close an IMAP connection.
 
bool imap_has_flag (struct ListHead *flag_list, const char *flag)
 Does the flag exist in the list.
 
static int imap_sort_email_uid (const void *a, const void *b, void *sdata)
 Compare two Emails by UID - Implements sort_t -.
 
int imap_sync_message_for_copy (struct Mailbox *m, struct Email *e, struct Buffer *cmd, enum QuadOption *err_continue)
 Update server to reflect the flags of a single message.
 
enum MxStatus imap_check_mailbox (struct Mailbox *m, bool force)
 Use the NOOP or IDLE command to poll for new mail.
 
static int imap_status (struct ImapAccountData *adata, struct ImapMboxData *mdata, bool queue)
 Refresh the number of total and new messages.
 
static enum MxStatus imap_mbox_check_stats (struct Mailbox *m, uint8_t flags)
 Check the Mailbox statistics - Implements MxOps::mbox_check_stats() -.
 
int imap_path_status (const char *path, bool queue)
 Refresh the number of total and new messages.
 
int imap_mailbox_status (struct Mailbox *m, bool queue)
 Refresh the number of total and new messages.
 
int imap_subscribe (const char *path, bool subscribe)
 Subscribe to a mailbox.
 
int imap_complete (struct Buffer *buf, const char *path)
 Try to complete an IMAP folder path.
 
int imap_fast_trash (struct Mailbox *m, const char *dest)
 Use server COPY command to copy deleted messages to trash.
 
enum MxStatus imap_sync_mailbox (struct Mailbox *m, bool expunge, bool close)
 Sync all the changes to the server.
 
static bool imap_ac_owns_path (struct Account *a, const char *path)
 Check whether an Account owns a Mailbox path - Implements MxOps::ac_owns_path() -.
 
static bool imap_ac_add (struct Account *a, struct Mailbox *m)
 Add a Mailbox to an Account - Implements MxOps::ac_add() -.
 
static void imap_mbox_select (struct Mailbox *m)
 Select a Mailbox.
 
int imap_login (struct ImapAccountData *adata)
 Open an IMAP connection.
 
static enum MxOpenReturns imap_mbox_open (struct Mailbox *m)
 Open a mailbox - Implements MxOps::mbox_open() -.
 
static bool imap_mbox_open_append (struct Mailbox *m, OpenMailboxFlags flags)
 Open a Mailbox for appending - Implements MxOps::mbox_open_append() -.
 
static enum MxStatus imap_mbox_check (struct Mailbox *m)
 Check for new mail - Implements MxOps::mbox_check() -.
 
static enum MxStatus imap_mbox_close (struct Mailbox *m)
 Close a Mailbox - Implements MxOps::mbox_close() -.
 
static bool imap_msg_open_new (struct Mailbox *m, struct Message *msg, const struct Email *e)
 Open a new message in a Mailbox - Implements MxOps::msg_open_new() -.
 
static int imap_tags_edit (struct Mailbox *m, const char *tags, struct Buffer *buf)
 Prompt and validate new messages tags - Implements MxOps::tags_edit() -.
 
static int imap_tags_commit (struct Mailbox *m, struct Email *e, const char *buf)
 Save the tags to a message - Implements MxOps::tags_commit() -.
 
enum MailboxType imap_path_probe (const char *path, const struct stat *st)
 Is this an IMAP Mailbox? - Implements MxOps::path_probe() -.
 
int imap_path_canon (struct Buffer *path)
 Canonicalise a Mailbox path - Implements MxOps::path_canon() -.
 
static int imap_path_is_empty (struct Buffer *path)
 Is the mailbox empty - Implements MxOps::path_is_empty() -.
 

Variables

static const struct Command ImapCommands []
 Imap Commands.
 
const struct MxOps MxImapOps
 IMAP Mailbox - Implements MxOps -.
 

Detailed Description

IMAP network mailbox.

Authors
  • Michael R. Elkins
  • Brandon Long
  • Brendan Cully
  • Richard Russon
  • Mehdi Abaakouk
  • Pietro Cerutti
  • Federico Kircheis
  • Ian Zimmerman
  • Sergey Alirzaev
  • Reto Brunner
  • Anna Figueiredo Gomes
  • Dennis Schön

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

Definition in file imap.c.

Function Documentation

◆ imap_init()

void imap_init ( void  )

Setup feature commands.

Definition at line 96 of file imap.c.

97{
99}
bool commands_register(struct CommandArray *ca, const struct Command *cmds)
Add commands to Commands array.
Definition: command.c:51
static const struct Command ImapCommands[]
Imap Commands.
Definition: imap.c:85
Container for Accounts, Notifications.
Definition: neomutt.h:43
struct CommandArray commands
NeoMutt commands.
Definition: neomutt.h:51
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ check_capabilities()

static int check_capabilities ( struct ImapAccountData adata)
static

Make sure we can log in to this server.

Parameters
adataImap Account data
Return values
0Success
-1Failure

Definition at line 107 of file imap.c.

108{
109 if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
110 {
111 imap_error("check_capabilities", adata->buf);
112 return -1;
113 }
114
115 if (!((adata->capabilities & IMAP_CAP_IMAP4) || (adata->capabilities & IMAP_CAP_IMAP4REV1)))
116 {
117 mutt_error(_("This IMAP server is ancient. NeoMutt does not work with it."));
118 return -1;
119 }
120
121 return 0;
122}
#define mutt_error(...)
Definition: logging2.h:93
int imap_exec(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags)
Execute a command and wait for the response from the server.
Definition: command.c:1303
#define IMAP_CMD_NO_FLAGS
No flags are set.
Definition: private.h:71
#define IMAP_CAP_IMAP4
Server supports IMAP4.
Definition: private.h:121
#define IMAP_CAP_IMAP4REV1
Server supports IMAP4rev1.
Definition: private.h:122
@ IMAP_EXEC_SUCCESS
Imap command executed or queued successfully.
Definition: private.h:82
void imap_error(const char *where, const char *msg)
Show an error and abort.
Definition: util.c:660
#define _(a)
Definition: message.h:28
ImapCapFlags capabilities
Capability flags.
Definition: adata.h:55
char * buf
Definition: adata.h:59
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ get_flags()

static char * get_flags ( struct ListHead *  hflags,
char *  s 
)
static

Make a simple list out of a FLAGS response.

Parameters
hflagsList to store flags
sString containing flags
Return values
ptrEnd of the flags
NULLFailure

return stream following FLAGS response

Definition at line 133 of file imap.c.

134{
135 /* sanity-check string */
136 const size_t plen = mutt_istr_startswith(s, "FLAGS");
137 if (plen == 0)
138 {
139 mutt_debug(LL_DEBUG1, "not a FLAGS response: %s\n", s);
140 return NULL;
141 }
142 s += plen;
143 SKIPWS(s);
144 if (*s != '(')
145 {
146 mutt_debug(LL_DEBUG1, "bogus FLAGS response: %s\n", s);
147 return NULL;
148 }
149
150 /* update caller's flags handle */
151 while (*s && (*s != ')'))
152 {
153 s++;
154 SKIPWS(s);
155 const char *flag_word = s;
156 while (*s && (*s != ')') && !isspace(*s))
157 s++;
158 const char ctmp = *s;
159 *s = '\0';
160 if (*flag_word)
161 mutt_list_insert_tail(hflags, mutt_str_dup(flag_word));
162 *s = ctmp;
163 }
164
165 /* note bad flags response */
166 if (*s != ')')
167 {
168 mutt_debug(LL_DEBUG1, "Unterminated FLAGS response: %s\n", s);
169 mutt_list_free(hflags);
170
171 return NULL;
172 }
173
174 s++;
175
176 return s;
177}
#define mutt_debug(LEVEL,...)
Definition: logging2.h:90
struct ListNode * mutt_list_insert_tail(struct ListHead *h, char *s)
Append a string to the end of a List.
Definition: list.c:65
void mutt_list_free(struct ListHead *h)
Free a List AND its strings.
Definition: list.c:123
@ LL_DEBUG1
Log at debug level 1.
Definition: logging2.h:44
char * mutt_str_dup(const char *str)
Copy a string, safely.
Definition: string.c:254
size_t mutt_istr_startswith(const char *str, const char *prefix)
Check whether a string starts with a prefix, ignoring case.
Definition: string.c:243
#define SKIPWS(ch)
Definition: string2.h:45
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ set_flag()

static void set_flag ( struct Mailbox m,
AclFlags  aclflag,
bool  flag,
const char *  str,
struct Buffer flags 
)
static

Append str to flags if we currently have permission according to aclflag.

Parameters
[in]mSelected Imap Mailbox
[in]aclflagPermissions, see AclFlags
[in]flagDoes the email have the flag set?
[in]strServer flag name
[out]flagsBuffer for server command

Definition at line 187 of file imap.c.

189{
190 if (m->rights & aclflag)
191 if (flag && imap_has_flag(&imap_mdata_get(m)->flags, str))
192 buf_addstr(flags, str);
193}
size_t buf_addstr(struct Buffer *buf, const char *s)
Add a string to a Buffer.
Definition: buffer.c:226
struct ImapMboxData * imap_mdata_get(struct Mailbox *m)
Get the Mailbox data for this mailbox.
Definition: mdata.c:61
bool imap_has_flag(struct ListHead *flag_list, const char *flag)
Does the flag exist in the list.
Definition: imap.c:877
AclFlags rights
ACL bits, see AclFlags.
Definition: mailbox.h:119
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ compare_flags_for_copy()

static bool compare_flags_for_copy ( struct Email e)
static

Compare local flags against the server.

Parameters
eEmail
Return values
trueFlags have changed
falseFlags match cached server flags

The comparison of flags EXCLUDES the deleted flag.

Definition at line 203 of file imap.c.

204{
205 struct ImapEmailData *edata = e->edata;
206
207 if (e->read != edata->read)
208 return true;
209 if (e->old != edata->old)
210 return true;
211 if (e->flagged != edata->flagged)
212 return true;
213 if (e->replied != edata->replied)
214 return true;
215
216 return false;
217}
bool read
Email is read.
Definition: email.h:50
void * edata
Driver-specific data.
Definition: email.h:74
bool old
Email is seen, but unread.
Definition: email.h:49
bool flagged
Marked important?
Definition: email.h:47
bool replied
Email has been replied to.
Definition: email.h:51
IMAP-specific Email data -.
Definition: edata.h:35
+ Here is the caller graph for this function:

◆ select_email_uids()

static int select_email_uids ( struct Email **  emails,
int  num_emails,
enum MessageType  flag,
bool  changed,
bool  invert,
struct UidArray *  uida 
)
static

Create a list of Email UIDs by type.

Parameters
emailsArray of Emails
num_emailsNumber of Emails in the array
flagFlag type on which to filter, e.g. MUTT_REPLIED
changedInclude only changed messages in message set
invertInvert sense of flag, eg MUTT_READ matches unread messages
uidaArray to fill with UIDs
Return values
numNumber of UIDs added
-1Error

Definition at line 230 of file imap.c.

232{
233 if (!emails || !uida)
234 return -1;
235
236 for (int i = 0; i < num_emails; i++)
237 {
238 struct Email *e = emails[i];
239 if (changed && !e->changed)
240 continue;
241
242 /* don't include pending expunged messages.
243 *
244 * TODO: can we unset active in cmd_parse_expunge() and
245 * cmd_parse_vanished() instead of checking for index != INT_MAX. */
246 if (!e || !e->active || (e->index == INT_MAX))
247 continue;
248
250
251 bool match = false;
252 switch (flag)
253 {
254 case MUTT_DELETED:
255 if (e->deleted != edata->deleted)
256 match = invert ^ e->deleted;
257 break;
258 case MUTT_FLAG:
259 if (e->flagged != edata->flagged)
260 match = invert ^ e->flagged;
261 break;
262 case MUTT_OLD:
263 if (e->old != edata->old)
264 match = invert ^ e->old;
265 break;
266 case MUTT_READ:
267 if (e->read != edata->read)
268 match = invert ^ e->read;
269 break;
270 case MUTT_REPLIED:
271 if (e->replied != edata->replied)
272 match = invert ^ e->replied;
273 break;
274 case MUTT_TRASH:
275 if (e->deleted && !e->purge)
276 match = true;
277 break;
278 default:
279 break;
280 }
281
282 if (match)
283 ARRAY_ADD(uida, edata->uid);
284 }
285
286 return ARRAY_SIZE(uida);
287}
#define ARRAY_ADD(head, elem)
Add an element at the end of the array.
Definition: array.h:156
#define ARRAY_SIZE(head)
The number of elements stored.
Definition: array.h:87
struct ImapEmailData * imap_edata_get(struct Email *e)
Get the private data for this Email.
Definition: edata.c:67
@ MUTT_TRASH
Trashed messages.
Definition: mutt.h:85
@ MUTT_READ
Messages that have been read.
Definition: mutt.h:73
@ MUTT_OLD
Old messages.
Definition: mutt.h:71
@ MUTT_FLAG
Flagged messages.
Definition: mutt.h:79
@ MUTT_DELETED
Deleted messages.
Definition: mutt.h:78
@ MUTT_REPLIED
Messages that have been replied to.
Definition: mutt.h:72
The envelope/body of an email.
Definition: email.h:39
bool purge
Skip trash folder when deleting.
Definition: email.h:79
bool active
Message is not to be removed.
Definition: email.h:76
bool changed
Email has been edited.
Definition: email.h:77
bool deleted
Email is deleted.
Definition: email.h:78
int index
The absolute (unsorted) message number.
Definition: email.h:110
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sync_helper()

static int sync_helper ( struct Mailbox m,
struct Email **  emails,
int  num_emails,
AclFlags  right,
enum MessageType  flag,
const char *  name 
)
static

Sync flag changes to the server.

Parameters
mSelected Imap Mailbox
emailsArray of Emails
num_emailsNumber of Emails in the array
rightACL, see AclFlags
flagNeoMutt flag, e.g. MUTT_DELETED
nameName of server flag
Return values
>=0Success, number of messages
-1Failure

Definition at line 300 of file imap.c.

302{
304 if (!adata)
305 return -1;
306
307 if ((m->rights & right) == 0)
308 return 0;
309
310 if ((right == MUTT_ACL_WRITE) && !imap_has_flag(&imap_mdata_get(m)->flags, name))
311 return 0;
312
313 int count = 0;
314 char buf[1024] = { 0 };
315
316 struct UidArray uida = ARRAY_HEAD_INITIALIZER;
317
318 // Set the flag (+FLAGS) on matching emails
319 select_email_uids(emails, num_emails, flag, true, false, &uida);
320 snprintf(buf, sizeof(buf), "+FLAGS.SILENT (%s)", name);
321 int rc = imap_exec_msg_set(adata, "UID STORE", buf, &uida);
322 if (rc < 0)
323 return rc;
324 count += rc;
325 ARRAY_FREE(&uida);
326
327 // Clear the flag (-FLAGS) on non-matching emails
328 select_email_uids(emails, num_emails, flag, true, true, &uida);
329 buf[0] = '-';
330 rc = imap_exec_msg_set(adata, "UID STORE", buf, &uida);
331 if (rc < 0)
332 return rc;
333 count += rc;
334 ARRAY_FREE(&uida);
335
336 return count;
337}
#define ARRAY_FREE(head)
Release all memory.
Definition: array.h:204
#define ARRAY_HEAD_INITIALIZER
Static initializer for arrays.
Definition: array.h:58
#define MUTT_ACL_WRITE
Write to a message (for flagging or linking threads)
Definition: mailbox.h:71
struct ImapAccountData * imap_adata_get(struct Mailbox *m)
Get the Account data for this mailbox.
Definition: adata.c:123
static int select_email_uids(struct Email **emails, int num_emails, enum MessageType flag, bool changed, bool invert, struct UidArray *uida)
Create a list of Email UIDs by type.
Definition: imap.c:230
int imap_exec_msg_set(struct ImapAccountData *adata, const char *pre, const char *post, struct UidArray *uida)
Execute a command using a set of UIDs.
Definition: msg_set.c:133
char * name
Name of Account.
Definition: account.h:38
void * adata
Private data (for Mailbox backends)
Definition: account.h:42
IMAP-specific Account data -.
Definition: adata.h:40
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ longest_common_prefix()

static size_t longest_common_prefix ( struct Buffer buf,
const char *  src,
size_t  start 
)
static

Find longest prefix common to two strings.

Parameters
bufDestination buffer
srcSource buffer
startStarting offset into string
Return values
numLength of the common string

Trim dest to the length of the longest prefix it shares with src.

Definition at line 348 of file imap.c.

349{
350 size_t pos = start;
351
352 size_t len = buf_len(buf);
353 while ((pos < len) && buf->data[pos] && (buf->data[pos] == src[pos]))
354 pos++;
355 buf->data[pos] = '\0';
356
357 buf_fix_dptr(buf);
358
359 return pos;
360}
size_t buf_len(const struct Buffer *buf)
Calculate the length of a Buffer.
Definition: buffer.c:491
void buf_fix_dptr(struct Buffer *buf)
Move the dptr to end of the Buffer.
Definition: buffer.c:182
char * data
Pointer to data.
Definition: buffer.h:37
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ complete_hosts()

static int complete_hosts ( struct Buffer buf)
static

Look for completion matches for mailboxes.

Parameters
bufPartial mailbox name to complete
Return values
0Success
-1Failure

look for IMAP URLs to complete from defined mailboxes. Could be extended to complete over open connections and account/folder hooks too.

Definition at line 371 of file imap.c.

372{
373 int rc = -1;
374 size_t matchlen;
375
376 matchlen = buf_len(buf);
377 struct MailboxList ml = STAILQ_HEAD_INITIALIZER(ml);
379 struct MailboxNode *np = NULL;
380 STAILQ_FOREACH(np, &ml, entries)
381 {
383 continue;
384
385 if (rc)
386 {
388 rc = 0;
389 }
390 else
391 {
392 longest_common_prefix(buf, mailbox_path(np->mailbox), matchlen);
393 }
394 }
396
397#if 0
398 TAILQ_FOREACH(conn, mutt_socket_head(), entries)
399 {
400 struct Url url = { 0 };
401 char urlstr[1024] = { 0 };
402
403 if (conn->account.type != MUTT_ACCT_TYPE_IMAP)
404 continue;
405
406 account_to_url(&conn->account, &url);
407 /* FIXME: how to handle multiple users on the same host? */
408 url.user = NULL;
409 url.path = NULL;
410 url_tostring(&url, urlstr, sizeof(urlstr), U_NO_FLAGS);
411 if (mutt_strn_equal(buf, urlstr, matchlen))
412 {
413 if (rc)
414 {
415 mutt_str_copy(buf, urlstr, buflen);
416 rc = 0;
417 }
418 else
419 {
420 longest_common_prefix(buf, urlstr, matchlen);
421 }
422 }
423 }
424#endif
425
426 return rc;
427}
size_t buf_strcpy(struct Buffer *buf, const char *s)
Copy a string into a Buffer.
Definition: buffer.c:395
static const char * buf_string(const struct Buffer *buf)
Convert a buffer to a const char * "string".
Definition: buffer.h:96
static const char * mailbox_path(const struct Mailbox *m)
Get the Mailbox's path string.
Definition: mailbox.h:223
@ MUTT_MAILBOX_ANY
Match any Mailbox type.
Definition: mailbox.h:42
static size_t longest_common_prefix(struct Buffer *buf, const char *src, size_t start)
Find longest prefix common to two strings.
Definition: imap.c:348
bool mutt_strn_equal(const char *a, const char *b, size_t num)
Check for equality of two strings (to a maximum), safely.
Definition: string.c:426
size_t mutt_str_startswith(const char *str, const char *prefix)
Check whether a string starts with a prefix.
Definition: string.c:231
size_t mutt_str_copy(char *dest, const char *src, size_t dsize)
Copy a string into a buffer (guaranteeing NUL-termination)
Definition: string.c:582
void account_to_url(struct ConnAccount *cac, struct Url *url)
Fill URL with info from account.
Definition: mutt_account.c:80
@ MUTT_ACCT_TYPE_IMAP
Imap Account.
Definition: mutt_account.h:36
void neomutt_mailboxlist_clear(struct MailboxList *ml)
Free a Mailbox List.
Definition: neomutt.c:173
size_t neomutt_mailboxlist_get_all(struct MailboxList *head, struct NeoMutt *n, enum MailboxType type)
Get a List of all Mailboxes.
Definition: neomutt.c:196
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:782
#define STAILQ_HEAD_INITIALIZER(head)
Definition: queue.h:324
#define STAILQ_FOREACH(var, head, field)
Definition: queue.h:390
List of Mailboxes.
Definition: mailbox.h:166
struct Mailbox * mailbox
Mailbox in the list.
Definition: mailbox.h:167
A parsed URL proto://user:password@host:port/path?a=1&b=2
Definition: url.h:69
char * user
Username.
Definition: url.h:71
char * path
Path.
Definition: url.h:75
int url_tostring(const struct Url *url, char *dest, size_t len, uint8_t flags)
Output the URL string for a given Url object.
Definition: url.c:423
#define U_NO_FLAGS
Definition: url.h:49
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_create_mailbox()

int imap_create_mailbox ( struct ImapAccountData adata,
const char *  mailbox 
)

Create a new mailbox.

Parameters
adataImap Account data
mailboxMailbox to create
Return values
0Success
-1Failure

Definition at line 436 of file imap.c.

437{
438 char buf[2048] = { 0 };
439 char mbox[1024] = { 0 };
440
441 imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), mailbox);
442 snprintf(buf, sizeof(buf), "CREATE %s", mbox);
443
445 {
446 mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(adata));
447 return -1;
448 }
449
450 return 0;
451}
const char * imap_cmd_trailer(struct ImapAccountData *adata)
Extra information after tagged command response if any.
Definition: command.c:1266
void imap_munge_mbox_name(bool unicode, char *dest, size_t dlen, const char *src)
Quote awkward characters in a mailbox name.
Definition: util.c:960
bool unicode
If true, we can send UTF-8, and the server will use UTF8 rather than mUTF7.
Definition: adata.h:62
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_access()

int imap_access ( const char *  path)

Check permissions on an IMAP mailbox with a new connection.

Parameters
pathMailbox path
Return values
0Success
<0Failure

TODO: ACL checks. Right now we assume if it exists we can mess with it. TODO: This method should take a Mailbox as parameter to be able to reuse the existing connection.

Definition at line 463 of file imap.c.

464{
465 if (imap_path_status(path, false) >= 0)
466 return 0;
467 return -1;
468}
int imap_path_status(const char *path, bool queue)
Refresh the number of total and new messages.
Definition: imap.c:1175
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_rename_mailbox()

int imap_rename_mailbox ( struct ImapAccountData adata,
char *  oldname,
const char *  newname 
)

Rename a mailbox.

Parameters
adataImap Account data
oldnameExisting mailbox
newnameNew name for mailbox
Return values
0Success
-1Failure

Definition at line 478 of file imap.c.

479{
480 char oldmbox[1024] = { 0 };
481 char newmbox[1024] = { 0 };
482 int rc = 0;
483
484 imap_munge_mbox_name(adata->unicode, oldmbox, sizeof(oldmbox), oldname);
485 imap_munge_mbox_name(adata->unicode, newmbox, sizeof(newmbox), newname);
486
487 struct Buffer *buf = buf_pool_get();
488 buf_printf(buf, "RENAME %s %s", oldmbox, newmbox);
489
491 rc = -1;
492
493 buf_pool_release(&buf);
494
495 return rc;
496}
int buf_printf(struct Buffer *buf, const char *fmt,...)
Format a string overwriting a Buffer.
Definition: buffer.c:161
struct Buffer * buf_pool_get(void)
Get a Buffer from the pool.
Definition: pool.c:82
void buf_pool_release(struct Buffer **ptr)
Return a Buffer to the pool.
Definition: pool.c:96
String manipulation buffer.
Definition: buffer.h:36
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_delete_mailbox()

int imap_delete_mailbox ( struct Mailbox m,
char *  path 
)

Delete a mailbox.

Parameters
mMailbox
pathname of the mailbox to delete
Return values
0Success
-1Failure

Definition at line 505 of file imap.c.

506{
507 char buf[PATH_MAX + 7];
508 char mbox[PATH_MAX] = { 0 };
509 struct Url *url = url_parse(path);
510 if (!url)
511 return -1;
512
514 imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), url->path);
515 url_free(&url);
516 snprintf(buf, sizeof(buf), "DELETE %s", mbox);
518 return -1;
519
520 return 0;
521}
#define PATH_MAX
Definition: mutt.h:42
struct Account * account
Account that owns this Mailbox.
Definition: mailbox.h:127
struct Url * url_parse(const char *src)
Fill in Url.
Definition: url.c:239
void url_free(struct Url **ptr)
Free the contents of a URL.
Definition: url.c:124
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_logout()

static void imap_logout ( struct ImapAccountData adata)
static

Gracefully log out of server.

Parameters
adataImap Account data

Definition at line 527 of file imap.c.

528{
529 if (adata->status != IMAP_FATAL)
530 {
531 /* we set status here to let imap_handle_untagged know we _expect_ to
532 * receive a bye response (so it doesn't freak out and close the conn) */
533 if (adata->state == IMAP_DISCONNECTED)
534 {
535 return;
536 }
537
538 adata->status = IMAP_BYE;
539 imap_cmd_start(adata, "LOGOUT");
540 const short c_imap_poll_timeout = cs_subset_number(NeoMutt->sub, "imap_poll_timeout");
541 if ((c_imap_poll_timeout <= 0) ||
542 (mutt_socket_poll(adata->conn, c_imap_poll_timeout) != 0))
543 {
544 while (imap_cmd_step(adata) == IMAP_RES_CONTINUE)
545 ; // do nothing
546 }
547 }
548 mutt_socket_close(adata->conn);
549 adata->state = IMAP_DISCONNECTED;
550}
short cs_subset_number(const struct ConfigSubset *sub, const char *name)
Get a number config item by name.
Definition: helpers.c:143
int imap_cmd_start(struct ImapAccountData *adata, const char *cmdstr)
Given an IMAP command, send it to the server.
Definition: command.c:1114
int imap_cmd_step(struct ImapAccountData *adata)
Reads server responses from an IMAP command.
Definition: command.c:1128
@ IMAP_DISCONNECTED
Disconnected from server.
Definition: private.h:105
@ IMAP_BYE
Logged out from server.
Definition: private.h:96
@ IMAP_FATAL
Unrecoverable error occurred.
Definition: private.h:95
#define IMAP_RES_CONTINUE
* ...
Definition: private.h:56
int mutt_socket_close(struct Connection *conn)
Close a socket.
Definition: socket.c:100
int mutt_socket_poll(struct Connection *conn, time_t wait_secs)
Checks whether reads would block.
Definition: socket.c:182
unsigned char state
ImapState, e.g. IMAP_AUTHENTICATED.
Definition: adata.h:44
unsigned char status
ImapFlags, e.g. IMAP_FATAL.
Definition: adata.h:45
struct Connection * conn
Connection to IMAP server.
Definition: adata.h:41
struct ConfigSubset * sub
Inherited config items.
Definition: neomutt.h:47
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_logout_all()

void imap_logout_all ( void  )

Close all open connections.

Quick and dirty until we can make sure we've got all the context we need.

Definition at line 557 of file imap.c.

558{
559 struct Account *np = NULL;
560 TAILQ_FOREACH(np, &NeoMutt->accounts, entries)
561 {
562 if (np->type != MUTT_IMAP)
563 continue;
564
565 struct ImapAccountData *adata = np->adata;
566 if (!adata)
567 continue;
568
569 struct Connection *conn = adata->conn;
570 if (!conn || (conn->fd < 0))
571 continue;
572
573 mutt_message(_("Closing connection to %s..."), conn->account.host);
574 imap_logout(np->adata);
576 }
577}
@ MUTT_IMAP
'IMAP' Mailbox type
Definition: mailbox.h:50
#define mutt_message(...)
Definition: logging2.h:92
static void imap_logout(struct ImapAccountData *adata)
Gracefully log out of server.
Definition: imap.c:527
void mutt_clear_error(void)
Clear the message line (bottom line of screen)
Definition: mutt_logging.c:74
A group of associated Mailboxes.
Definition: account.h:36
enum MailboxType type
Type of Mailboxes this Account contains.
Definition: account.h:37
char host[128]
Server to login to.
Definition: connaccount.h:54
struct ConnAccount account
Account details: username, password, etc.
Definition: connection.h:49
int fd
Socket file descriptor.
Definition: connection.h:53
struct AccountList accounts
List of all Accounts.
Definition: neomutt.h:48
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_read_literal()

int imap_read_literal ( FILE *  fp,
struct ImapAccountData adata,
unsigned long  bytes,
struct Progress *  progress 
)

Read bytes bytes from server into file.

Parameters
fpFile handle for email file
adataImap Account data
bytesNumber of bytes to read
progressProgress bar
Return values
0Success
-1Failure

Not explicitly buffered, relies on FILE buffering.

Note
Strips \r from \r\n. Apparently even literals use \r\n-terminated strings ?!

Definition at line 593 of file imap.c.

595{
596 char c;
597 bool r = false;
598 struct Buffer buf = { 0 }; // Do not allocate, maybe it won't be used
599
600 const short c_debug_level = cs_subset_number(NeoMutt->sub, "debug_level");
601 if (c_debug_level >= IMAP_LOG_LTRL)
602 buf_alloc(&buf, bytes + 1);
603
604 mutt_debug(LL_DEBUG2, "reading %lu bytes\n", bytes);
605
606 for (unsigned long pos = 0; pos < bytes; pos++)
607 {
608 if (mutt_socket_readchar(adata->conn, &c) != 1)
609 {
610 mutt_debug(LL_DEBUG1, "error during read, %lu bytes read\n", pos);
611 adata->status = IMAP_FATAL;
612
613 buf_dealloc(&buf);
614 return -1;
615 }
616
617 if (r && (c != '\n'))
618 fputc('\r', fp);
619
620 if (c == '\r')
621 {
622 r = true;
623 continue;
624 }
625 else
626 {
627 r = false;
628 }
629
630 fputc(c, fp);
631
632 if ((pos % 1024) == 0)
633 progress_update(progress, pos, -1);
634 if (c_debug_level >= IMAP_LOG_LTRL)
635 buf_addch(&buf, c);
636 }
637
638 if (c_debug_level >= IMAP_LOG_LTRL)
639 {
640 mutt_debug(IMAP_LOG_LTRL, "\n%s", buf.data);
641 buf_dealloc(&buf);
642 }
643 return 0;
644}
void buf_dealloc(struct Buffer *buf)
Release the memory allocated by a buffer.
Definition: buffer.c:377
size_t buf_addch(struct Buffer *buf, char c)
Add a single character to a Buffer.
Definition: buffer.c:241
void buf_alloc(struct Buffer *buf, size_t new_size)
Make sure a buffer can store at least new_size bytes.
Definition: buffer.c:337
#define IMAP_LOG_LTRL
Definition: private.h:49
@ LL_DEBUG2
Log at debug level 2.
Definition: logging2.h:45
bool progress_update(struct Progress *progress, size_t pos, int percent)
Update the state of the progress bar.
Definition: progress.c:80
int mutt_socket_readchar(struct Connection *conn, char *c)
Simple read buffering to speed things up.
Definition: socket.c:200
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_notify_delete_email()

void imap_notify_delete_email ( struct Mailbox m,
struct Email e 
)

Inform IMAP that an Email has been deleted.

Parameters
mMailbox
eEmail

Definition at line 651 of file imap.c.

652{
653 struct ImapMboxData *mdata = imap_mdata_get(m);
655
656 if (!mdata || !edata)
657 return;
658
659 imap_msn_remove(&mdata->msn, edata->msn - 1);
660 edata->msn = 0;
661}
void imap_msn_remove(struct MSNArray *msn, size_t idx)
Remove an entry from the cache.
Definition: msn.c:116
IMAP-specific Mailbox data -.
Definition: mdata.h:40
void * mdata
Driver specific data.
Definition: mailbox.h:132
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_expunge_mailbox()

void imap_expunge_mailbox ( struct Mailbox m,
bool  resort 
)

Purge messages from the server.

Parameters
mMailbox
resortTrigger a resort?

Purge IMAP portion of expunged messages from the context. Must not be done while something has a handle on any headers (eg inside pager or editor). That is, check IMAP_REOPEN_ALLOW.

Definition at line 672 of file imap.c.

673{
675 struct ImapMboxData *mdata = imap_mdata_get(m);
676 if (!adata || !mdata)
677 return;
678
679 struct Email *e = NULL;
680
681#ifdef USE_HCACHE
682 imap_hcache_open(adata, mdata, false);
683#endif
684
685 for (int i = 0; i < m->msg_count; i++)
686 {
687 e = m->emails[i];
688 if (!e)
689 break;
690
691 if (e->index == INT_MAX)
692 {
693 mutt_debug(LL_DEBUG2, "Expunging message UID %u\n", imap_edata_get(e)->uid);
694
695 e->deleted = true;
696
697 imap_cache_del(m, e);
698#ifdef USE_HCACHE
699 imap_hcache_del(mdata, imap_edata_get(e)->uid);
700#endif
701
702 mutt_hash_int_delete(mdata->uid_hash, imap_edata_get(e)->uid, e);
703
704 imap_edata_free((void **) &e->edata);
705 }
706 else
707 {
708 /* NeoMutt has several places where it turns off e->active as a
709 * hack. For example to avoid FLAG updates, or to exclude from
710 * imap_exec_msg_set.
711 *
712 * Unfortunately, when a reopen is allowed and the IMAP_EXPUNGE_PENDING
713 * flag becomes set (e.g. a flag update to a modified header),
714 * this function will be called by imap_cmd_finish().
715 *
716 * The ctx_update_tables() will free and remove these "inactive" headers,
717 * despite that an EXPUNGE was not received for them.
718 * This would result in memory leaks and segfaults due to dangling
719 * pointers in the msn_index and uid_hash.
720 *
721 * So this is another hack to work around the hacks. We don't want to
722 * remove the messages, so make sure active is on. */
723 e->active = true;
724 }
725 }
726
727#ifdef USE_HCACHE
728 imap_hcache_close(mdata);
729#endif
730
732 if (resort)
733 {
735 }
736}
void mailbox_changed(struct Mailbox *m, enum NotifyMailbox action)
Notify observers of a change to a Mailbox.
Definition: mailbox.c:233
@ NT_MAILBOX_RESORT
Email list needs resorting.
Definition: mailbox.h:190
@ NT_MAILBOX_UPDATE
Update internal tables.
Definition: mailbox.h:191
void imap_edata_free(void **ptr)
Free the private Email data - Implements Email::edata_free() -.
Definition: edata.c:40
void mutt_hash_int_delete(struct HashTable *table, unsigned int intkey, const void *data)
Remove an element from a Hash Table.
Definition: hash.c:444
int imap_cache_del(struct Mailbox *m, struct Email *e)
Delete an email from the body cache.
Definition: message.c:1869
void imap_hcache_open(struct ImapAccountData *adata, struct ImapMboxData *mdata, bool create)
Open a header cache.
Definition: util.c:302
void imap_hcache_close(struct ImapMboxData *mdata)
Close the header cache.
Definition: util.c:343
int imap_hcache_del(struct ImapMboxData *mdata, unsigned int uid)
Delete an item from the header cache.
Definition: util.c:401
struct HashTable * uid_hash
Hash Table: "uid" -> Email.
Definition: mdata.h:59
int msg_count
Total number of messages.
Definition: mailbox.h:88
struct Email ** emails
Array of Emails.
Definition: mailbox.h:96
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_open_connection()

int imap_open_connection ( struct ImapAccountData adata)

Open an IMAP connection.

Parameters
adataImap Account data
Return values
0Success
-1Failure

Definition at line 744 of file imap.c.

745{
746 if (mutt_socket_open(adata->conn) < 0)
747 return -1;
748
749 adata->state = IMAP_CONNECTED;
750
751 if (imap_cmd_step(adata) != IMAP_RES_OK)
752 {
754 return -1;
755 }
756
757 if (mutt_istr_startswith(adata->buf, "* OK"))
758 {
759 if (!mutt_istr_startswith(adata->buf, "* OK [CAPABILITY") && check_capabilities(adata))
760 {
761 goto bail;
762 }
763#ifdef USE_SSL
764 /* Attempt STARTTLS if available and desired. */
765 const bool c_ssl_force_tls = cs_subset_bool(NeoMutt->sub, "ssl_force_tls");
766 if ((adata->conn->ssf == 0) &&
767 (c_ssl_force_tls || (adata->capabilities & IMAP_CAP_STARTTLS)))
768 {
769 enum QuadOption ans;
770
771 if (c_ssl_force_tls)
772 {
773 ans = MUTT_YES;
774 }
775 else if ((ans = query_quadoption(_("Secure connection with TLS?"),
776 NeoMutt->sub, "ssl_starttls")) == MUTT_ABORT)
777 {
778 goto bail;
779 }
780 if (ans == MUTT_YES)
781 {
782 enum ImapExecResult rc = imap_exec(adata, "STARTTLS", IMAP_CMD_SINGLE);
783 // Clear any data after the STARTTLS acknowledgement
784 mutt_socket_empty(adata->conn);
785
786 if (rc == IMAP_EXEC_FATAL)
787 goto bail;
788 if (rc != IMAP_EXEC_ERROR)
789 {
790 if (mutt_ssl_starttls(adata->conn))
791 {
792 mutt_error(_("Could not negotiate TLS connection"));
793 goto bail;
794 }
795 else
796 {
797 /* RFC2595 demands we recheck CAPABILITY after TLS completes. */
798 if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
799 goto bail;
800 }
801 }
802 }
803 }
804
805 if (c_ssl_force_tls && (adata->conn->ssf == 0))
806 {
807 mutt_error(_("Encrypted connection unavailable"));
808 goto bail;
809 }
810#endif
811 }
812 else if (mutt_istr_startswith(adata->buf, "* PREAUTH"))
813 {
814#ifdef USE_SSL
815 /* Unless using a secure $tunnel, an unencrypted PREAUTH response may be a
816 * MITM attack. The only way to stop "STARTTLS" MITM attacks is via
817 * $ssl_force_tls: an attacker can easily spoof "* OK" and strip the
818 * STARTTLS capability. So consult $ssl_force_tls, not $ssl_starttls, to
819 * decide whether to abort. Note that if using $tunnel and
820 * $tunnel_is_secure, adata->conn->ssf will be set to 1. */
821 const bool c_ssl_force_tls = cs_subset_bool(NeoMutt->sub, "ssl_force_tls");
822 if ((adata->conn->ssf == 0) && c_ssl_force_tls)
823 {
824 mutt_error(_("Encrypted connection unavailable"));
825 goto bail;
826 }
827#endif
828
829 adata->state = IMAP_AUTHENTICATED;
830 if (check_capabilities(adata) != 0)
831 goto bail;
832 FREE(&adata->capstr);
833 }
834 else
835 {
836 imap_error("imap_open_connection()", adata->buf);
837 goto bail;
838 }
839
840 return 0;
841
842bail:
844 FREE(&adata->capstr);
845 return -1;
846}
bool cs_subset_bool(const struct ConfigSubset *sub, const char *name)
Get a boolean config item by name.
Definition: helpers.c:47
int mutt_ssl_starttls(struct Connection *conn)
Negotiate TLS over an already opened connection.
Definition: gnutls.c:1149
@ IMAP_AUTHENTICATED
Connection is authenticated.
Definition: private.h:107
@ IMAP_CONNECTED
Connected to server.
Definition: private.h:106
#define IMAP_RES_OK
<tag> OK ...
Definition: private.h:55
#define IMAP_CAP_STARTTLS
RFC2595: STARTTLS.
Definition: private.h:131
ImapExecResult
Imap_exec return code.
Definition: private.h:81
@ IMAP_EXEC_ERROR
Imap command failure.
Definition: private.h:83
@ IMAP_EXEC_FATAL
Imap connection failure.
Definition: private.h:84
#define IMAP_CMD_SINGLE
Run a single command.
Definition: private.h:75
void imap_close_connection(struct ImapAccountData *adata)
Close an IMAP connection.
Definition: imap.c:852
static int check_capabilities(struct ImapAccountData *adata)
Make sure we can log in to this server.
Definition: imap.c:107
#define FREE(x)
Definition: memory.h:55
QuadOption
Possible values for a quad-option.
Definition: quad.h:36
@ MUTT_ABORT
User aborted the question (with Ctrl-G)
Definition: quad.h:37
@ MUTT_YES
User answered 'Yes', or assume 'Yes'.
Definition: quad.h:39
enum QuadOption query_quadoption(const char *prompt, struct ConfigSubset *sub, const char *name)
Ask the user a quad-question.
Definition: question.c:379
void mutt_socket_empty(struct Connection *conn)
Clear out any queued data.
Definition: socket.c:306
int mutt_socket_open(struct Connection *conn)
Simple wrapper.
Definition: socket.c:76
unsigned int ssf
Security strength factor, in bits (see notes)
Definition: connection.h:50
char * capstr
Capability string from the server.
Definition: adata.h:54
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_close_connection()

void imap_close_connection ( struct ImapAccountData adata)

Close an IMAP connection.

Parameters
adataImap Account data

Definition at line 852 of file imap.c.

853{
854 if (adata->state != IMAP_DISCONNECTED)
855 {
856 mutt_socket_close(adata->conn);
857 adata->state = IMAP_DISCONNECTED;
858 }
859 adata->seqno = 0;
860 adata->nextcmd = 0;
861 adata->lastcmd = 0;
862 adata->status = 0;
863 memset(adata->cmds, 0, sizeof(struct ImapCommand) * adata->cmdslots);
864}
int lastcmd
Last command in the queue.
Definition: adata.h:72
int nextcmd
Next command to be sent.
Definition: adata.h:71
struct ImapCommand * cmds
Queue of commands for the server.
Definition: adata.h:69
int cmdslots
Size of the command queue.
Definition: adata.h:70
unsigned int seqno
tag sequence number, e.g. '{seqid}0001'
Definition: adata.h:57
IMAP command structure.
Definition: private.h:160
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_has_flag()

bool imap_has_flag ( struct ListHead *  flag_list,
const char *  flag 
)

Does the flag exist in the list.

Parameters
flag_listList of server flags
flagFlag to find
Return values
trueFlag exists

Do a caseless comparison of the flag against a flag list, return true if found or flag list has '*'. Note that "flag" might contain additional whitespace at the end, so we really need to compare up to the length of each element in "flag_list".

Definition at line 877 of file imap.c.

878{
879 if (STAILQ_EMPTY(flag_list))
880 return false;
881
882 const size_t flaglen = mutt_str_len(flag);
883 struct ListNode *np = NULL;
884 STAILQ_FOREACH(np, flag_list, entries)
885 {
886 const size_t nplen = strlen(np->data);
887 if ((flaglen >= nplen) && ((flag[nplen] == '\0') || (flag[nplen] == ' ')) &&
888 mutt_istrn_equal(np->data, flag, nplen))
889 {
890 return true;
891 }
892
893 if (mutt_str_equal(np->data, "\\*"))
894 return true;
895 }
896
897 return false;
898}
bool mutt_str_equal(const char *a, const char *b)
Compare two strings.
Definition: string.c:661
size_t mutt_str_len(const char *a)
Calculate the length of a string, safely.
Definition: string.c:497
bool mutt_istrn_equal(const char *a, const char *b, size_t num)
Check for equality of two strings ignoring case (to a maximum), safely.
Definition: string.c:454
#define STAILQ_EMPTY(head)
Definition: queue.h:382
A List node for strings.
Definition: list.h:37
char * data
String.
Definition: list.h:38
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_sync_message_for_copy()

int imap_sync_message_for_copy ( struct Mailbox m,
struct Email e,
struct Buffer cmd,
enum QuadOption err_continue 
)

Update server to reflect the flags of a single message.

Parameters
[in]mMailbox
[in]eEmail
[in]cmdBuffer for the command string
[out]err_continueDid the user force a continue?
Return values
0Success
-1Failure

Update the IMAP server to reflect the flags for a single message before performing a "UID COPY".

Note
This does not sync the "deleted" flag state, because it is not desirable to propagate that flag into the copy.

Definition at line 929 of file imap.c.

931{
934
935 if (!adata || (adata->mailbox != m) || !e)
936 return -1;
937
939 {
940 if (e->deleted == edata->deleted)
941 e->changed = false;
942 return 0;
943 }
944
945 buf_printf(cmd, "UID STORE %u", edata->uid);
946
947 struct Buffer *flags = buf_pool_get();
948
949 set_flag(m, MUTT_ACL_SEEN, e->read, "\\Seen ", flags);
950 set_flag(m, MUTT_ACL_WRITE, e->old, "Old ", flags);
951 set_flag(m, MUTT_ACL_WRITE, e->flagged, "\\Flagged ", flags);
952 set_flag(m, MUTT_ACL_WRITE, e->replied, "\\Answered ", flags);
953 set_flag(m, MUTT_ACL_DELETE, edata->deleted, "\\Deleted ", flags);
954
955 if (m->rights & MUTT_ACL_WRITE)
956 {
957 /* restore system flags */
958 if (edata->flags_system)
959 buf_addstr(flags, edata->flags_system);
960
961 /* set custom flags */
962 struct Buffer *tags = buf_pool_get();
964 if (!buf_is_empty(tags))
965 buf_addstr(flags, buf_string(tags));
966 buf_pool_release(&tags);
967 }
968
970 buf_fix_dptr(flags);
971
972 /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to
973 * explicitly revoke all system flags (if we have permission) */
974 if (buf_is_empty(flags))
975 {
976 set_flag(m, MUTT_ACL_SEEN, true, "\\Seen ", flags);
977 set_flag(m, MUTT_ACL_WRITE, true, "Old ", flags);
978 set_flag(m, MUTT_ACL_WRITE, true, "\\Flagged ", flags);
979 set_flag(m, MUTT_ACL_WRITE, true, "\\Answered ", flags);
980 set_flag(m, MUTT_ACL_DELETE, !edata->deleted, "\\Deleted ", flags);
981
982 /* erase custom flags */
983 if ((m->rights & MUTT_ACL_WRITE) && edata->flags_remote)
984 buf_addstr(flags, edata->flags_remote);
985
987 buf_fix_dptr(flags);
988
989 buf_addstr(cmd, " -FLAGS.SILENT (");
990 }
991 else
992 {
993 buf_addstr(cmd, " FLAGS.SILENT (");
994 }
995
996 buf_addstr(cmd, buf_string(flags));
997 buf_addstr(cmd, ")");
998
999 int rc = -1;
1000
1001 /* after all this it's still possible to have no flags, if you
1002 * have no ACL rights */
1003 if (!buf_is_empty(flags) &&
1005 err_continue && (*err_continue != MUTT_YES))
1006 {
1007 *err_continue = imap_continue("imap_sync_message: STORE failed", adata->buf);
1008 if (*err_continue != MUTT_YES)
1009 goto done;
1010 }
1011
1012 /* server have now the updated flags */
1013 FREE(&edata->flags_remote);
1014 struct Buffer *flags_remote = buf_pool_get();
1015 driver_tags_get_with_hidden(&e->tags, flags_remote);
1016 edata->flags_remote = buf_strdup(flags_remote);
1017 buf_pool_release(&flags_remote);
1018
1019 if (e->deleted == edata->deleted)
1020 e->changed = false;
1021
1022 rc = 0;
1023
1024done:
1025 buf_pool_release(&flags);
1026 return rc;
1027}
bool buf_is_empty(const struct Buffer *buf)
Is the Buffer empty?
Definition: buffer.c:291
char * buf_strdup(const struct Buffer *buf)
Copy a Buffer's string.
Definition: buffer.c:571
#define MUTT_ACL_DELETE
Delete a message.
Definition: mailbox.h:63
#define MUTT_ACL_SEEN
Change the 'seen' status of a message.
Definition: mailbox.h:70
enum QuadOption imap_continue(const char *msg, const char *resp)
Display a message and ask the user if they want to go on.
Definition: util.c:649
static void set_flag(struct Mailbox *m, AclFlags aclflag, bool flag, const char *str, struct Buffer *flags)
Append str to flags if we currently have permission according to aclflag.
Definition: imap.c:187
static bool compare_flags_for_copy(struct Email *e)
Compare local flags against the server.
Definition: imap.c:203
void mutt_str_remove_trailing_ws(char *s)
Trim trailing whitespace from a string.
Definition: string.c:566
struct TagList tags
For drivers that support server tagging.
Definition: email.h:72
struct Mailbox * mailbox
Current selected mailbox.
Definition: adata.h:76
char * flags_remote
Definition: edata.h:49
bool deleted
Email has been deleted.
Definition: edata.h:39
char * flags_system
Definition: edata.h:48
void driver_tags_get_with_hidden(struct TagList *tl, struct Buffer *tags)
Get all tags, also hidden ones, separated by space.
Definition: tags.c:174
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_check_mailbox()

enum MxStatus imap_check_mailbox ( struct Mailbox m,
bool  force 
)

Use the NOOP or IDLE command to poll for new mail.

Parameters
mMailbox
forceDon't wait
Return values
numMxStatus

Definition at line 1035 of file imap.c.

1036{
1037 if (!m || !m->account)
1038 return MX_STATUS_ERROR;
1039
1041 struct ImapMboxData *mdata = imap_mdata_get(m);
1042
1043 /* overload keyboard timeout to avoid many mailbox checks in a row.
1044 * Most users don't like having to wait exactly when they press a key. */
1045 int rc = 0;
1046
1047 /* try IDLE first, unless force is set */
1048 const bool c_imap_idle = cs_subset_bool(NeoMutt->sub, "imap_idle");
1049 const short c_imap_keep_alive = cs_subset_number(NeoMutt->sub, "imap_keep_alive");
1050 if (!force && c_imap_idle && (adata->capabilities & IMAP_CAP_IDLE) &&
1051 ((adata->state != IMAP_IDLE) || (mutt_date_now() >= adata->lastread + c_imap_keep_alive)))
1052 {
1053 if (imap_cmd_idle(adata) < 0)
1054 return MX_STATUS_ERROR;
1055 }
1056 if (adata->state == IMAP_IDLE)
1057 {
1058 while ((rc = mutt_socket_poll(adata->conn, 0)) > 0)
1059 {
1060 if (imap_cmd_step(adata) != IMAP_RES_CONTINUE)
1061 {
1062 mutt_debug(LL_DEBUG1, "Error reading IDLE response\n");
1063 return MX_STATUS_ERROR;
1064 }
1065 }
1066 if (rc < 0)
1067 {
1068 mutt_debug(LL_DEBUG1, "Poll failed, disabling IDLE\n");
1069 adata->capabilities &= ~IMAP_CAP_IDLE; // Clear the flag
1070 }
1071 }
1072
1073 const short c_timeout = cs_subset_number(NeoMutt->sub, "timeout");
1074 if ((force || ((adata->state != IMAP_IDLE) && (mutt_date_now() >= adata->lastread + c_timeout))) &&
1075 (imap_exec(adata, "NOOP", IMAP_CMD_POLL) != IMAP_EXEC_SUCCESS))
1076 {
1077 return MX_STATUS_ERROR;
1078 }
1079
1080 /* We call this even when we haven't run NOOP in case we have pending
1081 * changes to process, since we can reopen here. */
1082 imap_cmd_finish(adata);
1083
1084 enum MxStatus check = MX_STATUS_OK;
1085 if (mdata->check_status & IMAP_EXPUNGE_PENDING)
1086 check = MX_STATUS_REOPENED;
1087 else if (mdata->check_status & IMAP_NEWMAIL_PENDING)
1088 check = MX_STATUS_NEW_MAIL;
1089 else if (mdata->check_status & IMAP_FLAGS_PENDING)
1090 check = MX_STATUS_FLAGS;
1091 else if (rc < 0)
1092 check = MX_STATUS_ERROR;
1093
1094 mdata->check_status = IMAP_OPEN_NO_FLAGS;
1095
1096 if (force)
1097 m->last_checked = 0; // force a check on the next mx_mbox_check() call
1098 return check;
1099}
int imap_cmd_idle(struct ImapAccountData *adata)
Enter the IDLE state.
Definition: command.c:1435
void imap_cmd_finish(struct ImapAccountData *adata)
Attempt to perform cleanup.
Definition: command.c:1368
#define IMAP_CAP_IDLE
RFC2177: IDLE.
Definition: private.h:133
@ IMAP_IDLE
Connection is idle.
Definition: private.h:111
#define IMAP_EXPUNGE_PENDING
Messages on the server have been expunged.
Definition: private.h:66
#define IMAP_OPEN_NO_FLAGS
No flags are set.
Definition: private.h:63
#define IMAP_CMD_POLL
Poll the tcp connection before running the imap command.
Definition: private.h:74
#define IMAP_NEWMAIL_PENDING
New mail is waiting on the server.
Definition: private.h:67
#define IMAP_FLAGS_PENDING
Flags have changed on the server.
Definition: private.h:68
time_t mutt_date_now(void)
Return the number of seconds since the Unix epoch.
Definition: date.c:456
MxStatus
Return values from mbox_check(), mbox_check_stats(), mbox_sync(), and mbox_close()
Definition: mxapi.h:60
@ MX_STATUS_ERROR
An error occurred.
Definition: mxapi.h:61
@ MX_STATUS_OK
No changes.
Definition: mxapi.h:62
@ MX_STATUS_FLAGS
Nondestructive flags change (IMAP)
Definition: mxapi.h:66
@ MX_STATUS_REOPENED
Mailbox was reopened.
Definition: mxapi.h:65
@ MX_STATUS_NEW_MAIL
New mail received in Mailbox.
Definition: mxapi.h:63
time_t lastread
last time we read a command for the server
Definition: adata.h:58
time_t last_checked
Last time we checked this mailbox for new mail.
Definition: mailbox.h:105
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_status()

static int imap_status ( struct ImapAccountData adata,
struct ImapMboxData mdata,
bool  queue 
)
static

Refresh the number of total and new messages.

Parameters
adataIMAP Account data
mdataIMAP Mailbox data
queueQueue the STATUS command
Return values
numTotal number of messages

Definition at line 1108 of file imap.c.

1109{
1110 char *uidvalidity_flag = NULL;
1111 char cmd[2048] = { 0 };
1112
1113 if (!adata || !mdata)
1114 return -1;
1115
1116 /* Don't issue STATUS on the selected mailbox, it will be NOOPed or
1117 * IDLEd elsewhere.
1118 * adata->mailbox may be NULL for connections other than the current
1119 * mailbox's. */
1120 if (adata->mailbox && (adata->mailbox->mdata == mdata))
1121 {
1122 adata->mailbox->has_new = false;
1123 return mdata->messages;
1124 }
1125
1126 if (adata->mailbox && !adata->mailbox->poll_new_mail)
1127 return mdata->messages;
1128
1129 if (adata->capabilities & IMAP_CAP_IMAP4REV1)
1130 {
1131 uidvalidity_flag = "UIDVALIDITY";
1132 }
1133 else if (adata->capabilities & IMAP_CAP_STATUS)
1134 {
1135 uidvalidity_flag = "UID-VALIDITY";
1136 }
1137 else
1138 {
1139 mutt_debug(LL_DEBUG2, "Server doesn't support STATUS\n");
1140 return -1;
1141 }
1142
1143 snprintf(cmd, sizeof(cmd), "STATUS %s (UIDNEXT %s UNSEEN RECENT MESSAGES)",
1144 mdata->munge_name, uidvalidity_flag);
1145
1146 int rc = imap_exec(adata, cmd, queue ? IMAP_CMD_QUEUE : IMAP_CMD_POLL);
1147 if (rc != IMAP_EXEC_SUCCESS)
1148 {
1149 mutt_debug(LL_DEBUG1, "Error queueing command\n");
1150 return rc;
1151 }
1152 return mdata->messages;
1153}
#define IMAP_CAP_STATUS
Server supports STATUS command.
Definition: private.h:123
#define IMAP_CMD_QUEUE
Queue a command, do not execute.
Definition: private.h:73
unsigned int messages
Definition: mdata.h:54
char * munge_name
Munged version of the mailbox name.
Definition: mdata.h:42
bool has_new
Mailbox has new mail.
Definition: mailbox.h:85
bool poll_new_mail
Check for new mail.
Definition: mailbox.h:115
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_path_status()

int imap_path_status ( const char *  path,
bool  queue 
)

Refresh the number of total and new messages.

Parameters
pathMailbox path
queueQueue the STATUS command
Return values
numTotal number of messages

Definition at line 1175 of file imap.c.

1176{
1177 struct Mailbox *m = mx_mbox_find2(path);
1178
1179 const bool is_temp = !m;
1180 if (is_temp)
1181 {
1182 m = mx_path_resolve(path);
1183 if (!mx_mbox_ac_link(m))
1184 {
1185 mailbox_free(&m);
1186 return 0;
1187 }
1188 }
1189
1190 int rc = imap_mailbox_status(m, queue);
1191
1192 if (is_temp)
1193 {
1194 mx_ac_remove(m, false);
1195 mailbox_free(&m);
1196 }
1197
1198 return rc;
1199}
void mailbox_free(struct Mailbox **ptr)
Free a Mailbox.
Definition: mailbox.c:89
int imap_mailbox_status(struct Mailbox *m, bool queue)
Refresh the number of total and new messages.
Definition: imap.c:1210
int mx_ac_remove(struct Mailbox *m, bool keep_account)
Remove a Mailbox from an Account and delete Account if empty.
Definition: mx.c:1745
struct Mailbox * mx_mbox_find2(const char *path)
Find a Mailbox on an Account.
Definition: mx.c:1610
bool mx_mbox_ac_link(struct Mailbox *m)
Link a Mailbox to an existing or new Account.
Definition: mx.c:251
struct Mailbox * mx_path_resolve(const char *path)
Get a Mailbox for a path.
Definition: mx.c:1641
A mailbox.
Definition: mailbox.h:79
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_mailbox_status()

int imap_mailbox_status ( struct Mailbox m,
bool  queue 
)

Refresh the number of total and new messages.

Parameters
mMailbox
queueQueue the STATUS command
Return values
numTotal number of messages
-1Error
Note
Prepare the mailbox if we are not connected

Definition at line 1210 of file imap.c.

1211{
1213 struct ImapMboxData *mdata = imap_mdata_get(m);
1214 if (!adata || !mdata)
1215 return -1;
1216 return imap_status(adata, mdata, queue);
1217}
static int imap_status(struct ImapAccountData *adata, struct ImapMboxData *mdata, bool queue)
Refresh the number of total and new messages.
Definition: imap.c:1108
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_subscribe()

int imap_subscribe ( const char *  path,
bool  subscribe 
)

Subscribe to a mailbox.

Parameters
pathMailbox path
subscribeTrue: subscribe, false: unsubscribe
Return values
0Success
-1Failure

Definition at line 1226 of file imap.c.

1227{
1228 struct ImapAccountData *adata = NULL;
1229 struct ImapMboxData *mdata = NULL;
1230
1231 if (imap_adata_find(path, &adata, &mdata) < 0)
1232 return -1;
1233
1234 if (subscribe)
1235 mutt_message(_("Subscribing to %s..."), mdata->name);
1236 else
1237 mutt_message(_("Unsubscribing from %s..."), mdata->name);
1238
1239 char buf[2048] = { 0 };
1240 snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mdata->munge_name);
1241
1242 if (imap_exec(adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
1243 {
1244 imap_mdata_free((void *) &mdata);
1245 return -1;
1246 }
1247
1248 const bool c_imap_check_subscribed = cs_subset_bool(NeoMutt->sub, "imap_check_subscribed");
1249 if (c_imap_check_subscribed)
1250 {
1251 char mbox[1024] = { 0 };
1252 size_t len = snprintf(mbox, sizeof(mbox), "%smailboxes ", subscribe ? "" : "un");
1253 imap_quote_string(mbox + len, sizeof(mbox) - len, path, true);
1254 struct Buffer *err = buf_pool_get();
1255 if (parse_rc_line(mbox, err))
1256 mutt_debug(LL_DEBUG1, "Error adding subscribed mailbox: %s\n", buf_string(err));
1257 buf_pool_release(&err);
1258 }
1259
1260 if (subscribe)
1261 mutt_message(_("Subscribed to %s"), mdata->name);
1262 else
1263 mutt_message(_("Unsubscribed from %s"), mdata->name);
1264 imap_mdata_free((void *) &mdata);
1265 return 0;
1266}
void imap_mdata_free(void **ptr)
Free the private Mailbox data - Implements Mailbox::mdata_free() -.
Definition: mdata.c:40
void imap_quote_string(char *dest, size_t dlen, const char *src, bool quote_backtick)
Quote string according to IMAP rules.
Definition: util.c:886
int imap_adata_find(const char *path, struct ImapAccountData **adata, struct ImapMboxData **mdata)
Find the Account data for this path.
Definition: util.c:72
enum CommandResult parse_rc_line(const char *line, struct Buffer *err)
Parse a line of user config.
Definition: rc.c:109
char * name
Mailbox name.
Definition: mdata.h:41
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_complete()

int imap_complete ( struct Buffer buf,
const char *  path 
)

Try to complete an IMAP folder path.

Parameters
bufBuffer for result
pathPartial mailbox name to complete
Return values
0Success
-1Failure

Given a partial IMAP folder path, return a string which adds as much to the path as is unique

Definition at line 1278 of file imap.c.

1279{
1280 struct ImapAccountData *adata = NULL;
1281 struct ImapMboxData *mdata = NULL;
1282 char tmp[2048] = { 0 };
1283 struct ImapList listresp = { 0 };
1284 struct Buffer *completion_buf = NULL;
1285 size_t clen;
1286 int completions = 0;
1287 int rc;
1288
1289 if (imap_adata_find(path, &adata, &mdata) < 0)
1290 {
1291 buf_strcpy(buf, path);
1292 return complete_hosts(buf);
1293 }
1294
1295 /* fire off command */
1296 const bool c_imap_list_subscribed = cs_subset_bool(NeoMutt->sub, "imap_list_subscribed");
1297 snprintf(tmp, sizeof(tmp), "%s \"\" \"%s%%\"",
1298 c_imap_list_subscribed ? "LSUB" : "LIST", mdata->real_name);
1299
1300 imap_cmd_start(adata, tmp);
1301
1302 /* and see what the results are */
1303 completion_buf = buf_pool_get();
1304 buf_strcpy(completion_buf, mdata->name);
1305 imap_mdata_free((void *) &mdata);
1306
1307 adata->cmdresult = &listresp;
1308 do
1309 {
1310 listresp.name = NULL;
1311 rc = imap_cmd_step(adata);
1312
1313 if ((rc == IMAP_RES_CONTINUE) && listresp.name)
1314 {
1315 /* if the folder isn't selectable, append delimiter to force browse
1316 * to enter it on second tab. */
1317 if (listresp.noselect)
1318 {
1319 clen = strlen(listresp.name);
1320 listresp.name[clen++] = listresp.delim;
1321 listresp.name[clen] = '\0';
1322 }
1323 /* copy in first word */
1324 if (!completions)
1325 {
1326 buf_strcpy(completion_buf, listresp.name);
1327 completions++;
1328 continue;
1329 }
1330
1331 longest_common_prefix(completion_buf, listresp.name, 0);
1332 completions++;
1333 }
1334 } while (rc == IMAP_RES_CONTINUE);
1335 adata->cmdresult = NULL;
1336
1337 if (completions)
1338 {
1339 /* reformat output */
1340 imap_buf_qualify_path(buf, &adata->conn->account, completion_buf->data);
1341 buf_pretty_mailbox(buf);
1342 buf_fix_dptr(buf);
1343 buf_pool_release(&completion_buf);
1344 return 0;
1345 }
1346
1347 buf_pool_release(&completion_buf);
1348 return -1;
1349}
void imap_buf_qualify_path(struct Buffer *buf, struct ConnAccount *conn_account, char *path)
Make an absolute IMAP folder target to a buffer.
Definition: util.c:869
static int complete_hosts(struct Buffer *buf)
Look for completion matches for mailboxes.
Definition: imap.c:371
void buf_pretty_mailbox(struct Buffer *buf)
Shorten a mailbox path using '~' or '='.
Definition: muttlib.c:519
struct ImapList * cmdresult
Definition: adata.h:66
Items in an IMAP browser.
Definition: private.h:149
bool noselect
Definition: private.h:152
char * name
Definition: private.h:150
char delim
Definition: private.h:151
char * real_name
Original Mailbox name, e.g.: INBOX can be just \0.
Definition: mdata.h:43
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_fast_trash()

int imap_fast_trash ( struct Mailbox m,
const char *  dest 
)

Use server COPY command to copy deleted messages to trash.

Parameters
mMailbox
destMailbox to move to
Return values
-1Error
0Success
1Non-fatal error - try fetch/append

Definition at line 1359 of file imap.c.

1360{
1361 char prompt[1024] = { 0 };
1362 int rc = -1;
1363 bool triedcreate = false;
1364 enum QuadOption err_continue = MUTT_NO;
1365
1367 struct ImapAccountData *dest_adata = NULL;
1368 struct ImapMboxData *dest_mdata = NULL;
1369
1370 if (imap_adata_find(dest, &dest_adata, &dest_mdata) < 0)
1371 return -1;
1372
1373 struct Buffer *sync_cmd = buf_pool_get();
1374
1375 /* check that the save-to folder is in the same account */
1376 if (!imap_account_match(&(adata->conn->account), &(dest_adata->conn->account)))
1377 {
1378 mutt_debug(LL_DEBUG3, "%s not same server as %s\n", dest, mailbox_path(m));
1379 goto out;
1380 }
1381
1382 for (int i = 0; i < m->msg_count; i++)
1383 {
1384 struct Email *e = m->emails[i];
1385 if (!e)
1386 break;
1387 if (e->active && e->changed && e->deleted && !e->purge)
1388 {
1389 rc = imap_sync_message_for_copy(m, e, sync_cmd, &err_continue);
1390 if (rc < 0)
1391 {
1392 mutt_debug(LL_DEBUG1, "could not sync\n");
1393 goto out;
1394 }
1395 }
1396 }
1397
1398 /* loop in case of TRYCREATE */
1399 do
1400 {
1401 struct UidArray uida = ARRAY_HEAD_INITIALIZER;
1402 select_email_uids(m->emails, m->msg_count, MUTT_TRASH, false, false, &uida);
1403 ARRAY_SORT(&uida, imap_sort_uid, NULL);
1404 rc = imap_exec_msg_set(adata, "UID COPY", dest_mdata->munge_name, &uida);
1405 if (rc == 0)
1406 {
1407 mutt_debug(LL_DEBUG1, "No messages to trash\n");
1408 rc = -1;
1409 goto out;
1410 }
1411 else if (rc < 0)
1412 {
1413 mutt_debug(LL_DEBUG1, "could not queue copy\n");
1414 goto out;
1415 }
1416 else if (m->verbose)
1417 {
1418 mutt_message(ngettext("Copying %d message to %s...", "Copying %d messages to %s...", rc),
1419 rc, dest_mdata->name);
1420 }
1421 ARRAY_FREE(&uida);
1422
1423 /* let's get it on */
1424 rc = imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS);
1425 if (rc == IMAP_EXEC_ERROR)
1426 {
1427 if (triedcreate)
1428 {
1429 mutt_debug(LL_DEBUG1, "Already tried to create mailbox %s\n", dest_mdata->name);
1430 break;
1431 }
1432 /* bail out if command failed for reasons other than nonexistent target */
1433 if (!mutt_istr_startswith(imap_get_qualifier(adata->buf), "[TRYCREATE]"))
1434 break;
1435 mutt_debug(LL_DEBUG3, "server suggests TRYCREATE\n");
1436 snprintf(prompt, sizeof(prompt), _("Create %s?"), dest_mdata->name);
1437 const bool c_confirm_create = cs_subset_bool(NeoMutt->sub, "confirm_create");
1438 if (c_confirm_create &&
1439 (query_yesorno_help(prompt, MUTT_YES, NeoMutt->sub, "confirm_create") != MUTT_YES))
1440 {
1442 goto out;
1443 }
1444 if (imap_create_mailbox(adata, dest_mdata->name) < 0)
1445 break;
1446 triedcreate = true;
1447 }
1448 } while (rc == IMAP_EXEC_ERROR);
1449
1450 if (rc != IMAP_EXEC_SUCCESS)
1451 {
1452 imap_error("imap_fast_trash", adata->buf);
1453 goto out;
1454 }
1455
1456 rc = IMAP_EXEC_SUCCESS;
1457
1458out:
1459 buf_pool_release(&sync_cmd);
1460 imap_mdata_free((void *) &dest_mdata);
1461
1462 return ((rc == IMAP_EXEC_SUCCESS) ? 0 : -1);
1463}
#define ARRAY_SORT(head, fn, sdata)
Sort an array.
Definition: array.h:335
int imap_sort_uid(const void *a, const void *b, void *sdata)
Compare two UIDs - Implements sort_t -.
Definition: msg_set.c:55
bool imap_account_match(const struct ConnAccount *a1, const struct ConnAccount *a2)
Compare two Accounts.
Definition: util.c:1093
char * imap_get_qualifier(char *buf)
Get the qualifier from a tagged response.
Definition: util.c:807
int imap_create_mailbox(struct ImapAccountData *adata, const char *mailbox)
Create a new mailbox.
Definition: imap.c:436
int imap_sync_message_for_copy(struct Mailbox *m, struct Email *e, struct Buffer *cmd, enum QuadOption *err_continue)
Update server to reflect the flags of a single message.
Definition: imap.c:929
@ LL_DEBUG3
Log at debug level 3.
Definition: logging2.h:46
@ MUTT_NO
User answered 'No', or assume 'No'.
Definition: quad.h:38
enum QuadOption query_yesorno_help(const char *prompt, enum QuadOption def, struct ConfigSubset *sub, const char *name)
Ask the user a Yes/No question offering help.
Definition: question.c:355
bool verbose
Display status messages?
Definition: mailbox.h:117
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_sync_mailbox()

enum MxStatus imap_sync_mailbox ( struct Mailbox m,
bool  expunge,
bool  close 
)

Sync all the changes to the server.

Parameters
mMailbox
expungeif true do expunge
closeif true we move imap state to CLOSE
Return values
enumMxStatus
Note
The flag retvals come from a call to imap_check_mailbox()

Definition at line 1474 of file imap.c.

1475{
1476 if (!m)
1477 return -1;
1478
1479 struct Email **emails = NULL;
1480 int rc;
1481
1483 struct ImapMboxData *mdata = imap_mdata_get(m);
1484
1485 if (adata->state < IMAP_SELECTED)
1486 {
1487 mutt_debug(LL_DEBUG2, "no mailbox selected\n");
1488 return -1;
1489 }
1490
1491 /* This function is only called when the calling code expects the context
1492 * to be changed. */
1494
1495 enum MxStatus check = imap_check_mailbox(m, false);
1496 if (check == MX_STATUS_ERROR)
1497 return check;
1498
1499 /* if we are expunging anyway, we can do deleted messages very quickly... */
1500 if (expunge && (m->rights & MUTT_ACL_DELETE))
1501 {
1502 struct UidArray uida = ARRAY_HEAD_INITIALIZER;
1503 select_email_uids(m->emails, m->msg_count, MUTT_DELETED, true, false, &uida);
1504 ARRAY_SORT(&uida, imap_sort_uid, NULL);
1505 rc = imap_exec_msg_set(adata, "UID STORE", "+FLAGS.SILENT (\\Deleted)", &uida);
1506 ARRAY_FREE(&uida);
1507 if (rc < 0)
1508 {
1509 mutt_error(_("Expunge failed"));
1510 return rc;
1511 }
1512
1513 if (rc > 0)
1514 {
1515 /* mark these messages as unchanged so second pass ignores them. Done
1516 * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */
1517 for (int i = 0; i < m->msg_count; i++)
1518 {
1519 struct Email *e = m->emails[i];
1520 if (!e)
1521 break;
1522 if (e->deleted && e->changed)
1523 e->active = false;
1524 }
1525 if (m->verbose)
1526 {
1527 mutt_message(ngettext("Marking %d message deleted...",
1528 "Marking %d messages deleted...", rc),
1529 rc);
1530 }
1531 }
1532 }
1533
1534#ifdef USE_HCACHE
1535 imap_hcache_open(adata, mdata, true);
1536#endif
1537
1538 /* save messages with real (non-flag) changes */
1539 for (int i = 0; i < m->msg_count; i++)
1540 {
1541 struct Email *e = m->emails[i];
1542 if (!e)
1543 break;
1544
1545 if (e->deleted)
1546 {
1547 imap_cache_del(m, e);
1548#ifdef USE_HCACHE
1549 imap_hcache_del(mdata, imap_edata_get(e)->uid);
1550#endif
1551 }
1552
1553 if (e->active && e->changed)
1554 {
1555#ifdef USE_HCACHE
1556 imap_hcache_put(mdata, e);
1557#endif
1558 /* if the message has been rethreaded or attachments have been deleted
1559 * we delete the message and reupload it.
1560 * This works better if we're expunging, of course. */
1561 if (e->env->changed || e->attach_del)
1562 {
1563 /* L10N: The plural is chosen by the last %d, i.e. the total number */
1564 if (m->verbose)
1565 {
1566 mutt_message(ngettext("Saving changed message... [%d/%d]",
1567 "Saving changed messages... [%d/%d]", m->msg_count),
1568 i + 1, m->msg_count);
1569 }
1570 bool save_append = m->append;
1571 m->append = true;
1573 m->append = save_append;
1574 e->env->changed = false;
1575 }
1576 }
1577 }
1578
1579#ifdef USE_HCACHE
1580 imap_hcache_close(mdata);
1581#endif
1582
1583 /* presort here to avoid doing 10 resorts in imap_exec_msg_set */
1584 emails = MUTT_MEM_MALLOC(m->msg_count, struct Email *);
1585 memcpy(emails, m->emails, m->msg_count * sizeof(struct Email *));
1586 mutt_qsort_r(emails, m->msg_count, sizeof(struct Email *), imap_sort_email_uid, NULL);
1587
1588 rc = sync_helper(m, emails, m->msg_count, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted");
1589 if (rc >= 0)
1590 rc |= sync_helper(m, emails, m->msg_count, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged");
1591 if (rc >= 0)
1592 rc |= sync_helper(m, emails, m->msg_count, MUTT_ACL_WRITE, MUTT_OLD, "Old");
1593 if (rc >= 0)
1594 rc |= sync_helper(m, emails, m->msg_count, MUTT_ACL_SEEN, MUTT_READ, "\\Seen");
1595 if (rc >= 0)
1596 rc |= sync_helper(m, emails, m->msg_count, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered");
1597
1598 FREE(&emails);
1599
1600 /* Flush the queued flags if any were changed in sync_helper. */
1601 if (rc > 0)
1602 if (imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
1603 rc = -1;
1604
1605 if (rc < 0)
1606 {
1607 if (close)
1608 {
1609 if (query_yesorno(_("Error saving flags. Close anyway?"), MUTT_NO) == MUTT_YES)
1610 {
1611 adata->state = IMAP_AUTHENTICATED;
1612 return 0;
1613 }
1614 }
1615 else
1616 {
1617 mutt_error(_("Error saving flags"));
1618 }
1619 return -1;
1620 }
1621
1622 /* Update local record of server state to reflect the synchronization just
1623 * completed. imap_read_headers always overwrites hcache-origin flags, so
1624 * there is no need to mutate the hcache after flag-only changes. */
1625 for (int i = 0; i < m->msg_count; i++)
1626 {
1627 struct Email *e = m->emails[i];
1628 if (!e)
1629 break;
1630 struct ImapEmailData *edata = imap_edata_get(e);
1631 edata->deleted = e->deleted;
1632 edata->flagged = e->flagged;
1633 edata->old = e->old;
1634 edata->read = e->read;
1635 edata->replied = e->replied;
1636 e->changed = false;
1637 }
1638 m->changed = false;
1639
1640 /* We must send an EXPUNGE command if we're not closing. */
1641 if (expunge && !close && (m->rights & MUTT_ACL_DELETE))
1642 {
1643 if (m->verbose)
1644 mutt_message(_("Expunging messages from server..."));
1645 /* Set expunge bit so we don't get spurious reopened messages */
1646 mdata->reopen |= IMAP_EXPUNGE_EXPECTED;
1647 if (imap_exec(adata, "EXPUNGE", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
1648 {
1649 mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED;
1650 imap_error(_("imap_sync_mailbox: EXPUNGE failed"), adata->buf);
1651 return -1;
1652 }
1653 mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED;
1654 }
1655
1656 if (expunge && close)
1657 {
1658 adata->closing = true;
1659 imap_exec(adata, "CLOSE", IMAP_CMD_NO_FLAGS);
1660 adata->state = IMAP_AUTHENTICATED;
1661 }
1662
1663 const bool c_message_cache_clean = cs_subset_bool(NeoMutt->sub, "message_cache_clean");
1664 if (c_message_cache_clean)
1666
1667 return check;
1668}
int mutt_save_message_mbox(struct Mailbox *m_src, struct Email *e, enum MessageSaveOpt save_opt, enum MessageTransformOpt transform_opt, struct Mailbox *m_dst)
Save a message to a given mailbox.
Definition: external.c:737
@ TRANSFORM_NONE
No transformation.
Definition: external.h:42
@ SAVE_MOVE
Move message to another mailbox, removing the original.
Definition: external.h:53
static int imap_sort_email_uid(const void *a, const void *b, void *sdata)
Compare two Emails by UID - Implements sort_t -.
Definition: imap.c:903
int imap_cache_clean(struct Mailbox *m)
Delete all the entries in the message cache.
Definition: message.c:1888
void imap_allow_reopen(struct Mailbox *m)
Allow re-opening a folder upon expunge.
Definition: util.c:1065
@ IMAP_SELECTED
Mailbox is selected.
Definition: private.h:108
#define IMAP_EXPUNGE_EXPECTED
Messages will be expunged from the server.
Definition: private.h:65
int imap_hcache_put(struct ImapMboxData *mdata, struct Email *e)
Add an entry to the header cache.
Definition: util.c:383
static int sync_helper(struct Mailbox *m, struct Email **emails, int num_emails, AclFlags right, enum MessageType flag, const char *name)
Sync flag changes to the server.
Definition: imap.c:300
enum MxStatus imap_check_mailbox(struct Mailbox *m, bool force)
Use the NOOP or IDLE command to poll for new mail.
Definition: imap.c:1035
#define MUTT_MEM_MALLOC(n, type)
Definition: memory.h:41
void mutt_qsort_r(void *base, size_t nmemb, size_t size, sort_t compar, void *sdata)
Sort an array, where the comparator has access to opaque data rather than requiring global variables.
Definition: qsort_r.c:67
enum QuadOption query_yesorno(const char *prompt, enum QuadOption def)
Ask the user a Yes/No question.
Definition: question.c:327
struct Envelope * env
Envelope information.
Definition: email.h:68
bool attach_del
Has an attachment marked for deletion.
Definition: email.h:99
unsigned char changed
Changed fields, e.g. MUTT_ENV_CHANGED_SUBJECT.
Definition: envelope.h:90
bool closing
If true, we are waiting for CLOSE completion.
Definition: adata.h:43
ImapOpenFlags reopen
Flags, e.g. IMAP_REOPEN_ALLOW.
Definition: mdata.h:45
bool changed
Mailbox has been modified.
Definition: mailbox.h:110
bool append
Mailbox is opened in append mode.
Definition: mailbox.h:109
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_mbox_select()

static void imap_mbox_select ( struct Mailbox m)
static

Select a Mailbox.

Parameters
mMailbox

Definition at line 1747 of file imap.c.

1748{
1750 struct ImapMboxData *mdata = imap_mdata_get(m);
1751 if (!adata || !mdata)
1752 return;
1753
1754 const char *condstore = NULL;
1755#ifdef USE_HCACHE
1756 const bool c_imap_condstore = cs_subset_bool(NeoMutt->sub, "imap_condstore");
1757 if ((adata->capabilities & IMAP_CAP_CONDSTORE) && c_imap_condstore)
1758 condstore = " (CONDSTORE)";
1759 else
1760#endif
1761 condstore = "";
1762
1763 char buf[PATH_MAX] = { 0 };
1764 snprintf(buf, sizeof(buf), "%s %s%s", m->readonly ? "EXAMINE" : "SELECT",
1765 mdata->munge_name, condstore);
1766
1767 adata->state = IMAP_SELECTED;
1768
1769 imap_cmd_start(adata, buf);
1770}
#define IMAP_CAP_CONDSTORE
RFC7162.
Definition: private.h:136
bool readonly
Don't allow changes to the mailbox.
Definition: mailbox.h:116
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ imap_login()

int imap_login ( struct ImapAccountData adata)

Open an IMAP connection.

Parameters
adataImap Account data
Return values
0Success
-1Failure

Ensure ImapAccountData is connected and logged into the imap server.

Definition at line 1780 of file imap.c.

1781{
1782 if (!adata)
1783 return -1;
1784
1785 if (adata->state == IMAP_DISCONNECTED)
1786 {
1787 buf_reset(&adata->cmdbuf); // purge outstanding queued commands
1788 imap_open_connection(adata);
1789 }
1790 if (adata->state == IMAP_CONNECTED)
1791 {
1793 {
1794 adata->state = IMAP_AUTHENTICATED;
1795 FREE(&adata->capstr);
1796 if (adata->conn->ssf != 0)
1797 {
1798 mutt_debug(LL_DEBUG2, "Communication encrypted at %d bits\n",
1799 adata->conn->ssf);
1800 }
1801 }
1802 else
1803 {
1805 }
1806 }
1807 if (adata->state == IMAP_AUTHENTICATED)
1808 {
1809 /* capabilities may have changed */
1810 imap_exec(adata, "CAPABILITY", IMAP_CMD_PASS);
1811
1812#ifdef USE_ZLIB
1813 /* RFC4978 */
1814 const bool c_imap_deflate = cs_subset_bool(NeoMutt->sub, "imap_deflate");
1815 if ((adata->capabilities & IMAP_CAP_COMPRESS) && c_imap_deflate &&
1816 (imap_exec(adata, "COMPRESS DEFLATE", IMAP_CMD_PASS) == IMAP_EXEC_SUCCESS))
1817 {
1818 mutt_debug(LL_DEBUG2, "IMAP compression is enabled on connection to %s\n",
1819 adata->conn->account.host);
1820 mutt_zstrm_wrap_conn(adata->conn);
1821 }
1822#endif
1823
1824 /* enable RFC2971, if the server supports that */
1825 const bool c_imap_send_id = cs_subset_bool(NeoMutt->sub, "imap_send_id");
1826 if (c_imap_send_id && (adata->capabilities & IMAP_CAP_ID))
1827 {
1828 imap_exec(adata, "ID (\"name\" \"NeoMutt\" \"version\" \"" PACKAGE_VERSION "\")",
1830 }
1831
1832 /* enable RFC6855, if the server supports that */
1833 const bool c_imap_rfc5161 = cs_subset_bool(NeoMutt->sub, "imap_rfc5161");
1834 if (c_imap_rfc5161 && (adata->capabilities & IMAP_CAP_ENABLE))
1835 imap_exec(adata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE);
1836
1837 /* enable QRESYNC. Advertising QRESYNC also means CONDSTORE
1838 * is supported (even if not advertised), so flip that bit. */
1839 if (adata->capabilities & IMAP_CAP_QRESYNC)
1840 {
1842 const bool c_imap_qresync = cs_subset_bool(NeoMutt->sub, "imap_qresync");
1843 if (c_imap_rfc5161 && c_imap_qresync)
1844 imap_exec(adata, "ENABLE QRESYNC", IMAP_CMD_QUEUE);
1845 }
1846
1847 /* get root delimiter, '/' as default */
1848 adata->delim = '/';
1849 imap_exec(adata, "LIST \"\" \"\"", IMAP_CMD_QUEUE);
1850
1851 /* we may need the root delimiter before we open a mailbox */
1852 imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS);
1853
1854 /* select the mailbox that used to be open before disconnect */
1855 if (adata->mailbox)
1856 {
1857 imap_mbox_select(adata->mailbox);
1858 }
1859 }
1860
1861 if (adata->state < IMAP_AUTHENTICATED)
1862 return -1;
1863
1864 return 0;
1865}
@ IMAP_AUTH_SUCCESS
Authentication successful.
Definition: auth.h:40
void buf_reset(struct Buffer *buf)
Reset an existing Buffer.
Definition: buffer.c:76
void mutt_account_unsetpass(struct ConnAccount *cac)
Unset ConnAccount's password.
Definition: connaccount.c:178
int imap_authenticate(struct ImapAccountData *adata)
Authenticate to an IMAP server.
Definition: auth.c:115
#define IMAP_CAP_ENABLE
RFC5161.
Definition: private.h:135
#define IMAP_CAP_ID
RFC2971: IMAP4 ID extension.
Definition: private.h:141
#define IMAP_CMD_PASS
Command contains a password. Suppress logging.
Definition: private.h:72
#define IMAP_CAP_QRESYNC
RFC7162.
Definition: private.h:137
#define IMAP_CAP_COMPRESS
RFC4978: COMPRESS=DEFLATE.
Definition: private.h:139
int imap_open_connection(struct ImapAccountData *adata)
Open an IMAP connection.
Definition: imap.c:744
static void imap_mbox_select(struct Mailbox *m)
Select a Mailbox.
Definition: imap.c:1747
char delim
Path delimiter.
Definition: adata.h:75
struct Buffer cmdbuf
Definition: adata.h:73
void mutt_zstrm_wrap_conn(struct Connection *conn)
Wrap a compression layer around a Connection.
Definition: zstrm.c:291
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

Variable Documentation

◆ ImapCommands

const struct Command ImapCommands[]
static
Initial value:
= {
{ "subscribe-to", parse_subscribe_to, 0 },
{ "unsubscribe-from", parse_unsubscribe_from, 0 },
{ NULL, NULL, 0 },
}
enum CommandResult parse_unsubscribe_from(struct Buffer *buf, struct Buffer *s, intptr_t data, struct Buffer *err)
Parse the 'unsubscribe-from' command - Implements Command::parse() -.
Definition: commands.c:1590
enum CommandResult parse_subscribe_to(struct Buffer *buf, struct Buffer *s, intptr_t data, struct Buffer *err)
Parse the 'subscribe-to' command - Implements Command::parse() -.
Definition: commands.c:1252

Imap Commands.

Definition at line 85 of file imap.c.