f4b60a7ac1ad853833fde371d5ae60f9f877719b
[apps/madmutt.git] / imap / util.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-8 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1996-9 Brandon Long <blong@fiction.net>
5  * Copyright (C) 1999-2002 Brendan Cully <brendan@kublai.com>
6  *
7  * This file is part of mutt-ng, see http://www.muttng.org/.
8  * It's licensed under the GNU General Public License,
9  * please see the file GPL in the top level source directory.
10  */
11
12 /* general IMAP utility functions */
13
14 #include <lib-lib/lib-lib.h>
15 #include <signal.h>
16 #include <netdb.h>
17 #include <lib-mx/mx.h>
18
19 #include "mutt.h"
20 #include "imap_private.h"
21
22 /* -- public functions -- */
23
24 /* imap_parse_path: given an IMAP mailbox name, return host, port
25  *   and a path IMAP servers will recognise.
26  * mx.mbox is malloc'd, caller must free it */
27 int imap_parse_path (const char *path, IMAP_MBOX * mx)
28 {
29   static unsigned short ImapPort = 0;
30   static unsigned short ImapsPort = 0;
31   struct servent *service;
32   ciss_url_t url;
33   char *c;
34
35   if (!ImapPort) {
36     service = getservbyname ("imap", "tcp");
37     if (service)
38       ImapPort = ntohs (service->s_port);
39     else
40       ImapPort = IMAP_PORT;
41   }
42   if (!ImapsPort) {
43     service = getservbyname ("imaps", "tcp");
44     if (service)
45       ImapsPort = ntohs (service->s_port);
46     else
47       ImapsPort = IMAP_SSL_PORT;
48   }
49
50   /* Defaults */
51   mx->account.flags = 0;
52   mx->account.port = ImapPort;
53   mx->account.type = M_ACCT_TYPE_IMAP;
54
55   c = m_strdup(path);
56   url_parse_ciss (&url, c);
57
58   if (!(url.scheme == U_IMAP || url.scheme == U_IMAPS) ||
59       mutt_account_fromurl (&mx->account, &url) < 0 || !*mx->account.host) {
60     p_delete(&c);
61     return -1;
62   }
63
64   mx->mbox = m_strdup(url.path);
65
66   if (url.scheme == U_IMAPS)
67     mx->account.has_ssl = 1;
68
69   p_delete(&c);
70
71   if (mx->account.has_ssl && !mx->account.has_port)
72     mx->account.port = ImapsPort;
73
74   return 0;
75 }
76
77 /* imap_pretty_mailbox: called by mutt_pretty_mailbox to make IMAP paths
78  *   look nice. */
79 void imap_pretty_mailbox (char *path)
80 {
81   IMAP_MBOX home, target;
82   ciss_url_t url;
83   char *delim;
84   int tlen;
85   int hlen = 0;
86   char home_match = 0;
87
88   if (imap_parse_path (path, &target) < 0)
89     return;
90
91   tlen = m_strlen(target.mbox);
92   /* check whether we can do '=' substitution */
93   if (mx_get_magic (Maildir) == M_IMAP && !imap_parse_path (Maildir, &home)) {
94     hlen = m_strlen(home.mbox);
95     if (tlen && mutt_account_match (&home.account, &target.account) &&
96         !m_strncmp(home.mbox, target.mbox, hlen)) {
97       if (!hlen)
98         home_match = 1;
99       else
100         for (delim = ImapDelimChars; *delim != '\0'; delim++)
101           if (target.mbox[hlen] == *delim)
102             home_match = 1;
103     }
104     p_delete(&home.mbox);
105   }
106
107   /* do the '=' substitution */
108   if (home_match) {
109     *path++ = '=';
110     /* copy remaining path, skipping delimiter */
111     if (!hlen)
112       hlen = -1;
113     memcpy (path, target.mbox + hlen + 1, tlen - hlen - 1);
114     path[tlen - hlen - 1] = '\0';
115   }
116   else {
117     mutt_account_tourl (&target.account, &url);
118     url.path = target.mbox;
119     /* FIXME: That hard-coded constant is bogus. But we need the actual
120      *   size of the buffer from mutt_pretty_mailbox. And these pretty
121      *   operations usually shrink the result. Still... */
122     url_ciss_tostring (&url, path, 1024, 0);
123   }
124
125   p_delete(&target.mbox);
126 }
127
128 /* -- library functions -- */
129
130 /* imap_continue: display a message and ask the user if she wants to
131  *   go on. */
132 int imap_continue (const char *msg, const char *resp)
133 {
134   imap_error (msg, resp);
135   return mutt_yesorno (_("Continue?"), 0);
136 }
137
138 /* imap_error: show an error and abort */
139 void imap_error (const char *where, const char *msg)
140 {
141   mutt_error ("%s [%s]\n", where, msg);
142   mutt_sleep (2);
143 }
144
145 /* imap_new_idata: Allocate and initialise a new IMAP_DATA structure.
146  *   Returns NULL on failure (no mem) */
147 IMAP_DATA *imap_new_idata (void)
148 {
149   IMAP_DATA *res = p_new(IMAP_DATA, 1);
150   buffer_init(&res->cmd.buf);
151   res->isnew = 1;
152   return res;
153 }
154
155 /* imap_free_idata: Release and clear storage in an IMAP_DATA structure. */
156 void imap_free_idata (IMAP_DATA ** idata)
157 {
158     if (*idata) {
159         p_delete(&(*idata)->capstr);
160         string_list_wipe(&(*idata)->flags);
161         buffer_wipe(&((*idata)->cmd.buf));
162         p_delete(idata);
163     }
164 }
165
166 /*
167  * Fix up the imap path.  This is necessary because the rest of mutt
168  * assumes a hierarchy delimiter of '/', which is not necessarily true
169  * in IMAP.  Additionally, the filesystem converts multiple hierarchy
170  * delimiters into a single one, ie "///" is equal to "/".  IMAP servers
171  * are not required to do this.
172  * Moreover, IMAP servers may dislike the path ending with the delimiter.
173  */
174 char *imap_fix_path (IMAP_DATA * idata, char *mailbox, char *path,
175                      ssize_t plen)
176 {
177   int x = 0;
178
179   if (!mailbox || !*mailbox) {
180     m_strcpy(path, plen, "INBOX");
181     return path;
182   }
183
184   while (mailbox && *mailbox && (x < (plen - 1))) {
185     if ((*mailbox == '/') || (*mailbox == idata->delim)) {
186       while ((*mailbox == '/') || (*mailbox == idata->delim))
187         mailbox++;
188       path[x] = idata->delim;
189     }
190     else {
191       path[x] = *mailbox;
192       mailbox++;
193     }
194     x++;
195   }
196   if (x && path[--x] != idata->delim)
197     x++;
198   path[x] = '\0';
199   return path;
200 }
201
202 /* imap_get_literal_count: write number of bytes in an IMAP literal into
203  *   bytes, return 0 on success, -1 on failure. */
204 int imap_get_literal_count (const char *buf, long *bytes)
205 {
206   char *pc;
207   char *pn;
208
209   if (!(pc = strchr (buf, '{')))
210     return (-1);
211   pc++;
212   pn = pc;
213   while (isdigit ((unsigned char) *pc))
214     pc++;
215   *pc = 0;
216   *bytes = atoi (pn);
217   return (0);
218 }
219
220 /* imap_get_qualifier: in a tagged response, skip tag and status for
221  *   the qualifier message. Used by imap_copy_message for TRYCREATE */
222 char *imap_get_qualifier (char *buf)
223 {
224   char *s = buf;
225
226   /* skip tag */
227   s = imap_next_word (s);
228   /* skip OK/NO/BAD response */
229   s = imap_next_word (s);
230
231   return s;
232 }
233
234 /* imap_next_word: return index into string where next IMAP word begins */
235 char *imap_next_word (char *s)
236 {
237   int quoted = 0;
238
239   while (*s) {
240     if (*s == '\\') {
241       s++;
242       if (*s)
243         s++;
244       continue;
245     }
246     if (*s == '\"')
247       quoted = quoted ? 0 : 1;
248     if (!quoted && ISSPACE (*s))
249       break;
250     s++;
251   }
252
253   return vskipspaces(s);
254 }
255
256 /* imap_parse_date: date is of the form: DD-MMM-YYYY HH:MM:SS +ZZzz */
257 time_t imap_parse_date (char *s)
258 {
259     struct tm tm;
260     const char *loc;
261
262     p_clear(&tm, 1);
263     loc = setlocale(LC_TIME, "C");
264     strptime(s, "%d-%b-%Y %T %z", &tm);
265     setlocale(LC_TIME, loc);
266     return mutt_mktime(&tm, 1);
267 }
268
269 /* imap_qualify_path: make an absolute IMAP folder target, given IMAP_MBOX
270  *   and relative path. */
271 void imap_qualify_path (char *dest, size_t len, IMAP_MBOX * mx, char *path)
272 {
273   ciss_url_t url;
274
275   mutt_account_tourl (&mx->account, &url);
276   url.path = path;
277
278   url_ciss_tostring (&url, dest, len, 0);
279 }
280
281
282 /* imap_quote_string: quote string according to IMAP rules:
283  *   surround string with quotes, escape " and \ with \ */
284 void imap_quote_string (char *dest, size_t dlen, const char *src)
285 {
286   char quote[] = "\"\\", *pt;
287   const char *s;
288
289   pt = dest;
290   s = src;
291
292   *pt++ = '"';
293   /* save room for trailing quote-char */
294   dlen -= 2;
295
296   for (; *s && dlen; s++) {
297     if (strchr (quote, *s)) {
298       dlen -= 2;
299       if (!dlen)
300         break;
301       *pt++ = '\\';
302       *pt++ = *s;
303     }
304     else {
305       *pt++ = *s;
306       dlen--;
307     }
308   }
309   *pt++ = '"';
310   *pt = 0;
311 }
312
313 /* imap_unquote_string: equally stupid unquoting routine */
314 void imap_unquote_string (char *s)
315 {
316   char *d = s;
317
318   if (*s == '\"')
319     s++;
320   else
321     return;
322
323   while (*s) {
324     if (*s == '\"') {
325       *d = '\0';
326       return;
327     }
328     if (*s == '\\') {
329       s++;
330     }
331     if (*s) {
332       *d = *s;
333       d++;
334       s++;
335     }
336   }
337   *d = '\0';
338 }
339
340 /*
341  * Quoting and UTF-7 conversion
342  */
343
344 void imap_munge_mbox_name (char *dest, size_t dlen, const char *src)
345 {
346   char *buf;
347
348   buf = m_strdup(src);
349   imap_utf7_encode (&buf);
350
351   imap_quote_string (dest, dlen, buf);
352
353   p_delete(&buf);
354 }
355
356 void imap_unmunge_mbox_name (char *s)
357 {
358   char *buf;
359
360   imap_unquote_string (s);
361
362   buf = m_strdup(s);
363   if (buf) {
364     imap_utf7_decode (&buf);
365     m_strcpy(s, m_strlen(s) + 1, buf);
366   }
367
368   p_delete(&buf);
369 }
370
371 /* imap_wordcasecmp: find word a in word list b */
372 int imap_wordcasecmp (const char *a, const char *b)
373 {
374   char tmp[STRING];
375   char *s = (char *) b;
376   int i;
377
378   tmp[STRING - 1] = 0;
379   for (i = 0; i < STRING - 2; i++, s++) {
380     if (!*s || ISSPACE (*s)) {
381       tmp[i] = 0;
382       break;
383     }
384     tmp[i] = *s;
385   }
386   tmp[i + 1] = 0;
387
388   return ascii_strcasecmp (a, tmp);
389 }
390
391 /* 
392  * Imap keepalive: poll the current folder to keep the
393  * connection alive.
394  * 
395  */
396
397 static void alrm_handler (int sig __attribute__((unused)))
398 {
399   /* empty */
400 }
401
402 void imap_keepalive (void)
403 {
404   CONNECTION *conn;
405   CONTEXT *ctx = NULL;
406   IMAP_DATA *idata;
407
408   conn = mutt_socket_head ();
409   while (conn) {
410     if (conn->account.type == M_ACCT_TYPE_IMAP) {
411       idata = (IMAP_DATA *) conn->data;
412
413       if (idata->state >= IMAP_AUTHENTICATED
414           && time (NULL) >= idata->lastread + ImapKeepalive) {
415         if (idata->ctx)
416           ctx = idata->ctx;
417         else {
418           ctx = p_new(CONTEXT, 1);
419           ctx->data = idata;
420         }
421         imap_check_mailbox (ctx, NULL, 1);
422         if (!idata->ctx)
423           p_delete(&ctx);
424       }
425     }
426
427     conn = conn->next;
428   }
429 }
430
431 int imap_wait_keepalive (pid_t pid)
432 {
433   struct sigaction oldalrm;
434   struct sigaction act;
435   sigset_t oldmask;
436   int rc;
437
438   short imap_passive = option (OPTIMAPPASSIVE);
439   int imap_askreconnect = quadoption (OPT_IMAPRECONNECT);
440
441   set_option (OPTIMAPPASSIVE);
442   set_option (OPTKEEPQUIET);
443   set_quadoption (OPT_IMAPRECONNECT, M_NO);
444
445   sigprocmask (SIG_SETMASK, NULL, &oldmask);
446
447   sigemptyset (&act.sa_mask);
448   act.sa_handler = alrm_handler;
449 #ifdef SA_INTERRUPT
450   act.sa_flags = SA_INTERRUPT;
451 #else
452   act.sa_flags = 0;
453 #endif
454
455   sigaction (SIGALRM, &act, &oldalrm);
456
457   alarm (ImapKeepalive);
458   while (waitpid (pid, &rc, 0) < 0 && errno == EINTR) {
459     alarm (0);                  /* cancel a possibly pending alarm */
460     imap_keepalive ();
461     alarm (ImapKeepalive);
462   }
463
464   alarm (0);                    /* cancel a possibly pending alarm */
465
466   sigaction (SIGALRM, &oldalrm, NULL);
467   sigprocmask (SIG_SETMASK, &oldmask, NULL);
468
469   unset_option (OPTKEEPQUIET);
470   if (!imap_passive)
471     unset_option (OPTIMAPPASSIVE);
472   set_quadoption (OPT_IMAPRECONNECT, imap_askreconnect);
473
474   return rc;
475 }
476
477 /* Allow/disallow re-opening a folder upon expunge. */
478
479 void imap_allow_reopen (CONTEXT * ctx)
480 {
481   if (ctx && ctx->magic == M_IMAP && CTX_DATA->ctx == ctx)
482     CTX_DATA->reopen |= IMAP_REOPEN_ALLOW;
483 }
484
485 void imap_disallow_reopen (CONTEXT * ctx)
486 {
487   if (ctx && ctx->magic == M_IMAP && CTX_DATA->ctx == ctx)
488     CTX_DATA->reopen &= ~IMAP_REOPEN_ALLOW;
489 }