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