replace SKIPWS with a proper inline func with the right API.
[apps/madmutt.git] / imap / imap.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 /* Support for IMAP4rev1, with the occasional nod to IMAP 4. */
13
14 #if HAVE_CONFIG_H
15 # include "config.h"
16 #endif
17
18 #include <lib-lib/mem.h>
19 #include <lib-lib/ascii.h>
20 #include <lib-lib/str.h>
21 #include <lib-lib/buffer.h>
22
23 #include "mutt.h"
24 #include "mx.h"
25 #include "globals.h"
26 #include "sort.h"
27 #include "browser.h"
28 #include "message.h"
29 #include "imap_private.h"
30 #if defined(USE_SSL) || defined(USE_GNUTLS)
31 # include "mutt_ssl.h"
32 #endif
33 #include "buffy.h"
34
35 #include <lib-lib/macros.h>
36 #include "lib/debug.h"
37
38 #include <unistd.h>
39 #include <ctype.h>
40 #include <string.h>
41 #include <stdlib.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44
45 /* imap forward declarations */
46 static int imap_get_delim (IMAP_DATA * idata);
47 static char *imap_get_flags (LIST ** hflags, char *s);
48 static int imap_check_acl (IMAP_DATA * idata);
49 static int imap_check_capabilities (IMAP_DATA * idata);
50 static void imap_set_flag (IMAP_DATA * idata, int aclbit, int flag,
51                            const char *str, char *flags, size_t flsize);
52
53 /* imap_access: Check permissions on an IMAP mailbox.
54  * TODO: ACL checks. Right now we assume if it exists we can
55  * mess with it. */
56 int imap_access (const char *path, int flags)
57 {
58   IMAP_DATA *idata;
59   IMAP_MBOX mx;
60   char buf[LONG_STRING];
61   char mailbox[LONG_STRING];
62   char mbox[LONG_STRING];
63
64   if (imap_parse_path (path, &mx))
65     return -1;
66
67   if (!(idata = imap_conn_find (&mx.account,
68                                 option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW :
69                                 0))) {
70     p_delete(&mx.mbox);
71     return -1;
72   }
73
74   imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
75
76   /* we may already be in the folder we're checking */
77   if (!ascii_strcmp(idata->mailbox, mx.mbox)) {
78     p_delete(&mx.mbox);
79     return 0;
80   }
81
82   p_delete(&mx.mbox);
83   imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
84
85   if (mutt_bit_isset (idata->capabilities, IMAP4REV1))
86     snprintf (buf, sizeof (buf), "STATUS %s (UIDVALIDITY)", mbox);
87   else if (mutt_bit_isset (idata->capabilities, STATUS))
88     snprintf (buf, sizeof (buf), "STATUS %s (UID-VALIDITY)", mbox);
89   else {
90     debug_print (2, ("STATUS not supported?\n"));
91     return -1;
92   }
93
94   if (imap_exec (idata, buf, IMAP_CMD_FAIL_OK) < 0) {
95     debug_print (1, ("Can't check STATUS of %s\n", mbox));
96     return -1;
97   }
98
99   return 0;
100 }
101
102 int imap_create_mailbox (IMAP_DATA * idata, char *mailbox)
103 {
104   char buf[LONG_STRING], mbox[LONG_STRING];
105
106   imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
107   snprintf (buf, sizeof (buf), "CREATE %s", mbox);
108
109   if (imap_exec (idata, buf, 0) != 0)
110     return -1;
111
112   return 0;
113 }
114
115 int imap_rename_mailbox (IMAP_DATA * idata, IMAP_MBOX * mx,
116                          const char *newname)
117 {
118   char oldmbox[LONG_STRING];
119   char newmbox[LONG_STRING];
120   char buf[LONG_STRING];
121
122   imap_munge_mbox_name (oldmbox, sizeof (oldmbox), mx->mbox);
123   imap_munge_mbox_name (newmbox, sizeof (newmbox), newname);
124
125   snprintf (buf, sizeof (buf), "RENAME %s %s", oldmbox, newmbox);
126
127   if (imap_exec (idata, buf, 0) != 0)
128     return -1;
129
130   return 0;
131 }
132
133 int imap_delete_mailbox (CONTEXT * ctx, IMAP_MBOX mx)
134 {
135   char buf[LONG_STRING], mbox[LONG_STRING];
136   IMAP_DATA *idata;
137
138   if (!ctx || !ctx->data) {
139     if (!(idata = imap_conn_find (&mx.account,
140                                   option (OPTIMAPPASSIVE) ? M_IMAP_CONN_NONEW
141                                   : 0))) {
142       p_delete(&mx.mbox);
143       return -1;
144     }
145   }
146   else {
147     idata = ctx->data;
148   }
149
150   imap_munge_mbox_name (mbox, sizeof (mbox), mx.mbox);
151   snprintf (buf, sizeof (buf), "DELETE %s", mbox);
152
153   if (imap_exec ((IMAP_DATA *) idata, buf, 0) != 0)
154     return -1;
155
156   return 0;
157 }
158
159 /* imap_logout_all: close all open connections. Quick and dirty until we can
160  *   make sure we've got all the context we need. */
161 void imap_logout_all (void)
162 {
163   CONNECTION *conn;
164   CONNECTION *tmp;
165
166   conn = mutt_socket_head ();
167
168   while (conn) {
169     tmp = conn->next;
170
171     if (conn->account.type == M_ACCT_TYPE_IMAP && conn->fd >= 0) {
172       mutt_message (_("Closing connection to %s..."), conn->account.host);
173       imap_logout ((IMAP_DATA *) conn->data);
174       mutt_clear_error ();
175       mutt_socket_close (conn);
176       mutt_socket_free (conn);
177     }
178
179     conn = tmp;
180   }
181 }
182
183 /* imap_read_literal: read bytes bytes from server into file. Not explicitly
184  *   buffered, relies on FILE buffering. NOTE: strips \r from \r\n.
185  *   Apparently even literals use \r\n-terminated strings ?! */
186 int imap_read_literal (FILE * fp, IMAP_DATA * idata, long bytes, progress_t* bar)
187 {
188   long pos;
189   char c;
190
191   int r = 0;
192
193   debug_print (2, ("reading %ld bytes\n", bytes));
194
195   for (pos = 0; pos < bytes; pos++) {
196     if (mutt_socket_readchar (idata->conn, &c) != 1) {
197       debug_print (1, ("error during read, %ld bytes read\n", pos));
198       idata->status = IMAP_FATAL;
199
200       return -1;
201     }
202
203 #if 1
204     if (r == 1 && c != '\n')
205       fputc ('\r', fp);
206
207     if (c == '\r') {
208       r = 1;
209       continue;
210     }
211     else
212       r = 0;
213 #endif
214     fputc (c, fp);
215     if (bar && !(pos % 1024))
216       mutt_progress_bar (bar, pos);
217 #ifdef DEBUG
218     if (DebugFile && DebugLevel >= IMAP_LOG_LTRL)
219       fputc (c, DebugFile);
220 #endif
221   }
222
223   return 0;
224 }
225
226 /* imap_expunge_mailbox: Purge IMAP portion of expunged messages from the
227  *   context. Must not be done while something has a handle on any headers
228  *   (eg inside pager or editor). That is, check IMAP_REOPEN_ALLOW. */
229 void imap_expunge_mailbox (IMAP_DATA * idata)
230 {
231   HEADER *h;
232   int i, cacheno;
233
234   for (i = 0; i < idata->ctx->msgcount; i++) {
235     h = idata->ctx->hdrs[i];
236
237     if (h->index == -1) {
238       debug_print (2, ("Expunging message UID %d.\n", HEADER_DATA (h)->uid));
239
240       h->active = 0;
241
242       /* free cached body from disk, if neccessary */
243       cacheno = HEADER_DATA (h)->uid % IMAP_CACHE_LEN;
244       if (idata->cache[cacheno].uid == HEADER_DATA (h)->uid &&
245           idata->cache[cacheno].path) {
246         unlink (idata->cache[cacheno].path);
247         p_delete(&idata->cache[cacheno].path);
248       }
249
250       imap_free_header_data (&h->data);
251     }
252   }
253
254   /* We may be called on to expunge at any time. We can't rely on the caller
255    * to always know to rethread */
256   mx_update_tables (idata->ctx, 0);
257   mutt_sort_headers (idata->ctx, 1);
258 }
259
260 static int imap_get_delim (IMAP_DATA * idata)
261 {
262   char *s;
263   int rc;
264
265   /* assume that the delim is /.  If this fails, we're in bigger trouble
266    * than getting the delim wrong */
267   idata->delim = '/';
268
269   imap_cmd_start (idata, "LIST \"\" \"\"");
270
271   do {
272     if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
273       break;
274
275     s = imap_next_word (idata->cmd.buf);
276     if (ascii_strncasecmp ("LIST", s, 4) == 0) {
277       s = imap_next_word (s);
278       s = imap_next_word (s);
279       if (s && s[0] == '\"' && s[1] && s[2] == '\"')
280         idata->delim = s[1];
281       else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
282                && s[3] == '\"')
283         idata->delim = s[2];
284     }
285   }
286   while (rc == IMAP_CMD_CONTINUE);
287
288   if (rc != IMAP_CMD_OK) {
289     debug_print (1, ("failed.\n"));
290     return -1;
291   }
292
293   debug_print (2, ("Delimiter: %c\n", idata->delim));
294
295   return -1;
296 }
297
298 /* get rights for folder, let imap_handle_untagged do the rest */
299 static int imap_check_acl (IMAP_DATA * idata)
300 {
301   char buf[LONG_STRING];
302   char mbox[LONG_STRING];
303
304   imap_munge_mbox_name (mbox, sizeof (mbox), idata->mailbox);
305   snprintf (buf, sizeof (buf), "MYRIGHTS %s", mbox);
306   if (imap_exec (idata, buf, 0) != 0) {
307     imap_error ("imap_check_acl", buf);
308     return -1;
309   }
310   return 0;
311 }
312
313 /* imap_check_capabilities: make sure we can log in to this server. */
314 static int imap_check_capabilities (IMAP_DATA * idata)
315 {
316   if (imap_exec (idata, "CAPABILITY", 0) != 0) {
317     imap_error ("imap_check_capabilities", idata->cmd.buf);
318     return -1;
319   }
320
321   if (!(mutt_bit_isset (idata->capabilities, IMAP4)
322         || mutt_bit_isset (idata->capabilities, IMAP4REV1))) {
323     mutt_error _("This IMAP server is ancient. Mutt does not work with it.");
324
325     mutt_sleep (2);             /* pause a moment to let the user see the error */
326
327     return -1;
328   }
329
330   return 0;
331 }
332
333 /* imap_conn_find: Find an open IMAP connection matching account, or open
334  *   a new one if none can be found. */
335 IMAP_DATA *imap_conn_find (const ACCOUNT * account, int flags)
336 {
337   CONNECTION *conn;
338   IMAP_DATA *idata;
339   ACCOUNT *creds;
340   int new = 0;
341
342   if (!(conn = mutt_conn_find (NULL, account)))
343     return NULL;
344
345   /* if opening a new UNSELECTED connection, preserve existing creds */
346   creds = &(conn->account);
347
348   /* make sure this connection is not in SELECTED state, if neccessary */
349   if (flags & M_IMAP_CONN_NOSELECT)
350     while (conn->data && ((IMAP_DATA *) conn->data)->state == IMAP_SELECTED) {
351       if (!(conn = mutt_conn_find (conn, account)))
352         return NULL;
353       memcpy (&(conn->account), creds, sizeof (ACCOUNT));
354     }
355
356   idata = (IMAP_DATA *) conn->data;
357
358   /* don't open a new connection if one isn't wanted */
359   if (flags & M_IMAP_CONN_NONEW) {
360     if (!idata) {
361       mutt_socket_free (conn);
362       return NULL;
363     }
364     if (idata->state < IMAP_AUTHENTICATED)
365       return NULL;
366   }
367
368   if (!idata) {
369     /* The current connection is a new connection */
370     if (!(idata = imap_new_idata ())) {
371       mutt_socket_free (conn);
372       return NULL;
373     }
374
375     conn->data = idata;
376     idata->conn = conn;
377     new = 1;
378   }
379
380   if (idata->state == IMAP_DISCONNECTED)
381     imap_open_connection (idata);
382   if (idata->state == IMAP_CONNECTED) {
383     if (!imap_authenticate (idata)) {
384       idata->state = IMAP_AUTHENTICATED;
385       if (idata->conn->ssf)
386         debug_print (2, ("Communication encrypted at %d bits\n", idata->conn->ssf));
387     }
388     else
389       mutt_account_unsetpass (&idata->conn->account);
390
391     p_delete(&idata->capstr);
392   }
393   if (new && idata->state == IMAP_AUTHENTICATED) {
394     imap_get_delim (idata);
395     if (option (OPTIMAPCHECKSUBSCRIBED)) {
396       mutt_message _("Checking mailbox subscriptions");
397       imap_exec (idata, "LSUB \"\" \"*\"", 0);
398     }
399   }
400
401   return idata;
402 }
403
404 int imap_open_connection (IMAP_DATA * idata)
405 {
406   char buf[LONG_STRING];
407
408   if (mutt_socket_open (idata->conn) < 0)
409     return -1;
410
411   idata->state = IMAP_CONNECTED;
412
413   if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE) {
414     mutt_socket_close (idata->conn);
415     idata->state = IMAP_DISCONNECTED;
416     return -1;
417   }
418
419   if (ascii_strncasecmp ("* OK", idata->cmd.buf, 4) == 0) {
420     /* TODO: Parse new tagged CAPABILITY data (* OK [CAPABILITY...]) */
421     if (imap_check_capabilities (idata))
422       goto bail;
423 #if defined(USE_SSL) || defined(USE_GNUTLS)
424     /* Attempt STARTTLS if available and desired. */
425     if (!idata->conn->ssf && (option(OPTSSLFORCETLS) || 
426                               mutt_bit_isset (idata->capabilities, STARTTLS))) {
427       int rc;
428
429       if (option (OPTSSLFORCETLS))
430         rc = M_YES;
431       else if ((rc = query_quadoption (OPT_SSLSTARTTLS,
432                                        _("Secure connection with TLS?"))) == -1)
433         goto err_close_conn;
434       if (rc == M_YES) {
435         if ((rc = imap_exec (idata, "STARTTLS", IMAP_CMD_FAIL_OK)) == -1)
436           goto bail;
437         if (rc != -2) {
438 #if defined (USE_SSL) || defined (USE_GNUTLS)
439           if (mutt_ssl_starttls (idata->conn))
440 #endif
441           {
442             mutt_error (_("Could not negotiate TLS connection"));
443             mutt_sleep (1);
444             goto err_close_conn;
445           }
446           else {
447             /* RFC 2595 demands we recheck CAPABILITY after TLS completes. */
448             if (imap_exec (idata, "CAPABILITY", 0))
449               goto bail;
450           }
451         }
452       }
453     }
454
455     if (option(OPTSSLFORCETLS) && ! idata->conn->ssf) {
456       mutt_error _("Encrypted connection unavailable");
457       mutt_sleep (1);
458       goto err_close_conn;
459     }
460 #endif
461   }
462   else if (ascii_strncasecmp ("* PREAUTH", idata->cmd.buf, 9) == 0) {
463     idata->state = IMAP_AUTHENTICATED;
464     if (imap_check_capabilities (idata) != 0)
465       goto bail;
466     p_delete(&idata->capstr);
467   }
468   else {
469     imap_error ("imap_open_connection()", buf);
470     goto bail;
471   }
472
473   return 0;
474
475 err_close_conn:
476   mutt_socket_close (idata->conn);
477   idata->state = IMAP_DISCONNECTED;
478 bail:
479   p_delete(&idata->capstr);
480   return -1;
481 }
482
483 /* imap_get_flags: Make a simple list out of a FLAGS response.
484  *   return stream following FLAGS response */
485 static char *imap_get_flags (LIST ** hflags, char *s)
486 {
487   LIST *flags;
488   char *flag_word;
489   char ctmp;
490
491   /* sanity-check string */
492   if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
493     debug_print (1, ("not a FLAGS response: %s\n", s));
494     return NULL;
495   }
496   s = vskipspaces(s + 5);
497   if (*s != '(') {
498     debug_print (1, ("bogus FLAGS response: %s\n", s));
499     return NULL;
500   }
501
502   /* create list, update caller's flags handle */
503   flags = mutt_new_list ();
504   *hflags = flags;
505
506   while (*s && *s != ')') {
507     s = vskipspaces(s + 1);
508     flag_word = s;
509     while (*s && (*s != ')') && !ISSPACE (*s))
510       s++;
511     ctmp = *s;
512     *s = '\0';
513     if (*flag_word)
514       mutt_add_list (flags, flag_word);
515     *s = ctmp;
516   }
517
518   /* note bad flags response */
519   if (*s != ')') {
520     debug_print (1, ("Unterminated FLAGS response: %s\n", s));
521     mutt_free_list (hflags);
522
523     return NULL;
524   }
525
526   s++;
527
528   return s;
529 }
530
531 int imap_open_mailbox (CONTEXT * ctx)
532 {
533   CONNECTION *conn;
534   IMAP_DATA *idata;
535   char buf[LONG_STRING];
536   char bufout[LONG_STRING];
537   int count = 0;
538   IMAP_MBOX mx;
539   int rc;
540
541   if (imap_parse_path (ctx->path, &mx)) {
542     mutt_error (_("%s is an invalid IMAP path"), ctx->path);
543     return -1;
544   }
545
546   /* we require a connection which isn't currently in IMAP_SELECTED state */
547   if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NOSELECT)))
548     goto fail_noidata;
549   if (idata->state < IMAP_AUTHENTICATED)
550     goto fail;
551
552   conn = idata->conn;
553
554   /* once again the context is new */
555   ctx->data = idata;
556
557   /* Clean up path and replace the one in the ctx */
558   imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
559   p_delete(&(idata->mailbox));
560   idata->mailbox = m_strdup(buf);
561   imap_qualify_path (buf, sizeof (buf), &mx, idata->mailbox);
562
563   p_delete(&(ctx->path));
564   ctx->path = m_strdup(buf);
565
566   idata->ctx = ctx;
567
568   /* clear mailbox status */
569   idata->status = 0;
570   memset (idata->rights, 0, (RIGHTSMAX + 7) / 8);
571   idata->newMailCount = 0;
572
573   mutt_message (_("Selecting %s..."), idata->mailbox);
574   imap_munge_mbox_name (buf, sizeof (buf), idata->mailbox);
575   snprintf (bufout, sizeof (bufout), "%s %s",
576             ctx->readonly ? "EXAMINE" : "SELECT", buf);
577
578   idata->state = IMAP_SELECTED;
579
580   imap_cmd_start (idata, bufout);
581
582   do {
583     char *pc;
584
585     if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
586       break;
587
588     pc = idata->cmd.buf + 2;
589
590     /* Obtain list of available flags here, may be overridden by a
591      * PERMANENTFLAGS tag in the OK response */
592     if (ascii_strncasecmp ("FLAGS", pc, 5) == 0) {
593       /* don't override PERMANENTFLAGS */
594       if (!idata->flags) {
595         debug_print (2, ("Getting mailbox FLAGS\n"));
596         if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
597           goto fail;
598       }
599     }
600     /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
601     else if (ascii_strncasecmp ("OK [PERMANENTFLAGS", pc, 18) == 0) {
602       debug_print (2, ("Getting mailbox PERMANENTFLAGS\n"));
603       /* safe to call on NULL */
604       mutt_free_list (&(idata->flags));
605       /* skip "OK [PERMANENT" so syntax is the same as FLAGS */
606       pc += 13;
607       if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
608         goto fail;
609     }
610 #ifdef USE_HCACHE
611     /* save UIDVALIDITY for the header cache */
612     else if (ascii_strncasecmp ("OK [UIDVALIDITY", pc, 14) == 0) {
613       debug_print (2, ("Getting mailbox UIDVALIDITY\n"));
614       pc += 3;
615       pc = imap_next_word (pc);
616
617       sscanf (pc, "%lu", &(idata->uid_validity));
618     }
619 #endif
620     else {
621       pc = imap_next_word (pc);
622       if (!ascii_strncasecmp ("EXISTS", pc, 6)) {
623         count = idata->newMailCount;
624         idata->newMailCount = 0;
625       }
626     }
627   }
628   while (rc == IMAP_CMD_CONTINUE);
629
630   if (rc == IMAP_CMD_NO) {
631     char *s;
632
633     s = imap_next_word (idata->cmd.buf);        /* skip seq */
634     s = imap_next_word (s);     /* Skip response */
635     mutt_error ("%s", s);
636     mutt_sleep (2);
637     goto fail;
638   }
639
640   if (rc != IMAP_CMD_OK)
641     goto fail;
642
643   /* check for READ-ONLY notification */
644   if (!ascii_strncasecmp
645       (imap_get_qualifier (idata->cmd.buf), "[READ-ONLY]", 11)
646       && !mutt_bit_isset (idata->capabilities, ACL)) {
647     debug_print (2, ("Mailbox is read-only.\n"));
648     ctx->readonly = 1;
649   }
650
651 #ifdef DEBUG
652   /* dump the mailbox flags we've found */
653   if (DebugLevel > 2) {
654     if (!idata->flags)
655       debug_print (3, ("No folder flags found\n"));
656     else {
657       LIST *t = idata->flags;
658
659       debug_print (3, ("Mailbox flags:\n"));
660
661       t = t->next;
662       while (t) {
663         debug_print (3, ("[%s]\n", t->data));
664         t = t->next;
665       }
666     }
667   }
668 #endif
669
670   if (mutt_bit_isset (idata->capabilities, ACL)) {
671     if (imap_check_acl (idata))
672       goto fail;
673     if (!(mutt_bit_isset (idata->rights, ACL_DELETE) ||
674           mutt_bit_isset (idata->rights, ACL_SEEN) ||
675           mutt_bit_isset (idata->rights, ACL_WRITE) ||
676           mutt_bit_isset (idata->rights, ACL_INSERT)))
677       ctx->readonly = 1;
678   }
679   /* assume we have all rights if ACL is unavailable */
680   else {
681     mutt_bit_set (idata->rights, ACL_LOOKUP);
682     mutt_bit_set (idata->rights, ACL_READ);
683     mutt_bit_set (idata->rights, ACL_SEEN);
684     mutt_bit_set (idata->rights, ACL_WRITE);
685     mutt_bit_set (idata->rights, ACL_INSERT);
686     mutt_bit_set (idata->rights, ACL_POST);
687     mutt_bit_set (idata->rights, ACL_CREATE);
688     mutt_bit_set (idata->rights, ACL_DELETE);
689   }
690
691   ctx->hdrmax = count;
692   ctx->hdrs = p_new(HEADER *, count);
693   ctx->v2r = p_new(int, count);
694   ctx->msgcount = 0;
695   if (count && (imap_read_headers (idata, 0, count - 1) < 0)) {
696     mutt_error _("Error opening mailbox");
697
698     mutt_sleep (1);
699     goto fail;
700   }
701
702   debug_print (2, ("msgcount is %d\n", ctx->msgcount));
703   p_delete(&mx.mbox);
704   return 0;
705
706 fail:
707   if (idata->state == IMAP_SELECTED)
708     idata->state = IMAP_AUTHENTICATED;
709 fail_noidata:
710   p_delete(&mx.mbox);
711   return -1;
712 }
713
714 int imap_open_mailbox_append (CONTEXT * ctx)
715 {
716   CONNECTION *conn;
717   IMAP_DATA *idata;
718   char buf[LONG_STRING];
719   char mailbox[LONG_STRING];
720   IMAP_MBOX mx;
721
722   if (imap_parse_path (ctx->path, &mx))
723     return -1;
724
725   /* in APPEND mode, we appear to hijack an existing IMAP connection -
726    * ctx is brand new and mostly empty */
727
728   if (!(idata = imap_conn_find (&(mx.account), 0))) {
729     p_delete(&mx.mbox);
730     return (-1);
731   }
732   conn = idata->conn;
733
734   ctx->magic = M_IMAP;
735   ctx->data = idata;
736
737   imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
738
739   p_delete(&mx.mbox);
740
741   /* really we should also check for W_OK */
742   if (!imap_access (ctx->path, F_OK))
743     return 0;
744
745   snprintf (buf, sizeof (buf), _("Create %s?"), mailbox);
746   if (option (OPTCONFIRMCREATE) && mutt_yesorno (buf, 1) < 1)
747     return -1;
748
749   if (imap_create_mailbox (idata, mailbox) < 0)
750     return -1;
751
752   return (0);
753 }
754
755 /* imap_logout: Gracefully log out of server. */
756 void imap_logout (IMAP_DATA * idata)
757 {
758   /* we set status here to let imap_handle_untagged know we _expect_ to
759    * receive a bye response (so it doesn't freak out and close the conn) */
760   idata->status = IMAP_BYE;
761   imap_cmd_start (idata, "LOGOUT");
762   while (imap_cmd_step (idata) == IMAP_CMD_CONTINUE);
763   p_delete(&idata->cmd.buf);
764   p_delete(&idata);
765 }
766
767 /*
768 int imap_close_connection (CONTEXT *ctx)
769 {
770   debug_print (1, (debugfile, "imap_close_connection(): closing connection\n"));
771   if (CTX_DATA->status != IMAP_BYE)
772   {
773     mutt_message _("Closing connection to IMAP server...");
774     imap_logout (CTX_DATA);
775     mutt_clear_error ();
776   }
777   mutt_socket_close (CTX_DATA->conn);
778   CTX_DATA->state = IMAP_DISCONNECTED;
779   CTX_DATA->conn->data = NULL;
780   return 0;
781 }
782 */
783
784 /* imap_set_flag: append str to flags if we currently have permission
785  *   according to aclbit */
786 static void imap_set_flag(IMAP_DATA *idata, int aclbit, int flag,
787                           const char *str, char *flags, size_t flsize)
788 {
789     if (mutt_bit_isset(idata->rights, aclbit)) {
790         if (flag)
791             m_strcat(flags, flsize, str);
792     }
793 }
794
795 /* imap_make_msg_set: make an IMAP4rev1 UID message set out of a set of
796  *   headers, given a flag enum to filter on.
797  * Params: idata: IMAP_DATA containing context containing header set
798  *         buf: to write message set into
799  *         buflen: length of buffer
800  *         flag: enum of flag type on which to filter
801  *         changed: include only changed messages in message set
802  * Returns: number of messages in message set (0 if no matches) */
803 int imap_make_msg_set (IMAP_DATA * idata, BUFFER * buf, int flag, int changed)
804 {
805   HEADER **hdrs;                /* sorted local copy */
806   int count = 0;                /* number of messages in message set */
807   int match = 0;                /* whether current message matches flag condition */
808   unsigned int setstart = 0;    /* start of current message range */
809   int n;
810   short oldsort;                /* we clobber reverse, must restore it */
811
812   /* assuming 32-bit UIDs */
813   char uid[12];
814   int started = 0;
815
816   /* make copy of header pointers to sort in natural order */
817   hdrs = p_dup(idata->ctx->hdrs, idata->ctx->msgcount);
818
819   if (Sort != SORT_ORDER) {
820     oldsort = Sort;
821     Sort = SORT_ORDER;
822     qsort ((void *) hdrs, idata->ctx->msgcount, sizeof (HEADER *),
823            mutt_get_sort_func (SORT_ORDER));
824     Sort = oldsort;
825   }
826
827   for (n = 0; n < idata->ctx->msgcount; n++) {
828     match = 0;
829     /* don't include pending expunged messages */
830     if (hdrs[n]->active)
831       switch (flag) {
832       case M_DELETE:
833         if (hdrs[n]->deleted)
834           match = 1;
835         break;
836       case M_TAG:
837         if (hdrs[n]->tagged)
838           match = 1;
839         break;
840       }
841
842     if (match && (!changed || hdrs[n]->changed)) {
843       count++;
844       if (setstart == 0) {
845         setstart = HEADER_DATA (hdrs[n])->uid;
846         if (started == 0) {
847           snprintf (uid, sizeof (uid), "%u", HEADER_DATA (hdrs[n])->uid);
848           mutt_buffer_addstr (buf, uid);
849           started = 1;
850         }
851         else {
852           snprintf (uid, sizeof (uid), ",%u", HEADER_DATA (hdrs[n])->uid);
853           mutt_buffer_addstr (buf, uid);
854         }
855       }
856       /* tie up if the last message also matches */
857       else if (n == idata->ctx->msgcount - 1) {
858         snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n])->uid);
859         mutt_buffer_addstr (buf, uid);
860       }
861     }
862     /* this message is not expunged and doesn't match. End current set. */
863     else if (setstart && hdrs[n]->active) {
864       if (HEADER_DATA (hdrs[n - 1])->uid > setstart) {
865         snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n - 1])->uid);
866         mutt_buffer_addstr (buf, uid);
867       }
868       setstart = 0;
869     }
870   }
871
872   p_delete(&hdrs);
873
874   return count;
875 }
876
877 /* Update the IMAP server to reflect the flags a single message.  */
878
879 int imap_sync_message (IMAP_DATA *idata, HEADER *hdr, BUFFER *cmd,
880                        int *err_continue)
881 {
882   char flags[LONG_STRING];
883   char uid[11];
884
885   hdr->changed = 0;
886
887   snprintf (uid, sizeof (uid), "%u", HEADER_DATA(hdr)->uid);
888   cmd->dptr = cmd->data;
889   mutt_buffer_addstr (cmd, "UID STORE ");
890   mutt_buffer_addstr (cmd, uid);
891
892   flags[0] = '\0';
893       
894   imap_set_flag (idata, ACL_SEEN, hdr->read, "\\Seen ",
895                  flags, sizeof (flags));
896   imap_set_flag (idata, ACL_WRITE, hdr->flagged,
897                  "\\Flagged ", flags, sizeof (flags));
898   imap_set_flag (idata, ACL_WRITE, hdr->replied,
899                  "\\Answered ", flags, sizeof (flags));
900   imap_set_flag (idata, ACL_DELETE, hdr->deleted,
901                  "\\Deleted ", flags, sizeof (flags));
902
903   /* now make sure we don't lose custom tags */
904   if (mutt_bit_isset (idata->rights, ACL_WRITE))
905     imap_add_keywords (flags, hdr, idata->flags, sizeof (flags));
906
907   str_skip_trailws (flags);
908
909   /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to
910    * explicitly revoke all system flags (if we have permission) */
911   if (!*flags)
912   {
913     imap_set_flag (idata, ACL_SEEN, 1, "\\Seen ", flags, sizeof (flags));
914     imap_set_flag (idata, ACL_WRITE, 1, "\\Flagged ", flags, sizeof (flags));
915     imap_set_flag (idata, ACL_WRITE, 1, "\\Answered ", flags, sizeof (flags));
916     imap_set_flag (idata, ACL_DELETE, 1, "\\Deleted ", flags, sizeof (flags));
917
918     str_skip_trailws (flags);
919
920     mutt_buffer_addstr (cmd, " -FLAGS.SILENT (");
921   } else
922     mutt_buffer_addstr (cmd, " FLAGS.SILENT (");
923
924   mutt_buffer_addstr (cmd, flags);
925   mutt_buffer_addstr (cmd, ")");
926
927   /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */
928   hdr->active = 0;
929
930   /* after all this it's still possible to have no flags, if you
931    * have no ACL rights */
932   if (*flags && (imap_exec (idata, cmd->data, 0) != 0) &&
933       err_continue && (*err_continue != M_YES))
934   {
935     *err_continue = imap_continue ("imap_sync_message: STORE failed",
936                                    idata->cmd.buf);
937     if (*err_continue != M_YES)
938       return -1;
939   }
940
941   hdr->active = 1;
942   idata->ctx->changed--;
943
944   return 0;
945 }
946
947 /* update the IMAP server to reflect message changes done within mutt.
948  * Arguments
949  *   ctx: the current context
950  *   expunge: 0 or 1 - do expunge? 
951  */
952
953 int imap_sync_mailbox (CONTEXT * ctx, int expunge, int *index_hint)
954 {
955   IMAP_DATA *idata;
956   CONTEXT *appendctx = NULL;
957   BUFFER cmd;
958   int deleted;
959   int n;
960   int err_continue = M_NO;      /* continue on error? */
961   int rc;
962
963   idata = (IMAP_DATA *) ctx->data;
964
965   if (idata->state != IMAP_SELECTED) {
966     debug_print (2, ("no mailbox selected\n"));
967     return -1;
968   }
969
970   /* This function is only called when the calling code expects the context
971    * to be changed. */
972   imap_allow_reopen (ctx);
973
974   if ((rc = imap_check_mailbox (ctx, index_hint, 0)) != 0)
975     return rc;
976
977   p_clear(&cmd, 1);
978
979   /* if we are expunging anyway, we can do deleted messages very quickly... */
980   if (expunge && mutt_bit_isset (idata->rights, ACL_DELETE)) {
981     mutt_buffer_addstr (&cmd, "UID STORE ");
982     deleted = imap_make_msg_set (idata, &cmd, M_DELETE, 1);
983
984     /* if we have a message set, then let's delete */
985     if (deleted) {
986       mutt_message (_("Marking %d messages deleted..."), deleted);
987       mutt_buffer_addstr (&cmd, " +FLAGS.SILENT (\\Deleted)");
988       /* mark these messages as unchanged so second pass ignores them. Done
989        * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */
990       for (n = 0; n < ctx->msgcount; n++)
991         if (ctx->hdrs[n]->deleted && ctx->hdrs[n]->changed)
992           ctx->hdrs[n]->active = 0;
993       if (imap_exec (idata, cmd.data, 0) != 0) {
994         mutt_error (_("Expunge failed"));
995         mutt_sleep (1);
996         rc = -1;
997         goto out;
998       }
999     }
1000   }
1001
1002   /* save status changes */
1003   for (n = 0; n < ctx->msgcount; n++) {
1004     if (ctx->hdrs[n]->active && ctx->hdrs[n]->changed) {
1005
1006       mutt_message (_("Saving message status flags... [%d/%d]"), n + 1,
1007                     ctx->msgcount);
1008
1009       /* if the message has been rethreaded or attachments have been deleted
1010        * we delete the message and reupload it.
1011        * This works better if we're expunging, of course. */
1012       if ((ctx->hdrs[n]->env && (ctx->hdrs[n]->env->refs_changed || ctx->hdrs[n]->env->irt_changed)) ||
1013           ctx->hdrs[n]->attach_del) {
1014         debug_print (3, ("Attachments to be deleted, falling back to _mutt_save_message\n"));
1015         if (!appendctx)
1016           appendctx = mx_open_mailbox (ctx->path, M_APPEND | M_QUIET, NULL);
1017         if (!appendctx) {
1018           debug_print (1, ("Error opening mailbox in append mode\n"));
1019         }
1020         else
1021           _mutt_save_message (ctx->hdrs[n], appendctx, 1, 0, 0);
1022       }
1023
1024       if (imap_sync_message (idata, ctx->hdrs[n], &cmd, &err_continue) < 0) {
1025         rc = -1;
1026         goto out;
1027       }
1028     }
1029   }
1030   ctx->changed = 0;
1031
1032   /* We must send an EXPUNGE command if we're not closing. */
1033   if (expunge && !(ctx->closing) &&
1034       mutt_bit_isset (idata->rights, ACL_DELETE)) {
1035     mutt_message _("Expunging messages from server...");
1036
1037     /* Set expunge bit so we don't get spurious reopened messages */
1038     idata->reopen |= IMAP_EXPUNGE_EXPECTED;
1039     if (imap_exec (idata, "EXPUNGE", 0) != 0) {
1040       imap_error (_("imap_sync_mailbox: EXPUNGE failed"), idata->cmd.buf);
1041       rc = imap_reconnect (ctx);
1042       goto out;
1043     }
1044   }
1045
1046   if (expunge && ctx->closing) {
1047     if (imap_exec (idata, "CLOSE", 0))
1048       mutt_error (_("CLOSE failed"));
1049     idata->state = IMAP_AUTHENTICATED;
1050   }
1051
1052   rc = 0;
1053 out:
1054   if (cmd.data)
1055     p_delete(&cmd.data);
1056   if (appendctx) {
1057     mx_fastclose_mailbox (appendctx);
1058     p_delete(&appendctx);
1059   }
1060   return rc;
1061 }
1062
1063 /* imap_close_mailbox: clean up IMAP data in CONTEXT */
1064 void imap_close_mailbox (CONTEXT * ctx)
1065 {
1066   IMAP_DATA *idata;
1067   int i;
1068
1069   idata = (IMAP_DATA *) ctx->data;
1070   /* Check to see if the mailbox is actually open */
1071   if (!idata)
1072     return;
1073
1074   if (ctx == idata->ctx) {
1075     if (idata->state != IMAP_FATAL && idata->state == IMAP_SELECTED) {
1076       /* mx_close_mailbox won't sync if there are no deleted messages
1077       * and the mailbox is unchanged, so we may have to close here */
1078       if (!ctx->deleted && imap_exec (idata, "CLOSE", 0))
1079         mutt_error (_("CLOSE failed"));
1080       idata->state = IMAP_AUTHENTICATED;
1081     }
1082
1083     idata->reopen &= IMAP_REOPEN_ALLOW;
1084     p_delete(&(idata->mailbox));
1085     mutt_free_list (&idata->flags);
1086     idata->ctx = NULL;
1087   }
1088
1089   /* free IMAP part of headers */
1090   for (i = 0; i < ctx->msgcount; i++)
1091     imap_free_header_data (&(ctx->hdrs[i]->data));
1092
1093   for (i = 0; i < IMAP_CACHE_LEN; i++) {
1094     if (idata->cache[i].path) {
1095       unlink (idata->cache[i].path);
1096       p_delete(&idata->cache[i].path);
1097     }
1098   }
1099 }
1100
1101 /* use the NOOP command to poll for new mail
1102  *
1103  * return values:
1104  *      M_REOPENED      mailbox has been externally modified
1105  *      M_NEW_MAIL      new mail has arrived!
1106  *      0               no change
1107  *      -1              error
1108  */
1109 int imap_check_mailbox (CONTEXT * ctx, int *index_hint, int force)
1110 {
1111   /* overload keyboard timeout to avoid many mailbox checks in a row.
1112    * Most users don't like having to wait exactly when they press a key. */
1113   IMAP_DATA *idata;
1114   int result = 0;
1115
1116   idata = (IMAP_DATA *) ctx->data;
1117
1118   if ((force || time (NULL) >= idata->lastread + Timeout)
1119       && imap_exec (idata, "NOOP", 0) != 0)
1120     return -1;
1121
1122   /* We call this even when we haven't run NOOP in case we have pending
1123    * changes to process, since we can reopen here. */
1124   imap_cmd_finish (idata);
1125
1126   if (idata->check_status & IMAP_EXPUNGE_PENDING)
1127     result = M_REOPENED;
1128   else if (idata->check_status & IMAP_NEWMAIL_PENDING)
1129     result = M_NEW_MAIL;
1130   else if (idata->check_status & IMAP_FLAGS_PENDING)
1131     result = M_FLAGS;
1132
1133   idata->check_status = 0;
1134
1135   return result;
1136 }
1137
1138 /*
1139  * count messages:
1140  *      new == 1:  recent
1141  *      new == 2:  unseen
1142  *      otherwise: total
1143  * return:
1144  *   0+   number of messages in mailbox
1145  *  -1    error while polling mailboxes
1146  */
1147 int imap_mailbox_check (char *path, int new)
1148 {
1149   CONNECTION *conn;
1150   IMAP_DATA *idata;
1151   char buf[LONG_STRING];
1152   char mbox[LONG_STRING];
1153   char mbox_unquoted[LONG_STRING];
1154   char *s;
1155   int msgcount = 0;
1156   int connflags = 0;
1157   IMAP_MBOX mx;
1158   int rc;
1159
1160   if (imap_parse_path (path, &mx))
1161     return -1;
1162
1163   /* If imap_passive is set, don't open a connection to check for new mail */
1164   if (option (OPTIMAPPASSIVE))
1165     connflags = M_IMAP_CONN_NONEW;
1166
1167   if (!(idata = imap_conn_find (&(mx.account), connflags))) {
1168     p_delete(&mx.mbox);
1169     return -1;
1170   }
1171   conn = idata->conn;
1172
1173   imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1174   p_delete(&mx.mbox);
1175
1176   imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1177   m_strcpy(mbox_unquoted, sizeof(mbox_unquoted), buf);
1178
1179   /* The draft IMAP implementor's guide warns againts using the STATUS
1180    * command on a mailbox that you have selected 
1181    */
1182
1183   if (m_strcmp(mbox_unquoted, idata->mailbox) == 0
1184       || (ascii_strcasecmp (mbox_unquoted, "INBOX") == 0
1185           && m_strcasecmp(mbox_unquoted, idata->mailbox) == 0)) {
1186     m_strcpy(buf, sizeof(buf), "NOOP");
1187   }
1188   else if (mutt_bit_isset (idata->capabilities, IMAP4REV1) ||
1189            mutt_bit_isset (idata->capabilities, STATUS)) {
1190     snprintf (buf, sizeof (buf), "STATUS %s (%s)", mbox,
1191               new == 1 ? "RECENT" : (new == 2 ? "UNSEEN" : "MESSAGES"));
1192   }
1193   else
1194     /* Server does not support STATUS, and this is not the current mailbox.
1195      * There is no lightweight way to check recent arrivals */
1196     return -1;
1197
1198   imap_cmd_start (idata, buf);
1199
1200   do {
1201     if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
1202       break;
1203
1204     s = imap_next_word (idata->cmd.buf);
1205     if (ascii_strncasecmp ("STATUS", s, 6) == 0) {
1206       s = imap_next_word (s);
1207       /* The mailbox name may or may not be quoted here. We could try to 
1208        * munge the server response and compare with quoted (or vise versa)
1209        * but it is probably more efficient to just strncmp against both. */
1210       if (m_strncmp(mbox_unquoted, s, m_strlen(mbox_unquoted)) == 0
1211           || m_strncmp(mbox, s, m_strlen(mbox)) == 0) {
1212         s = imap_next_word (s);
1213         s = imap_next_word (s);
1214         if (isdigit ((unsigned char) *s)) {
1215           if (*s != '0') {
1216             msgcount = atoi (s);
1217             debug_print (2, ("%d new messages in %s\n", msgcount, path));
1218           }
1219         }
1220       }
1221       else
1222         debug_print (1, ("STATUS response doesn't match requested mailbox.\n"));
1223     }
1224   }
1225   while (rc == IMAP_CMD_CONTINUE);
1226
1227   return msgcount;
1228 }
1229
1230 /* returns number of patterns in the search that should be done server-side
1231  * (eg are full-text) */
1232 static int do_search (const pattern_t* search, int allpats)
1233 {
1234   int rc = 0;
1235   const pattern_t* pat;
1236
1237   for (pat = search; pat; pat = pat->next) {
1238     switch (pat->op) {
1239       case M_BODY:
1240       case M_HEADER:
1241       case M_WHOLE_MSG:
1242         if (pat->stringmatch)
1243           rc++;
1244         break;
1245       default:
1246       if (pat->child && do_search (pat->child, 1))
1247         rc++;
1248     }
1249
1250     if (!allpats)
1251       break;
1252   }
1253
1254   return rc;
1255 }
1256
1257 /* convert mutt pattern_t to IMAP SEARCH command containing only elements
1258 * that require full-text search (mutt already has what it needs for most
1259 * match types, and does a better job (eg server doesn't support regexps). */
1260 static int imap_compile_search (const pattern_t* pat, BUFFER* buf)
1261 {
1262   if (! do_search (pat, 0))
1263     return 0;
1264
1265   if (pat->not)
1266     mutt_buffer_addstr (buf, "NOT ");
1267
1268   if (pat->child) {
1269     int clauses;
1270
1271     if ((clauses = do_search (pat->child, 1)) > 0) {
1272       const pattern_t* clause = pat->child;
1273
1274       mutt_buffer_addch (buf, '(');
1275
1276       while (clauses) {
1277         if (do_search (clause, 0)) {
1278           if (pat->op == M_OR && clauses > 1)
1279             mutt_buffer_addstr (buf, "OR ");
1280           clauses--;
1281           if (imap_compile_search (clause, buf) < 0)
1282             return -1;
1283
1284           if (clauses)
1285             mutt_buffer_addch (buf, ' ');
1286           
1287           clause = clause->next;
1288         }
1289       }
1290
1291       mutt_buffer_addch (buf, ')');
1292     }
1293   } else {
1294     char term[STRING];
1295     char *delim;
1296
1297     switch (pat->op) {
1298       case M_HEADER:
1299         mutt_buffer_addstr (buf, "HEADER ");
1300
1301         /* extract header name */
1302         if (! (delim = strchr (pat->str, ':'))) {
1303           mutt_error (_("Header search without header name: %s"), pat->str);
1304           return -1;
1305         }
1306         *delim = '\0';
1307         imap_quote_string (term, sizeof (term), pat->str);
1308         mutt_buffer_addstr (buf, term);
1309         mutt_buffer_addch (buf, ' ');
1310
1311         /* and field */
1312         *delim++ = ':';
1313         delim = vskipspaces(delim);
1314         imap_quote_string (term, sizeof (term), delim);
1315         mutt_buffer_addstr (buf, term);
1316         break;
1317
1318       case M_BODY:
1319         mutt_buffer_addstr (buf, "BODY ");
1320         imap_quote_string (term, sizeof (term), pat->str);
1321         mutt_buffer_addstr (buf, term);
1322         break;
1323
1324       case M_WHOLE_MSG:
1325         mutt_buffer_addstr (buf, "TEXT ");
1326         imap_quote_string (term, sizeof (term), pat->str);
1327         mutt_buffer_addstr (buf, term);
1328       break;
1329     }
1330   }
1331
1332   return 0;
1333 }
1334
1335 int imap_search (CONTEXT* ctx, const pattern_t* pat) {
1336   BUFFER buf;
1337   IMAP_DATA* idata = (IMAP_DATA*)ctx->data;
1338   int i;
1339
1340   for (i = 0; i < ctx->msgcount; i++)
1341     ctx->hdrs[i]->matched = 0;
1342
1343   if (!do_search (pat, 1))
1344     return 0;
1345
1346   p_clear(&buf, 1);
1347   mutt_buffer_addstr (&buf, "UID SEARCH ");
1348   if (imap_compile_search (pat, &buf) < 0) {
1349     p_delete(&buf.data);
1350     return -1;
1351   }
1352   if (imap_exec (idata, buf.data, 0) < 0) {
1353     p_delete(&buf.data);
1354     return -1;
1355   }
1356
1357   p_delete(&buf.data);
1358   return 0;
1359 }
1360
1361 /* all this listing/browsing is a mess. I don't like that name is a pointer
1362  *   into idata->buf (used to be a pointer into the passed in buffer, just
1363  *   as bad), nor do I like the fact that the fetch is done here. This
1364  *   code can't possibly handle non-LIST untagged responses properly.
1365  *   FIXME. ?! */
1366 int imap_parse_list_response (IMAP_DATA * idata, char **name, int *noselect,
1367                               int *noinferiors, char *delim)
1368 {
1369   char *s;
1370   long bytes;
1371   int rc;
1372
1373   *name = NULL;
1374
1375   rc = imap_cmd_step (idata);
1376   if (rc == IMAP_CMD_OK)
1377     return 0;
1378   if (rc != IMAP_CMD_CONTINUE)
1379     return -1;
1380
1381   s = imap_next_word (idata->cmd.buf);
1382   if ((ascii_strncasecmp ("LIST", s, 4) == 0) ||
1383       (ascii_strncasecmp ("LSUB", s, 4) == 0)) {
1384     *noselect = 0;
1385     *noinferiors = 0;
1386
1387     s = imap_next_word (s);     /* flags */
1388     if (*s == '(') {
1389       char *ep;
1390
1391       s++;
1392       ep = s;
1393       while (*ep && *ep != ')')
1394         ep++;
1395       do {
1396         if (!ascii_strncasecmp (s, "\\NoSelect", 9))
1397           *noselect = 1;
1398         if (!ascii_strncasecmp (s, "\\NoInferiors", 12))
1399           *noinferiors = 1;
1400         /* See draft-gahrns-imap-child-mailbox-?? */
1401         if (!ascii_strncasecmp (s, "\\HasNoChildren", 14))
1402           *noinferiors = 1;
1403         if (*s != ')')
1404           s++;
1405         while (*s && *s != '\\' && *s != ')')
1406           s++;
1407       } while (s != ep);
1408     }
1409     else
1410       return 0;
1411     s = imap_next_word (s);     /* delim */
1412     /* Reset the delimiter, this can change */
1413     if (ascii_strncasecmp (s, "NIL", 3)) {
1414       if (s && s[0] == '\"' && s[1] && s[2] == '\"')
1415         *delim = s[1];
1416       else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2]
1417                && s[3] == '\"')
1418         *delim = s[2];
1419     }
1420     s = imap_next_word (s);     /* name */
1421     if (s && *s == '{') {       /* Literal */
1422       if (imap_get_literal_count (idata->cmd.buf, &bytes) < 0)
1423         return -1;
1424       if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
1425         return -1;
1426       *name = idata->cmd.buf;
1427     }
1428     else
1429       *name = s;
1430   }
1431
1432   return 0;
1433 }
1434
1435 int imap_subscribe (char *path, int subscribe)
1436 {
1437   CONNECTION *conn;
1438   IMAP_DATA *idata;
1439   char buf[LONG_STRING];
1440   char mbox[LONG_STRING];
1441   char errstr[STRING];
1442   BUFFER err, token;
1443   IMAP_MBOX mx;
1444
1445   if (mx_get_magic (path) != M_IMAP || imap_parse_path (path, &mx) < 0) {
1446     mutt_error (_("Bad mailbox name"));
1447     return -1;
1448   }
1449
1450   if (!(idata = imap_conn_find (&(mx.account), 0)))
1451     goto fail;
1452
1453   conn = idata->conn;
1454
1455   imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1456
1457   if (option (OPTIMAPCHECKSUBSCRIBED)) {
1458     p_clear(&token, 1);
1459     err.data = errstr;
1460     err.dsize = sizeof (errstr);
1461     snprintf (mbox, sizeof (mbox), "%smailboxes \"%s\"",
1462               subscribe ? "" : "un", path);
1463     if (mutt_parse_rc_line (mbox, &token, &err))
1464       debug_print (1, ("Error adding subscribed mailbox: %s\n", errstr));
1465     p_delete(&token.data);
1466   }
1467
1468   if (subscribe)
1469     mutt_message (_("Subscribing to %s..."), buf);
1470   else
1471     mutt_message (_("Unsubscribing to %s..."), buf);
1472   imap_munge_mbox_name (mbox, sizeof (mbox), buf);
1473
1474   snprintf (buf, sizeof (buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);
1475
1476   if (imap_exec (idata, buf, 0) < 0)
1477     goto fail;
1478
1479   p_delete(&mx.mbox);
1480   return 0;
1481
1482 fail:
1483   p_delete(&mx.mbox);
1484   return -1;
1485 }
1486
1487 /* trim dest to the length of the longest prefix it shares with src,
1488  * returning the length of the trimmed string */
1489 static int longest_common_prefix (char *dest, const char* src,
1490                                   int start, size_t dlen) {
1491   int pos = start;
1492
1493   while (pos < dlen && dest[pos] && dest[pos] == src[pos])
1494     pos++;
1495   dest[pos] = '\0';
1496
1497   return pos;
1498 }
1499
1500 /* look for IMAP URLs to complete from defined mailboxes. Could be extended
1501  * to complete over open connections and account/folder hooks too. */
1502 static int imap_complete_hosts (char *dest, size_t len) {
1503   BUFFY* mailbox;
1504   CONNECTION* conn;
1505   int rc = -1;
1506   int matchlen;
1507   int i = 0;
1508
1509   matchlen = m_strlen(dest);
1510   if (list_empty (Incoming))
1511     return (-1);
1512   for (i = 0; i < Incoming->length; i++) {
1513     mailbox = (BUFFY*) Incoming->data[i];
1514     if (!m_strncmp(dest, mailbox->path, matchlen)) {
1515       if (rc) {
1516         m_strcpy(dest, len, mailbox->path);
1517         rc = 0;
1518       } else
1519         longest_common_prefix (dest, mailbox->path, matchlen, len);
1520     }
1521   }
1522
1523   for (conn = mutt_socket_head (); conn && conn->next; conn = conn->next) {
1524     ciss_url_t url;
1525     char urlstr[LONG_STRING];
1526
1527     if (conn->account.type != M_ACCT_TYPE_IMAP)
1528       continue;
1529
1530     mutt_account_tourl (&conn->account, &url);
1531     /* FIXME: how to handle multiple users on the same host? */
1532     url.user = NULL;
1533     url.path = NULL;
1534     url_ciss_tostring (&url, urlstr, sizeof (urlstr), 0);
1535     if (!m_strncmp(dest, urlstr, matchlen)) {
1536       if (rc) {
1537         m_strcpy(dest, len, urlstr);
1538         rc = 0;
1539       } else
1540         longest_common_prefix (dest, urlstr, matchlen, len);
1541     }
1542   }
1543
1544   return rc;
1545 }
1546
1547 /* imap_complete: given a partial IMAP folder path, return a string which
1548  *   adds as much to the path as is unique */
1549 int imap_complete (char *dest, size_t dlen, char *path) {
1550   CONNECTION *conn;
1551   IMAP_DATA *idata;
1552   char list[LONG_STRING];
1553   char buf[LONG_STRING];
1554   char *list_word = NULL;
1555   int noselect, noinferiors;
1556   char delim;
1557   char completion[LONG_STRING];
1558   int clen, matchlen = 0;
1559   int completions = 0;
1560   IMAP_MBOX mx;
1561
1562   if (imap_parse_path (path, &mx) || !mx.mbox) {
1563     m_strcpy(dest, dlen, path);
1564     return imap_complete_hosts (dest, dlen);
1565   }
1566
1567   /* don't open a new socket just for completion. Instead complete over
1568    * known mailboxes/hooks/etc */
1569   if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NONEW))) {
1570     p_delete(&mx.mbox);
1571     m_strcpy(dest, dlen, path);
1572     return imap_complete_hosts (dest, dlen);
1573   }
1574   conn = idata->conn;
1575
1576   /* reformat path for IMAP list, and append wildcard */
1577   /* don't use INBOX in place of "" */
1578   if (mx.mbox && mx.mbox[0])
1579     imap_fix_path (idata, mx.mbox, list, sizeof (list));
1580   else
1581     list[0] = '\0';
1582
1583   /* fire off command */
1584   snprintf (buf, sizeof (buf), "%s \"\" \"%s%%\"",
1585             option (OPTIMAPLSUB) ? "LSUB" : "LIST", list);
1586
1587   imap_cmd_start (idata, buf);
1588
1589   /* and see what the results are */
1590   m_strcpy(completion, sizeof(completion), NONULL(mx.mbox));
1591   do {
1592     if (imap_parse_list_response (idata, &list_word, &noselect, &noinferiors,
1593                                   &delim))
1594       break;
1595
1596     if (list_word) {
1597       /* store unquoted */
1598       imap_unmunge_mbox_name (list_word);
1599
1600       /* if the folder isn't selectable, append delimiter to force browse
1601        * to enter it on second tab. */
1602       if (noselect) {
1603         clen = m_strlen(list_word);
1604         list_word[clen++] = delim;
1605         list_word[clen] = '\0';
1606       }
1607       /* copy in first word */
1608       if (!completions) {
1609         m_strcpy(completion, sizeof(completion), list_word);
1610         matchlen = m_strlen(completion);
1611         completions++;
1612         continue;
1613       }
1614
1615       matchlen = longest_common_prefix (completion, list_word, 0, matchlen);
1616       completions++;
1617     }
1618   }
1619   while (ascii_strncmp (idata->cmd.seq, idata->cmd.buf, SEQLEN));
1620
1621   if (completions) {
1622     /* reformat output */
1623     imap_qualify_path (dest, dlen, &mx, completion);
1624     mutt_pretty_mailbox (dest);
1625
1626     p_delete(&mx.mbox);
1627     return 0;
1628   }
1629
1630   return -1;
1631 }
1632
1633 /* reconnect if connection was lost */
1634 int imap_reconnect (CONTEXT * ctx)
1635 {
1636   IMAP_DATA *imap_data;
1637
1638   if (!ctx)
1639     return (-1);
1640
1641   imap_data = (IMAP_DATA *) ctx->data;
1642
1643   if (imap_data) {
1644     if (imap_data->status == IMAP_CONNECTED)
1645       return -1;
1646   }
1647
1648   if (query_quadoption
1649       (OPT_IMAPRECONNECT,
1650        _("Connection lost. Reconnect to IMAP server?")) != M_YES)
1651     return -1;
1652
1653   mx_open_mailbox (ctx->path, 0, ctx);
1654   return 0;
1655 }