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