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 /* command.c: routines for sending commands to an IMAP server and parsing
21 #include "lib/debug.h"
27 #include "imap_private.h"
32 #define IMAP_CMD_BUFSIZE 512
34 /* forward declarations */
35 static void cmd_handle_fatal (IMAP_DATA * idata);
36 static int cmd_handle_untagged (IMAP_DATA * idata);
37 static void cmd_make_sequence (IMAP_DATA * idata);
38 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s);
39 static void cmd_parse_expunge (IMAP_DATA * idata, const char *s);
40 static void cmd_parse_lsub (IMAP_DATA* idata, char* s);
41 static void cmd_parse_fetch (IMAP_DATA * idata, char *s);
42 static void cmd_parse_myrights (IMAP_DATA * idata, char *s);
43 static void cmd_parse_search (IMAP_DATA* idata, char* s);
45 static char *Capabilities[] = {
60 /* imap_cmd_start: Given an IMAP command, send it to the server.
61 * Currently a minor convenience, but helps to route all IMAP commands
62 * through a single interface. */
63 int imap_cmd_start (IMAP_DATA * idata, const char *cmd)
69 if (idata->status == IMAP_FATAL) {
70 cmd_handle_fatal (idata);
74 cmd_make_sequence (idata);
75 /* seq, space, cmd, \r\n\0 */
76 outlen = str_len (idata->cmd.seq) + str_len (cmd) + 4;
77 out = (char *) mem_malloc (outlen);
78 snprintf (out, outlen, "%s %s\r\n", idata->cmd.seq, cmd);
80 rc = mutt_socket_write (idata->conn, out);
84 return (rc < 0) ? IMAP_CMD_BAD : 0;
87 /* imap_cmd_step: Reads server responses from an IMAP command, detects
88 * tagged completion response, handles untagged messages, can read
89 * arbitrarily large strings (using malloc, so don't make it _too_
91 int imap_cmd_step (IMAP_DATA * idata)
93 IMAP_COMMAND *cmd = &idata->cmd;
97 if (idata->status == IMAP_FATAL) {
98 cmd_handle_fatal (idata);
102 /* read into buffer, expanding buffer as necessary until we have a full
105 if (len == cmd->blen) {
106 mem_realloc (&cmd->buf, cmd->blen + IMAP_CMD_BUFSIZE);
107 cmd->blen = cmd->blen + IMAP_CMD_BUFSIZE;
108 debug_print (3, ("grew buffer to %u bytes\n", cmd->blen));
114 c = mutt_socket_readln (cmd->buf + len, cmd->blen - len, idata->conn);
116 debug_print (1, ("Error reading server response.\n"));
117 /* cmd_handle_fatal (idata); */
123 /* if we've read all the way to the end of the buffer, we haven't read a
124 * full line (mutt_socket_readln strips the \r, so we always have at least
125 * one character free when we've read a full line) */
126 while (len == cmd->blen);
128 /* don't let one large string make cmd->buf hog memory forever */
129 if ((cmd->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE)) {
130 mem_realloc (&cmd->buf, IMAP_CMD_BUFSIZE);
131 cmd->blen = IMAP_CMD_BUFSIZE;
132 debug_print (3, ("shrank buffer to %u bytes\n", cmd->blen));
135 idata->lastread = time (NULL);
137 /* handle untagged messages. The caller still gets its shot afterwards. */
138 if (!ascii_strncmp (cmd->buf, "* ", 2) && cmd_handle_untagged (idata))
141 /* server demands a continuation response from us */
142 if (cmd->buf[0] == '+')
143 return IMAP_CMD_RESPOND;
145 /* tagged completion code */
146 if (!ascii_strncmp (cmd->buf, cmd->seq, SEQLEN)) {
147 imap_cmd_finish (idata);
148 return imap_code (cmd->buf) ? IMAP_CMD_OK : IMAP_CMD_NO;
151 return IMAP_CMD_CONTINUE;
154 /* imap_code: returns 1 if the command result was OK, or 0 if NO or BAD */
155 int imap_code (const char *s)
159 return (ascii_strncasecmp ("OK", s, 2) == 0);
162 /* imap_exec: execute a command, and wait for the response from the server.
163 * Also, handle untagged responses.
165 * IMAP_CMD_FAIL_OK: the calling procedure can handle failure. This is used
166 * for checking for a mailbox on append and login
167 * IMAP_CMD_PASS: command contains a password. Suppress logging.
168 * Return 0 on success, -1 on Failure, -2 on OK Failure
170 int imap_exec (IMAP_DATA * idata, const char *cmd, int flags)
177 mutt_error (_("No mailbox is open."));
182 if (idata->status == IMAP_FATAL) {
183 cmd_handle_fatal (idata);
187 /* create sequence for command */
188 cmd_make_sequence (idata);
189 /* seq, space, cmd, \r\n\0 */
190 outlen = str_len (idata->cmd.seq) + str_len (cmd) + 4;
191 out = (char *) mem_malloc (outlen);
192 snprintf (out, outlen, "%s %s\r\n", idata->cmd.seq, cmd);
194 rc = mutt_socket_write_d (idata->conn, out,
195 flags & IMAP_CMD_PASS ? IMAP_LOG_PASS :
200 cmd_handle_fatal (idata);
205 rc = imap_cmd_step (idata);
206 while (rc == IMAP_CMD_CONTINUE);
208 if (rc == IMAP_CMD_BAD) {
209 if (imap_reconnect (idata->ctx) != 0) {
215 if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK))
218 if (rc != IMAP_CMD_OK) {
219 if (flags & IMAP_CMD_FAIL_OK)
222 debug_print (1, ("command failed: %s\n", idata->cmd.buf));
229 /* imap_cmd_running: Returns whether an IMAP command is in progress. */
230 int imap_cmd_running (IMAP_DATA * idata)
232 if (idata->cmd.state == IMAP_CMD_CONTINUE ||
233 idata->cmd.state == IMAP_CMD_RESPOND)
239 /* imap_cmd_finish: Attempts to perform cleanup (eg fetch new mail if
240 * detected, do expunge). Called automatically by imap_cmd_step, but
241 * may be called at any time. Called by imap_check_mailbox just before
242 * the index is refreshed, for instance. */
243 void imap_cmd_finish (IMAP_DATA * idata)
245 if (idata->status == IMAP_FATAL) {
246 cmd_handle_fatal (idata);
250 if (!(idata->state == IMAP_SELECTED) || idata->ctx->closing)
253 if (idata->reopen & IMAP_REOPEN_ALLOW) {
254 int count = idata->newMailCount;
256 if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
257 (idata->reopen & IMAP_NEWMAIL_PENDING)
258 && count > idata->ctx->msgcount) {
259 /* read new mail messages */
260 debug_print (2, ("Fetching new mail\n"));
261 /* check_status: curs_main uses imap_check_mailbox to detect
262 * whether the index needs updating */
263 idata->check_status = IMAP_NEWMAIL_PENDING;
264 imap_read_headers (idata, idata->ctx->msgcount, count - 1);
266 else if (idata->reopen & IMAP_EXPUNGE_PENDING) {
267 debug_print (2, ("Expunging mailbox\n"));
268 imap_expunge_mailbox (idata);
269 /* Detect whether we've gotten unexpected EXPUNGE messages */
270 if (idata->reopen & IMAP_EXPUNGE_PENDING &&
271 !(idata->reopen & IMAP_EXPUNGE_EXPECTED))
272 idata->check_status = IMAP_EXPUNGE_PENDING;
273 idata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING |
274 IMAP_EXPUNGE_EXPECTED);
281 /* cmd_handle_fatal: when IMAP_DATA is in fatal state, do what we can */
282 static void cmd_handle_fatal (IMAP_DATA * idata)
284 idata->status = IMAP_FATAL;
286 if ((idata->state == IMAP_SELECTED) &&
287 (idata->reopen & IMAP_REOPEN_ALLOW)) {
288 /* mx_fastclose_mailbox (idata->ctx); */
289 mutt_error (_("Mailbox closed"));
291 idata->state = IMAP_DISCONNECTED;
292 if (imap_reconnect (idata->ctx) != 0)
293 mx_fastclose_mailbox (idata->ctx);
296 if (idata->state != IMAP_SELECTED) {
297 idata->state = IMAP_DISCONNECTED;
298 mutt_socket_close (idata->conn);
303 /* cmd_handle_untagged: fallback parser for otherwise unhandled messages. */
304 static int cmd_handle_untagged (IMAP_DATA * idata)
310 s = imap_next_word (idata->cmd.buf);
312 if ((idata->state == IMAP_SELECTED) && isdigit ((unsigned char) *s)) {
314 s = imap_next_word (s);
316 /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
317 * connection, so update that one.
319 if (ascii_strncasecmp ("EXISTS", s, 6) == 0) {
320 debug_print (2, ("Handling EXISTS\n"));
322 /* new mail arrived */
325 if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
326 count < idata->ctx->msgcount) {
327 /* something is wrong because the server reported fewer messages
328 * than we previously saw
330 mutt_error _("Fatal error. Message count is out of sync!");
332 idata->status = IMAP_FATAL;
335 /* at least the InterChange server sends EXISTS messages freely,
336 * even when there is no new mail */
337 else if (count == idata->ctx->msgcount)
338 debug_print (3, ("superfluous EXISTS message.\n"));
340 if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) {
341 debug_print (2, ("New mail in %s - %d messages total.\n", idata->mailbox, count));
342 idata->reopen |= IMAP_NEWMAIL_PENDING;
344 idata->newMailCount = count;
347 /* pn vs. s: need initial seqno */
348 else if (ascii_strncasecmp ("EXPUNGE", s, 7) == 0)
349 cmd_parse_expunge (idata, pn);
350 else if (ascii_strncasecmp ("FETCH", s, 5) == 0)
351 cmd_parse_fetch (idata, pn);
353 else if (ascii_strncasecmp ("CAPABILITY", s, 10) == 0)
354 cmd_parse_capabilities (idata, s);
355 else if (ascii_strncasecmp ("LSUB", s, 4) == 0)
356 cmd_parse_lsub (idata, s);
357 else if (ascii_strncasecmp ("MYRIGHTS", s, 8) == 0)
358 cmd_parse_myrights (idata, s);
359 else if (ascii_strncasecmp ("SEARCH", s, 6) == 0)
360 cmd_parse_search (idata, s);
361 else if (ascii_strncasecmp ("BYE", s, 3) == 0) {
362 debug_print (2, ("Handling BYE\n"));
364 /* check if we're logging out */
365 if (idata->status == IMAP_BYE)
368 /* server shut down our connection */
371 mutt_error ("%s", s);
373 cmd_handle_fatal (idata);
376 else if (option (OPTIMAPSERVERNOISE)
377 && (ascii_strncasecmp ("NO", s, 2) == 0)) {
378 debug_print (2, ("Handling untagged NO\n"));
380 /* Display the warning message from the server */
381 mutt_error ("%s", s + 3);
388 /* This should be optimised (eg with a tree or hash) */
389 static int uid2msgno (IMAP_DATA* idata, unsigned int uid) {
392 for (i = 0; i < idata->ctx->msgcount; i++) {
393 HEADER* h = idata->ctx->hdrs[i];
394 if (HEADER_DATA(h)->uid == uid)
401 /* cmd_parse_search: store SEARCH response for later use */
402 static void cmd_parse_search (IMAP_DATA* idata, char* s) {
406 debug_print (2, ("Handling SEARCH\n"));
408 while ((s = imap_next_word (s)) && *s != '\0') {
410 msgno = uid2msgno (idata, uid);
413 idata->ctx->hdrs[uid2msgno (idata, uid)]->matched = 1;
417 /* cmd_make_sequence: make a tag suitable for starting an IMAP command */
418 static void cmd_make_sequence (IMAP_DATA * idata)
420 snprintf (idata->cmd.seq, sizeof (idata->cmd.seq), "a%04u", idata->seqno++);
422 if (idata->seqno > 9999)
426 /* cmd_parse_capabilities: set capability bits according to CAPABILITY
428 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s)
432 debug_print (2, ("Handling CAPABILITY\n"));
434 s = imap_next_word (s);
435 mem_free (&idata->capstr);
436 idata->capstr = str_dup (s);
438 memset (idata->capabilities, 0, sizeof (idata->capabilities));
441 for (x = 0; x < CAPMAX; x++)
442 if (imap_wordcasecmp (Capabilities[x], s) == 0) {
443 mutt_bit_set (idata->capabilities, x);
446 s = imap_next_word (s);
450 /* cmd_parse_expunge: mark headers with new sequence ID and mark idata to
451 * be reopened at our earliest convenience */
452 static void cmd_parse_expunge (IMAP_DATA * idata, const char *s)
457 debug_print (2, ("Handling EXPUNGE\n"));
461 /* walk headers, zero seqno of expunged message, decrement seqno of those
462 * above. Possibly we could avoid walking the whole list by resorting
463 * and guessing a good starting point, but I'm guessing the resort would
464 * nullify the gains */
465 for (cur = 0; cur < idata->ctx->msgcount; cur++) {
466 h = idata->ctx->hdrs[cur];
468 if (h->index + 1 == expno)
470 else if (h->index + 1 > expno)
474 idata->reopen |= IMAP_EXPUNGE_PENDING;
477 /* cmd_parse_fetch: Load fetch response into IMAP_DATA. Currently only
478 * handles unanticipated FETCH responses, and only FLAGS data. We get
479 * these if another client has changed flags for a mailbox we've selected.
480 * Of course, a lot of code here duplicates code in message.c. */
481 static void cmd_parse_fetch (IMAP_DATA * idata, char *s)
486 debug_print (2, ("Handling FETCH\n"));
490 if (msgno <= idata->ctx->msgcount)
491 /* see cmd_parse_expunge */
492 for (cur = 0; cur < idata->ctx->msgcount; cur++) {
493 h = idata->ctx->hdrs[cur];
495 if (h->active && h->index + 1 == msgno) {
496 debug_print (2, ("Message UID %d updated\n", HEADER_DATA (h)->uid));
504 debug_print (1, ("FETCH response ignored for this message\n"));
509 s = imap_next_word (s);
510 s = imap_next_word (s);
513 debug_print (1, ("Malformed FETCH response\n"));
518 if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
519 debug_print (2, ("Only handle FLAGS updates\n"));
523 /* If server flags could conflict with mutt's flags, reopen the mailbox. */
525 idata->reopen |= IMAP_EXPUNGE_PENDING;
527 imap_set_flags (idata, h, s);
528 idata->check_status = IMAP_FLAGS_PENDING;
532 static void cmd_parse_lsub (IMAP_DATA* idata, char* s) {
539 if (!option (OPTIMAPCHECKSUBSCRIBED))
542 s = imap_next_word (s); /* flags */
545 debug_print (1, ("Bad LSUB response\n"));
551 for (ep = s; *ep && *ep != ')'; ep++);
553 if (!ascii_strncasecmp (s, "\\NoSelect", 9))
555 while (s < ep && *s != ' ' && *s != ')')
561 s = imap_next_word (s); /* delim */
562 s = imap_next_word (s); /* name */
565 imap_unmunge_mbox_name (s);
566 debug_print (2, ("Subscribing to %s\n", s));
568 strfcpy (buf, "mailboxes \"", sizeof (buf));
569 mutt_account_tourl (&idata->conn->account, &url);
571 if (!str_cmp (url.user, ImapUser))
573 url_ciss_tostring (&url, buf + 11, sizeof (buf) - 10, 0);
574 str_cat (buf, sizeof (buf), "\"");
575 memset (&token, 0, sizeof (token));
577 err.dsize = sizeof (errstr);
578 if (mutt_parse_rc_line (buf, &token, &err))
579 debug_print (1, ("Error adding subscribed mailbox: %s\n", errstr));
580 mem_free (&token.data);
583 debug_print (1, ("Bad LSUB response\n"));
586 /* cmd_parse_myrights: set rights bits according to MYRIGHTS response */
587 static void cmd_parse_myrights (IMAP_DATA * idata, char *s)
589 debug_print (2, ("Handling MYRIGHTS\n"));
591 s = imap_next_word (s);
592 s = imap_next_word (s);
594 /* zero out current rights set */
595 memset (idata->rights, 0, sizeof (idata->rights));
597 while (*s && !isspace ((unsigned char) *s)) {
600 mutt_bit_set (idata->rights, ACL_LOOKUP);
603 mutt_bit_set (idata->rights, ACL_READ);
606 mutt_bit_set (idata->rights, ACL_SEEN);
609 mutt_bit_set (idata->rights, ACL_WRITE);
612 mutt_bit_set (idata->rights, ACL_INSERT);
615 mutt_bit_set (idata->rights, ACL_POST);
618 mutt_bit_set (idata->rights, ACL_CREATE);
621 mutt_bit_set (idata->rights, ACL_DELETE);
624 mutt_bit_set (idata->rights, ACL_ADMIN);