45d6ba313625f13ff543f232006679c3fa82b6b9
[apps/madmutt.git] / imap / command.c
1 /*
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>
6  *
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.
10  */
11
12 /* command.c: routines for sending commands to an IMAP server and parsing
13  *  responses */
14
15 #if HAVE_CONFIG_H
16 # include "config.h"
17 #endif
18
19 #include "lib/mem.h"
20 #include "lib/intl.h"
21 #include "lib/debug.h"
22
23 #include "mutt.h"
24 #include "message.h"
25 #include "mx.h"
26 #include "ascii.h"
27 #include "imap_private.h"
28
29 #include <ctype.h>
30 #include <stdlib.h>
31
32 #define IMAP_CMD_BUFSIZE 512
33
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
44 static char *Capabilities[] = {
45   "IMAP4",
46   "IMAP4rev1",
47   "STATUS",
48   "ACL",
49   "NAMESPACE",
50   "AUTH=CRAM-MD5",
51   "AUTH=GSSAPI",
52   "AUTH=ANONYMOUS",
53   "STARTTLS",
54   "LOGINDISABLED",
55
56   NULL
57 };
58
59 /* imap_cmd_start: Given an IMAP command, send it to the server.
60  *   Currently a minor convenience, but helps to route all IMAP commands
61  *   through a single interface. */
62 int imap_cmd_start (IMAP_DATA * idata, const char *cmd)
63 {
64   char *out;
65   int outlen;
66   int rc;
67
68   if (idata->status == IMAP_FATAL) {
69     cmd_handle_fatal (idata);
70     return IMAP_CMD_BAD;
71   }
72
73   cmd_make_sequence (idata);
74   /* seq, space, cmd, \r\n\0 */
75   outlen = str_len (idata->cmd.seq) + str_len (cmd) + 4;
76   out = (char *) mem_malloc (outlen);
77   snprintf (out, outlen, "%s %s\r\n", idata->cmd.seq, cmd);
78
79   rc = mutt_socket_write (idata->conn, out);
80
81   mem_free (&out);
82
83   return (rc < 0) ? IMAP_CMD_BAD : 0;
84 }
85
86 /* imap_cmd_step: Reads server responses from an IMAP command, detects
87  *   tagged completion response, handles untagged messages, can read
88  *   arbitrarily large strings (using malloc, so don't make it _too_
89  *   large!). */
90 int imap_cmd_step (IMAP_DATA * idata)
91 {
92   IMAP_COMMAND *cmd = &idata->cmd;
93   unsigned int len = 0;
94   int c;
95
96   if (idata->status == IMAP_FATAL) {
97     cmd_handle_fatal (idata);
98     return IMAP_CMD_BAD;
99   }
100
101   /* read into buffer, expanding buffer as necessary until we have a full
102    * line */
103   do {
104     if (len == cmd->blen) {
105       mem_realloc (&cmd->buf, cmd->blen + IMAP_CMD_BUFSIZE);
106       cmd->blen = cmd->blen + IMAP_CMD_BUFSIZE;
107       debug_print (3, ("grew buffer to %u bytes\n", cmd->blen));
108     }
109
110     c = mutt_socket_readln (cmd->buf + len, cmd->blen - len, idata->conn);
111     if (c <= 0) {
112       debug_print (1, ("Error reading server response.\n"));
113       /* cmd_handle_fatal (idata); */
114       return IMAP_CMD_BAD;
115     }
116
117     len += c;
118   }
119   /* if we've read all the way to the end of the buffer, we haven't read a
120    * full line (mutt_socket_readln strips the \r, so we always have at least
121    * one character free when we've read a full line) */
122   while (len == cmd->blen);
123
124   /* don't let one large string make cmd->buf hog memory forever */
125   if ((cmd->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE)) {
126     mem_realloc (&cmd->buf, IMAP_CMD_BUFSIZE);
127     cmd->blen = IMAP_CMD_BUFSIZE;
128     debug_print (3, ("shrank buffer to %u bytes\n", cmd->blen));
129   }
130
131   idata->lastread = time (NULL);
132
133   /* handle untagged messages. The caller still gets its shot afterwards. */
134   if (!ascii_strncmp (cmd->buf, "* ", 2) && cmd_handle_untagged (idata))
135     return IMAP_CMD_BAD;
136
137   /* server demands a continuation response from us */
138   if (!ascii_strncmp (cmd->buf, "+ ", 2)) {
139     return IMAP_CMD_RESPOND;
140   }
141
142   /* tagged completion code */
143   if (!ascii_strncmp (cmd->buf, cmd->seq, SEQLEN)) {
144     imap_cmd_finish (idata);
145     return imap_code (cmd->buf) ? IMAP_CMD_OK : IMAP_CMD_NO;
146   }
147
148   return IMAP_CMD_CONTINUE;
149 }
150
151 /* imap_code: returns 1 if the command result was OK, or 0 if NO or BAD */
152 int imap_code (const char *s)
153 {
154   s += SEQLEN;
155   SKIPWS (s);
156   return (ascii_strncasecmp ("OK", s, 2) == 0);
157 }
158
159 /* imap_exec: execute a command, and wait for the response from the server.
160  * Also, handle untagged responses.
161  * Flags:
162  *   IMAP_CMD_FAIL_OK: the calling procedure can handle failure. This is used
163  *     for checking for a mailbox on append and login
164  *   IMAP_CMD_PASS: command contains a password. Suppress logging.
165  * Return 0 on success, -1 on Failure, -2 on OK Failure
166  */
167 int imap_exec (IMAP_DATA * idata, const char *cmd, int flags)
168 {
169   char *out;
170   int outlen;
171   int rc;
172
173   if (!idata) {
174     mutt_error (_("No mailbox is open."));
175     mutt_sleep (1);
176     return (-1);
177   }
178
179   if (idata->status == IMAP_FATAL) {
180     cmd_handle_fatal (idata);
181     return -1;
182   }
183
184   /* create sequence for command */
185   cmd_make_sequence (idata);
186   /* seq, space, cmd, \r\n\0 */
187   outlen = str_len (idata->cmd.seq) + str_len (cmd) + 4;
188   out = (char *) mem_malloc (outlen);
189   snprintf (out, outlen, "%s %s\r\n", idata->cmd.seq, cmd);
190
191   rc = mutt_socket_write_d (idata->conn, out,
192                             flags & IMAP_CMD_PASS ? IMAP_LOG_PASS :
193                             IMAP_LOG_CMD);
194   mem_free (&out);
195
196   if (rc < 0) {
197     cmd_handle_fatal (idata);
198     return -1;
199   }
200
201   do
202     rc = imap_cmd_step (idata);
203   while (rc == IMAP_CMD_CONTINUE);
204
205   if (rc == IMAP_CMD_BAD) {
206     if (imap_reconnect (idata->ctx) != 0) {
207       return -1;
208     }
209     return 0;
210   }
211
212   if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK))
213     return -2;
214
215   if (rc != IMAP_CMD_OK) {
216     if (flags & IMAP_CMD_FAIL_OK)
217       return -2;
218
219     debug_print (1, ("command failed: %s\n", idata->cmd.buf));
220     return -1;
221   }
222
223   return 0;
224 }
225
226 /* imap_cmd_running: Returns whether an IMAP command is in progress. */
227 int imap_cmd_running (IMAP_DATA * idata)
228 {
229   if (idata->cmd.state == IMAP_CMD_CONTINUE ||
230       idata->cmd.state == IMAP_CMD_RESPOND)
231     return 1;
232
233   return 0;
234 }
235
236 /* imap_cmd_finish: Attempts to perform cleanup (eg fetch new mail if
237  *   detected, do expunge). Called automatically by imap_cmd_step, but
238  *   may be called at any time. Called by imap_check_mailbox just before
239  *   the index is refreshed, for instance. */
240 void imap_cmd_finish (IMAP_DATA * idata)
241 {
242   if (idata->status == IMAP_FATAL) {
243     cmd_handle_fatal (idata);
244     return;
245   }
246
247   if (!(idata->state == IMAP_SELECTED) || idata->ctx->closing)
248     return;
249
250   if (idata->reopen & IMAP_REOPEN_ALLOW) {
251     int count = idata->newMailCount;
252
253     if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
254         (idata->reopen & IMAP_NEWMAIL_PENDING)
255         && count > idata->ctx->msgcount) {
256       /* read new mail messages */
257       debug_print (2, ("Fetching new mail\n"));
258       /* check_status: curs_main uses imap_check_mailbox to detect
259        *   whether the index needs updating */
260       idata->check_status = IMAP_NEWMAIL_PENDING;
261       imap_read_headers (idata, idata->ctx->msgcount, count - 1);
262     }
263     else if (idata->reopen & IMAP_EXPUNGE_PENDING) {
264       debug_print (2, ("Expunging mailbox\n"));
265       imap_expunge_mailbox (idata);
266       /* Detect whether we've gotten unexpected EXPUNGE messages */
267       if (idata->reopen & IMAP_EXPUNGE_PENDING &&
268           !(idata->reopen & IMAP_EXPUNGE_EXPECTED))
269         idata->check_status = IMAP_EXPUNGE_PENDING;
270       idata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING |
271                          IMAP_EXPUNGE_EXPECTED);
272     }
273   }
274
275   idata->status = 0;
276 }
277
278 /* cmd_handle_fatal: when IMAP_DATA is in fatal state, do what we can */
279 static void cmd_handle_fatal (IMAP_DATA * idata)
280 {
281   idata->status = IMAP_FATAL;
282
283   if ((idata->state == IMAP_SELECTED) &&
284       (idata->reopen & IMAP_REOPEN_ALLOW)) {
285     /* mx_fastclose_mailbox (idata->ctx); */
286     mutt_error (_("Mailbox closed"));
287     mutt_sleep (1);
288     idata->state = IMAP_DISCONNECTED;
289     if (imap_reconnect (idata->ctx) != 0)
290       mx_fastclose_mailbox (idata->ctx);
291   }
292
293   if (idata->state != IMAP_SELECTED) {
294     idata->state = IMAP_DISCONNECTED;
295     mutt_socket_close (idata->conn);
296     idata->status = 0;
297   }
298 }
299
300 /* cmd_handle_untagged: fallback parser for otherwise unhandled messages. */
301 static int cmd_handle_untagged (IMAP_DATA * idata)
302 {
303   char *s;
304   char *pn;
305   int count;
306
307   s = imap_next_word (idata->cmd.buf);
308
309   if ((idata->state == IMAP_SELECTED) && isdigit ((unsigned char) *s)) {
310     pn = s;
311     s = imap_next_word (s);
312
313     /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
314      * connection, so update that one.
315      */
316     if (ascii_strncasecmp ("EXISTS", s, 6) == 0) {
317       debug_print (2, ("Handling EXISTS\n"));
318
319       /* new mail arrived */
320       count = atoi (pn);
321
322       if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
323           count < idata->ctx->msgcount) {
324         /* something is wrong because the server reported fewer messages
325          * than we previously saw
326          */
327         mutt_error _("Fatal error.  Message count is out of sync!");
328
329         idata->status = IMAP_FATAL;
330         return -1;
331       }
332       /* at least the InterChange server sends EXISTS messages freely,
333        * even when there is no new mail */
334       else if (count == idata->ctx->msgcount)
335         debug_print (3, ("superfluous EXISTS message.\n"));
336       else {
337         if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) {
338           debug_print (2, ("New mail in %s - %d messages total.\n", idata->mailbox, count));
339           idata->reopen |= IMAP_NEWMAIL_PENDING;
340         }
341         idata->newMailCount = count;
342       }
343     }
344     /* pn vs. s: need initial seqno */
345     else if (ascii_strncasecmp ("EXPUNGE", s, 7) == 0)
346       cmd_parse_expunge (idata, pn);
347     else if (ascii_strncasecmp ("FETCH", s, 5) == 0)
348       cmd_parse_fetch (idata, pn);
349   }
350   else if (ascii_strncasecmp ("CAPABILITY", s, 10) == 0)
351     cmd_parse_capabilities (idata, s);
352   else if (ascii_strncasecmp ("LSUB", s, 4) == 0)
353     cmd_parse_lsub (idata, s);
354   else if (ascii_strncasecmp ("MYRIGHTS", s, 8) == 0)
355     cmd_parse_myrights (idata, s);
356   else if (ascii_strncasecmp ("BYE", s, 3) == 0) {
357     debug_print (2, ("Handling BYE\n"));
358
359     /* check if we're logging out */
360     if (idata->status == IMAP_BYE)
361       return 0;
362
363     /* server shut down our connection */
364     s += 3;
365     SKIPWS (s);
366     mutt_error ("%s", s);
367     mutt_sleep (2);
368     cmd_handle_fatal (idata);
369     return -1;
370   }
371   else if (option (OPTIMAPSERVERNOISE)
372            && (ascii_strncasecmp ("NO", s, 2) == 0)) {
373     debug_print (2, ("Handling untagged NO\n"));
374
375     /* Display the warning message from the server */
376     mutt_error ("%s", s + 3);
377     mutt_sleep (2);
378   }
379
380   return 0;
381 }
382
383 /* cmd_make_sequence: make a tag suitable for starting an IMAP command */
384 static void cmd_make_sequence (IMAP_DATA * idata)
385 {
386   snprintf (idata->cmd.seq, sizeof (idata->cmd.seq), "a%04u", idata->seqno++);
387
388   if (idata->seqno > 9999)
389     idata->seqno = 0;
390 }
391
392 /* cmd_parse_capabilities: set capability bits according to CAPABILITY
393  *   response */
394 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s)
395 {
396   int x;
397
398   debug_print (2, ("Handling CAPABILITY\n"));
399
400   s = imap_next_word (s);
401   mem_free (&idata->capstr);
402   idata->capstr = str_dup (s);
403
404   memset (idata->capabilities, 0, sizeof (idata->capabilities));
405
406   while (*s) {
407     for (x = 0; x < CAPMAX; x++)
408       if (imap_wordcasecmp (Capabilities[x], s) == 0) {
409         mutt_bit_set (idata->capabilities, x);
410         break;
411       }
412     s = imap_next_word (s);
413   }
414 }
415
416 /* cmd_parse_expunge: mark headers with new sequence ID and mark idata to
417  *   be reopened at our earliest convenience */
418 static void cmd_parse_expunge (IMAP_DATA * idata, const char *s)
419 {
420   int expno, cur;
421   HEADER *h;
422
423   debug_print (2, ("Handling EXPUNGE\n"));
424
425   expno = atoi (s);
426
427   /* walk headers, zero seqno of expunged message, decrement seqno of those
428    * above. Possibly we could avoid walking the whole list by resorting
429    * and guessing a good starting point, but I'm guessing the resort would
430    * nullify the gains */
431   for (cur = 0; cur < idata->ctx->msgcount; cur++) {
432     h = idata->ctx->hdrs[cur];
433
434     if (h->index + 1 == expno)
435       h->index = -1;
436     else if (h->index + 1 > expno)
437       h->index--;
438   }
439
440   idata->reopen |= IMAP_EXPUNGE_PENDING;
441 }
442
443 /* cmd_parse_fetch: Load fetch response into IMAP_DATA. Currently only
444  *   handles unanticipated FETCH responses, and only FLAGS data. We get
445  *   these if another client has changed flags for a mailbox we've selected.
446  *   Of course, a lot of code here duplicates code in message.c. */
447 static void cmd_parse_fetch (IMAP_DATA * idata, char *s)
448 {
449   int msgno, cur;
450   HEADER *h = NULL;
451
452   debug_print (2, ("Handling FETCH\n"));
453
454   msgno = atoi (s);
455
456   if (msgno <= idata->ctx->msgcount)
457     /* see cmd_parse_expunge */
458     for (cur = 0; cur < idata->ctx->msgcount; cur++) {
459       h = idata->ctx->hdrs[cur];
460
461       if (h->active && h->index + 1 == msgno) {
462         debug_print (2, ("Message UID %d updated\n", HEADER_DATA (h)->uid));
463         break;
464       }
465
466       h = NULL;
467     }
468
469   if (!h) {
470     debug_print (1, ("FETCH response ignored for this message\n"));
471     return;
472   }
473
474   /* skip FETCH */
475   s = imap_next_word (s);
476   s = imap_next_word (s);
477
478   if (*s != '(') {
479     debug_print (1, ("Malformed FETCH response\n"));
480     return;
481   }
482   s++;
483
484   if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
485     debug_print (2, ("Only handle FLAGS updates\n"));
486     return;
487   }
488
489   /* If server flags could conflict with mutt's flags, reopen the mailbox. */
490   if (h->changed)
491     idata->reopen |= IMAP_EXPUNGE_PENDING;
492   else {
493     imap_set_flags (idata, h, s);
494     idata->check_status = IMAP_FLAGS_PENDING;
495   }
496 }
497
498 static void cmd_parse_lsub (IMAP_DATA* idata, char* s) {
499   char buf[STRING];
500   char errstr[STRING];
501   BUFFER err, token;
502   ciss_url_t url;
503   char *ep;
504
505   if (!option (OPTIMAPCHECKSUBSCRIBED))
506     return;
507
508   s = imap_next_word (s); /* flags */
509
510   if (*s != '(') {
511     debug_print (1, ("Bad LSUB response\n"));
512     return;
513   }
514
515   s++;
516   ep = s;
517   for (ep = s; *ep && *ep != ')'; ep++);
518   do {
519     if (!ascii_strncasecmp (s, "\\NoSelect", 9))
520       return;
521     while (s < ep && *s != ' ' && *s != ')')
522       s++;
523     if (*s == ' ')
524       s++;
525   } while (s != ep);
526
527   s = imap_next_word (s); /* delim */
528   s = imap_next_word (s); /* name */
529
530   if (s) {
531     imap_unmunge_mbox_name (s);
532     debug_print (2, ("Subscribing to %s\n", s));
533
534     strfcpy (buf, "mailboxes \"", sizeof (buf));
535     mutt_account_tourl (&idata->conn->account, &url);
536     url.path = s;
537     if (!str_cmp (url.user, ImapUser))
538       url.user = NULL;
539     url_ciss_tostring (&url, buf + 11, sizeof (buf) - 10, 0);
540     str_cat (buf, sizeof (buf), "\"");
541     memset (&token, 0, sizeof (token));
542     err.data = errstr;
543     err.dsize = sizeof (errstr);
544     if (mutt_parse_rc_line (buf, &token, &err))
545       debug_print (1, ("Error adding subscribed mailbox: %s\n", errstr));
546     mem_free (&token.data);
547   }
548   else
549     debug_print (1, ("Bad LSUB response\n"));
550 }
551
552 /* cmd_parse_myrights: set rights bits according to MYRIGHTS response */
553 static void cmd_parse_myrights (IMAP_DATA * idata, char *s)
554 {
555   debug_print (2, ("Handling MYRIGHTS\n"));
556
557   s = imap_next_word (s);
558   s = imap_next_word (s);
559
560   /* zero out current rights set */
561   memset (idata->rights, 0, sizeof (idata->rights));
562
563   while (*s && !isspace ((unsigned char) *s)) {
564     switch (*s) {
565     case 'l':
566       mutt_bit_set (idata->rights, ACL_LOOKUP);
567       break;
568     case 'r':
569       mutt_bit_set (idata->rights, ACL_READ);
570       break;
571     case 's':
572       mutt_bit_set (idata->rights, ACL_SEEN);
573       break;
574     case 'w':
575       mutt_bit_set (idata->rights, ACL_WRITE);
576       break;
577     case 'i':
578       mutt_bit_set (idata->rights, ACL_INSERT);
579       break;
580     case 'p':
581       mutt_bit_set (idata->rights, ACL_POST);
582       break;
583     case 'c':
584       mutt_bit_set (idata->rights, ACL_CREATE);
585       break;
586     case 'd':
587       mutt_bit_set (idata->rights, ACL_DELETE);
588       break;
589     case 'a':
590       mutt_bit_set (idata->rights, ACL_ADMIN);
591       break;
592     }
593     s++;
594   }
595 }