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