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
19 #include <lib-lib/mem.h>
20 #include <lib-lib/ascii.h>
21 #include <lib-lib/macros.h>
23 #include "lib/debug.h"
28 #include "imap_private.h"
33 #define IMAP_CMD_BUFSIZE 512
35 /* forward declarations */
36 static void cmd_handle_fatal (IMAP_DATA * idata);
37 static int cmd_handle_untagged (IMAP_DATA * idata);
38 static void cmd_make_sequence (IMAP_DATA * idata);
39 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s);
40 static void cmd_parse_expunge (IMAP_DATA * idata, const char *s);
41 static void cmd_parse_lsub (IMAP_DATA* idata, char* s);
42 static void cmd_parse_fetch (IMAP_DATA * idata, char *s);
43 static void cmd_parse_myrights (IMAP_DATA * idata, char *s);
44 static void cmd_parse_search (IMAP_DATA* idata, char* s);
46 static const char *Capabilities[] = {
61 /* imap_cmd_start: Given an IMAP command, send it to the server.
62 * Currently a minor convenience, but helps to route all IMAP commands
63 * through a single interface. */
64 int imap_cmd_start (IMAP_DATA * idata, const char *cmd)
70 if (idata->status == IMAP_FATAL) {
71 cmd_handle_fatal (idata);
75 cmd_make_sequence (idata);
76 /* seq, space, cmd, \r\n\0 */
77 outlen = m_strlen(idata->cmd.seq) + m_strlen(cmd) + 4;
78 out = p_new(char, outlen);
79 snprintf (out, outlen, "%s %s\r\n", idata->cmd.seq, cmd);
81 rc = mutt_socket_write (idata->conn, out);
85 return (rc < 0) ? IMAP_CMD_BAD : 0;
88 /* imap_cmd_step: Reads server responses from an IMAP command, detects
89 * tagged completion response, handles untagged messages, can read
90 * arbitrarily large strings (using malloc, so don't make it _too_
92 int imap_cmd_step (IMAP_DATA * idata)
94 IMAP_COMMAND *cmd = &idata->cmd;
98 if (idata->status == IMAP_FATAL) {
99 cmd_handle_fatal (idata);
103 /* read into buffer, expanding buffer as necessary until we have a full
106 if (len == cmd->blen) {
107 p_realloc(&cmd->buf, cmd->blen + IMAP_CMD_BUFSIZE);
108 cmd->blen = cmd->blen + IMAP_CMD_BUFSIZE;
109 debug_print (3, ("grew buffer to %u bytes\n", cmd->blen));
115 c = mutt_socket_readln (cmd->buf + len, cmd->blen - len, idata->conn);
117 debug_print (1, ("Error reading server response.\n"));
118 /* cmd_handle_fatal (idata); */
124 /* if we've read all the way to the end of the buffer, we haven't read a
125 * full line (mutt_socket_readln strips the \r, so we always have at least
126 * one character free when we've read a full line) */
127 while (len == cmd->blen);
129 /* don't let one large string make cmd->buf hog memory forever */
130 if ((cmd->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE)) {
131 p_realloc(&cmd->buf, IMAP_CMD_BUFSIZE);
132 cmd->blen = IMAP_CMD_BUFSIZE;
133 debug_print (3, ("shrank buffer to %u bytes\n", cmd->blen));
136 idata->lastread = time (NULL);
138 /* handle untagged messages. The caller still gets its shot afterwards. */
139 if (!ascii_strncmp (cmd->buf, "* ", 2) && cmd_handle_untagged (idata))
142 /* server demands a continuation response from us */
143 if (cmd->buf[0] == '+')
144 return IMAP_CMD_RESPOND;
146 /* tagged completion code */
147 if (!ascii_strncmp (cmd->buf, cmd->seq, SEQLEN)) {
148 imap_cmd_finish (idata);
149 return imap_code (cmd->buf) ? IMAP_CMD_OK : IMAP_CMD_NO;
152 return IMAP_CMD_CONTINUE;
155 /* imap_code: returns 1 if the command result was OK, or 0 if NO or BAD */
156 int imap_code (const char *s)
160 return (ascii_strncasecmp ("OK", s, 2) == 0);
163 /* imap_exec: execute a command, and wait for the response from the server.
164 * Also, handle untagged responses.
166 * IMAP_CMD_FAIL_OK: the calling procedure can handle failure. This is used
167 * for checking for a mailbox on append and login
168 * IMAP_CMD_PASS: command contains a password. Suppress logging.
169 * Return 0 on success, -1 on Failure, -2 on OK Failure
171 int imap_exec (IMAP_DATA * idata, const char *cmd, int flags)
178 mutt_error (_("No mailbox is open."));
183 if (idata->status == IMAP_FATAL) {
184 cmd_handle_fatal (idata);
188 /* create sequence for command */
189 cmd_make_sequence (idata);
190 /* seq, space, cmd, \r\n\0 */
191 outlen = m_strlen(idata->cmd.seq) + m_strlen(cmd) + 4;
192 out = p_new(char, outlen);
193 snprintf (out, outlen, "%s %s\r\n", idata->cmd.seq, cmd);
195 rc = mutt_socket_write_d (idata->conn, out,
196 flags & IMAP_CMD_PASS ? IMAP_LOG_PASS :
201 cmd_handle_fatal (idata);
206 rc = imap_cmd_step (idata);
207 while (rc == IMAP_CMD_CONTINUE);
209 if (rc == IMAP_CMD_BAD) {
210 if (imap_reconnect (idata->ctx) != 0) {
216 if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK))
219 if (rc != IMAP_CMD_OK) {
220 if (flags & IMAP_CMD_FAIL_OK)
223 debug_print (1, ("command failed: %s\n", idata->cmd.buf));
230 /* imap_cmd_running: Returns whether an IMAP command is in progress. */
231 int imap_cmd_running (IMAP_DATA * idata)
233 if (idata->cmd.state == IMAP_CMD_CONTINUE ||
234 idata->cmd.state == IMAP_CMD_RESPOND)
240 /* imap_cmd_finish: Attempts to perform cleanup (eg fetch new mail if
241 * detected, do expunge). Called automatically by imap_cmd_step, but
242 * may be called at any time. Called by imap_check_mailbox just before
243 * the index is refreshed, for instance. */
244 void imap_cmd_finish (IMAP_DATA * idata)
246 if (idata->status == IMAP_FATAL) {
247 cmd_handle_fatal (idata);
251 if (!(idata->state == IMAP_SELECTED) || idata->ctx->closing)
254 if (idata->reopen & IMAP_REOPEN_ALLOW) {
255 int count = idata->newMailCount;
257 if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
258 (idata->reopen & IMAP_NEWMAIL_PENDING)
259 && count > idata->ctx->msgcount) {
260 /* read new mail messages */
261 debug_print (2, ("Fetching new mail\n"));
262 /* check_status: curs_main uses imap_check_mailbox to detect
263 * whether the index needs updating */
264 idata->check_status = IMAP_NEWMAIL_PENDING;
265 imap_read_headers (idata, idata->ctx->msgcount, count - 1);
267 else if (idata->reopen & IMAP_EXPUNGE_PENDING) {
268 debug_print (2, ("Expunging mailbox\n"));
269 imap_expunge_mailbox (idata);
270 /* Detect whether we've gotten unexpected EXPUNGE messages */
271 if (idata->reopen & IMAP_EXPUNGE_PENDING &&
272 !(idata->reopen & IMAP_EXPUNGE_EXPECTED))
273 idata->check_status = IMAP_EXPUNGE_PENDING;
274 idata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING |
275 IMAP_EXPUNGE_EXPECTED);
282 /* cmd_handle_fatal: when IMAP_DATA is in fatal state, do what we can */
283 static void cmd_handle_fatal (IMAP_DATA * idata)
285 idata->status = IMAP_FATAL;
287 if ((idata->state == IMAP_SELECTED) &&
288 (idata->reopen & IMAP_REOPEN_ALLOW)) {
289 /* mx_fastclose_mailbox (idata->ctx); */
290 mutt_error (_("Mailbox closed"));
292 idata->state = IMAP_DISCONNECTED;
293 if (imap_reconnect (idata->ctx) != 0)
294 mx_fastclose_mailbox (idata->ctx);
297 if (idata->state != IMAP_SELECTED) {
298 idata->state = IMAP_DISCONNECTED;
299 mutt_socket_close (idata->conn);
304 /* cmd_handle_untagged: fallback parser for otherwise unhandled messages. */
305 static int cmd_handle_untagged (IMAP_DATA * idata)
311 s = imap_next_word (idata->cmd.buf);
313 if ((idata->state == IMAP_SELECTED) && isdigit ((unsigned char) *s)) {
315 s = imap_next_word (s);
317 /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
318 * connection, so update that one.
320 if (ascii_strncasecmp ("EXISTS", s, 6) == 0) {
321 debug_print (2, ("Handling EXISTS\n"));
323 /* new mail arrived */
326 if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
327 count < idata->ctx->msgcount) {
328 /* something is wrong because the server reported fewer messages
329 * than we previously saw
331 mutt_error _("Fatal error. Message count is out of sync!");
333 idata->status = IMAP_FATAL;
336 /* at least the InterChange server sends EXISTS messages freely,
337 * even when there is no new mail */
338 else if (count == idata->ctx->msgcount)
339 debug_print (3, ("superfluous EXISTS message.\n"));
341 if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) {
342 debug_print (2, ("New mail in %s - %d messages total.\n", idata->mailbox, count));
343 idata->reopen |= IMAP_NEWMAIL_PENDING;
345 idata->newMailCount = count;
348 /* pn vs. s: need initial seqno */
349 else if (ascii_strncasecmp ("EXPUNGE", s, 7) == 0)
350 cmd_parse_expunge (idata, pn);
351 else if (ascii_strncasecmp ("FETCH", s, 5) == 0)
352 cmd_parse_fetch (idata, pn);
354 else if (ascii_strncasecmp ("CAPABILITY", s, 10) == 0)
355 cmd_parse_capabilities (idata, s);
356 else if (ascii_strncasecmp ("LSUB", s, 4) == 0)
357 cmd_parse_lsub (idata, s);
358 else if (ascii_strncasecmp ("MYRIGHTS", s, 8) == 0)
359 cmd_parse_myrights (idata, s);
360 else if (ascii_strncasecmp ("SEARCH", s, 6) == 0)
361 cmd_parse_search (idata, s);
362 else if (ascii_strncasecmp ("BYE", s, 3) == 0) {
363 debug_print (2, ("Handling BYE\n"));
365 /* check if we're logging out */
366 if (idata->status == IMAP_BYE)
369 /* server shut down our connection */
372 mutt_error ("%s", s);
374 cmd_handle_fatal (idata);
377 else if (option (OPTIMAPSERVERNOISE)
378 && (ascii_strncasecmp ("NO", s, 2) == 0)) {
379 debug_print (2, ("Handling untagged NO\n"));
381 /* Display the warning message from the server */
382 mutt_error ("%s", s + 3);
389 /* This should be optimised (eg with a tree or hash) */
390 static int uid2msgno (IMAP_DATA* idata, unsigned int uid) {
393 for (i = 0; i < idata->ctx->msgcount; i++) {
394 HEADER* h = idata->ctx->hdrs[i];
395 if (HEADER_DATA(h)->uid == uid)
402 /* cmd_parse_search: store SEARCH response for later use */
403 static void cmd_parse_search (IMAP_DATA* idata, char* s) {
407 debug_print (2, ("Handling SEARCH\n"));
409 while ((s = imap_next_word (s)) && *s != '\0') {
411 msgno = uid2msgno (idata, uid);
414 idata->ctx->hdrs[uid2msgno (idata, uid)]->matched = 1;
418 /* cmd_make_sequence: make a tag suitable for starting an IMAP command */
419 static void cmd_make_sequence (IMAP_DATA * idata)
421 snprintf (idata->cmd.seq, sizeof (idata->cmd.seq), "a%04u", idata->seqno++);
423 if (idata->seqno > 9999)
427 /* cmd_parse_capabilities: set capability bits according to CAPABILITY
429 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s)
433 debug_print (2, ("Handling CAPABILITY\n"));
435 s = imap_next_word (s);
436 p_delete(&idata->capstr);
437 idata->capstr = m_strdup(s);
439 p_clear(idata->capabilities, 1);
442 for (x = 0; x < CAPMAX; x++)
443 if (imap_wordcasecmp (Capabilities[x], s) == 0) {
444 mutt_bit_set (idata->capabilities, x);
447 s = imap_next_word (s);
451 /* cmd_parse_expunge: mark headers with new sequence ID and mark idata to
452 * be reopened at our earliest convenience */
453 static void cmd_parse_expunge (IMAP_DATA * idata, const char *s)
458 debug_print (2, ("Handling EXPUNGE\n"));
462 /* walk headers, zero seqno of expunged message, decrement seqno of those
463 * above. Possibly we could avoid walking the whole list by resorting
464 * and guessing a good starting point, but I'm guessing the resort would
465 * nullify the gains */
466 for (cur = 0; cur < idata->ctx->msgcount; cur++) {
467 h = idata->ctx->hdrs[cur];
469 if (h->index + 1 == expno)
471 else if (h->index + 1 > expno)
475 idata->reopen |= IMAP_EXPUNGE_PENDING;
478 /* cmd_parse_fetch: Load fetch response into IMAP_DATA. Currently only
479 * handles unanticipated FETCH responses, and only FLAGS data. We get
480 * these if another client has changed flags for a mailbox we've selected.
481 * Of course, a lot of code here duplicates code in message.c. */
482 static void cmd_parse_fetch (IMAP_DATA * idata, char *s)
487 debug_print (2, ("Handling FETCH\n"));
491 if (msgno <= idata->ctx->msgcount)
492 /* see cmd_parse_expunge */
493 for (cur = 0; cur < idata->ctx->msgcount; cur++) {
494 h = idata->ctx->hdrs[cur];
499 if (h->active && h->index + 1 == msgno) {
500 debug_print (2, ("Message UID %d updated\n", HEADER_DATA (h)->uid));
508 debug_print (1, ("FETCH response ignored for this message\n"));
513 s = imap_next_word (s);
514 s = imap_next_word (s);
517 debug_print (1, ("Malformed FETCH response\n"));
522 if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
523 debug_print (2, ("Only handle FLAGS updates\n"));
527 /* If server flags could conflict with mutt's flags, reopen the mailbox. */
529 idata->reopen |= IMAP_EXPUNGE_PENDING;
531 imap_set_flags (idata, h, s);
532 idata->check_status = IMAP_FLAGS_PENDING;
536 static void cmd_parse_lsub (IMAP_DATA* idata, char* s) {
543 if (!option (OPTIMAPCHECKSUBSCRIBED))
546 s = imap_next_word (s); /* flags */
549 debug_print (1, ("Bad LSUB response\n"));
555 for (ep = s; *ep && *ep != ')'; ep++);
557 if (!ascii_strncasecmp (s, "\\NoSelect", 9))
559 while (s < ep && *s != ' ' && *s != ')')
565 s = imap_next_word (s); /* delim */
566 s = imap_next_word (s); /* name */
569 imap_unmunge_mbox_name (s);
570 debug_print (2, ("Subscribing to %s\n", s));
572 strfcpy (buf, "mailboxes \"", sizeof (buf));
573 mutt_account_tourl (&idata->conn->account, &url);
575 if (!str_cmp (url.user, ImapUser))
577 url_ciss_tostring (&url, buf + 11, sizeof (buf) - 10, 0);
578 str_cat (buf, sizeof (buf), "\"");
581 err.dsize = sizeof (errstr);
582 if (mutt_parse_rc_line (buf, &token, &err))
583 debug_print (1, ("Error adding subscribed mailbox: %s\n", errstr));
584 p_delete(&token.data);
587 debug_print (1, ("Bad LSUB response\n"));
590 /* cmd_parse_myrights: set rights bits according to MYRIGHTS response */
591 static void cmd_parse_myrights (IMAP_DATA * idata, char *s)
593 debug_print (2, ("Handling MYRIGHTS\n"));
595 s = imap_next_word (s);
596 s = imap_next_word (s);
598 /* zero out current rights set */
599 p_clear(idata->rights, 1);
601 while (*s && !isspace ((unsigned char) *s)) {
604 mutt_bit_set (idata->rights, ACL_LOOKUP);
607 mutt_bit_set (idata->rights, ACL_READ);
610 mutt_bit_set (idata->rights, ACL_SEEN);
613 mutt_bit_set (idata->rights, ACL_WRITE);
616 mutt_bit_set (idata->rights, ACL_INSERT);
619 mutt_bit_set (idata->rights, ACL_POST);
622 mutt_bit_set (idata->rights, ACL_CREATE);
625 mutt_bit_set (idata->rights, ACL_DELETE);
628 mutt_bit_set (idata->rights, ACL_ADMIN);