Rocco Rutte:
[apps/madmutt.git] / imap / browse.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-9 Brandon Long <blong@fiction.net>
4  * Copyright (C) 1999-2002 Brendan Cully <brendan@kublai.com>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 /* Mutt browser support routines */
12
13 #if HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #include <stdlib.h>
18 #include <ctype.h>
19
20 #include "lib/mem.h"
21 #include "lib/str.h"
22 #include "lib/intl.h"
23 #include "lib/debug.h"
24
25 #include "mutt.h"
26 #include "imap_private.h"
27
28 /* -- forward declarations -- */
29 static int browse_add_list_result (IMAP_DATA * idata, const char *cmd,
30                                    struct browser_state *state,
31                                    short isparent);
32 static void imap_add_folder (char delim, char *folder, int noselect,
33                              int noinferiors, struct browser_state *state,
34                              short isparent);
35 static int compare_names (struct folder_file *a, struct folder_file *b);
36 static int browse_get_namespace (IMAP_DATA * idata, char *nsbuf, int nsblen,
37                                  IMAP_NAMESPACE_INFO * nsi, int nsilen,
38                                  int *nns);
39 static int browse_verify_namespace (IMAP_DATA * idata,
40                                     IMAP_NAMESPACE_INFO * nsi, int nns);
41
42 /* imap_browse: IMAP hook into the folder browser, fills out browser_state,
43  *   given a current folder to browse */
44 int imap_browse (char *path, struct browser_state *state)
45 {
46   IMAP_DATA *idata;
47   char buf[LONG_STRING];
48   char buf2[LONG_STRING];
49   char nsbuf[LONG_STRING];
50   char mbox[LONG_STRING];
51   char list_cmd[5];
52   IMAP_NAMESPACE_INFO nsi[16];
53   int home_namespace = 0;
54   int n;
55   int i;
56   int nsup;
57   char ctmp;
58   int nns = 0;
59   char *cur_folder;
60   short showparents = 0;
61   int noselect;
62   int noinferiors;
63   IMAP_MBOX mx;
64
65   if (imap_parse_path (path, &mx)) {
66     mutt_error (_("%s is an invalid IMAP path"), path);
67     return -1;
68   }
69
70   strfcpy (list_cmd, option (OPTIMAPLSUB) ? "LSUB" : "LIST",
71            sizeof (list_cmd));
72
73   if (!(idata = imap_conn_find (&(mx.account), 0)))
74     goto fail;
75
76   if (!mx.mbox) {
77     home_namespace = 1;
78     mbox[0] = '\0';             /* Do not replace "" with "INBOX" here */
79     mx.mbox = str_dup (ImapHomeNamespace);
80     if (mutt_bit_isset (idata->capabilities, NAMESPACE)) {
81       mutt_message _("Getting namespaces...");
82
83       if (browse_get_namespace (idata, nsbuf, sizeof (nsbuf),
84                                 nsi, sizeof (nsi), &nns) != 0)
85         goto fail;
86       if (browse_verify_namespace (idata, nsi, nns) != 0)
87         goto fail;
88     }
89   }
90
91   mutt_message _("Getting folder list...");
92
93   /* skip check for parents when at the root */
94   if (mx.mbox && mx.mbox[0] != '\0') {
95     imap_fix_path (idata, mx.mbox, mbox, sizeof (mbox));
96     imap_munge_mbox_name (buf, sizeof (buf), mbox);
97     imap_unquote_string (buf);  /* As kludgy as it gets */
98     mbox[sizeof (mbox) - 1] = '\0';
99     strncpy (mbox, buf, sizeof (mbox) - 1);
100     n = str_len (mbox);
101
102     debug_print (3, ("mbox: %s\n", mbox));
103
104     /* if our target exists and has inferiors, enter it if we
105      * aren't already going to */
106     if (mbox[n - 1] != idata->delim) {
107       snprintf (buf, sizeof (buf), "%s \"\" \"%s\"", list_cmd, mbox);
108       imap_cmd_start (idata, buf);
109       do {
110         if (imap_parse_list_response (idata, &cur_folder, &noselect,
111                                       &noinferiors, &idata->delim) != 0)
112           goto fail;
113
114         if (cur_folder) {
115           imap_unmunge_mbox_name (cur_folder);
116
117           if (!noinferiors && cur_folder[0] &&
118               (n = str_len (mbox)) < LONG_STRING - 1) {
119             mbox[n++] = idata->delim;
120             mbox[n] = '\0';
121           }
122         }
123       }
124       while (ascii_strncmp (idata->cmd.buf, idata->cmd.seq, SEQLEN));
125     }
126
127     /* if we're descending a folder, mark it as current in browser_state */
128     if (mbox[n - 1] == idata->delim) {
129       /* don't show parents in the home namespace */
130       if (!home_namespace)
131         showparents = 1;
132       imap_qualify_path (buf, sizeof (buf), &mx, mbox);
133       state->folder = str_dup (buf);
134       n--;
135     }
136
137     /* Find superiors to list
138      * Note: UW-IMAP servers return folder + delimiter when asked to list
139      *  folder + delimiter. Cyrus servers don't. So we ask for folder,
140      *  and tack on delimiter ourselves.
141      * Further note: UW-IMAP servers return nothing when asked for 
142      *  NAMESPACES without delimiters at the end. Argh! */
143     for (n--; n >= 0 && mbox[n] != idata->delim; n--);
144     if (n > 0) {                /* "aaaa/bbbb/" -> "aaaa" */
145       /* forget the check, it is too delicate (see above). Have we ever
146        * had the parent not exist? */
147       ctmp = mbox[n];
148       mbox[n] = '\0';
149
150       if (showparents) {
151         debug_print (3, ("adding parent %s\n", mbox));
152         imap_add_folder (idata->delim, mbox, 1, 0, state, 1);
153       }
154
155       /* if our target isn't a folder, we are in our superior */
156       if (!state->folder) {
157         /* store folder with delimiter */
158         mbox[n++] = ctmp;
159         ctmp = mbox[n];
160         mbox[n] = '\0';
161         imap_qualify_path (buf, sizeof (buf), &mx, mbox);
162         state->folder = str_dup (buf);
163       }
164       mbox[n] = ctmp;
165     }
166     /* "/bbbb/" -> add  "/", "aaaa/" -> add "" */
167     else {
168       char relpath[2];
169
170       /* folder may be "/" */
171       snprintf (relpath, sizeof (relpath), "%c", n < 0 ? '\0' : idata->delim);
172       if (showparents)
173         imap_add_folder (idata->delim, relpath, 1, 0, state, 1);
174       if (!state->folder) {
175         imap_qualify_path (buf, sizeof (buf), &mx, relpath);
176         state->folder = str_dup (buf);
177       }
178     }
179   }
180
181   /* no namespace, no folder: set folder to host only */
182   if (!state->folder) {
183     imap_qualify_path (buf, sizeof (buf), &mx, NULL);
184     state->folder = str_dup (buf);
185   }
186
187   if (home_namespace && mbox[0] != '\0') {
188     /* Listing the home namespace, so INBOX should be included. Home 
189      * namespace is not "", so we have to list it explicitly. We ask the 
190      * server to see if it has descendants. */
191     debug_print (3, ("adding INBOX\n"));
192     if (browse_add_list_result (idata, "LIST \"\" \"INBOX\"", state, 0))
193       goto fail;
194   }
195
196   nsup = state->entrylen;
197
198   debug_print (3, ("Quoting mailbox scan: %s:\n", mbox));
199   snprintf (buf, sizeof (buf), "%s%%", mbox);
200   imap_quote_string (buf2, sizeof (buf2), buf);
201   debug_print (3, ("%s\n", buf2));
202   snprintf (buf, sizeof (buf), "%s \"\" %s", list_cmd, buf2);
203   if (browse_add_list_result (idata, buf, state, 0))
204     goto fail;
205
206   if (!state->entrylen) {
207     mutt_error _("No such folder");
208
209     goto fail;
210   }
211
212   mutt_clear_error ();
213
214   qsort (&(state->entry[nsup]), state->entrylen - nsup,
215          sizeof (state->entry[0]),
216          (int (*)(const void *, const void *)) compare_names);
217   if (home_namespace) {         /* List additional namespaces */
218     for (i = 0; i < nns; i++)
219       if (nsi[i].listable && !nsi[i].home_namespace) {
220         imap_add_folder (nsi[i].delim, nsi[i].prefix, nsi[i].noselect,
221                          nsi[i].noinferiors, state, 0);
222         debug_print (3, ("adding namespace: %s\n", nsi[i].prefix));
223       }
224   }
225
226   FREE (&mx.mbox);
227   return 0;
228
229 fail:
230   FREE (&mx.mbox);
231   return -1;
232 }
233
234 /* imap_mailbox_create: Prompt for a new mailbox name, and try to create it */
235 int imap_mailbox_create (const char *folder)
236 {
237   IMAP_DATA *idata;
238   IMAP_MBOX mx;
239   char buf[LONG_STRING];
240   short n;
241
242   if (imap_parse_path (folder, &mx) < 0) {
243     debug_print (1, ("Bad starting path %s\n", folder));
244     return -1;
245   }
246
247   if (!(idata = imap_conn_find (&mx.account, M_IMAP_CONN_NONEW))) {
248     debug_print (1, ("Couldn't find open connection to %s\n", mx.account.host));
249     goto fail;
250   }
251
252   strfcpy (buf, NONULL (mx.mbox), sizeof (buf));
253
254   /* append a delimiter if necessary */
255   n = str_len (buf);
256   if (n && (n < sizeof (buf) - 1) && (buf[n - 1] != idata->delim)) {
257     buf[n++] = idata->delim;
258     buf[n] = '\0';
259   }
260
261   if (mutt_get_field (_("Create mailbox: "), buf, sizeof (buf), M_FILE) < 0)
262     goto fail;
263
264   if (!str_len (buf)) {
265     mutt_error (_("Mailbox must have a name."));
266     mutt_sleep (1);
267     goto fail;
268   }
269
270   if (imap_create_mailbox (idata, buf) < 0)
271     goto fail;
272
273   mutt_message _("Mailbox created.");
274
275   mutt_sleep (0);
276
277   FREE (&mx.mbox);
278   return 0;
279
280 fail:
281   FREE (&mx.mbox);
282   return -1;
283 }
284
285 int imap_mailbox_rename (const char *mailbox)
286 {
287   IMAP_DATA *idata;
288   IMAP_MBOX mx;
289   char buf[LONG_STRING];
290   char newname[SHORT_STRING];
291
292   if (imap_parse_path (mailbox, &mx) < 0) {
293     debug_print (1, ("Bad source mailbox %s\n", mailbox));
294     return -1;
295   }
296
297   if (!(idata = imap_conn_find (&mx.account, M_IMAP_CONN_NONEW))) {
298     debug_print (1, ("Couldn't find open connection to %s\n", mx.account.host));
299     goto fail;
300   }
301
302   snprintf (buf, sizeof (buf), _("Rename mailbox %s to: "), mx.mbox);
303
304   if (mutt_get_field (buf, newname, sizeof (newname), M_FILE) < 0)
305     goto fail;
306
307   if (!str_len (newname)) {
308     mutt_error (_("Mailbox must have a name."));
309     mutt_sleep (1);
310     goto fail;
311   }
312
313   if (imap_rename_mailbox (idata, &mx, newname) < 0) {
314     mutt_error (_("Rename failed: %s"), imap_get_qualifier (idata->cmd.buf));
315     mutt_sleep (1);
316     goto fail;
317   }
318
319   mutt_message (_("Mailbox renamed."));
320   mutt_sleep (0);
321
322   FREE (&mx.mbox);
323   return 0;
324
325 fail:
326   FREE (&mx.mbox);
327   return -1;
328 }
329
330 static int browse_add_list_result (IMAP_DATA * idata, const char *cmd,
331                                    struct browser_state *state,
332                                    short isparent)
333 {
334   char *name;
335   int noselect;
336   int noinferiors;
337   IMAP_MBOX mx;
338
339   if (imap_parse_path (state->folder, &mx)) {
340     debug_print (2, ("current folder %s makes no sense\n", state->folder));
341     return -1;
342   }
343
344   imap_cmd_start (idata, cmd);
345
346   do {
347     if (imap_parse_list_response (idata, &name, &noselect, &noinferiors,
348                                   &idata->delim) != 0) {
349       FREE (&mx.mbox);
350       return -1;
351     }
352
353     if (name) {
354       /* Let a parent folder never be selectable for navigation */
355       if (isparent)
356         noselect = 1;
357       /* prune current folder from output */
358       if (isparent || str_ncmp (name, mx.mbox, str_len (name)))
359         imap_add_folder (idata->delim, name, noselect, noinferiors, state,
360                          isparent);
361     }
362   }
363   while ((ascii_strncmp (idata->cmd.buf, idata->cmd.seq, SEQLEN) != 0));
364
365   FREE (&mx.mbox);
366   return 0;
367 }
368
369 /* imap_add_folder: add a folder name to the browser list, formatting it as
370  *   necessary. */
371 static void imap_add_folder (char delim, char *folder, int noselect,
372                              int noinferiors, struct browser_state *state,
373                              short isparent)
374 {
375   char tmp[LONG_STRING];
376   char relpath[LONG_STRING];
377   IMAP_MBOX mx;
378
379   if (imap_parse_path (state->folder, &mx))
380     return;
381
382   imap_unmunge_mbox_name (folder);
383
384   if (state->entrylen + 1 == state->entrymax) {
385     safe_realloc (&state->entry,
386                   sizeof (struct folder_file) * (state->entrymax += 256));
387     memset (state->entry + state->entrylen, 0,
388             (sizeof (struct folder_file) *
389              (state->entrymax - state->entrylen)));
390   }
391
392   /* render superiors as unix-standard ".." */
393   if (isparent)
394     strfcpy (relpath, "../", sizeof (relpath));
395   /* strip current folder from target, to render a relative path */
396   else if (!str_ncmp (mx.mbox, folder, str_len (mx.mbox)))
397     strfcpy (relpath, folder + str_len (mx.mbox), sizeof (relpath));
398   else
399     strfcpy (relpath, folder, sizeof (relpath));
400
401   /* apply filemask filter. This should really be done at menu setup rather
402    * than at scan, since it's so expensive to scan. But that's big changes
403    * to browser.c */
404   if (!((regexec (Mask.rx, relpath, 0, NULL, 0) == 0) ^ Mask.not)) {
405     FREE (&mx.mbox);
406     return;
407   }
408
409   imap_qualify_path (tmp, sizeof (tmp), &mx, folder);
410   (state->entry)[state->entrylen].name = str_dup (tmp);
411
412   /* mark desc with delim in browser if it can have subfolders */
413   if (!isparent && !noinferiors && str_len (relpath) < sizeof (relpath) - 1) {
414     relpath[str_len (relpath) + 1] = '\0';
415     relpath[str_len (relpath)] = delim;
416   }
417
418   (state->entry)[state->entrylen].desc = str_dup (relpath);
419
420   (state->entry)[state->entrylen].imap = 1;
421   /* delimiter at the root is useless. */
422   if (folder[0] == '\0')
423     delim = '\0';
424   (state->entry)[state->entrylen].delim = delim;
425   (state->entry)[state->entrylen].selectable = !noselect;
426   (state->entry)[state->entrylen].inferiors = !noinferiors;
427   (state->entrylen)++;
428
429   FREE (&mx.mbox);
430 }
431
432 static int compare_names (struct folder_file *a, struct folder_file *b)
433 {
434   return str_cmp (a->name, b->name);
435 }
436
437 static int browse_get_namespace (IMAP_DATA * idata, char *nsbuf, int nsblen,
438                                  IMAP_NAMESPACE_INFO * nsi, int nsilen,
439                                  int *nns)
440 {
441   char *s;
442   int n;
443   char ns[LONG_STRING];
444   char delim = '/';
445   int type;
446   int nsbused = 0;
447   int rc;
448
449   *nns = 0;
450   nsbuf[nsblen - 1] = '\0';
451
452   imap_cmd_start (idata, "NAMESPACE");
453
454   do {
455     if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
456       break;
457
458     s = imap_next_word (idata->cmd.buf);
459     if (ascii_strncasecmp ("NAMESPACE", s, 9) == 0) {
460       /* There are three sections to the response, User, Other, Shared,
461        * and maybe more by extension */
462       for (type = IMAP_NS_PERSONAL; *s; type++) {
463         s = imap_next_word (s);
464         if (*s && ascii_strncasecmp (s, "NIL", 3)) {
465           s++;
466           while (*s && *s != ')') {
467             s++;                /* skip ( */
468             /* copy namespace */
469             n = 0;
470             delim = '\0';
471
472             if (*s == '\"') {
473               s++;
474               while (*s && *s != '\"') {
475                 if (*s == '\\')
476                   s++;
477                 ns[n++] = *s;
478                 s++;
479               }
480               if (*s)
481                 s++;
482             }
483             else
484               while (*s && !ISSPACE (*s)) {
485                 ns[n++] = *s;
486                 s++;
487               }
488             ns[n] = '\0';
489             /* delim? */
490             s = imap_next_word (s);
491             /* delimiter is meaningless if namespace is "". Why does
492              * Cyrus provide one?! */
493             if (n && *s && *s == '\"') {
494               if (s[1] && s[2] == '\"')
495                 delim = s[1];
496               else if (s[1] && s[1] == '\\' && s[2] && s[3] == '\"')
497                 delim = s[2];
498             }
499             /* skip "" namespaces, they are already listed at the root */
500             if ((ns[0] != '\0') && (nsbused < nsblen) && (*nns < nsilen)) {
501               debug_print (3, ("adding %s\n", ns));
502               nsi->type = type;
503               /* Cyrus doesn't append the delimiter to the namespace,
504                * but UW-IMAP does. We'll strip it here and add it back
505                * as if it were a normal directory, from the browser */
506               if (n && (ns[n - 1] == delim))
507                 ns[--n] = '\0';
508               strncpy (nsbuf + nsbused, ns, nsblen - nsbused - 1);
509               nsi->prefix = nsbuf + nsbused;
510               nsbused += n + 1;
511               nsi->delim = delim;
512               nsi++;
513               (*nns)++;
514             }
515             while (*s && *s != ')')
516               s++;
517             if (*s)
518               s++;
519           }
520         }
521       }
522     }
523   }
524   while (rc == IMAP_CMD_CONTINUE);
525
526   if (rc != IMAP_CMD_OK)
527     return -1;
528
529   return 0;
530 }
531
532 /* Check which namespaces have contents */
533 static int browse_verify_namespace (IMAP_DATA * idata,
534                                     IMAP_NAMESPACE_INFO * nsi, int nns)
535 {
536   char buf[LONG_STRING];
537   int i = 0;
538   char *name;
539   char delim;
540
541   for (i = 0; i < nns; i++, nsi++) {
542     /* Cyrus gives back nothing if the % isn't added. This may return lots
543      * of data in some cases, I guess, but I currently feel that's better
544      * than invisible namespaces */
545     if (nsi->delim)
546       snprintf (buf, sizeof (buf), "%s \"\" \"%s%c%%\"",
547                 option (OPTIMAPLSUB) ? "LSUB" : "LIST", nsi->prefix,
548                 nsi->delim);
549     else
550       snprintf (buf, sizeof (buf), "%s \"\" \"%s%%\"",
551                 option (OPTIMAPLSUB) ? "LSUB" : "LIST", nsi->prefix);
552
553     imap_cmd_start (idata, buf);
554
555     nsi->listable = 0;
556     nsi->home_namespace = 0;
557     do {
558       if (imap_parse_list_response (idata, &name, &nsi->noselect,
559                                     &nsi->noinferiors, &delim) != 0)
560         return -1;
561       nsi->listable |= (name != NULL);
562     }
563     while ((ascii_strncmp (idata->cmd.buf, idata->cmd.seq, SEQLEN) != 0));
564   }
565
566   return 0;
567 }