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