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