2 * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
3 * Copyright (C) 2000-2001 Edmund Grimley Evans <edmundo@rano.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
35 /* If you are debugging this file, comment out the following line. */
44 #define ENCWORD_LEN_MAX 75
45 #define ENCWORD_LEN_MIN 9 /* strlen ("=?.?.?.?=") */
47 #define HSPACE(x) ((x) == '\0' || (x) == ' ' || (x) == '\t')
49 #define CONTINUATION_BYTE(c) (((c) & 0xc0) == 0x80)
51 extern char RFC822Specials[];
53 typedef size_t (*encoder_t) (char *, ICONV_CONST char *, size_t,
56 static size_t convert_string (ICONV_CONST char *f, size_t flen,
57 const char *from, const char *to,
58 char **t, size_t *tlen)
65 cd = mutt_iconv_open (to, from, 0);
66 if (cd == (iconv_t)(-1))
69 ob = buf = safe_malloc (obl);
70 n = iconv (cd, &f, &flen, &ob, &obl);
71 if (n == (size_t)(-1) || iconv (cd, 0, 0, &ob, &obl) == (size_t)(-1))
83 safe_realloc (&buf, ob - buf + 1);
90 int convert_nonmime_string (char **ps)
94 for (c = AssumedCharset; c; c = c1 ? c1 + 1 : 0)
100 size_t ulen = mutt_strlen (*ps);
106 c1 = strchr (c, ':');
107 n = c1 ? c1 - c : mutt_strlen (c);
110 fromcode = safe_malloc (n + 1);
111 strfcpy (fromcode, c, n + 1);
112 m = convert_string (u, ulen, fromcode, Charset, &s, &slen);
114 if (m != (size_t)(-1))
116 FREE (ps); /* __FREE_CHECKED__ */
121 mutt_convert_string (ps,
122 (const char *)mutt_get_default_charset (AssumedCharset),
123 Charset, M_ICONV_HOOK_FROM);
127 char *mutt_choose_charset (const char *fromcode, const char *charsets,
128 char *u, size_t ulen, char **d, size_t *dlen)
130 char canonical_buff[LONG_STRING];
131 char *e = 0, *tocode = 0;
132 size_t elen = 0, bestn = 0;
135 for (p = charsets; p; p = q ? q + 1 : 0)
142 n = q ? q - p : strlen (p);
145 /* Assume that we never need more than 12 characters of
146 encoded-text to encode a single character. */
147 n > (ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 2 - 12))
150 t = safe_malloc (n + 1);
154 n = convert_string (u, ulen, fromcode, t, &s, &slen);
155 if (n == (size_t)(-1))
158 if (!tocode || n < bestn)
187 mutt_canonical_charset (canonical_buff, sizeof (canonical_buff), tocode);
188 mutt_str_replace (&tocode, canonical_buff);
193 static size_t b_encoder (char *s, ICONV_CONST char *d, size_t dlen,
198 memcpy (s, "=?", 2), s += 2;
199 memcpy (s, tocode, strlen (tocode)), s += strlen (tocode);
200 memcpy (s, "?B?", 3), s += 3;
207 *s++ = B64Chars[(*d >> 2) & 0x3f];
208 *s++ = B64Chars[(*d & 0x03) << 4];
215 *s++ = B64Chars[(*d >> 2) & 0x3f];
216 *s++ = B64Chars[((*d & 0x03) << 4) | ((d[1] >> 4) & 0x0f)];
217 *s++ = B64Chars[(d[1] & 0x0f) << 2];
223 *s++ = B64Chars[(*d >> 2) & 0x3f];
224 *s++ = B64Chars[((*d & 0x03) << 4) | ((d[1] >> 4) & 0x0f)];
225 *s++ = B64Chars[((d[1] & 0x0f) << 2) | ((d[2] >> 6) & 0x03)];
226 *s++ = B64Chars[d[2] & 0x3f];
230 memcpy (s, "?=", 2), s += 2;
234 static size_t q_encoder (char *s, ICONV_CONST char *d, size_t dlen,
237 char hex[] = "0123456789ABCDEF";
240 memcpy (s, "=?", 2), s += 2;
241 memcpy (s, tocode, strlen (tocode)), s += strlen (tocode);
242 memcpy (s, "?Q?", 3), s += 3;
245 unsigned char c = *d++;
248 else if (c >= 0x7f || c < 0x20 || c == '_' || strchr (MimeSpecials, c))
251 *s++ = hex[(c & 0xf0) >> 4];
252 *s++ = hex[c & 0x0f];
257 memcpy (s, "?=", 2), s += 2;
262 * Return 0 if and set *encoder and *wlen if the data (d, dlen) could
263 * be converted to an encoded word of length *wlen using *encoder.
264 * Otherwise return an upper bound on the maximum length of the data
265 * which could be converted.
266 * The data is converted from fromcode (which must be stateless) to
267 * tocode, unless fromcode is 0, in which case the data is assumed to
268 * be already in tocode, which should be 8-bit and stateless.
270 static size_t try_block (ICONV_CONST char *d, size_t dlen,
271 const char *fromcode, const char *tocode,
272 encoder_t *encoder, size_t *wlen)
274 char buf1[ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 1];
276 ICONV_CONST char *ib;
279 int count, len, len_b, len_q;
283 cd = mutt_iconv_open (tocode, fromcode, 0);
284 assert (cd != (iconv_t)(-1));
285 ib = d, ibl = dlen, ob = buf1, obl = sizeof (buf1) - strlen (tocode);
286 if (iconv (cd, &ib, &ibl, &ob, &obl) == (size_t)(-1) ||
287 iconv (cd, 0, 0, &ob, &obl) == (size_t)(-1))
289 assert (errno == E2BIG);
292 return (ib - d == dlen) ? dlen : ib - d + 1;
298 if (dlen > sizeof (buf1) - strlen (tocode))
299 return sizeof (buf1) - strlen (tocode) + 1;
300 memcpy (buf1, d, dlen);
305 for (p = buf1; p < ob; p++)
307 unsigned char c = *p;
308 assert (strchr (MimeSpecials, '?'));
309 if (c >= 0x7f || c < 0x20 || *p == '_' ||
310 (c != ' ' && strchr (MimeSpecials, *p)))
314 len = ENCWORD_LEN_MIN - 2 + strlen (tocode);
315 len_b = len + (((ob - buf1) + 2) / 3) * 4;
316 len_q = len + (ob - buf1) + 2 * count;
318 /* Apparently RFC 1468 says to use B encoding for iso-2022-jp. */
319 if (!ascii_strcasecmp (tocode, "ISO-2022-JP"))
320 len_q = ENCWORD_LEN_MAX + 1;
322 if (len_b < len_q && len_b <= ENCWORD_LEN_MAX)
324 *encoder = b_encoder;
328 else if (len_q <= ENCWORD_LEN_MAX)
330 *encoder = q_encoder;
339 * Encode the data (d, dlen) into s using the encoder.
340 * Return the length of the encoded word.
342 static size_t encode_block (char *s, char *d, size_t dlen,
343 const char *fromcode, const char *tocode,
346 char buf1[ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 1];
348 ICONV_CONST char *ib;
350 size_t ibl, obl, n1, n2;
354 cd = mutt_iconv_open (tocode, fromcode, 0);
355 assert (cd != (iconv_t)(-1));
356 ib = d, ibl = dlen, ob = buf1, obl = sizeof (buf1) - strlen (tocode);
357 n1 = iconv (cd, &ib, &ibl, &ob, &obl);
358 n2 = iconv (cd, 0, 0, &ob, &obl);
359 assert (n1 != (size_t)(-1) && n2 != (size_t)(-1));
361 return (*encoder) (s, buf1, ob - buf1, tocode);
364 return (*encoder) (s, d, dlen, tocode);
368 * Discover how much of the data (d, dlen) can be converted into
369 * a single encoded word. Return how much data can be converted,
370 * and set the length *wlen of the encoded word and *encoder.
371 * We start in column col, which limits the length of the word.
373 static size_t choose_block (char *d, size_t dlen, int col,
374 const char *fromcode, const char *tocode,
375 encoder_t *encoder, size_t *wlen)
378 int utf8 = fromcode && !ascii_strcasecmp (fromcode, "utf-8");
384 nn = try_block (d, n, fromcode, tocode, encoder, wlen);
385 if (!nn && (col + *wlen <= ENCWORD_LEN_MAX + 1 || n <= 1))
387 n = (nn ? nn : n) - 1;
390 while (n > 1 && CONTINUATION_BYTE(d[n]))
397 * Place the result of RFC-2047-encoding (d, dlen) into the dynamically
398 * allocated buffer (e, elen). The input data is in charset fromcode
399 * and is converted into a charset chosen from charsets.
400 * Return 1 if the conversion to UTF-8 failed, 2 if conversion from UTF-8
401 * failed, otherwise 0. If conversion failed, fromcode is assumed to be
402 * compatible with us-ascii and the original data is used.
403 * The input data is assumed to be a single line starting at column col;
404 * if col is non-zero, the preceding character was a space.
406 static int rfc2047_encode (ICONV_CONST char *d, size_t dlen, int col,
407 const char *fromcode, const char *charsets,
408 char **e, size_t *elen, char *specials)
412 size_t bufpos, buflen;
413 char *u, *t0, *t1, *t;
415 size_t ulen, r, n, wlen;
419 char *icode = "utf-8";
421 /* Try to convert to UTF-8. */
422 if (convert_string (d, dlen, fromcode, icode, &u, &ulen))
426 u = safe_malloc ((ulen = dlen) + 1);
431 /* Find earliest and latest things we must encode. */
432 s0 = s1 = t0 = t1 = 0;
433 for (t = u; t < u + ulen; t++)
436 (*t == '=' && t[1] == '?' && (t == u || HSPACE(*(t-1)))))
441 else if (specials && strchr (specials, *t))
448 /* If we have something to encode, include RFC822 specials */
449 if (t0 && s0 && s0 < t0)
451 if (t1 && s1 && s1 > t1)
456 /* No encoding is required. */
462 /* Choose target charset. */
466 if ((tocode1 = mutt_choose_charset (icode, charsets, u, ulen, 0, 0)))
472 /* Hack to avoid labelling 8-bit data as us-ascii. */
473 if (!icode && mutt_is_us_ascii (tocode))
474 tocode = "unknown-8bit";
476 /* Adjust t0 for maximum length of line. */
477 t = u + (ENCWORD_LEN_MAX + 1) - col - ENCWORD_LEN_MIN;
482 /* Adjust t0 until we can encode a character after a space. */
485 if (!HSPACE(*(t0-1)))
489 while (t < u + ulen && CONTINUATION_BYTE(*t))
491 if (!try_block (t0, t - t0, icode, tocode, &encoder, &wlen) &&
492 col + (t0 - u) + wlen <= ENCWORD_LEN_MAX + 1)
496 /* Adjust t1 until we can encode a character before a space. */
497 for (; t1 < u + ulen; t1++)
503 while (CONTINUATION_BYTE(*t))
505 if (!try_block (t, t1 - t, icode, tocode, &encoder, &wlen) &&
506 1 + wlen + (u + ulen - t1) <= ENCWORD_LEN_MAX + 1)
510 /* We shall encode the region [t0,t1). */
512 /* Initialise the output buffer with the us-ascii prefix. */
514 buf = safe_malloc (buflen);
516 memcpy (buf, u, t0 - u);
523 /* Find how much we can encode. */
524 n = choose_block (t, t1 - t, col, icode, tocode, &encoder, &wlen);
527 /* See if we can fit the us-ascii suffix, too. */
528 if (col + wlen + (u + ulen - t1) <= ENCWORD_LEN_MAX + 1)
532 while (CONTINUATION_BYTE(t[n]))
537 /* This should only happen in the really stupid case where the
538 only word that needs encoding is one character long, but
539 there is too much us-ascii stuff after it to use a single
540 encoded word. We add the next word to the encoded region
542 assert (t1 < u + ulen);
543 for (t1++; t1 < u + ulen && !HSPACE(*t1); t1++)
547 n = choose_block (t, n, col, icode, tocode, &encoder, &wlen);
550 /* Add to output buffer. */
551 #define LINEBREAK "\n\t"
552 if (bufpos + wlen + strlen (LINEBREAK) > buflen)
554 buflen = bufpos + wlen + strlen (LINEBREAK);
555 safe_realloc (&buf, buflen);
557 r = encode_block (buf + bufpos, t, n, icode, tocode, encoder);
560 memcpy (buf + bufpos, LINEBREAK, strlen (LINEBREAK));
561 bufpos += strlen (LINEBREAK);
569 /* Add last encoded word and us-ascii suffix to buffer. */
570 buflen = bufpos + wlen + (u + ulen - t1);
571 safe_realloc (&buf, buflen + 1);
572 r = encode_block (buf + bufpos, t, t1 - t, icode, tocode, encoder);
575 memcpy (buf + bufpos, t1, u + ulen - t1);
587 void _rfc2047_encode_string (char **pd, int encode_specials, int col)
593 if (!Charset || !*pd)
596 charsets = SendCharset;
597 if (!charsets || !*charsets)
600 rfc2047_encode (*pd, strlen (*pd), col,
601 Charset, charsets, &e, &elen,
602 encode_specials ? RFC822Specials : NULL);
604 FREE (pd); /* __FREE_CHECKED__ */
608 void rfc2047_encode_adrlist (ADDRESS *addr, const char *tag)
611 int col = tag ? strlen (tag) + 2 : 32;
616 _rfc2047_encode_string (&ptr->personal, 1, col);
619 _rfc2047_encode_string (&ptr->val, 1, col);
625 static int rfc2047_decode_word (char *d, const char *s, size_t len)
627 const char *pp, *pp1;
630 int enc = 0, count = 0;
631 char *charset = NULL;
633 pd = d0 = safe_malloc (strlen (s));
635 for (pp = s; (pp1 = strchr (pp, '?')); pp = pp1 + 1)
641 /* ignore language specification a la RFC 2231 */
643 if ((t1 = memchr (pp, '*', t - pp)))
645 charset = safe_malloc (t - pp + 1);
646 memcpy (charset, pp, t - pp);
647 charset[t-pp] = '\0';
650 if (toupper ((unsigned char) *pp) == 'Q')
651 enc = ENCQUOTEDPRINTABLE;
652 else if (toupper ((unsigned char) *pp) == 'B')
662 if (enc == ENCQUOTEDPRINTABLE)
664 for (; pp < pp1; pp++)
668 else if (*pp == '=' &&
669 (!(pp[1] & ~127) && hexval(pp[1]) != -1) &&
670 (!(pp[2] & ~127) && hexval(pp[2]) != -1))
672 *pd++ = (hexval(pp[1]) << 4) | hexval(pp[2]);
680 else if (enc == ENCBASE64)
684 for (; pp < pp1; pp++)
688 if ((*pp & ~127) || (c = base64val(*pp)) == -1)
693 *pd++ = b | (c >> k);
709 mutt_convert_string (&d0, charset, Charset, M_ICONV_HOOK_FROM);
710 mutt_filter_unprintable (&d0);
711 strfcpy (d, d0, len);
718 * Find the start and end of the first encoded word in the string.
719 * We use the grammar in section 2 of RFC 2047, but the "encoding"
720 * must be B or Q. Also, we don't require the encoded word to be
721 * separated by linear-white-space (section 5(1)).
723 static const char *find_encoded_word (const char *s, const char **x)
728 while ((p = strstr (q, "=?")))
731 0x20 < *q && *q < 0x7f && !strchr ("()<>@,;:\"/[]?.=", *q);
734 if (q[0] != '?' || !strchr ("BbQq", q[1]) || q[2] != '?')
736 for (q = q + 3; 0x20 < *q && *q < 0x7f && *q != '?'; q++)
738 if (q[0] != '?' || q[1] != '=')
751 /* return length of linear-white-space */
752 static size_t lwslen (const char *s, size_t n)
760 for (; p < s + n; p++)
761 if (!strchr (" \t\r\n", *p))
763 len = (size_t)(p - s);
766 if (strchr ("\r\n", *(p-1))) /* LWS doesn't end with CRLF */
771 /* return length of linear-white-space : reverse */
772 static size_t lwsrlen (const char *s, size_t n)
774 const char *p = s + n - 1;
780 if (strchr ("\r\n", *p)) /* LWS doesn't end with CRLF */
784 if (!strchr (" \t\r\n", *p))
786 len = (size_t)(s + n - 1 - p);
792 /* try to decode anything that looks like a valid RFC2047 encoded
793 * header field, ignoring RFC822 parsing rules
795 void rfc2047_decode (char **pd)
799 int found_encoded = 0;
807 dlen = 4 * strlen (s); /* should be enough */
808 d = d0 = safe_malloc (dlen + 1);
810 while (*s && dlen > 0)
812 if (!(p = find_encoded_word (s, &q)))
814 /* no encoded words */
815 if (option (OPTIGNORELWS))
818 if (found_encoded && (m = lwslen (s, n)) != 0)
821 *d = ' ', d++, dlen--;
825 if (AssumedCharset && *AssumedCharset)
831 t = safe_malloc (n + 1);
832 strfcpy (t, s, n + 1);
833 convert_nonmime_string (&t);
834 tlen = mutt_strlen (t);
835 strncpy (d, t, tlen);
840 strncpy (d, s, dlen);
847 n = (size_t) (p - s);
848 /* ignore spaces between encoded word
849 * and linear-white-space between encoded word and *text */
850 if (option (OPTIGNORELWS))
852 if (found_encoded && (m = lwslen (s, n)) != 0)
855 *d = ' ', d++, dlen--;
859 if ((m = n - lwsrlen (s, n)) != 0)
867 *d = ' ', d++, dlen--;
870 else if (!found_encoded || strspn (s, " \t\r\n") != n)
880 rfc2047_decode_word (d, p, dlen);
889 FREE (pd); /* __FREE_CHECKED__ */
891 mutt_str_adjust (pd);
894 void rfc2047_decode_adrlist (ADDRESS *a)
898 if (a->personal && ((strstr (a->personal, "=?") != NULL) ||
899 (AssumedCharset && *AssumedCharset)))
900 rfc2047_decode (&a->personal);
902 if (a->val && strstr (a->val, "=?") != NULL)
903 rfc2047_decode (&a->val);