Rocco Rutte:
[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 "config.h"
15
16 #include "mutt.h"
17 #include "mx.h"                 /* for M_IMAP */
18 #include "url.h"
19 #include "imap_private.h"
20 #include "mutt_ssl.h"
21
22 #include "lib/mem.h"
23 #include "lib/intl.h"
24 #include "lib/debug.h"
25
26 #include <stdlib.h>
27 #include <ctype.h>
28
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <signal.h>
32 #include <netdb.h>
33 #include <netinet/in.h>
34
35 #include <errno.h>
36
37 /* -- public functions -- */
38
39 /* imap_expand_path: IMAP implementation of mutt_expand_path. Rewrite
40  *   an IMAP path in canonical and absolute form.
41  * Inputs: a buffer containing an IMAP path, and the number of bytes in
42  *   that buffer.
43  * Outputs: The buffer is rewritten in place with the canonical IMAP path.
44  * Returns 0 on success, or -1 if imap_parse_path chokes or url_ciss_tostring
45  *   fails, which it might if there isn't enough room in the buffer. */
46 int imap_expand_path (char *path, size_t len)
47 {
48   IMAP_MBOX mx;
49   ciss_url_t url;
50   int rc;
51
52   if (imap_parse_path (path, &mx) < 0)
53     return -1;
54
55   mutt_account_tourl (&mx.account, &url);
56   url.path = mx.mbox;
57
58   rc = url_ciss_tostring (&url, path, len, U_DECODE_PASSWD);
59   mem_free (&mx.mbox);
60
61   return rc;
62 }
63
64 /* imap_parse_path: given an IMAP mailbox name, return host, port
65  *   and a path IMAP servers will recognise.
66  * mx.mbox is malloc'd, caller must free it */
67 int imap_parse_path (const char *path, IMAP_MBOX * mx)
68 {
69   static unsigned short ImapPort = 0;
70   static unsigned short ImapsPort = 0;
71   struct servent *service;
72   ciss_url_t url;
73   char *c;
74
75   if (!ImapPort) {
76     service = getservbyname ("imap", "tcp");
77     if (service)
78       ImapPort = ntohs (service->s_port);
79     else
80       ImapPort = IMAP_PORT;
81     debug_print (3, ("Using default IMAP port %d\n", ImapPort));
82   }
83   if (!ImapsPort) {
84     service = getservbyname ("imaps", "tcp");
85     if (service)
86       ImapsPort = ntohs (service->s_port);
87     else
88       ImapsPort = IMAP_SSL_PORT;
89     debug_print (3, ("Using default IMAPS port %d\n", ImapsPort));
90   }
91
92   /* Defaults */
93   mx->account.flags = 0;
94   mx->account.port = ImapPort;
95   mx->account.type = M_ACCT_TYPE_IMAP;
96
97   c = str_dup (path);
98   url_parse_ciss (&url, c);
99
100   if (!(url.scheme == U_IMAP || url.scheme == U_IMAPS) ||
101       mutt_account_fromurl (&mx->account, &url) < 0) {
102     mem_free (&c);
103     return -1;
104   }
105
106   mx->mbox = str_dup (url.path);
107
108   if (url.scheme == U_IMAPS)
109     mx->account.flags |= M_ACCT_SSL;
110
111   mem_free (&c);
112
113   if ((mx->account.flags & M_ACCT_SSL) && !(mx->account.flags & M_ACCT_PORT))
114     mx->account.port = ImapsPort;
115
116   return 0;
117 }
118
119 /* imap_pretty_mailbox: called by mutt_pretty_mailbox to make IMAP paths
120  *   look nice. */
121 void imap_pretty_mailbox (char *path)
122 {
123   IMAP_MBOX home, target;
124   ciss_url_t url;
125   char *delim;
126   int tlen;
127   int hlen = 0;
128   char home_match = 0;
129
130   if (imap_parse_path (path, &target) < 0)
131     return;
132
133   tlen = str_len (target.mbox);
134   /* check whether we can do '=' substitution */
135   if (mx_get_magic (Maildir) == M_IMAP && !imap_parse_path (Maildir, &home)) {
136     hlen = str_len (home.mbox);
137     if (tlen && mutt_account_match (&home.account, &target.account) &&
138         !str_ncmp (home.mbox, target.mbox, hlen)) {
139       if (!hlen)
140         home_match = 1;
141       else
142         for (delim = ImapDelimChars; *delim != '\0'; delim++)
143           if (target.mbox[hlen] == *delim)
144             home_match = 1;
145     }
146     mem_free (&home.mbox);
147   }
148
149   /* do the '=' substitution */
150   if (home_match) {
151     *path++ = '=';
152     /* copy remaining path, skipping delimiter */
153     if (!hlen)
154       hlen = -1;
155     memcpy (path, target.mbox + hlen + 1, tlen - hlen - 1);
156     path[tlen - hlen - 1] = '\0';
157   }
158   else {
159     mutt_account_tourl (&target.account, &url);
160     url.path = target.mbox;
161     /* FIXME: That hard-coded constant is bogus. But we need the actual
162      *   size of the buffer from mutt_pretty_mailbox. And these pretty
163      *   operations usually shrink the result. Still... */
164     url_ciss_tostring (&url, path, 1024, 0);
165   }
166
167   mem_free (&target.mbox);
168 }
169
170 /* -- library functions -- */
171
172 /* imap_continue: display a message and ask the user if she wants to
173  *   go on. */
174 int imap_continue (const char *msg, const char *resp)
175 {
176   imap_error (msg, resp);
177   return mutt_yesorno (_("Continue?"), 0);
178 }
179
180 /* imap_error: show an error and abort */
181 void imap_error (const char *where, const char *msg)
182 {
183   mutt_error ("%s [%s]\n", where, msg);
184   mutt_sleep (2);
185 }
186
187 /* imap_new_idata: Allocate and initialise a new IMAP_DATA structure.
188  *   Returns NULL on failure (no mem) */
189 IMAP_DATA *imap_new_idata (void)
190 {
191   return mem_calloc (1, sizeof (IMAP_DATA));
192 }
193
194 /* imap_free_idata: Release and clear storage in an IMAP_DATA structure. */
195 void imap_free_idata (IMAP_DATA ** idata)
196 {
197   if (!idata)
198     return;
199
200   mem_free (&(*idata)->capstr);
201   mutt_free_list (&(*idata)->flags);
202   mem_free (&((*idata)->cmd.buf));
203   mem_free (idata);
204 }
205
206 /*
207  * Fix up the imap path.  This is necessary because the rest of mutt
208  * assumes a hierarchy delimiter of '/', which is not necessarily true
209  * in IMAP.  Additionally, the filesystem converts multiple hierarchy
210  * delimiters into a single one, ie "///" is equal to "/".  IMAP servers
211  * are not required to do this.
212  * Moreover, IMAP servers may dislike the path ending with the delimiter.
213  */
214 char *imap_fix_path (IMAP_DATA * idata, char *mailbox, char *path,
215                      size_t plen)
216 {
217   int x = 0;
218
219   if (!mailbox || !*mailbox) {
220     strfcpy (path, "INBOX", plen);
221     return path;
222   }
223
224   while (mailbox && *mailbox && (x < (plen - 1))) {
225     if ((*mailbox == '/') || (*mailbox == idata->delim)) {
226       while ((*mailbox == '/') || (*mailbox == idata->delim))
227         mailbox++;
228       path[x] = idata->delim;
229     }
230     else {
231       path[x] = *mailbox;
232       mailbox++;
233     }
234     x++;
235   }
236   if (x && path[--x] != idata->delim)
237     x++;
238   path[x] = '\0';
239   return path;
240 }
241
242 /* imap_get_literal_count: write number of bytes in an IMAP literal into
243  *   bytes, return 0 on success, -1 on failure. */
244 int imap_get_literal_count (const char *buf, long *bytes)
245 {
246   char *pc;
247   char *pn;
248
249   if (!(pc = strchr (buf, '{')))
250     return (-1);
251   pc++;
252   pn = pc;
253   while (isdigit ((unsigned char) *pc))
254     pc++;
255   *pc = 0;
256   *bytes = atoi (pn);
257   return (0);
258 }
259
260 /* imap_get_qualifier: in a tagged response, skip tag and status for
261  *   the qualifier message. Used by imap_copy_message for TRYCREATE */
262 char *imap_get_qualifier (char *buf)
263 {
264   char *s = buf;
265
266   /* skip tag */
267   s = imap_next_word (s);
268   /* skip OK/NO/BAD response */
269   s = imap_next_word (s);
270
271   return s;
272 }
273
274 /* imap_next_word: return index into string where next IMAP word begins */
275 char *imap_next_word (char *s)
276 {
277   int quoted = 0;
278
279   while (*s) {
280     if (*s == '\\') {
281       s++;
282       if (*s)
283         s++;
284       continue;
285     }
286     if (*s == '\"')
287       quoted = quoted ? 0 : 1;
288     if (!quoted && ISSPACE (*s))
289       break;
290     s++;
291   }
292
293   SKIPWS (s);
294   return s;
295 }
296
297 /* imap_parse_date: date is of the form: DD-MMM-YYYY HH:MM:SS +ZZzz */
298 time_t imap_parse_date (char *s)
299 {
300   struct tm t;
301   time_t tz;
302
303   t.tm_mday = (s[0] == ' ' ? s[1] - '0' : (s[0] - '0') * 10 + (s[1] - '0'));
304   s += 2;
305   if (*s != '-')
306     return 0;
307   s++;
308   t.tm_mon = mutt_check_month (s);
309   s += 3;
310   if (*s != '-')
311     return 0;
312   s++;
313   t.tm_year =
314     (s[0] - '0') * 1000 + (s[1] - '0') * 100 + (s[2] - '0') * 10 + (s[3] -
315                                                                     '0') -
316     1900;
317   s += 4;
318   if (*s != ' ')
319     return 0;
320   s++;
321
322   /* time */
323   t.tm_hour = (s[0] - '0') * 10 + (s[1] - '0');
324   s += 2;
325   if (*s != ':')
326     return 0;
327   s++;
328   t.tm_min = (s[0] - '0') * 10 + (s[1] - '0');
329   s += 2;
330   if (*s != ':')
331     return 0;
332   s++;
333   t.tm_sec = (s[0] - '0') * 10 + (s[1] - '0');
334   s += 2;
335   if (*s != ' ')
336     return 0;
337   s++;
338
339   /* timezone */
340   tz = ((s[1] - '0') * 10 + (s[2] - '0')) * 3600 +
341     ((s[3] - '0') * 10 + (s[4] - '0')) * 60;
342   if (s[0] == '+')
343     tz = -tz;
344
345   return (mutt_mktime (&t, 0) + tz);
346 }
347
348 /* imap_qualify_path: make an absolute IMAP folder target, given IMAP_MBOX
349  *   and relative path. */
350 void imap_qualify_path (char *dest, size_t len, IMAP_MBOX * mx, char *path)
351 {
352   ciss_url_t url;
353
354   mutt_account_tourl (&mx->account, &url);
355   url.path = path;
356
357   url_ciss_tostring (&url, dest, len, 0);
358 }
359
360
361 /* imap_quote_string: quote string according to IMAP rules:
362  *   surround string with quotes, escape " and \ with \ */
363 void imap_quote_string (char *dest, size_t dlen, const char *src)
364 {
365   char quote[] = "\"\\", *pt;
366   const char *s;
367
368   pt = dest;
369   s = src;
370
371   *pt++ = '"';
372   /* save room for trailing quote-char */
373   dlen -= 2;
374
375   for (; *s && dlen; s++) {
376     if (strchr (quote, *s)) {
377       dlen -= 2;
378       if (!dlen)
379         break;
380       *pt++ = '\\';
381       *pt++ = *s;
382     }
383     else {
384       *pt++ = *s;
385       dlen--;
386     }
387   }
388   *pt++ = '"';
389   *pt = 0;
390 }
391
392 /* imap_unquote_string: equally stupid unquoting routine */
393 void imap_unquote_string (char *s)
394 {
395   char *d = s;
396
397   if (*s == '\"')
398     s++;
399   else
400     return;
401
402   while (*s) {
403     if (*s == '\"') {
404       *d = '\0';
405       return;
406     }
407     if (*s == '\\') {
408       s++;
409     }
410     if (*s) {
411       *d = *s;
412       d++;
413       s++;
414     }
415   }
416   *d = '\0';
417 }
418
419 /*
420  * Quoting and UTF-7 conversion
421  */
422
423 void imap_munge_mbox_name (char *dest, size_t dlen, const char *src)
424 {
425   char *buf;
426
427   buf = str_dup (src);
428   imap_utf7_encode (&buf);
429
430   imap_quote_string (dest, dlen, buf);
431
432   mem_free (&buf);
433 }
434
435 void imap_unmunge_mbox_name (char *s)
436 {
437   char *buf;
438
439   imap_unquote_string (s);
440
441   buf = str_dup (s);
442   if (buf) {
443     imap_utf7_decode (&buf);
444     strncpy (s, buf, str_len (s));
445   }
446
447   mem_free (&buf);
448 }
449
450 /* imap_wordcasecmp: find word a in word list b */
451 int imap_wordcasecmp (const char *a, const char *b)
452 {
453   char tmp[SHORT_STRING];
454   char *s = (char *) b;
455   int i;
456
457   tmp[SHORT_STRING - 1] = 0;
458   for (i = 0; i < SHORT_STRING - 2; i++, s++) {
459     if (!*s || ISSPACE (*s)) {
460       tmp[i] = 0;
461       break;
462     }
463     tmp[i] = *s;
464   }
465   tmp[i + 1] = 0;
466
467   return ascii_strcasecmp (a, tmp);
468 }
469
470 /* 
471  * Imap keepalive: poll the current folder to keep the
472  * connection alive.
473  * 
474  */
475
476 static RETSIGTYPE alrm_handler (int sig)
477 {
478   /* empty */
479 }
480
481 void imap_keepalive (void)
482 {
483   CONNECTION *conn;
484   CONTEXT *ctx = NULL;
485   IMAP_DATA *idata;
486
487   conn = mutt_socket_head ();
488   while (conn) {
489     if (conn->account.type == M_ACCT_TYPE_IMAP) {
490       idata = (IMAP_DATA *) conn->data;
491
492       if (idata->state >= IMAP_AUTHENTICATED
493           && time (NULL) >= idata->lastread + ImapKeepalive) {
494         if (idata->ctx)
495           ctx = idata->ctx;
496         else {
497           ctx = mem_calloc (1, sizeof (CONTEXT));
498           ctx->data = idata;
499         }
500         imap_check_mailbox (ctx, NULL, 1);
501         if (!idata->ctx)
502           mem_free (&ctx);
503       }
504     }
505
506     conn = conn->next;
507   }
508 }
509
510 int imap_wait_keepalive (pid_t pid)
511 {
512   struct sigaction oldalrm;
513   struct sigaction act;
514   sigset_t oldmask;
515   int rc;
516
517   short imap_passive = option (OPTIMAPPASSIVE);
518
519   set_option (OPTIMAPPASSIVE);
520   set_option (OPTKEEPQUIET);
521
522   sigprocmask (SIG_SETMASK, NULL, &oldmask);
523
524   sigemptyset (&act.sa_mask);
525   act.sa_handler = alrm_handler;
526 #ifdef SA_INTERRUPT
527   act.sa_flags = SA_INTERRUPT;
528 #else
529   act.sa_flags = 0;
530 #endif
531
532   sigaction (SIGALRM, &act, &oldalrm);
533
534   alarm (ImapKeepalive);
535   while (waitpid (pid, &rc, 0) < 0 && errno == EINTR) {
536     alarm (0);                  /* cancel a possibly pending alarm */
537     imap_keepalive ();
538     alarm (ImapKeepalive);
539   }
540
541   alarm (0);                    /* cancel a possibly pending alarm */
542
543   sigaction (SIGALRM, &oldalrm, NULL);
544   sigprocmask (SIG_SETMASK, &oldmask, NULL);
545
546   unset_option (OPTKEEPQUIET);
547   if (!imap_passive)
548     unset_option (OPTIMAPPASSIVE);
549
550   return rc;
551 }
552
553 /* Allow/disallow re-opening a folder upon expunge. */
554
555 void imap_allow_reopen (CONTEXT * ctx)
556 {
557   if (ctx && ctx->magic == M_IMAP && CTX_DATA->ctx == ctx)
558     CTX_DATA->reopen |= IMAP_REOPEN_ALLOW;
559 }
560
561 void imap_disallow_reopen (CONTEXT * ctx)
562 {
563   if (ctx && ctx->magic == M_IMAP && CTX_DATA->ctx == ctx)
564     CTX_DATA->reopen &= ~IMAP_REOPEN_ALLOW;
565 }