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 #if defined(USE_SSL) || defined(USE_GNUTLS)
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_GNUTLS)
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 #ifdef USE_SSL
426           if (mutt_ssl_starttls (idata->conn))
427 #elif USE_GNUTLS
428           if (mutt_gnutls_starttls (idata->conn))
429 #endif
430           {
431             mutt_error (_("Could not negotiate TLS connection"));
432             mutt_sleep (1);
433             goto bail;
434           }
435           else
436           {
437             /* RFC 2595 demands we recheck CAPABILITY after TLS completes. */
438             if (imap_exec (idata, "CAPABILITY", 0))
439               goto bail;
440           }
441         }
442       }
443     }
444 #endif    
445   }
446   else if (ascii_strncasecmp ("* PREAUTH", idata->cmd.buf, 9) == 0)
447   {
448     idata->state = IMAP_AUTHENTICATED;
449     if (imap_check_capabilities (idata) != 0)
450       goto bail;
451     FREE (&idata->capstr);
452   } 
453   else
454   {
455     imap_error ("imap_open_connection()", buf);
456     goto bail;
457   }
458
459   return 0;
460
461  err_close_conn:
462   mutt_socket_close (idata->conn);
463  bail:
464   FREE (&idata->capstr);
465   return -1;
466 }
467
468 /* imap_get_flags: Make a simple list out of a FLAGS response.
469  *   return stream following FLAGS response */
470 static char* imap_get_flags (LIST** hflags, char* s)
471 {
472   LIST* flags;
473   char* flag_word;
474   char ctmp;
475
476   /* sanity-check string */
477   if (ascii_strncasecmp ("FLAGS", s, 5) != 0)
478   {
479     dprint (1, (debugfile, "imap_get_flags: not a FLAGS response: %s\n",
480       s));
481     return NULL;
482   }
483   s += 5;
484   SKIPWS(s);
485   if (*s != '(')
486   {
487     dprint (1, (debugfile, "imap_get_flags: bogus FLAGS response: %s\n",
488       s));
489     return NULL;
490   }
491
492   /* create list, update caller's flags handle */
493   flags = mutt_new_list();
494   *hflags = flags;
495
496   while (*s && *s != ')')
497   {
498     s++;
499     SKIPWS(s);
500     flag_word = s;
501     while (*s && (*s != ')') && !ISSPACE (*s))
502       s++;
503     ctmp = *s;
504     *s = '\0';
505     if (*flag_word)
506       mutt_add_list (flags, flag_word);
507     *s = ctmp;
508   }
509
510   /* note bad flags response */
511   if (*s != ')')
512   {
513     dprint (1, (debugfile,
514       "imap_get_flags: Unterminated FLAGS response: %s\n", s));
515     mutt_free_list (hflags);
516
517     return NULL;
518   }
519
520   s++;
521
522   return s;
523 }
524
525 int imap_open_mailbox (CONTEXT* ctx)
526 {
527   CONNECTION *conn;
528   IMAP_DATA *idata;
529   char buf[LONG_STRING];
530   char bufout[LONG_STRING];
531   int count = 0;
532   IMAP_MBOX mx;
533   int rc;
534   
535   if (imap_parse_path (ctx->path, &mx))
536   {
537     mutt_error (_("%s is an invalid IMAP path"), ctx->path);
538     return -1;
539   }
540
541   /* we require a connection which isn't currently in IMAP_SELECTED state */
542   if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NOSELECT)))
543     goto fail_noidata;
544   if (idata->state < IMAP_AUTHENTICATED)
545     goto fail;
546
547   conn = idata->conn;
548
549   /* once again the context is new */
550   ctx->data = idata;
551
552   /* Clean up path and replace the one in the ctx */
553   imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
554   FREE(&(idata->mailbox));
555   idata->mailbox = safe_strdup (buf);
556   imap_qualify_path (buf, sizeof (buf), &mx, idata->mailbox);
557
558   FREE (&(ctx->path));
559   ctx->path = safe_strdup (buf);
560
561   idata->ctx = ctx;
562
563   /* clear mailbox status */
564   idata->status = 0;
565   memset (idata->rights, 0, (RIGHTSMAX+7)/8);
566   idata->newMailCount = 0;
567
568   mutt_message (_("Selecting %s..."), idata->mailbox);
569   imap_munge_mbox_name (buf, sizeof(buf), idata->mailbox);
570   snprintf (bufout, sizeof (bufout), "%s %s",
571     ctx->readonly ? "EXAMINE" : "SELECT", buf);
572
573   idata->state = IMAP_SELECTED;
574
575   imap_cmd_start (idata, bufout);
576
577   do
578   {
579     char *pc;
580     
581     if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
582       break;
583
584     pc = idata->cmd.buf + 2;
585
586     /* Obtain list of available flags here, may be overridden by a
587      * PERMANENTFLAGS tag in the OK response */
588     if (ascii_strncasecmp ("FLAGS", pc, 5) == 0)
589     {
590       /* don't override PERMANENTFLAGS */
591       if (!idata->flags)
592       {
593         dprint (2, (debugfile, "Getting mailbox FLAGS\n"));
594         if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
595           goto fail;
596       }
597     }
598     /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
599     else if (ascii_strncasecmp ("OK [PERMANENTFLAGS", pc, 18) == 0)
600     {
601       dprint (2, (debugfile, "Getting mailbox PERMANENTFLAGS\n"));
602       /* safe to call on NULL */
603       mutt_free_list (&(idata->flags));
604       /* skip "OK [PERMANENT" so syntax is the same as FLAGS */
605       pc += 13;
606       if ((pc = imap_get_flags (&(idata->flags), pc)) == NULL)
607         goto fail;
608     }
609 #ifdef USE_HCACHE
610     /* save UIDVALIDITY for the header cache */
611     else if (ascii_strncasecmp("OK [UIDVALIDITY", pc, 14) == 0)
612     {
613             dprint(2, (debugfile, "Getting mailbox UIDVALIDITY\n"));
614             pc += 3;
615             pc = imap_next_word(pc);
616
617             sscanf(pc, "%u", &(idata->uid_validity));
618     }
619 #endif
620     else
621     {
622       pc = imap_next_word (pc);
623       if (!ascii_strncasecmp ("EXISTS", pc, 6))
624       {
625         count = idata->newMailCount;
626         idata->newMailCount = 0;
627       }
628     }
629   }
630   while (rc == IMAP_CMD_CONTINUE);
631
632   if (rc == IMAP_CMD_NO)
633   {
634     char *s;
635     s = imap_next_word (idata->cmd.buf); /* skip seq */
636     s = imap_next_word (s); /* Skip response */
637     mutt_error ("%s", s);
638     mutt_sleep (2);
639     goto fail;
640   }
641
642   if (rc != IMAP_CMD_OK)
643     goto fail;
644
645   /* check for READ-ONLY notification */
646   if (!ascii_strncasecmp (imap_get_qualifier (idata->cmd.buf), "[READ-ONLY]", 11)  \
647   && !mutt_bit_isset (idata->capabilities, ACL))
648   {
649     dprint (2, (debugfile, "Mailbox is read-only.\n"));
650     ctx->readonly = 1;
651   }
652
653 #ifdef DEBUG
654   /* dump the mailbox flags we've found */
655   if (debuglevel > 2)
656   {
657     if (!idata->flags)
658       dprint (3, (debugfile, "No folder flags found\n"));
659     else
660     {
661       LIST* t = idata->flags;
662
663       dprint (3, (debugfile, "Mailbox flags: "));
664
665       t = t->next;
666       while (t)
667       {
668         dprint (3, (debugfile, "[%s] ", t->data));
669         t = t->next;
670       }
671       dprint (3, (debugfile, "\n"));
672     }
673   }
674 #endif
675
676   if (mutt_bit_isset (idata->capabilities, ACL))
677   {
678     if (imap_check_acl (idata))
679       goto fail;
680     if (!(mutt_bit_isset(idata->rights, IMAP_ACL_DELETE) ||
681           mutt_bit_isset(idata->rights, IMAP_ACL_SEEN) ||
682           mutt_bit_isset(idata->rights, IMAP_ACL_WRITE) ||
683           mutt_bit_isset(idata->rights, IMAP_ACL_INSERT)))
684        ctx->readonly = 1;
685   }
686   /* assume we have all rights if ACL is unavailable */
687   else
688   {
689     mutt_bit_set (idata->rights, IMAP_ACL_LOOKUP);
690     mutt_bit_set (idata->rights, IMAP_ACL_READ);
691     mutt_bit_set (idata->rights, IMAP_ACL_SEEN);
692     mutt_bit_set (idata->rights, IMAP_ACL_WRITE);
693     mutt_bit_set (idata->rights, IMAP_ACL_INSERT);
694     mutt_bit_set (idata->rights, IMAP_ACL_POST);
695     mutt_bit_set (idata->rights, IMAP_ACL_CREATE);
696     mutt_bit_set (idata->rights, IMAP_ACL_DELETE);
697   }
698
699   ctx->hdrmax = count;
700   ctx->hdrs = safe_calloc (count, sizeof (HEADER *));
701   ctx->v2r = safe_calloc (count, sizeof (int));
702   ctx->msgcount = 0;
703   if (count && (imap_read_headers (idata, 0, count-1) < 0))
704   {
705     mutt_error _("Error opening mailbox");
706     mutt_sleep (1);
707     goto fail;
708   }
709
710   dprint (2, (debugfile, "imap_open_mailbox: msgcount is %d\n", ctx->msgcount));
711   FREE (&mx.mbox);
712   return 0;
713
714  fail:
715   if (idata->state == IMAP_SELECTED)
716     idata->state = IMAP_AUTHENTICATED;
717  fail_noidata:
718   FREE (&mx.mbox);
719   return -1;
720 }
721
722 int imap_open_mailbox_append (CONTEXT *ctx)
723 {
724   CONNECTION *conn;
725   IMAP_DATA *idata;
726   char buf[LONG_STRING], mbox[LONG_STRING];
727   char mailbox[LONG_STRING];
728   int r;
729   IMAP_MBOX mx;
730
731   if (imap_parse_path (ctx->path, &mx))
732     return -1;
733
734   /* in APPEND mode, we appear to hijack an existing IMAP connection -
735    * ctx is brand new and mostly empty */
736
737   if (!(idata = imap_conn_find (&(mx.account), 0)))
738     goto fail;
739   conn = idata->conn;
740
741   ctx->magic = M_IMAP;
742   ctx->data = idata;
743
744   /* check mailbox existance */
745
746   imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
747
748   imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
749                                 
750   if (mutt_bit_isset(idata->capabilities,IMAP4REV1))
751     snprintf (buf, sizeof (buf), "STATUS %s (UIDVALIDITY)", mbox);
752   else if (mutt_bit_isset(idata->capabilities,STATUS))
753     /* We have no idea what the other guy wants. UW imapd 8.3 wants this
754      * (but it does not work if another mailbox is selected) */
755     snprintf (buf, sizeof (buf), "STATUS %s (UID-VALIDITY)", mbox);
756   else
757   {
758     /* STATUS not supported */
759     mutt_message _("Unable to append to IMAP mailboxes at this server");
760
761     goto fail;
762   }
763
764   r = imap_exec (idata, buf, IMAP_CMD_FAIL_OK);
765   if (r == -2)
766   {
767     /* command failed cause folder doesn't exist */
768     snprintf (buf, sizeof (buf), _("Create %s?"), mailbox);
769     if (option (OPTCONFIRMCREATE) && mutt_yesorno (buf, 1) < 1)
770       goto fail;
771
772     if (imap_create_mailbox (idata, mailbox) < 0)
773       goto fail;
774   }
775   else if (r == -1)
776     /* Hmm, some other failure */
777     goto fail;
778
779   FREE (&mx.mbox);
780   return 0;
781
782  fail:
783   FREE (&mx.mbox);
784   return -1;
785 }
786
787 /* imap_logout: Gracefully log out of server. */
788 void imap_logout (IMAP_DATA* idata)
789 {
790   /* we set status here to let imap_handle_untagged know we _expect_ to
791    * receive a bye response (so it doesn't freak out and close the conn) */
792   idata->status = IMAP_BYE;
793   imap_cmd_start (idata, "LOGOUT");
794   while (imap_cmd_step (idata) == IMAP_CMD_CONTINUE)
795     ;
796 }
797
798 int imap_close_connection (CONTEXT *ctx)
799 {
800   dprint (1, (debugfile, "imap_close_connection(): closing connection\n"));
801   /* if the server didn't shut down on us, close the connection gracefully */
802   if (CTX_DATA->status != IMAP_BYE)
803   {
804     mutt_message _("Closing connection to IMAP server...");
805     imap_logout (CTX_DATA);
806     mutt_clear_error ();
807   }
808   mutt_socket_close (CTX_DATA->conn);
809   CTX_DATA->state = IMAP_DISCONNECTED;
810   CTX_DATA->conn->data = NULL;
811   return 0;
812 }
813
814 /* imap_set_flag: append str to flags if we currently have permission
815  *   according to aclbit */
816 static void imap_set_flag (IMAP_DATA* idata, int aclbit, int flag,
817   const char *str, char *flags, size_t flsize)
818 {
819   if (mutt_bit_isset (idata->rights, aclbit))
820     if (flag)
821       strncat (flags, str, flsize);
822 }
823
824 /* imap_make_msg_set: make an IMAP4rev1 UID message set out of a set of
825  *   headers, given a flag enum to filter on.
826  * Params: idata: IMAP_DATA containing context containing header set
827  *         buf: to write message set into
828  *         buflen: length of buffer
829  *         flag: enum of flag type on which to filter
830  *         changed: include only changed messages in message set
831  * Returns: number of messages in message set (0 if no matches) */
832 int imap_make_msg_set (IMAP_DATA* idata, BUFFER* buf, int flag, int changed)
833 {
834   HEADER** hdrs;        /* sorted local copy */
835   int count = 0;        /* number of messages in message set */
836   int match = 0;        /* whether current message matches flag condition */
837   unsigned int setstart = 0;    /* start of current message range */
838   int n;
839   short oldsort;        /* we clobber reverse, must restore it */
840   /* assuming 32-bit UIDs */
841   char uid[12];
842   int started = 0;
843
844   /* make copy of header pointers to sort in natural order */
845   hdrs = safe_calloc (idata->ctx->msgcount, sizeof (HEADER*));
846   memcpy (hdrs, idata->ctx->hdrs, idata->ctx->msgcount * sizeof (HEADER*));
847
848   if (Sort != SORT_ORDER)
849   {
850     oldsort = Sort;
851     Sort = SORT_ORDER;
852     qsort ((void*) hdrs, idata->ctx->msgcount, sizeof (HEADER*),
853       mutt_get_sort_func (SORT_ORDER));
854     Sort = oldsort;
855   }
856   
857   for (n = 0; n < idata->ctx->msgcount; n++)
858   {
859     match = 0;
860     /* don't include pending expunged messages */
861     if (hdrs[n]->active)
862       switch (flag)
863       {
864         case M_DELETE:
865           if (hdrs[n]->deleted)
866             match = 1;
867           break;
868         case M_TAG:
869           if (hdrs[n]->tagged)
870             match = 1;
871           break;
872       }
873
874     if (match && (!changed || hdrs[n]->changed))
875     {
876       count++;
877       if (setstart == 0)
878       {
879         setstart = HEADER_DATA (hdrs[n])->uid;
880         if (started == 0)
881         {
882           snprintf (uid, sizeof (uid), "%u", HEADER_DATA (hdrs[n])->uid);
883           mutt_buffer_addstr (buf, uid);
884           started = 1;
885         }
886         else
887         {
888           snprintf (uid, sizeof (uid), ",%u", HEADER_DATA (hdrs[n])->uid);
889           mutt_buffer_addstr (buf, uid);
890         }
891       }
892       /* tie up if the last message also matches */
893       else if (n == idata->ctx->msgcount-1)
894       {
895         snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n])->uid);
896         mutt_buffer_addstr (buf, uid);
897       }
898     }
899     /* this message is not expunged and doesn't match. End current set. */
900     else if (setstart && hdrs[n]->active)
901     {
902       if (HEADER_DATA (hdrs[n-1])->uid > setstart)
903       {
904         snprintf (uid, sizeof (uid), ":%u", HEADER_DATA (hdrs[n-1])->uid);
905         mutt_buffer_addstr (buf, uid);
906       }
907       setstart = 0;
908     }
909   }
910
911   FREE (&hdrs);
912
913   return count;
914 }
915
916 /* update the IMAP server to reflect message changes done within mutt.
917  * Arguments
918  *   ctx: the current context
919  *   expunge: 0 or 1 - do expunge? 
920  */
921
922 int imap_sync_mailbox (CONTEXT* ctx, int expunge, int* index_hint)
923 {
924   IMAP_DATA* idata;
925   CONTEXT* appendctx = NULL;
926   BUFFER cmd;
927   char flags[LONG_STRING];
928   char uid[11];
929   int deleted;
930   int n;
931   int err_continue = M_NO;      /* continue on error? */
932   int rc;
933
934   idata = (IMAP_DATA*) ctx->data;
935
936   if (idata->state != IMAP_SELECTED)
937   {
938     dprint (2, (debugfile, "imap_sync_mailbox: no mailbox selected\n"));
939     return -1;
940   }
941
942   /* CLOSE purges deleted messages. If we don't want to purge them, we must
943    * tell imap_close_mailbox not to issue the CLOSE command */
944   if (expunge)
945     idata->noclose = 0;
946   else
947     idata->noclose = 1;
948
949   /* This function is only called when the calling code expects the context
950    * to be changed. */
951   imap_allow_reopen (ctx);
952
953   if ((rc = imap_check_mailbox (ctx, index_hint, 0)) != 0)
954     return rc;
955
956   memset (&cmd, 0, sizeof (cmd));
957
958   /* if we are expunging anyway, we can do deleted messages very quickly... */
959   if (expunge && mutt_bit_isset (idata->rights, IMAP_ACL_DELETE))
960   {
961     mutt_buffer_addstr (&cmd, "UID STORE ");
962     deleted = imap_make_msg_set (idata, &cmd, M_DELETE, 1);
963
964     /* if we have a message set, then let's delete */
965     if (deleted)
966     {
967       mutt_message (_("Marking %d messages deleted..."), deleted);
968       mutt_buffer_addstr (&cmd, " +FLAGS.SILENT (\\Deleted)");
969       /* mark these messages as unchanged so second pass ignores them. Done
970        * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */
971       for (n = 0; n < ctx->msgcount; n++)
972         if (ctx->hdrs[n]->deleted && ctx->hdrs[n]->changed)
973           ctx->hdrs[n]->active = 0;
974       if (imap_exec (idata, cmd.data, 0) != 0)
975       {
976         mutt_error (_("Expunge failed"));
977         mutt_sleep (1);
978         rc = -1;
979         goto out;
980       }
981     }
982   }
983
984   /* save status changes */
985   for (n = 0; n < ctx->msgcount; n++)
986   {
987     if (ctx->hdrs[n]->active && ctx->hdrs[n]->changed)
988     {
989       ctx->hdrs[n]->changed = 0;
990
991       mutt_message (_("Saving message status flags... [%d/%d]"), n+1,
992         ctx->msgcount);
993
994       snprintf (uid, sizeof (uid), "%u", HEADER_DATA(ctx->hdrs[n])->uid);
995       cmd.dptr = cmd.data;
996       mutt_buffer_addstr (&cmd, "UID STORE ");
997       mutt_buffer_addstr (&cmd, uid);
998
999       /* if the message has been rethreaded or attachments have been deleted
1000        * we delete the message and reupload it.
1001        * This works better if we're expunging, of course. */
1002       if (ctx->hdrs[n]->refs_changed || ctx->hdrs[n]->irt_changed ||
1003           ctx->hdrs[n]->attach_del)
1004       {
1005         dprint (3, (debugfile, "imap_sync_mailbox: Attachments to be deleted, falling back to _mutt_save_message\n"));
1006         if (!appendctx)
1007           appendctx = mx_open_mailbox (ctx->path, M_APPEND | M_QUIET, NULL);
1008         if (!appendctx)
1009         {
1010           dprint (1, (debugfile, "imap_sync_mailbox: Error opening mailbox in append mode\n"));
1011         }
1012         else
1013           _mutt_save_message (ctx->hdrs[n], appendctx, 1, 0, 0);
1014       }
1015       flags[0] = '\0';
1016       
1017       imap_set_flag (idata, IMAP_ACL_SEEN, ctx->hdrs[n]->read, "\\Seen ",
1018         flags, sizeof (flags));
1019       imap_set_flag (idata, IMAP_ACL_WRITE, ctx->hdrs[n]->flagged,
1020         "\\Flagged ", flags, sizeof (flags));
1021       imap_set_flag (idata, IMAP_ACL_WRITE, ctx->hdrs[n]->replied,
1022         "\\Answered ", flags, sizeof (flags));
1023       imap_set_flag (idata, IMAP_ACL_DELETE, ctx->hdrs[n]->deleted,
1024         "\\Deleted ", flags, sizeof (flags));
1025
1026       /* now make sure we don't lose custom tags */
1027       if (mutt_bit_isset (idata->rights, IMAP_ACL_WRITE))
1028         imap_add_keywords (flags, ctx->hdrs[n], idata->flags, sizeof (flags));
1029       
1030       mutt_remove_trailing_ws (flags);
1031       
1032       /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to
1033        * explicitly revoke all system flags (if we have permission) */
1034       if (!*flags)
1035       {
1036         imap_set_flag (idata, IMAP_ACL_SEEN, 1, "\\Seen ", flags, sizeof (flags));
1037         imap_set_flag (idata, IMAP_ACL_WRITE, 1, "\\Flagged ", flags, sizeof (flags));
1038         imap_set_flag (idata, IMAP_ACL_WRITE, 1, "\\Answered ", flags, sizeof (flags));
1039         imap_set_flag (idata, IMAP_ACL_DELETE, 1, "\\Deleted ", flags, sizeof (flags));
1040
1041         mutt_remove_trailing_ws (flags);
1042
1043         mutt_buffer_addstr (&cmd, " -FLAGS.SILENT (");
1044       }
1045       else
1046         mutt_buffer_addstr (&cmd, " FLAGS.SILENT (");
1047       
1048       mutt_buffer_addstr (&cmd, flags);
1049       mutt_buffer_addstr (&cmd, ")");
1050
1051       /* dumb hack for bad UW-IMAP 4.7 servers spurious FLAGS updates */
1052       ctx->hdrs[n]->active = 0;
1053
1054       /* after all this it's still possible to have no flags, if you
1055        * have no ACL rights */
1056       if (*flags && (imap_exec (idata, cmd.data, 0) != 0) &&
1057         (err_continue != M_YES))
1058       {
1059         err_continue = imap_continue ("imap_sync_mailbox: STORE failed",
1060           idata->cmd.buf);
1061         if (err_continue != M_YES)
1062         {
1063           rc = -1;
1064           goto out;
1065         }
1066       }
1067
1068       ctx->hdrs[n]->active = 1;
1069     }
1070   }
1071   ctx->changed = 0;
1072
1073   /* We must send an EXPUNGE command if we're not closing. */
1074   if (expunge && !(ctx->closing) &&
1075       mutt_bit_isset(idata->rights, IMAP_ACL_DELETE))
1076   {
1077     mutt_message _("Expunging messages from server...");
1078     /* Set expunge bit so we don't get spurious reopened messages */
1079     idata->reopen |= IMAP_EXPUNGE_EXPECTED;
1080     if (imap_exec (idata, "EXPUNGE", 0) != 0)
1081     {
1082       imap_error (_("imap_sync_mailbox: EXPUNGE failed"), idata->cmd.buf);
1083       rc = -1;
1084       goto out;
1085     }
1086   }
1087
1088   rc = 0;
1089  out:
1090   if (cmd.data)
1091     FREE (&cmd.data);
1092   if (appendctx)
1093   {
1094     mx_fastclose_mailbox (appendctx);
1095     FREE (&appendctx);
1096   }
1097   return rc;
1098 }
1099
1100 /* imap_close_mailbox: issue close command if neccessary, reset IMAP_DATA */
1101 void imap_close_mailbox (CONTEXT* ctx)
1102 {
1103   IMAP_DATA* idata;
1104   int i;
1105
1106   idata = (IMAP_DATA*) ctx->data;
1107   /* Check to see if the mailbox is actually open */
1108   if (!idata)
1109     return;
1110
1111   if ((idata->status != IMAP_FATAL) &&
1112       (idata->state == IMAP_SELECTED) &&
1113       (ctx == idata->ctx))
1114   {
1115     if (!(idata->noclose) && imap_exec (idata, "CLOSE", 0))
1116       mutt_error (_("CLOSE failed"));
1117
1118     idata->reopen &= IMAP_REOPEN_ALLOW;
1119     idata->state = IMAP_AUTHENTICATED;
1120     FREE (&(idata->mailbox));
1121     mutt_free_list (&idata->flags);
1122     idata->ctx = NULL;
1123   }
1124
1125   /* free IMAP part of headers */
1126   for (i = 0; i < ctx->msgcount; i++)
1127     imap_free_header_data (&(ctx->hdrs[i]->data));
1128
1129   for (i = 0; i < IMAP_CACHE_LEN; i++)
1130   {
1131     if (idata->cache[i].path)
1132     {
1133       unlink (idata->cache[i].path);
1134       FREE (&idata->cache[i].path);
1135     }
1136   }
1137 }
1138
1139 /* use the NOOP command to poll for new mail
1140  *
1141  * return values:
1142  *      M_REOPENED      mailbox has been externally modified
1143  *      M_NEW_MAIL      new mail has arrived!
1144  *      0               no change
1145  *      -1              error
1146  */
1147 int imap_check_mailbox (CONTEXT *ctx, int *index_hint, int force)
1148 {
1149   /* overload keyboard timeout to avoid many mailbox checks in a row.
1150    * Most users don't like having to wait exactly when they press a key. */
1151   IMAP_DATA* idata;
1152   int result = 0;
1153
1154   idata = (IMAP_DATA*) ctx->data;
1155
1156   if ((force || time(NULL) > idata->lastread + Timeout)
1157       && imap_exec (idata, "NOOP", 0) != 0)
1158     return -1;
1159
1160   /* We call this even when we haven't run NOOP in case we have pending
1161    * changes to process, since we can reopen here. */
1162   imap_cmd_finish (idata);
1163
1164   if (idata->check_status & IMAP_EXPUNGE_PENDING)
1165     result = M_REOPENED;
1166   else if (idata->check_status & IMAP_NEWMAIL_PENDING)
1167     result = M_NEW_MAIL;
1168   else if (idata->check_status & IMAP_FLAGS_PENDING)
1169     result = M_FLAGS;
1170
1171   idata->check_status = 0;
1172
1173   return result;
1174 }
1175
1176 /* returns count of recent messages if new = 1, else count of total messages.
1177  * (useful for at least postponed function)
1178  * Question of taste: use RECENT or UNSEEN for new?
1179  *   0+   number of messages in mailbox
1180  *  -1    error while polling mailboxes
1181  */
1182 int imap_mailbox_check (char* path, int new)
1183 {
1184   CONNECTION *conn;
1185   IMAP_DATA *idata;
1186   char buf[LONG_STRING];
1187   char mbox[LONG_STRING];
1188   char mbox_unquoted[LONG_STRING];
1189   char *s;
1190   int msgcount = 0;
1191   int connflags = 0;
1192   IMAP_MBOX mx;
1193   int rc;
1194   
1195   if (imap_parse_path (path, &mx))
1196     return -1;
1197
1198   /* If imap_passive is set, don't open a connection to check for new mail */
1199   if (option (OPTIMAPPASSIVE))
1200     connflags = M_IMAP_CONN_NONEW;
1201
1202   if (!(idata = imap_conn_find (&(mx.account), connflags)))
1203   {
1204     FREE (&mx.mbox);
1205     return -1;
1206   }
1207   conn = idata->conn;
1208
1209   imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1210   FREE (&mx.mbox);
1211
1212   imap_munge_mbox_name (mbox, sizeof(mbox), buf);
1213   strfcpy (mbox_unquoted, buf, sizeof (mbox_unquoted));
1214
1215   /* The draft IMAP implementor's guide warns againts using the STATUS
1216    * command on a mailbox that you have selected 
1217    */
1218
1219   if (mutt_strcmp (mbox_unquoted, idata->mailbox) == 0
1220       || (ascii_strcasecmp (mbox_unquoted, "INBOX") == 0
1221           && mutt_strcasecmp (mbox_unquoted, idata->mailbox) == 0))
1222   {
1223     strfcpy (buf, "NOOP", sizeof (buf));
1224   }
1225   else if (mutt_bit_isset(idata->capabilities,IMAP4REV1) ||
1226            mutt_bit_isset(idata->capabilities,STATUS))
1227   {                             
1228     snprintf (buf, sizeof (buf), "STATUS %s (%s)", mbox,
1229       new ? "RECENT" : "MESSAGES");
1230   }
1231   else
1232     /* Server does not support STATUS, and this is not the current mailbox.
1233      * There is no lightweight way to check recent arrivals */
1234     return -1;
1235
1236   imap_cmd_start (idata, buf);
1237
1238   do 
1239   {
1240     if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
1241       break;
1242
1243     s = imap_next_word (idata->cmd.buf);
1244     if (ascii_strncasecmp ("STATUS", s, 6) == 0)
1245     {
1246       s = imap_next_word (s);
1247       /* The mailbox name may or may not be quoted here. We could try to 
1248        * munge the server response and compare with quoted (or vise versa)
1249        * but it is probably more efficient to just strncmp against both. */
1250       if (mutt_strncmp (mbox_unquoted, s, mutt_strlen (mbox_unquoted)) == 0
1251           || mutt_strncmp (mbox, s, mutt_strlen (mbox)) == 0)
1252       {
1253         s = imap_next_word (s);
1254         s = imap_next_word (s);
1255         if (isdigit ((unsigned char) *s))
1256         {
1257           if (*s != '0')
1258           {
1259             msgcount = atoi(s);
1260             dprint (2, (debugfile, "%d new messages in %s\n", msgcount, path));
1261           }
1262         }
1263       }
1264       else
1265         dprint (1, (debugfile, "imap_mailbox_check: STATUS response doesn't match requested mailbox.\n"));
1266     }
1267   }
1268   while (rc == IMAP_CMD_CONTINUE);
1269
1270   return msgcount;
1271 }
1272
1273 /* all this listing/browsing is a mess. I don't like that name is a pointer
1274  *   into idata->buf (used to be a pointer into the passed in buffer, just
1275  *   as bad), nor do I like the fact that the fetch is done here. This
1276  *   code can't possibly handle non-LIST untagged responses properly.
1277  *   FIXME. ?! */
1278 int imap_parse_list_response(IMAP_DATA* idata, char **name, int *noselect,
1279   int *noinferiors, char *delim)
1280 {
1281   char *s;
1282   long bytes;
1283   int rc;
1284
1285   *name = NULL;
1286
1287   rc = imap_cmd_step (idata);
1288   if (rc == IMAP_CMD_OK)
1289     return 0;
1290   if (rc != IMAP_CMD_CONTINUE)
1291     return -1;
1292
1293   s = imap_next_word (idata->cmd.buf);
1294   if ((ascii_strncasecmp ("LIST", s, 4) == 0) ||
1295       (ascii_strncasecmp ("LSUB", s, 4) == 0))
1296   {
1297     *noselect = 0;
1298     *noinferiors = 0;
1299       
1300     s = imap_next_word (s); /* flags */
1301     if (*s == '(')
1302     {
1303       char *ep;
1304
1305       s++;
1306       ep = s;
1307       while (*ep && *ep != ')') ep++;
1308       do
1309       {
1310         if (!ascii_strncasecmp (s, "\\NoSelect", 9))
1311           *noselect = 1;
1312         if (!ascii_strncasecmp (s, "\\NoInferiors", 12))
1313           *noinferiors = 1;
1314         /* See draft-gahrns-imap-child-mailbox-?? */
1315         if (!ascii_strncasecmp (s, "\\HasNoChildren", 14))
1316           *noinferiors = 1;
1317         if (*s != ')')
1318           s++;
1319         while (*s && *s != '\\' && *s != ')') s++;
1320       } while (s != ep);
1321     }
1322     else
1323       return 0;
1324     s = imap_next_word (s); /* delim */
1325     /* Reset the delimiter, this can change */
1326     if (ascii_strncasecmp (s, "NIL", 3))
1327     {
1328       if (s && s[0] == '\"' && s[1] && s[2] == '\"')
1329         *delim = s[1];
1330       else if (s && s[0] == '\"' && s[1] && s[1] == '\\' && s[2] && s[3] == '\"')
1331         *delim = s[2];
1332     }
1333     s = imap_next_word (s); /* name */
1334     if (s && *s == '{') /* Literal */
1335     { 
1336       if (imap_get_literal_count(idata->cmd.buf, &bytes) < 0)
1337         return -1;
1338       if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
1339         return -1;
1340       *name = idata->cmd.buf;
1341     }
1342     else
1343       *name = s;
1344   }
1345
1346   return 0;
1347 }
1348
1349 int imap_subscribe (char *path, int subscribe)
1350 {
1351   CONNECTION *conn;
1352   IMAP_DATA *idata;
1353   char buf[LONG_STRING];
1354   char mbox[LONG_STRING];
1355   IMAP_MBOX mx;
1356
1357   if (!mx_is_imap (path) || imap_parse_path (path, &mx))
1358   {
1359     mutt_error (_("Bad mailbox name"));
1360     return -1;
1361   }
1362   
1363
1364   if (!(idata = imap_conn_find (&(mx.account), 0)))
1365     goto fail;
1366   
1367   conn = idata->conn;
1368
1369   imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
1370   if (subscribe)
1371     mutt_message (_("Subscribing to %s..."), buf);
1372   else
1373     mutt_message (_("Unsubscribing to %s..."), buf);
1374   imap_munge_mbox_name (mbox, sizeof(mbox), buf);
1375
1376   snprintf (buf, sizeof (buf), "%s %s", subscribe ? "SUBSCRIBE" :
1377     "UNSUBSCRIBE", mbox);
1378
1379   if (imap_exec (idata, buf, 0) < 0)
1380     goto fail;
1381
1382   FREE (&mx.mbox);
1383   return 0;
1384
1385  fail:
1386   FREE (&mx.mbox);
1387   return -1;
1388 }
1389
1390 /* imap_complete: given a partial IMAP folder path, return a string which
1391  *   adds as much to the path as is unique */
1392 int imap_complete(char* dest, size_t dlen, char* path) {
1393   CONNECTION* conn;
1394   IMAP_DATA* idata;
1395   char list[LONG_STRING];
1396   char buf[LONG_STRING];
1397   char* list_word = NULL;
1398   int noselect, noinferiors;
1399   char delim;
1400   char completion[LONG_STRING];
1401   int clen, matchlen = 0;
1402   int completions = 0;
1403   int pos = 0;
1404   IMAP_MBOX mx;
1405
1406   /* verify passed in path is an IMAP path */
1407   if (imap_parse_path (path, &mx))
1408   {
1409     dprint(2, (debugfile, "imap_complete: bad path %s\n", path));
1410     return -1;
1411   }
1412
1413   /* don't open a new socket just for completion */
1414   if (!(idata = imap_conn_find (&(mx.account), M_IMAP_CONN_NONEW)))
1415     goto fail;
1416   conn = idata->conn;
1417
1418   /* reformat path for IMAP list, and append wildcard */
1419   /* don't use INBOX in place of "" */
1420   if (mx.mbox && mx.mbox[0])
1421     imap_fix_path (idata, mx.mbox, list, sizeof(list));
1422   else
1423     list[0] = '\0';
1424
1425   /* fire off command */
1426   snprintf (buf, sizeof(buf), "%s \"\" \"%s%%\"",
1427     option (OPTIMAPLSUB) ? "LSUB" : "LIST", list);
1428
1429   imap_cmd_start (idata, buf);
1430
1431   /* and see what the results are */
1432   strfcpy (completion, NONULL(mx.mbox), sizeof(completion));
1433   do
1434   {
1435     if (imap_parse_list_response(idata, &list_word, &noselect, &noinferiors,
1436         &delim))
1437       break;
1438
1439     if (list_word)
1440     {
1441       /* store unquoted */
1442       imap_unmunge_mbox_name (list_word);
1443
1444       /* if the folder isn't selectable, append delimiter to force browse
1445        * to enter it on second tab. */
1446       if (noselect)
1447       {
1448         clen = strlen(list_word);
1449         list_word[clen++] = delim;
1450         list_word[clen] = '\0';
1451       }
1452       /* copy in first word */
1453       if (!completions)
1454       {
1455         strfcpy (completion, list_word, sizeof(completion));
1456         matchlen = strlen (completion);
1457         completions++;
1458         continue;
1459       }
1460
1461       pos = 0;
1462       while (pos < matchlen && list_word[pos] &&
1463           completion[pos] == list_word[pos])
1464         pos++;
1465       completion[pos] = '\0';
1466       matchlen = pos;
1467
1468       completions++;
1469     }
1470   }
1471   while (ascii_strncmp(idata->cmd.seq, idata->cmd.buf, SEQLEN));
1472
1473   if (completions)
1474   {
1475     /* reformat output */
1476     imap_qualify_path (dest, dlen, &mx, completion);
1477     mutt_pretty_mailbox (dest);
1478
1479     FREE (&mx.mbox);
1480     return 0;
1481   }
1482
1483  fail:
1484   FREE (&mx.mbox);
1485   return -1;
1486 }
1487
1488 /* reconnect if connection was lost */
1489 int imap_reconnect(CONTEXT* ctx) {
1490   IMAP_DATA* imap_data = (IMAP_DATA *)ctx->data;
1491
1492   if (imap_data) {
1493     if (imap_data->status == IMAP_CONNECTED)
1494       return -1;
1495   }
1496
1497   if (query_quadoption(OPT_IMAPRECONNECT,_("Connection lost. Reconnect to IMAP server?")) != M_YES)
1498     return -1;
1499
1500   mx_open_mailbox(ctx->path,0,ctx);
1501   return 0;
1502 }
1503