use a proper "hack" for iconv functions:
[apps/madmutt.git] / charset.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9
10 #if HAVE_CONFIG_H
11 # include "config.h"
12 #endif
13
14 #include <string.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17
18 #include <ctype.h>
19
20 #include <sys/types.h>
21 #include <dirent.h>
22 #include <unistd.h>
23 #include <errno.h>
24
25 #include "mutt.h"
26 #include "charset.h"
27 #include "ascii.h"
28
29 #include "lib/mem.h"
30 #include "lib/intl.h"
31 #include "lib/str.h"
32
33 #ifndef EILSEQ
34 # define EILSEQ EINVAL
35 #endif
36
37 /* 
38  * The following list has been created manually from the data under:
39  * http://www.isi.edu/in-notes/iana/assignments/character-sets
40  * Last update: 2000-09-07
41  *
42  * Note that it includes only the subset of character sets for which
43  * a preferred MIME name is given.
44  */
45
46 static struct {
47   const char *key;
48   const char *pref;
49 } PreferredMIMENames[] = {
50   {
51   "ansi_x3.4-1968", "us-ascii"}, {
52   "iso-ir-6", "us-ascii"}, {
53   "iso_646.irv:1991", "us-ascii"}, {
54   "ascii", "us-ascii"}, {
55   "iso646-us", "us-ascii"}, {
56   "us", "us-ascii"}, {
57   "ibm367", "us-ascii"}, {
58   "cp367", "us-ascii"}, {
59   "csASCII", "us-ascii"}, {
60   "csISO2022KR", "iso-2022-kr"}, {
61   "csEUCKR", "euc-kr"}, {
62   "csISO2022JP", "iso-2022-jp"}, {
63   "csISO2022JP2", "iso-2022-jp-2"}, {
64   "ISO_8859-1:1987", "iso-8859-1"}, {
65   "iso-ir-100", "iso-8859-1"}, {
66   "iso_8859-1", "iso-8859-1"}, {
67   "latin1", "iso-8859-1"}, {
68   "l1", "iso-8859-1"}, {
69   "IBM819", "iso-8859-1"}, {
70   "CP819", "iso-8859-1"}, {
71   "csISOLatin1", "iso-8859-1"}, {
72   "ISO_8859-2:1987", "iso-8859-2"}, {
73   "iso-ir-101", "iso-8859-2"}, {
74   "iso_8859-2", "iso-8859-2"}, {
75   "latin2", "iso-8859-2"}, {
76   "l2", "iso-8859-2"}, {
77   "csISOLatin2", "iso-8859-2"}, {
78   "ISO_8859-3:1988", "iso-8859-3"}, {
79   "iso-ir-109", "iso-8859-3"}, {
80   "ISO_8859-3", "iso-8859-3"}, {
81   "latin3", "iso-8859-3"}, {
82   "l3", "iso-8859-3"}, {
83   "csISOLatin3", "iso-8859-3"}, {
84   "ISO_8859-4:1988", "iso-8859-4"}, {
85   "iso-ir-110", "iso-8859-4"}, {
86   "ISO_8859-4", "iso-8859-4"}, {
87   "latin4", "iso-8859-4"}, {
88   "l4", "iso-8859-4"}, {
89   "csISOLatin4", "iso-8859-4"}, {
90   "ISO_8859-6:1987", "iso-8859-6"}, {
91   "iso-ir-127", "iso-8859-6"}, {
92   "iso_8859-6", "iso-8859-6"}, {
93   "ECMA-114", "iso-8859-6"}, {
94   "ASMO-708", "iso-8859-6"}, {
95   "arabic", "iso-8859-6"}, {
96   "csISOLatinArabic", "iso-8859-6"}, {
97   "ISO_8859-7:1987", "iso-8859-7"}, {
98   "iso-ir-126", "iso-8859-7"}, {
99   "ISO_8859-7", "iso-8859-7"}, {
100   "ELOT_928", "iso-8859-7"}, {
101   "ECMA-118", "iso-8859-7"}, {
102   "greek", "iso-8859-7"}, {
103   "greek8", "iso-8859-7"}, {
104   "csISOLatinGreek", "iso-8859-7"}, {
105   "ISO_8859-8:1988", "iso-8859-8"}, {
106   "iso-ir-138", "iso-8859-8"}, {
107   "ISO_8859-8", "iso-8859-8"}, {
108   "hebrew", "iso-8859-8"}, {
109   "csISOLatinHebrew", "iso-8859-8"}, {
110   "ISO_8859-5:1988", "iso-8859-5"}, {
111   "iso-ir-144", "iso-8859-5"}, {
112   "ISO_8859-5", "iso-8859-5"}, {
113   "cyrillic", "iso-8859-5"}, {
114   "csISOLatinCyrillic", "iso8859-5"}, {
115   "ISO_8859-9:1989", "iso-8859-9"}, {
116   "iso-ir-148", "iso-8859-9"}, {
117   "ISO_8859-9", "iso-8859-9"}, {
118   "latin5", "iso-8859-9"},      /* this is not a bug */
119   {
120   "l5", "iso-8859-9"}, {
121   "csISOLatin5", "iso-8859-9"}, {
122   "ISO_8859-10:1992", "iso-8859-10"}, {
123   "iso-ir-157", "iso-8859-10"}, {
124   "latin6", "iso-8859-10"},     /* this is not a bug */
125   {
126   "l6", "iso-8859-10"}, {
127   "csISOLatin6", "iso-8859-10"}, {
128   "csKOI8r", "koi8-r"}, {
129   "MS_Kanji", "Shift_JIS"},     /* Note the underscore! */
130   {
131   "csShiftJis", "Shift_JIS"}, {
132   "Extended_UNIX_Code_Packed_Format_for_Japanese", "EUC-JP"}, {
133   "csEUCPkdFmtJapanese", "EUC-JP"}, {
134   "csGB2312", "gb2312"}, {
135   "csbig5", "big5"},
136     /* 
137      * End of official brain damage.  What follows has been taken
138      * from glibc's localedata files. 
139      */
140   {
141   "iso_8859-13", "iso-8859-13"}, {
142   "iso-ir-179", "iso-8859-13"}, {
143   "latin7", "iso-8859-13"},     /* this is not a bug */
144   {
145   "l7", "iso-8859-13"}, {
146   "iso_8859-14", "iso-8859-14"}, {
147   "latin8", "iso-8859-14"},     /* this is not a bug */
148   {
149   "l8", "iso-8859-14"}, {
150   "iso_8859-15", "iso-8859-15"}, {
151   "latin9", "iso-8859-15"},     /* this is not a bug */
152     /* Suggested by Ionel Mugurel Ciobica <tgakic@sg10.chem.tue.nl> */
153   {
154   "latin0", "iso-8859-15"},     /* this is not a bug */
155   {
156   "iso_8859-16", "iso-8859-16"}, {
157   "latin10", "iso-8859-16"},    /* this is not a bug */
158     /* 
159      * David Champion <dgc@uchicago.edu> has observed this with
160      * nl_langinfo under SunOS 5.8. 
161      */
162   {
163   "646", "us-ascii"},
164     /* 
165      * http://www.sun.com/software/white-papers/wp-unicode/
166      */
167   {
168   "eucJP", "euc-jp"}, {
169   "PCK", "Shift_JIS"}, {
170   "ko_KR-euc", "euc-kr"}, {
171   "zh_TW-big5", "big5"},
172     /* seems to be common on some systems */
173   {
174   "sjis", "Shift_JIS"}, {
175   "euc-jp-ms", "eucJP-ms"},
176     /*
177      * If you happen to encounter system-specific brain-damage with
178      * respect to character set naming, please add it above this
179      * comment, and submit a patch to <mutt-dev@mutt.org>. 
180      */
181     /* End of aliases.  Please keep this line last. */
182   {
183   NULL, NULL}
184 };
185
186 #ifdef HAVE_LANGINFO_CODESET
187 # include <langinfo.h>
188
189
190 void mutt_set_langinfo_charset (void)
191 {
192   char buff[LONG_STRING];
193   char buff2[LONG_STRING];
194
195   strfcpy (buff, nl_langinfo (CODESET), sizeof (buff));
196   mutt_canonical_charset (buff2, sizeof (buff2), buff);
197
198   /* finally, set $charset */
199   if (!(Charset = str_dup (buff2)))
200     Charset = str_dup ("iso-8859-1");
201 }
202
203 #else
204
205 void mutt_set_langinfo_charset (void)
206 {
207   Charset = str_dup ("iso-8859-1");
208 }
209
210 #endif
211
212 void mutt_canonical_charset (char *dest, size_t dlen, const char *name)
213 {
214   size_t i;
215   char *p;
216   char scratch[LONG_STRING];
217
218   /* catch some common iso-8859-something misspellings */
219   if (!ascii_strncasecmp (name, "8859", 4) && name[4] != '-')
220     snprintf (scratch, sizeof (scratch), "iso-8859-%s", name + 4);
221   else if (!ascii_strncasecmp (name, "8859-", 5))
222     snprintf (scratch, sizeof (scratch), "iso-8859-%s", name + 5);
223   else if (!ascii_strncasecmp (name, "iso8859", 7) && name[7] != '-')
224     snprintf (scratch, sizeof (scratch), "iso_8859-%s", name + 7);
225   else if (!ascii_strncasecmp (name, "iso8859-", 8))
226     snprintf (scratch, sizeof (scratch), "iso_8859-%s", name + 8);
227   else
228     strfcpy (scratch, NONULL (name), sizeof (scratch));
229
230   for (i = 0; PreferredMIMENames[i].key; i++)
231     if (!ascii_strcasecmp (scratch, PreferredMIMENames[i].key) ||
232         !str_casecmp (scratch, PreferredMIMENames[i].key)) {
233       strfcpy (dest, PreferredMIMENames[i].pref, dlen);
234       return;
235     }
236
237   strfcpy (dest, scratch, dlen);
238
239   /* for cosmetics' sake, transform to lowercase. */
240   for (p = dest; *p; p++)
241     *p = ascii_tolower (*p);
242 }
243
244 int mutt_chscmp (const char *s, const char *chs)
245 {
246   char buffer[STRING];
247
248   if (!s)
249     return 0;
250
251   mutt_canonical_charset (buffer, sizeof (buffer), s);
252   return !ascii_strcasecmp (buffer, chs);
253 }
254
255
256 /*
257  * Like iconv_open, but canonicalises the charsets
258  */
259
260 iconv_t mutt_iconv_open (const char *tocode, const char *fromcode, int flags)
261 {
262   char tocode1[SHORT_STRING];
263   char fromcode1[SHORT_STRING];
264   char *tocode2, *fromcode2;
265   char *tmp;
266
267   iconv_t cd;
268
269   mutt_canonical_charset (tocode1, sizeof (tocode1), tocode);
270
271 #ifdef M_ICONV_HOOK_TO
272   /* Not used. */
273   if ((flags & M_ICONV_HOOK_TO) && (tmp = mutt_charset_hook (tocode1)))
274     mutt_canonical_charset (tocode1, sizeof (tocode1), tmp);
275 #endif
276
277   mutt_canonical_charset (fromcode1, sizeof (fromcode1), fromcode);
278   if ((flags & M_ICONV_HOOK_FROM) && (tmp = mutt_charset_hook (fromcode1)))
279     mutt_canonical_charset (fromcode1, sizeof (fromcode1), tmp);
280
281   if ((cd = iconv_open (tocode1, fromcode1)) != (iconv_t) - 1)
282     return cd;
283   if ((tocode2 = mutt_iconv_hook (tocode1))
284       && (fromcode2 = mutt_iconv_hook (fromcode1)))
285     return iconv_open (tocode2, fromcode2);
286
287   return (iconv_t) - 1;
288 }
289
290
291 /*
292  * Like iconv, but keeps going even when the input is invalid
293  * If you're supplying inrepls, the source charset should be stateless;
294  * if you're supplying an outrepl, the target charset should be.
295  */
296
297 size_t mutt_iconv (iconv_t cd, const char **inbuf, size_t * inbytesleft,
298                    char **outbuf, size_t * outbytesleft,
299                    const char **inrepls, const char *outrepl)
300 {
301   size_t ret = 0, ret1;
302   const char *ib = *inbuf;
303   size_t ibl = *inbytesleft;
304   char *ob = *outbuf;
305   size_t obl = *outbytesleft;
306
307   for (;;) {
308     ret1 = my_iconv(cd, &ib, &ibl, &ob, &obl);
309     if (ret1 != (size_t) - 1)
310       ret += ret1;
311     if (ibl && obl && errno == EILSEQ) {
312       if (inrepls) {
313         /* Try replacing the input */
314         const char **t;
315
316         for (t = inrepls; *t; t++) {
317           const char *ib1 = *t;
318           size_t ibl1 = str_len (*t);
319           char *ob1 = ob;
320           size_t obl1 = obl;
321
322           my_iconv(cd, &ib1, &ibl1, &ob1, &obl1);
323           if (!ibl1) {
324             ++ib, --ibl;
325             ob = ob1, obl = obl1;
326             ++ret;
327             break;
328           }
329         }
330         if (*t)
331           continue;
332       }
333       /* Replace the output */
334       if (!outrepl)
335         outrepl = "?";
336       my_iconv(cd, 0, 0, &ob, &obl);
337       if (obl) {
338         int n = str_len (outrepl);
339
340         if (n > obl) {
341           outrepl = "?";
342           n = 1;
343         }
344         memcpy (ob, outrepl, n);
345         ++ib, --ibl;
346         ob += n, obl -= n;
347         ++ret;
348         my_iconv(cd, 0, 0, 0, 0); /* for good measure */
349         continue;
350       }
351     }
352     *inbuf = ib, *inbytesleft = ibl;
353     *outbuf = ob, *outbytesleft = obl;
354     return ret;
355   }
356 }
357
358
359 /*
360  * Convert a string
361  * Used in rfc2047.c and rfc2231.c
362  */
363
364 int mutt_convert_string (char **ps, const char *from, const char *to,
365                          int flags)
366 {
367   iconv_t cd;
368   const char *repls[] = { "\357\277\275", "?", 0 };
369   char *s = *ps;
370
371   if (!s || !*s)
372     return 0;
373
374   if (to && from && (cd = mutt_iconv_open (to, from, flags)) != (iconv_t) - 1) {
375     int len;
376     const char *ib;
377     char *buf, *ob;
378     size_t ibl, obl;
379     const char **inrepls = NULL;
380     const char *outrepl = NULL;
381
382     if (mutt_is_utf8 (to))
383       outrepl = "\357\277\275";
384     else if (mutt_is_utf8 (from))
385       inrepls = repls;
386     else
387       outrepl = "?";
388
389     len = str_len (s);
390     ib = s, ibl = len + 1;
391     obl = MB_LEN_MAX * ibl;
392     ob = buf = mem_malloc (obl + 1);
393
394     mutt_iconv (cd, &ib, &ibl, &ob, &obl, inrepls, outrepl);
395     iconv_close (cd);
396
397     *ob = '\0';
398
399     mem_free (ps);
400     *ps = buf;
401
402     str_adjust (ps);
403     return 0;
404   }
405   else
406     return -1;
407 }
408
409
410 /*
411  * FGETCONV stuff for converting a file while reading it
412  * Used in sendlib.c for converting from mutt's Charset
413  */
414
415 struct fgetconv_s {
416   FILE *file;
417   iconv_t cd;
418   char bufi[512];
419   char bufo[512];
420   char *p;
421   char *ob;
422   char *ib;
423   size_t ibl;
424   const char **inrepls;
425 };
426
427 struct fgetconv_not {
428   FILE *file;
429   iconv_t cd;
430 };
431
432 FGETCONV *fgetconv_open (FILE * file, const char *from, const char *to,
433                          int flags)
434 {
435   struct fgetconv_s *fc;
436   iconv_t cd = (iconv_t) - 1;
437   static const char *repls[] = { "\357\277\275", "?", 0 };
438
439   if (from && to)
440     cd = mutt_iconv_open (to, from, flags);
441
442   if (cd != (iconv_t) - 1) {
443     fc = mem_malloc (sizeof (struct fgetconv_s));
444     fc->p = fc->ob = fc->bufo;
445     fc->ib = fc->bufi;
446     fc->ibl = 0;
447     fc->inrepls = mutt_is_utf8 (to) ? repls : repls + 1;
448   }
449   else
450     fc = mem_malloc (sizeof (struct fgetconv_not));
451   fc->file = file;
452   fc->cd = cd;
453   return (FGETCONV *) fc;
454 }
455
456 char *fgetconvs (char *buf, size_t l, FGETCONV * _fc)
457 {
458   int c;
459   size_t r;
460
461   for (r = 0; r + 1 < l;) {
462     if ((c = fgetconv (_fc)) == EOF)
463       break;
464     buf[r++] = (char) c;
465     if (c == '\n')
466       break;
467   }
468   buf[r] = '\0';
469
470   if (r)
471     return buf;
472   else
473     return NULL;
474 }
475
476 int fgetconv (FGETCONV * _fc)
477 {
478   struct fgetconv_s *fc = (struct fgetconv_s *) _fc;
479
480   if (!fc)
481     return EOF;
482   if (fc->cd == (iconv_t) - 1)
483     return fgetc (fc->file);
484   if (!fc->p)
485     return EOF;
486   if (fc->p < fc->ob)
487     return (unsigned char) *(fc->p)++;
488
489   /* Try to convert some more */
490   fc->p = fc->ob = fc->bufo;
491   if (fc->ibl) {
492     size_t obl = sizeof (fc->bufo);
493
494     my_iconv(fc->cd, (const char **) &fc->ib, &fc->ibl, &fc->ob, &obl);
495     if (fc->p < fc->ob)
496       return (unsigned char) *(fc->p)++;
497   }
498
499   /* If we trusted iconv a bit more, we would at this point
500    * ask why it had stopped converting ... */
501
502   /* Try to read some more */
503   if (fc->ibl == sizeof (fc->bufi) ||
504       (fc->ibl && fc->ib + fc->ibl < fc->bufi + sizeof (fc->bufi))) {
505     fc->p = 0;
506     return EOF;
507   }
508   if (fc->ibl)
509     memcpy (fc->bufi, fc->ib, fc->ibl);
510   fc->ib = fc->bufi;
511   fc->ibl +=
512     fread (fc->ib + fc->ibl, 1, sizeof (fc->bufi) - fc->ibl, fc->file);
513
514   /* Try harder this time to convert some */
515   if (fc->ibl) {
516     size_t obl = sizeof (fc->bufo);
517
518     mutt_iconv (fc->cd, (const char **) &fc->ib, &fc->ibl, &fc->ob,
519                 &obl, fc->inrepls, 0);
520     if (fc->p < fc->ob)
521       return (unsigned char) *(fc->p)++;
522   }
523
524   /* Either the file has finished or one of the buffers is too small */
525   fc->p = 0;
526   return EOF;
527 }
528
529 void fgetconv_close (FGETCONV ** _fc)
530 {
531   struct fgetconv_s *fc = (struct fgetconv_s *) *_fc;
532
533   if (fc->cd != (iconv_t) - 1)
534     iconv_close (fc->cd);
535   mem_free (_fc);
536 }
537
538 const char *mutt_get_first_charset (const char *charset)
539 {
540   static char fcharset[SHORT_STRING];
541   const char *c, *c1;
542
543   c = charset;
544   if (!str_len (c))
545     return "us-ascii";
546   if (!(c1 = strchr (c, ':')))
547     return ((char*) charset);
548   strfcpy (fcharset, c, c1 - c + 1);
549   return fcharset;
550 }
551
552 static size_t convert_string (const char *f, size_t flen,
553                               const char *from, const char *to,
554                               char **t, size_t * tlen)
555 {
556   iconv_t cd;
557   char *buf, *ob;
558   size_t obl, n;
559   int e;
560
561   cd = mutt_iconv_open (to, from, 0);
562   if (cd == (iconv_t) (-1))
563     return (size_t) (-1);
564   obl = 4 * flen + 1;
565   ob = buf = mem_malloc (obl);
566   n = my_iconv(cd, &f, &flen, &ob, &obl);
567   if (n == (size_t) (-1) || my_iconv(cd, 0, 0, &ob, &obl) == (size_t) (-1)) {
568     e = errno;
569     mem_free (&buf);
570     iconv_close (cd);
571     errno = e;
572     return (size_t) (-1);
573   }
574   *ob = '\0';
575
576   *tlen = ob - buf;
577
578   mem_realloc (&buf, ob - buf + 1);
579   *t = buf;
580   iconv_close (cd);
581
582   return n;
583 }
584
585 int mutt_convert_nonmime_string (char **ps)
586 {
587   const char *c, *c1;
588
589   for (c = AssumedCharset; c; c = c1 ? c1 + 1 : 0) {
590     char *u = *ps;
591     char *s = NULL;
592     char *fromcode;
593     size_t m, n;
594     size_t ulen = str_len (*ps);
595     size_t slen;
596
597     if (!u || !*u)
598       return 0;
599
600     c1 = strchr (c, ':');
601     n = c1 ? c1 - c : str_len (c);
602     if (!n)
603       continue;
604     fromcode = mem_malloc (n + 1);
605     strfcpy (fromcode, c, n + 1);
606     m = convert_string (u, ulen, fromcode, Charset, &s, &slen);
607     mem_free (&fromcode);
608     if (m != (size_t) (-1)) {
609       mem_free (ps);
610       *ps = s;
611       return 0;
612     }
613   }
614   return -1;
615 }