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)
158 s = vskipspaces(s + SEQLEN);
159 return !ascii_strncasecmp("OK", s, 2);
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 = m_strlen(idata->cmd.seq) + m_strlen(cmd) + 4;
191 out = p_new(char, 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 */
369 s = vskipspaces(s + 3);
370 mutt_error ("%s", s);
372 cmd_handle_fatal (idata);
375 else if (option (OPTIMAPSERVERNOISE)
376 && (ascii_strncasecmp ("NO", s, 2) == 0)) {
377 debug_print (2, ("Handling untagged NO\n"));
379 /* Display the warning message from the server */
380 mutt_error ("%s", s + 3);
387 /* This should be optimised (eg with a tree or hash) */
388 static int uid2msgno (IMAP_DATA* idata, unsigned int uid) {
391 for (i = 0; i < idata->ctx->msgcount; i++) {
392 HEADER* h = idata->ctx->hdrs[i];
393 if (HEADER_DATA(h)->uid == uid)
400 /* cmd_parse_search: store SEARCH response for later use */
401 static void cmd_parse_search (IMAP_DATA* idata, char* s) {
405 debug_print (2, ("Handling SEARCH\n"));
407 while ((s = imap_next_word (s)) && *s != '\0') {
409 msgno = uid2msgno (idata, uid);
412 idata->ctx->hdrs[uid2msgno (idata, uid)]->matched = 1;
416 /* cmd_make_sequence: make a tag suitable for starting an IMAP command */
417 static void cmd_make_sequence (IMAP_DATA * idata)
419 snprintf (idata->cmd.seq, sizeof (idata->cmd.seq), "a%04u", idata->seqno++);
421 if (idata->seqno > 9999)
425 /* cmd_parse_capabilities: set capability bits according to CAPABILITY
427 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s)
431 debug_print (2, ("Handling CAPABILITY\n"));
433 s = imap_next_word (s);
434 p_delete(&idata->capstr);
435 idata->capstr = m_strdup(s);
437 p_clear(idata->capabilities, 1);
440 for (x = 0; x < CAPMAX; x++)
441 if (imap_wordcasecmp (Capabilities[x], s) == 0) {
442 mutt_bit_set (idata->capabilities, x);
445 s = imap_next_word (s);
449 /* cmd_parse_expunge: mark headers with new sequence ID and mark idata to
450 * be reopened at our earliest convenience */
451 static void cmd_parse_expunge (IMAP_DATA * idata, const char *s)
456 debug_print (2, ("Handling EXPUNGE\n"));
460 /* walk headers, zero seqno of expunged message, decrement seqno of those
461 * above. Possibly we could avoid walking the whole list by resorting
462 * and guessing a good starting point, but I'm guessing the resort would
463 * nullify the gains */
464 for (cur = 0; cur < idata->ctx->msgcount; cur++) {
465 h = idata->ctx->hdrs[cur];
467 if (h->index + 1 == expno)
469 else if (h->index + 1 > expno)
473 idata->reopen |= IMAP_EXPUNGE_PENDING;
476 /* cmd_parse_fetch: Load fetch response into IMAP_DATA. Currently only
477 * handles unanticipated FETCH responses, and only FLAGS data. We get
478 * these if another client has changed flags for a mailbox we've selected.
479 * Of course, a lot of code here duplicates code in message.c. */
480 static void cmd_parse_fetch (IMAP_DATA * idata, char *s)
485 debug_print (2, ("Handling FETCH\n"));
489 if (msgno <= idata->ctx->msgcount)
490 /* see cmd_parse_expunge */
491 for (cur = 0; cur < idata->ctx->msgcount; cur++) {
492 h = idata->ctx->hdrs[cur];
497 if (h->active && h->index + 1 == msgno) {
498 debug_print (2, ("Message UID %d updated\n", HEADER_DATA (h)->uid));
506 debug_print (1, ("FETCH response ignored for this message\n"));
511 s = imap_next_word (s);
512 s = imap_next_word (s);
515 debug_print (1, ("Malformed FETCH response\n"));
520 if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
521 debug_print (2, ("Only handle FLAGS updates\n"));
525 /* If server flags could conflict with mutt's flags, reopen the mailbox. */
527 idata->reopen |= IMAP_EXPUNGE_PENDING;
529 imap_set_flags (idata, h, s);
530 idata->check_status = IMAP_FLAGS_PENDING;
534 static void cmd_parse_lsub (IMAP_DATA* idata, char* s) {
541 if (!option (OPTIMAPCHECKSUBSCRIBED))
544 s = imap_next_word (s); /* flags */
547 debug_print (1, ("Bad LSUB response\n"));
553 for (ep = s; *ep && *ep != ')'; ep++);
555 if (!ascii_strncasecmp (s, "\\NoSelect", 9))
557 while (s < ep && *s != ' ' && *s != ')')
563 s = imap_next_word (s); /* delim */
564 s = imap_next_word (s); /* name */
567 imap_unmunge_mbox_name (s);
568 debug_print (2, ("Subscribing to %s\n", s));
570 m_strcpy(buf, sizeof(buf), "mailboxes \"");
571 mutt_account_tourl (&idata->conn->account, &url);
573 if (!m_strcmp(url.user, ImapUser))
575 url_ciss_tostring (&url, buf + 11, sizeof (buf) - 10, 0);
576 m_strcat(buf, sizeof(buf), "\"");
579 err.dsize = sizeof (errstr);
580 if (mutt_parse_rc_line (buf, &token, &err))
581 debug_print (1, ("Error adding subscribed mailbox: %s\n", errstr));
582 p_delete(&token.data);
585 debug_print (1, ("Bad LSUB response\n"));
588 /* cmd_parse_myrights: set rights bits according to MYRIGHTS response */
589 static void cmd_parse_myrights (IMAP_DATA * idata, char *s)
591 debug_print (2, ("Handling MYRIGHTS\n"));
593 s = imap_next_word (s);
594 s = imap_next_word (s);
596 /* zero out current rights set */
597 p_clear(idata->rights, 1);
599 while (*s && !isspace ((unsigned char) *s)) {
602 mutt_bit_set (idata->rights, ACL_LOOKUP);
605 mutt_bit_set (idata->rights, ACL_READ);
608 mutt_bit_set (idata->rights, ACL_SEEN);
611 mutt_bit_set (idata->rights, ACL_WRITE);
614 mutt_bit_set (idata->rights, ACL_INSERT);
617 mutt_bit_set (idata->rights, ACL_POST);
620 mutt_bit_set (idata->rights, ACL_CREATE);
623 mutt_bit_set (idata->rights, ACL_DELETE);
626 mutt_bit_set (idata->rights, ACL_ADMIN);