From: Lars Ellenberg <Lars.Ellenberg@linbit.com>
[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 static void cmd_parse_search (IMAP_DATA* idata, char* s);
44
45 static char *Capabilities[] = {
46   "IMAP4",
47   "IMAP4rev1",
48   "STATUS",
49   "ACL",
50   "NAMESPACE",
51   "AUTH=CRAM-MD5",
52   "AUTH=GSSAPI",
53   "AUTH=ANONYMOUS",
54   "STARTTLS",
55   "LOGINDISABLED",
56
57   NULL
58 };
59
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)
64 {
65   char *out;
66   int outlen;
67   int rc;
68
69   if (idata->status == IMAP_FATAL) {
70     cmd_handle_fatal (idata);
71     return IMAP_CMD_BAD;
72   }
73
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);
79
80   rc = mutt_socket_write (idata->conn, out);
81
82   mem_free (&out);
83
84   return (rc < 0) ? IMAP_CMD_BAD : 0;
85 }
86
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_
90  *   large!). */
91 int imap_cmd_step (IMAP_DATA * idata)
92 {
93   IMAP_COMMAND *cmd = &idata->cmd;
94   unsigned int len = 0;
95   int c;
96
97   if (idata->status == IMAP_FATAL) {
98     cmd_handle_fatal (idata);
99     return IMAP_CMD_BAD;
100   }
101
102   /* read into buffer, expanding buffer as necessary until we have a full
103    * line */
104   do {
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));
109     }
110
111     if (len)
112       len--;
113
114     c = mutt_socket_readln (cmd->buf + len, cmd->blen - len, idata->conn);
115     if (c <= 0) {
116       debug_print (1, ("Error reading server response.\n"));
117       /* cmd_handle_fatal (idata); */
118       return IMAP_CMD_BAD;
119     }
120
121     len += c;
122   }
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);
127
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));
133   }
134
135   idata->lastread = time (NULL);
136
137   /* handle untagged messages. The caller still gets its shot afterwards. */
138   if (!ascii_strncmp (cmd->buf, "* ", 2) && cmd_handle_untagged (idata))
139     return IMAP_CMD_BAD;
140
141   /* server demands a continuation response from us */
142   if (cmd->buf[0] == '+')
143     return IMAP_CMD_RESPOND;
144
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;
149   }
150
151   return IMAP_CMD_CONTINUE;
152 }
153
154 /* imap_code: returns 1 if the command result was OK, or 0 if NO or BAD */
155 int imap_code (const char *s)
156 {
157   s += SEQLEN;
158   SKIPWS (s);
159   return (ascii_strncasecmp ("OK", s, 2) == 0);
160 }
161
162 /* imap_exec: execute a command, and wait for the response from the server.
163  * Also, handle untagged responses.
164  * Flags:
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
169  */
170 int imap_exec (IMAP_DATA * idata, const char *cmd, int flags)
171 {
172   char *out;
173   int outlen;
174   int rc;
175
176   if (!idata) {
177     mutt_error (_("No mailbox is open."));
178     mutt_sleep (1);
179     return (-1);
180   }
181
182   if (idata->status == IMAP_FATAL) {
183     cmd_handle_fatal (idata);
184     return -1;
185   }
186
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);
193
194   rc = mutt_socket_write_d (idata->conn, out,
195                             flags & IMAP_CMD_PASS ? IMAP_LOG_PASS :
196                             IMAP_LOG_CMD);
197   mem_free (&out);
198
199   if (rc < 0) {
200     cmd_handle_fatal (idata);
201     return -1;
202   }
203
204   do
205     rc = imap_cmd_step (idata);
206   while (rc == IMAP_CMD_CONTINUE);
207
208   if (rc == IMAP_CMD_BAD) {
209     if (imap_reconnect (idata->ctx) != 0) {
210       return -1;
211     }
212     return 0;
213   }
214
215   if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK))
216     return -2;
217
218   if (rc != IMAP_CMD_OK) {
219     if (flags & IMAP_CMD_FAIL_OK)
220       return -2;
221
222     debug_print (1, ("command failed: %s\n", idata->cmd.buf));
223     return -1;
224   }
225
226   return 0;
227 }
228
229 /* imap_cmd_running: Returns whether an IMAP command is in progress. */
230 int imap_cmd_running (IMAP_DATA * idata)
231 {
232   if (idata->cmd.state == IMAP_CMD_CONTINUE ||
233       idata->cmd.state == IMAP_CMD_RESPOND)
234     return 1;
235
236   return 0;
237 }
238
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)
244 {
245   if (idata->status == IMAP_FATAL) {
246     cmd_handle_fatal (idata);
247     return;
248   }
249
250   if (!(idata->state == IMAP_SELECTED) || idata->ctx->closing)
251     return;
252
253   if (idata->reopen & IMAP_REOPEN_ALLOW) {
254     int count = idata->newMailCount;
255
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);
265     }
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);
275     }
276   }
277
278   idata->status = 0;
279 }
280
281 /* cmd_handle_fatal: when IMAP_DATA is in fatal state, do what we can */
282 static void cmd_handle_fatal (IMAP_DATA * idata)
283 {
284   idata->status = IMAP_FATAL;
285
286   if ((idata->state == IMAP_SELECTED) &&
287       (idata->reopen & IMAP_REOPEN_ALLOW)) {
288     /* mx_fastclose_mailbox (idata->ctx); */
289     mutt_error (_("Mailbox closed"));
290     mutt_sleep (1);
291     idata->state = IMAP_DISCONNECTED;
292     if (imap_reconnect (idata->ctx) != 0)
293       mx_fastclose_mailbox (idata->ctx);
294   }
295
296   if (idata->state != IMAP_SELECTED) {
297     idata->state = IMAP_DISCONNECTED;
298     mutt_socket_close (idata->conn);
299     idata->status = 0;
300   }
301 }
302
303 /* cmd_handle_untagged: fallback parser for otherwise unhandled messages. */
304 static int cmd_handle_untagged (IMAP_DATA * idata)
305 {
306   char *s;
307   char *pn;
308   int count;
309
310   s = imap_next_word (idata->cmd.buf);
311
312   if ((idata->state == IMAP_SELECTED) && isdigit ((unsigned char) *s)) {
313     pn = s;
314     s = imap_next_word (s);
315
316     /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
317      * connection, so update that one.
318      */
319     if (ascii_strncasecmp ("EXISTS", s, 6) == 0) {
320       debug_print (2, ("Handling EXISTS\n"));
321
322       /* new mail arrived */
323       count = atoi (pn);
324
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
329          */
330         mutt_error _("Fatal error.  Message count is out of sync!");
331
332         idata->status = IMAP_FATAL;
333         return -1;
334       }
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"));
339       else {
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;
343         }
344         idata->newMailCount = count;
345       }
346     }
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);
352   }
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"));
363
364     /* check if we're logging out */
365     if (idata->status == IMAP_BYE)
366       return 0;
367
368     /* server shut down our connection */
369     s += 3;
370     SKIPWS (s);
371     mutt_error ("%s", s);
372     mutt_sleep (2);
373     cmd_handle_fatal (idata);
374     return -1;
375   }
376   else if (option (OPTIMAPSERVERNOISE)
377            && (ascii_strncasecmp ("NO", s, 2) == 0)) {
378     debug_print (2, ("Handling untagged NO\n"));
379
380     /* Display the warning message from the server */
381     mutt_error ("%s", s + 3);
382     mutt_sleep (2);
383   }
384
385   return 0;
386 }
387
388 /* This should be optimised (eg with a tree or hash) */
389 static int uid2msgno (IMAP_DATA* idata, unsigned int uid) {
390   int i;
391
392   for (i = 0; i < idata->ctx->msgcount; i++) {
393     HEADER* h = idata->ctx->hdrs[i];
394     if (HEADER_DATA(h)->uid == uid)
395       return i;
396   }
397
398  return -1;
399 }
400
401 /* cmd_parse_search: store SEARCH response for later use */
402 static void cmd_parse_search (IMAP_DATA* idata, char* s) {
403   unsigned int uid;
404   int msgno;
405
406   debug_print (2, ("Handling SEARCH\n"));
407
408   while ((s = imap_next_word (s)) && *s != '\0') {
409     uid = atoi (s);
410     msgno = uid2msgno (idata, uid);
411     
412     if (msgno >= 0)
413       idata->ctx->hdrs[uid2msgno (idata, uid)]->matched = 1;
414   }
415 }
416
417 /* cmd_make_sequence: make a tag suitable for starting an IMAP command */
418 static void cmd_make_sequence (IMAP_DATA * idata)
419 {
420   snprintf (idata->cmd.seq, sizeof (idata->cmd.seq), "a%04u", idata->seqno++);
421
422   if (idata->seqno > 9999)
423     idata->seqno = 0;
424 }
425
426 /* cmd_parse_capabilities: set capability bits according to CAPABILITY
427  *   response */
428 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s)
429 {
430   int x;
431
432   debug_print (2, ("Handling CAPABILITY\n"));
433
434   s = imap_next_word (s);
435   mem_free (&idata->capstr);
436   idata->capstr = str_dup (s);
437
438   memset (idata->capabilities, 0, sizeof (idata->capabilities));
439
440   while (*s) {
441     for (x = 0; x < CAPMAX; x++)
442       if (imap_wordcasecmp (Capabilities[x], s) == 0) {
443         mutt_bit_set (idata->capabilities, x);
444         break;
445       }
446     s = imap_next_word (s);
447   }
448 }
449
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)
453 {
454   int expno, cur;
455   HEADER *h;
456
457   debug_print (2, ("Handling EXPUNGE\n"));
458
459   expno = atoi (s);
460
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];
467
468     if (h->index + 1 == expno)
469       h->index = -1;
470     else if (h->index + 1 > expno)
471       h->index--;
472   }
473
474   idata->reopen |= IMAP_EXPUNGE_PENDING;
475 }
476
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)
482 {
483   int msgno, cur;
484   HEADER *h = NULL;
485
486   debug_print (2, ("Handling FETCH\n"));
487
488   msgno = atoi (s);
489
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];
494
495       if (h->active && h->index + 1 == msgno) {
496         debug_print (2, ("Message UID %d updated\n", HEADER_DATA (h)->uid));
497         break;
498       }
499
500       h = NULL;
501     }
502
503   if (!h) {
504     debug_print (1, ("FETCH response ignored for this message\n"));
505     return;
506   }
507
508   /* skip FETCH */
509   s = imap_next_word (s);
510   s = imap_next_word (s);
511
512   if (*s != '(') {
513     debug_print (1, ("Malformed FETCH response\n"));
514     return;
515   }
516   s++;
517
518   if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
519     debug_print (2, ("Only handle FLAGS updates\n"));
520     return;
521   }
522
523   /* If server flags could conflict with mutt's flags, reopen the mailbox. */
524   if (h->changed)
525     idata->reopen |= IMAP_EXPUNGE_PENDING;
526   else {
527     imap_set_flags (idata, h, s);
528     idata->check_status = IMAP_FLAGS_PENDING;
529   }
530 }
531
532 static void cmd_parse_lsub (IMAP_DATA* idata, char* s) {
533   char buf[STRING];
534   char errstr[STRING];
535   BUFFER err, token;
536   ciss_url_t url;
537   char *ep;
538
539   if (!option (OPTIMAPCHECKSUBSCRIBED))
540     return;
541
542   s = imap_next_word (s); /* flags */
543
544   if (*s != '(') {
545     debug_print (1, ("Bad LSUB response\n"));
546     return;
547   }
548
549   s++;
550   ep = s;
551   for (ep = s; *ep && *ep != ')'; ep++);
552   do {
553     if (!ascii_strncasecmp (s, "\\NoSelect", 9))
554       return;
555     while (s < ep && *s != ' ' && *s != ')')
556       s++;
557     if (*s == ' ')
558       s++;
559   } while (s != ep);
560
561   s = imap_next_word (s); /* delim */
562   s = imap_next_word (s); /* name */
563
564   if (s) {
565     imap_unmunge_mbox_name (s);
566     debug_print (2, ("Subscribing to %s\n", s));
567
568     strfcpy (buf, "mailboxes \"", sizeof (buf));
569     mutt_account_tourl (&idata->conn->account, &url);
570     url.path = s;
571     if (!str_cmp (url.user, ImapUser))
572       url.user = NULL;
573     url_ciss_tostring (&url, buf + 11, sizeof (buf) - 10, 0);
574     str_cat (buf, sizeof (buf), "\"");
575     memset (&token, 0, sizeof (token));
576     err.data = errstr;
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);
581   }
582   else
583     debug_print (1, ("Bad LSUB response\n"));
584 }
585
586 /* cmd_parse_myrights: set rights bits according to MYRIGHTS response */
587 static void cmd_parse_myrights (IMAP_DATA * idata, char *s)
588 {
589   debug_print (2, ("Handling MYRIGHTS\n"));
590
591   s = imap_next_word (s);
592   s = imap_next_word (s);
593
594   /* zero out current rights set */
595   memset (idata->rights, 0, sizeof (idata->rights));
596
597   while (*s && !isspace ((unsigned char) *s)) {
598     switch (*s) {
599     case 'l':
600       mutt_bit_set (idata->rights, ACL_LOOKUP);
601       break;
602     case 'r':
603       mutt_bit_set (idata->rights, ACL_READ);
604       break;
605     case 's':
606       mutt_bit_set (idata->rights, ACL_SEEN);
607       break;
608     case 'w':
609       mutt_bit_set (idata->rights, ACL_WRITE);
610       break;
611     case 'i':
612       mutt_bit_set (idata->rights, ACL_INSERT);
613       break;
614     case 'p':
615       mutt_bit_set (idata->rights, ACL_POST);
616       break;
617     case 'c':
618       mutt_bit_set (idata->rights, ACL_CREATE);
619       break;
620     case 'd':
621       mutt_bit_set (idata->rights, ACL_DELETE);
622       break;
623     case 'a':
624       mutt_bit_set (idata->rights, ACL_ADMIN);
625       break;
626     }
627     s++;
628   }
629 }