replace SKIPWS with a proper inline func with the right API.
[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/ascii.h>
21 #include <lib-lib/macros.h>
22
23 #include "lib/debug.h"
24
25 #include "mutt.h"
26 #include "message.h"
27 #include "mx.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 = vskipspaces(s + SEQLEN);
159   return !ascii_strncasecmp("OK", s, 2);
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 = m_strlen(idata->cmd.seq) + m_strlen(cmd) + 4;
191   out = p_new(char, 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   p_delete(&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 = vskipspaces(s + 3);
370     mutt_error ("%s", s);
371     mutt_sleep (2);
372     cmd_handle_fatal (idata);
373     return -1;
374   }
375   else if (option (OPTIMAPSERVERNOISE)
376            && (ascii_strncasecmp ("NO", s, 2) == 0)) {
377     debug_print (2, ("Handling untagged NO\n"));
378
379     /* Display the warning message from the server */
380     mutt_error ("%s", s + 3);
381     mutt_sleep (2);
382   }
383
384   return 0;
385 }
386
387 /* This should be optimised (eg with a tree or hash) */
388 static int uid2msgno (IMAP_DATA* idata, unsigned int uid) {
389   int i;
390
391   for (i = 0; i < idata->ctx->msgcount; i++) {
392     HEADER* h = idata->ctx->hdrs[i];
393     if (HEADER_DATA(h)->uid == uid)
394       return i;
395   }
396
397  return -1;
398 }
399
400 /* cmd_parse_search: store SEARCH response for later use */
401 static void cmd_parse_search (IMAP_DATA* idata, char* s) {
402   unsigned int uid;
403   int msgno;
404
405   debug_print (2, ("Handling SEARCH\n"));
406
407   while ((s = imap_next_word (s)) && *s != '\0') {
408     uid = atoi (s);
409     msgno = uid2msgno (idata, uid);
410     
411     if (msgno >= 0)
412       idata->ctx->hdrs[uid2msgno (idata, uid)]->matched = 1;
413   }
414 }
415
416 /* cmd_make_sequence: make a tag suitable for starting an IMAP command */
417 static void cmd_make_sequence (IMAP_DATA * idata)
418 {
419   snprintf (idata->cmd.seq, sizeof (idata->cmd.seq), "a%04u", idata->seqno++);
420
421   if (idata->seqno > 9999)
422     idata->seqno = 0;
423 }
424
425 /* cmd_parse_capabilities: set capability bits according to CAPABILITY
426  *   response */
427 static void cmd_parse_capabilities (IMAP_DATA * idata, char *s)
428 {
429   int x;
430
431   debug_print (2, ("Handling CAPABILITY\n"));
432
433   s = imap_next_word (s);
434   p_delete(&idata->capstr);
435   idata->capstr = m_strdup(s);
436
437   p_clear(idata->capabilities, 1);
438
439   while (*s) {
440     for (x = 0; x < CAPMAX; x++)
441       if (imap_wordcasecmp (Capabilities[x], s) == 0) {
442         mutt_bit_set (idata->capabilities, x);
443         break;
444       }
445     s = imap_next_word (s);
446   }
447 }
448
449 /* cmd_parse_expunge: mark headers with new sequence ID and mark idata to
450  *   be reopened at our earliest convenience */
451 static void cmd_parse_expunge (IMAP_DATA * idata, const char *s)
452 {
453   int expno, cur;
454   HEADER *h;
455
456   debug_print (2, ("Handling EXPUNGE\n"));
457
458   expno = atoi (s);
459
460   /* walk headers, zero seqno of expunged message, decrement seqno of those
461    * above. Possibly we could avoid walking the whole list by resorting
462    * and guessing a good starting point, but I'm guessing the resort would
463    * nullify the gains */
464   for (cur = 0; cur < idata->ctx->msgcount; cur++) {
465     h = idata->ctx->hdrs[cur];
466
467     if (h->index + 1 == expno)
468       h->index = -1;
469     else if (h->index + 1 > expno)
470       h->index--;
471   }
472
473   idata->reopen |= IMAP_EXPUNGE_PENDING;
474 }
475
476 /* cmd_parse_fetch: Load fetch response into IMAP_DATA. Currently only
477  *   handles unanticipated FETCH responses, and only FLAGS data. We get
478  *   these if another client has changed flags for a mailbox we've selected.
479  *   Of course, a lot of code here duplicates code in message.c. */
480 static void cmd_parse_fetch (IMAP_DATA * idata, char *s)
481 {
482   int msgno, cur;
483   HEADER *h = NULL;
484
485   debug_print (2, ("Handling FETCH\n"));
486
487   msgno = atoi (s);
488
489   if (msgno <= idata->ctx->msgcount)
490     /* see cmd_parse_expunge */
491     for (cur = 0; cur < idata->ctx->msgcount; cur++) {
492       h = idata->ctx->hdrs[cur];
493
494       if (!h)
495         break;
496
497       if (h->active && h->index + 1 == msgno) {
498         debug_print (2, ("Message UID %d updated\n", HEADER_DATA (h)->uid));
499         break;
500       }
501
502       h = NULL;
503     }
504
505   if (!h) {
506     debug_print (1, ("FETCH response ignored for this message\n"));
507     return;
508   }
509
510   /* skip FETCH */
511   s = imap_next_word (s);
512   s = imap_next_word (s);
513
514   if (*s != '(') {
515     debug_print (1, ("Malformed FETCH response\n"));
516     return;
517   }
518   s++;
519
520   if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
521     debug_print (2, ("Only handle FLAGS updates\n"));
522     return;
523   }
524
525   /* If server flags could conflict with mutt's flags, reopen the mailbox. */
526   if (h->changed)
527     idata->reopen |= IMAP_EXPUNGE_PENDING;
528   else {
529     imap_set_flags (idata, h, s);
530     idata->check_status = IMAP_FLAGS_PENDING;
531   }
532 }
533
534 static void cmd_parse_lsub (IMAP_DATA* idata, char* s) {
535   char buf[STRING];
536   char errstr[STRING];
537   BUFFER err, token;
538   ciss_url_t url;
539   char *ep;
540
541   if (!option (OPTIMAPCHECKSUBSCRIBED))
542     return;
543
544   s = imap_next_word (s); /* flags */
545
546   if (*s != '(') {
547     debug_print (1, ("Bad LSUB response\n"));
548     return;
549   }
550
551   s++;
552   ep = s;
553   for (ep = s; *ep && *ep != ')'; ep++);
554   do {
555     if (!ascii_strncasecmp (s, "\\NoSelect", 9))
556       return;
557     while (s < ep && *s != ' ' && *s != ')')
558       s++;
559     if (*s == ' ')
560       s++;
561   } while (s != ep);
562
563   s = imap_next_word (s); /* delim */
564   s = imap_next_word (s); /* name */
565
566   if (s) {
567     imap_unmunge_mbox_name (s);
568     debug_print (2, ("Subscribing to %s\n", s));
569
570     m_strcpy(buf, sizeof(buf), "mailboxes \"");
571     mutt_account_tourl (&idata->conn->account, &url);
572     url.path = s;
573     if (!m_strcmp(url.user, ImapUser))
574       url.user = NULL;
575     url_ciss_tostring (&url, buf + 11, sizeof (buf) - 10, 0);
576     m_strcat(buf, sizeof(buf), "\"");
577     p_clear(&token, 1);
578     err.data = errstr;
579     err.dsize = sizeof (errstr);
580     if (mutt_parse_rc_line (buf, &token, &err))
581       debug_print (1, ("Error adding subscribed mailbox: %s\n", errstr));
582     p_delete(&token.data);
583   }
584   else
585     debug_print (1, ("Bad LSUB response\n"));
586 }
587
588 /* cmd_parse_myrights: set rights bits according to MYRIGHTS response */
589 static void cmd_parse_myrights (IMAP_DATA * idata, char *s)
590 {
591   debug_print (2, ("Handling MYRIGHTS\n"));
592
593   s = imap_next_word (s);
594   s = imap_next_word (s);
595
596   /* zero out current rights set */
597   p_clear(idata->rights, 1);
598
599   while (*s && !isspace ((unsigned char) *s)) {
600     switch (*s) {
601     case 'l':
602       mutt_bit_set (idata->rights, ACL_LOOKUP);
603       break;
604     case 'r':
605       mutt_bit_set (idata->rights, ACL_READ);
606       break;
607     case 's':
608       mutt_bit_set (idata->rights, ACL_SEEN);
609       break;
610     case 'w':
611       mutt_bit_set (idata->rights, ACL_WRITE);
612       break;
613     case 'i':
614       mutt_bit_set (idata->rights, ACL_INSERT);
615       break;
616     case 'p':
617       mutt_bit_set (idata->rights, ACL_POST);
618       break;
619     case 'c':
620       mutt_bit_set (idata->rights, ACL_CREATE);
621       break;
622     case 'd':
623       mutt_bit_set (idata->rights, ACL_DELETE);
624       break;
625     case 'a':
626       mutt_bit_set (idata->rights, ACL_ADMIN);
627       break;
628     }
629     s++;
630   }
631 }