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>
23 #include "lib/debug.h"
29 #include "imap_private.h"
34 #define IMAP_CMD_BUFSIZE 512
36 /* forward declarations */
37 static void cmd_handle_fatal (IMAP_DATA * idata);
38 static int cmd_handle_untagged (IMAP_DATA * idata);
39 static void cmd_make_sequence (IMAP_DATA * idata);
40 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s);
41 static void cmd_parse_expunge (IMAP_DATA * idata, const char *s);
42 static void cmd_parse_lsub (IMAP_DATA* idata, char* s);
43 static void cmd_parse_fetch (IMAP_DATA * idata, char *s);
44 static void cmd_parse_myrights (IMAP_DATA * idata, char *s);
45 static void cmd_parse_search (IMAP_DATA* idata, char* s);
47 static const char *Capabilities[] = {
62 /* imap_cmd_start: Given an IMAP command, send it to the server.
63 * Currently a minor convenience, but helps to route all IMAP commands
64 * through a single interface. */
65 int imap_cmd_start (IMAP_DATA * idata, const char *cmd)
71 if (idata->status == IMAP_FATAL) {
72 cmd_handle_fatal (idata);
76 cmd_make_sequence (idata);
77 /* seq, space, cmd, \r\n\0 */
78 outlen = str_len (idata->cmd.seq) + str_len (cmd) + 4;
79 out = p_new(char, outlen);
80 snprintf (out, outlen, "%s %s\r\n", idata->cmd.seq, cmd);
82 rc = mutt_socket_write (idata->conn, out);
86 return (rc < 0) ? IMAP_CMD_BAD : 0;
89 /* imap_cmd_step: Reads server responses from an IMAP command, detects
90 * tagged completion response, handles untagged messages, can read
91 * arbitrarily large strings (using malloc, so don't make it _too_
93 int imap_cmd_step (IMAP_DATA * idata)
95 IMAP_COMMAND *cmd = &idata->cmd;
99 if (idata->status == IMAP_FATAL) {
100 cmd_handle_fatal (idata);
104 /* read into buffer, expanding buffer as necessary until we have a full
107 if (len == cmd->blen) {
108 mem_realloc (&cmd->buf, cmd->blen + IMAP_CMD_BUFSIZE);
109 cmd->blen = cmd->blen + IMAP_CMD_BUFSIZE;
110 debug_print (3, ("grew buffer to %u bytes\n", cmd->blen));
116 c = mutt_socket_readln (cmd->buf + len, cmd->blen - len, idata->conn);
118 debug_print (1, ("Error reading server response.\n"));
119 /* cmd_handle_fatal (idata); */
125 /* if we've read all the way to the end of the buffer, we haven't read a
126 * full line (mutt_socket_readln strips the \r, so we always have at least
127 * one character free when we've read a full line) */
128 while (len == cmd->blen);
130 /* don't let one large string make cmd->buf hog memory forever */
131 if ((cmd->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE)) {
132 mem_realloc (&cmd->buf, IMAP_CMD_BUFSIZE);
133 cmd->blen = IMAP_CMD_BUFSIZE;
134 debug_print (3, ("shrank buffer to %u bytes\n", cmd->blen));
137 idata->lastread = time (NULL);
139 /* handle untagged messages. The caller still gets its shot afterwards. */
140 if (!ascii_strncmp (cmd->buf, "* ", 2) && cmd_handle_untagged (idata))
143 /* server demands a continuation response from us */
144 if (cmd->buf[0] == '+')
145 return IMAP_CMD_RESPOND;
147 /* tagged completion code */
148 if (!ascii_strncmp (cmd->buf, cmd->seq, SEQLEN)) {
149 imap_cmd_finish (idata);
150 return imap_code (cmd->buf) ? IMAP_CMD_OK : IMAP_CMD_NO;
153 return IMAP_CMD_CONTINUE;
156 /* imap_code: returns 1 if the command result was OK, or 0 if NO or BAD */
157 int imap_code (const char *s)
161 return (ascii_strncasecmp ("OK", s, 2) == 0);
164 /* imap_exec: execute a command, and wait for the response from the server.
165 * Also, handle untagged responses.
167 * IMAP_CMD_FAIL_OK: the calling procedure can handle failure. This is used
168 * for checking for a mailbox on append and login
169 * IMAP_CMD_PASS: command contains a password. Suppress logging.
170 * Return 0 on success, -1 on Failure, -2 on OK Failure
172 int imap_exec (IMAP_DATA * idata, const char *cmd, int flags)
179 mutt_error (_("No mailbox is open."));
184 if (idata->status == IMAP_FATAL) {
185 cmd_handle_fatal (idata);
189 /* create sequence for command */
190 cmd_make_sequence (idata);
191 /* seq, space, cmd, \r\n\0 */
192 outlen = str_len (idata->cmd.seq) + str_len (cmd) + 4;
193 out = p_new(char, outlen);
194 snprintf (out, outlen, "%s %s\r\n", idata->cmd.seq, cmd);
196 rc = mutt_socket_write_d (idata->conn, out,
197 flags & IMAP_CMD_PASS ? IMAP_LOG_PASS :
202 cmd_handle_fatal (idata);
207 rc = imap_cmd_step (idata);
208 while (rc == IMAP_CMD_CONTINUE);
210 if (rc == IMAP_CMD_BAD) {
211 if (imap_reconnect (idata->ctx) != 0) {
217 if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK))
220 if (rc != IMAP_CMD_OK) {
221 if (flags & IMAP_CMD_FAIL_OK)
224 debug_print (1, ("command failed: %s\n", idata->cmd.buf));
231 /* imap_cmd_running: Returns whether an IMAP command is in progress. */
232 int imap_cmd_running (IMAP_DATA * idata)
234 if (idata->cmd.state == IMAP_CMD_CONTINUE ||
235 idata->cmd.state == IMAP_CMD_RESPOND)
241 /* imap_cmd_finish: Attempts to perform cleanup (eg fetch new mail if
242 * detected, do expunge). Called automatically by imap_cmd_step, but
243 * may be called at any time. Called by imap_check_mailbox just before
244 * the index is refreshed, for instance. */
245 void imap_cmd_finish (IMAP_DATA * idata)
247 if (idata->status == IMAP_FATAL) {
248 cmd_handle_fatal (idata);
252 if (!(idata->state == IMAP_SELECTED) || idata->ctx->closing)
255 if (idata->reopen & IMAP_REOPEN_ALLOW) {
256 int count = idata->newMailCount;
258 if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
259 (idata->reopen & IMAP_NEWMAIL_PENDING)
260 && count > idata->ctx->msgcount) {
261 /* read new mail messages */
262 debug_print (2, ("Fetching new mail\n"));
263 /* check_status: curs_main uses imap_check_mailbox to detect
264 * whether the index needs updating */
265 idata->check_status = IMAP_NEWMAIL_PENDING;
266 imap_read_headers (idata, idata->ctx->msgcount, count - 1);
268 else if (idata->reopen & IMAP_EXPUNGE_PENDING) {
269 debug_print (2, ("Expunging mailbox\n"));
270 imap_expunge_mailbox (idata);
271 /* Detect whether we've gotten unexpected EXPUNGE messages */
272 if (idata->reopen & IMAP_EXPUNGE_PENDING &&
273 !(idata->reopen & IMAP_EXPUNGE_EXPECTED))
274 idata->check_status = IMAP_EXPUNGE_PENDING;
275 idata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING |
276 IMAP_EXPUNGE_EXPECTED);
283 /* cmd_handle_fatal: when IMAP_DATA is in fatal state, do what we can */
284 static void cmd_handle_fatal (IMAP_DATA * idata)
286 idata->status = IMAP_FATAL;
288 if ((idata->state == IMAP_SELECTED) &&
289 (idata->reopen & IMAP_REOPEN_ALLOW)) {
290 /* mx_fastclose_mailbox (idata->ctx); */
291 mutt_error (_("Mailbox closed"));
293 idata->state = IMAP_DISCONNECTED;
294 if (imap_reconnect (idata->ctx) != 0)
295 mx_fastclose_mailbox (idata->ctx);
298 if (idata->state != IMAP_SELECTED) {
299 idata->state = IMAP_DISCONNECTED;
300 mutt_socket_close (idata->conn);
305 /* cmd_handle_untagged: fallback parser for otherwise unhandled messages. */
306 static int cmd_handle_untagged (IMAP_DATA * idata)
312 s = imap_next_word (idata->cmd.buf);
314 if ((idata->state == IMAP_SELECTED) && isdigit ((unsigned char) *s)) {
316 s = imap_next_word (s);
318 /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
319 * connection, so update that one.
321 if (ascii_strncasecmp ("EXISTS", s, 6) == 0) {
322 debug_print (2, ("Handling EXISTS\n"));
324 /* new mail arrived */
327 if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
328 count < idata->ctx->msgcount) {
329 /* something is wrong because the server reported fewer messages
330 * than we previously saw
332 mutt_error _("Fatal error. Message count is out of sync!");
334 idata->status = IMAP_FATAL;
337 /* at least the InterChange server sends EXISTS messages freely,
338 * even when there is no new mail */
339 else if (count == idata->ctx->msgcount)
340 debug_print (3, ("superfluous EXISTS message.\n"));
342 if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) {
343 debug_print (2, ("New mail in %s - %d messages total.\n", idata->mailbox, count));
344 idata->reopen |= IMAP_NEWMAIL_PENDING;
346 idata->newMailCount = count;
349 /* pn vs. s: need initial seqno */
350 else if (ascii_strncasecmp ("EXPUNGE", s, 7) == 0)
351 cmd_parse_expunge (idata, pn);
352 else if (ascii_strncasecmp ("FETCH", s, 5) == 0)
353 cmd_parse_fetch (idata, pn);
355 else if (ascii_strncasecmp ("CAPABILITY", s, 10) == 0)
356 cmd_parse_capabilities (idata, s);
357 else if (ascii_strncasecmp ("LSUB", s, 4) == 0)
358 cmd_parse_lsub (idata, s);
359 else if (ascii_strncasecmp ("MYRIGHTS", s, 8) == 0)
360 cmd_parse_myrights (idata, s);
361 else if (ascii_strncasecmp ("SEARCH", s, 6) == 0)
362 cmd_parse_search (idata, s);
363 else if (ascii_strncasecmp ("BYE", s, 3) == 0) {
364 debug_print (2, ("Handling BYE\n"));
366 /* check if we're logging out */
367 if (idata->status == IMAP_BYE)
370 /* server shut down our connection */
373 mutt_error ("%s", s);
375 cmd_handle_fatal (idata);
378 else if (option (OPTIMAPSERVERNOISE)
379 && (ascii_strncasecmp ("NO", s, 2) == 0)) {
380 debug_print (2, ("Handling untagged NO\n"));
382 /* Display the warning message from the server */
383 mutt_error ("%s", s + 3);
390 /* This should be optimised (eg with a tree or hash) */
391 static int uid2msgno (IMAP_DATA* idata, unsigned int uid) {
394 for (i = 0; i < idata->ctx->msgcount; i++) {
395 HEADER* h = idata->ctx->hdrs[i];
396 if (HEADER_DATA(h)->uid == uid)
403 /* cmd_parse_search: store SEARCH response for later use */
404 static void cmd_parse_search (IMAP_DATA* idata, char* s) {
408 debug_print (2, ("Handling SEARCH\n"));
410 while ((s = imap_next_word (s)) && *s != '\0') {
412 msgno = uid2msgno (idata, uid);
415 idata->ctx->hdrs[uid2msgno (idata, uid)]->matched = 1;
419 /* cmd_make_sequence: make a tag suitable for starting an IMAP command */
420 static void cmd_make_sequence (IMAP_DATA * idata)
422 snprintf (idata->cmd.seq, sizeof (idata->cmd.seq), "a%04u", idata->seqno++);
424 if (idata->seqno > 9999)
428 /* cmd_parse_capabilities: set capability bits according to CAPABILITY
430 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s)
434 debug_print (2, ("Handling CAPABILITY\n"));
436 s = imap_next_word (s);
437 p_delete(&idata->capstr);
438 idata->capstr = str_dup (s);
440 memset (idata->capabilities, 0, sizeof (idata->capabilities));
443 for (x = 0; x < CAPMAX; x++)
444 if (imap_wordcasecmp (Capabilities[x], s) == 0) {
445 mutt_bit_set (idata->capabilities, x);
448 s = imap_next_word (s);
452 /* cmd_parse_expunge: mark headers with new sequence ID and mark idata to
453 * be reopened at our earliest convenience */
454 static void cmd_parse_expunge (IMAP_DATA * idata, const char *s)
459 debug_print (2, ("Handling EXPUNGE\n"));
463 /* walk headers, zero seqno of expunged message, decrement seqno of those
464 * above. Possibly we could avoid walking the whole list by resorting
465 * and guessing a good starting point, but I'm guessing the resort would
466 * nullify the gains */
467 for (cur = 0; cur < idata->ctx->msgcount; cur++) {
468 h = idata->ctx->hdrs[cur];
470 if (h->index + 1 == expno)
472 else if (h->index + 1 > expno)
476 idata->reopen |= IMAP_EXPUNGE_PENDING;
479 /* cmd_parse_fetch: Load fetch response into IMAP_DATA. Currently only
480 * handles unanticipated FETCH responses, and only FLAGS data. We get
481 * these if another client has changed flags for a mailbox we've selected.
482 * Of course, a lot of code here duplicates code in message.c. */
483 static void cmd_parse_fetch (IMAP_DATA * idata, char *s)
488 debug_print (2, ("Handling FETCH\n"));
492 if (msgno <= idata->ctx->msgcount)
493 /* see cmd_parse_expunge */
494 for (cur = 0; cur < idata->ctx->msgcount; cur++) {
495 h = idata->ctx->hdrs[cur];
500 if (h->active && h->index + 1 == msgno) {
501 debug_print (2, ("Message UID %d updated\n", HEADER_DATA (h)->uid));
509 debug_print (1, ("FETCH response ignored for this message\n"));
514 s = imap_next_word (s);
515 s = imap_next_word (s);
518 debug_print (1, ("Malformed FETCH response\n"));
523 if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
524 debug_print (2, ("Only handle FLAGS updates\n"));
528 /* If server flags could conflict with mutt's flags, reopen the mailbox. */
530 idata->reopen |= IMAP_EXPUNGE_PENDING;
532 imap_set_flags (idata, h, s);
533 idata->check_status = IMAP_FLAGS_PENDING;
537 static void cmd_parse_lsub (IMAP_DATA* idata, char* s) {
544 if (!option (OPTIMAPCHECKSUBSCRIBED))
547 s = imap_next_word (s); /* flags */
550 debug_print (1, ("Bad LSUB response\n"));
556 for (ep = s; *ep && *ep != ')'; ep++);
558 if (!ascii_strncasecmp (s, "\\NoSelect", 9))
560 while (s < ep && *s != ' ' && *s != ')')
566 s = imap_next_word (s); /* delim */
567 s = imap_next_word (s); /* name */
570 imap_unmunge_mbox_name (s);
571 debug_print (2, ("Subscribing to %s\n", s));
573 strfcpy (buf, "mailboxes \"", sizeof (buf));
574 mutt_account_tourl (&idata->conn->account, &url);
576 if (!str_cmp (url.user, ImapUser))
578 url_ciss_tostring (&url, buf + 11, sizeof (buf) - 10, 0);
579 str_cat (buf, sizeof (buf), "\"");
580 memset (&token, 0, sizeof (token));
582 err.dsize = sizeof (errstr);
583 if (mutt_parse_rc_line (buf, &token, &err))
584 debug_print (1, ("Error adding subscribed mailbox: %s\n", errstr));
585 p_delete(&token.data);
588 debug_print (1, ("Bad LSUB response\n"));
591 /* cmd_parse_myrights: set rights bits according to MYRIGHTS response */
592 static void cmd_parse_myrights (IMAP_DATA * idata, char *s)
594 debug_print (2, ("Handling MYRIGHTS\n"));
596 s = imap_next_word (s);
597 s = imap_next_word (s);
599 /* zero out current rights set */
600 memset (idata->rights, 0, sizeof (idata->rights));
602 while (*s && !isspace ((unsigned char) *s)) {
605 mutt_bit_set (idata->rights, ACL_LOOKUP);
608 mutt_bit_set (idata->rights, ACL_READ);
611 mutt_bit_set (idata->rights, ACL_SEEN);
614 mutt_bit_set (idata->rights, ACL_WRITE);
617 mutt_bit_set (idata->rights, ACL_INSERT);
620 mutt_bit_set (idata->rights, ACL_POST);
623 mutt_bit_set (idata->rights, ACL_CREATE);
626 mutt_bit_set (idata->rights, ACL_DELETE);
629 mutt_bit_set (idata->rights, ACL_ADMIN);