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., 59 Temple Place - Suite 330, Boston, MA 02111, 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)) {
82 safe_realloc (&buf, ob - buf + 1);
89 char *mutt_choose_charset (const char *fromcode, const char *charsets,
90 char *u, size_t ulen, char **d, size_t * dlen)
92 char canonical_buff[LONG_STRING];
93 char *e = 0, *tocode = 0;
94 size_t elen = 0, bestn = 0;
97 for (p = charsets; p; p = q ? q + 1 : 0) {
103 n = q ? q - p : strlen (p);
106 /* Assume that we never need more than 12 characters of
107 encoded-text to encode a single character. */
108 n > (ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 2 - 12))
111 t = safe_malloc (n + 1);
115 n = convert_string (u, ulen, fromcode, t, &s, &slen);
116 if (n == (size_t) (-1))
119 if (!tocode || n < bestn) {
144 mutt_canonical_charset (canonical_buff, sizeof (canonical_buff), tocode);
145 mutt_str_replace (&tocode, canonical_buff);
150 static size_t b_encoder (char *s, ICONV_CONST char *d, size_t dlen,
155 memcpy (s, "=?", 2), s += 2;
156 memcpy (s, tocode, strlen (tocode)), s += strlen (tocode);
157 memcpy (s, "?B?", 3), s += 3;
161 else if (dlen == 1) {
162 *s++ = B64Chars[(*d >> 2) & 0x3f];
163 *s++ = B64Chars[(*d & 0x03) << 4];
168 else if (dlen == 2) {
169 *s++ = B64Chars[(*d >> 2) & 0x3f];
170 *s++ = B64Chars[((*d & 0x03) << 4) | ((d[1] >> 4) & 0x0f)];
171 *s++ = B64Chars[(d[1] & 0x0f) << 2];
176 *s++ = B64Chars[(*d >> 2) & 0x3f];
177 *s++ = B64Chars[((*d & 0x03) << 4) | ((d[1] >> 4) & 0x0f)];
178 *s++ = B64Chars[((d[1] & 0x0f) << 2) | ((d[2] >> 6) & 0x03)];
179 *s++ = B64Chars[d[2] & 0x3f];
183 memcpy (s, "?=", 2), s += 2;
187 static size_t q_encoder (char *s, ICONV_CONST char *d, size_t dlen,
190 char hex[] = "0123456789ABCDEF";
193 memcpy (s, "=?", 2), s += 2;
194 memcpy (s, tocode, strlen (tocode)), s += strlen (tocode);
195 memcpy (s, "?Q?", 3), s += 3;
197 unsigned char c = *d++;
201 else if (c >= 0x7f || c < 0x20 || c == '_' || strchr (MimeSpecials, c)) {
203 *s++ = hex[(c & 0xf0) >> 4];
204 *s++ = hex[c & 0x0f];
209 memcpy (s, "?=", 2), s += 2;
214 * Return 0 if and set *encoder and *wlen if the data (d, dlen) could
215 * be converted to an encoded word of length *wlen using *encoder.
216 * Otherwise return an upper bound on the maximum length of the data
217 * which could be converted.
218 * The data is converted from fromcode (which must be stateless) to
219 * tocode, unless fromcode is 0, in which case the data is assumed to
220 * be already in tocode, which should be 8-bit and stateless.
222 static size_t try_block (ICONV_CONST char *d, size_t dlen,
223 const char *fromcode, const char *tocode,
224 encoder_t * encoder, size_t * wlen)
226 char buf1[ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 1];
228 ICONV_CONST char *ib;
231 int count, len, len_b, len_q;
234 cd = mutt_iconv_open (tocode, fromcode, 0);
235 assert (cd != (iconv_t) (-1));
236 ib = d, ibl = dlen, ob = buf1, obl = sizeof (buf1) - strlen (tocode);
237 if (iconv (cd, &ib, &ibl, &ob, &obl) == (size_t) (-1) ||
238 iconv (cd, 0, 0, &ob, &obl) == (size_t) (-1)) {
239 assert (errno == E2BIG);
242 return (ib - d == dlen) ? dlen : ib - d + 1;
247 if (dlen > sizeof (buf1) - strlen (tocode))
248 return sizeof (buf1) - strlen (tocode) + 1;
249 memcpy (buf1, d, dlen);
254 for (p = buf1; p < ob; p++) {
255 unsigned char c = *p;
257 assert (strchr (MimeSpecials, '?'));
258 if (c >= 0x7f || c < 0x20 || *p == '_' ||
259 (c != ' ' && strchr (MimeSpecials, *p)))
263 len = ENCWORD_LEN_MIN - 2 + strlen (tocode);
264 len_b = len + (((ob - buf1) + 2) / 3) * 4;
265 len_q = len + (ob - buf1) + 2 * count;
267 /* Apparently RFC 1468 says to use B encoding for iso-2022-jp. */
268 if (!ascii_strcasecmp (tocode, "ISO-2022-JP"))
269 len_q = ENCWORD_LEN_MAX + 1;
271 if (len_b < len_q && len_b <= ENCWORD_LEN_MAX) {
272 *encoder = b_encoder;
276 else if (len_q <= ENCWORD_LEN_MAX) {
277 *encoder = q_encoder;
286 * Encode the data (d, dlen) into s using the encoder.
287 * Return the length of the encoded word.
289 static size_t encode_block (char *s, char *d, size_t dlen,
290 const char *fromcode, const char *tocode,
293 char buf1[ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 1];
295 ICONV_CONST char *ib;
297 size_t ibl, obl, n1, n2;
300 cd = mutt_iconv_open (tocode, fromcode, 0);
301 assert (cd != (iconv_t) (-1));
302 ib = d, ibl = dlen, ob = buf1, obl = sizeof (buf1) - strlen (tocode);
303 n1 = iconv (cd, &ib, &ibl, &ob, &obl);
304 n2 = iconv (cd, 0, 0, &ob, &obl);
305 assert (n1 != (size_t) (-1) && n2 != (size_t) (-1));
307 return (*encoder) (s, buf1, ob - buf1, tocode);
310 return (*encoder) (s, d, dlen, tocode);
314 * Discover how much of the data (d, dlen) can be converted into
315 * a single encoded word. Return how much data can be converted,
316 * and set the length *wlen of the encoded word and *encoder.
317 * We start in column col, which limits the length of the word.
319 static size_t choose_block (char *d, size_t dlen, int col,
320 const char *fromcode, const char *tocode,
321 encoder_t * encoder, size_t * wlen)
324 int utf8 = fromcode && !ascii_strcasecmp (fromcode, "UTF-8");
329 nn = try_block (d, n, fromcode, tocode, encoder, wlen);
330 if (!nn && (col + *wlen <= ENCWORD_LEN_MAX + 1 || n <= 1))
332 n = (nn ? nn : n) - 1;
335 while (n > 1 && CONTINUATION_BYTE (d[n]))
342 * Place the result of RFC-2047-encoding (d, dlen) into the dynamically
343 * allocated buffer (e, elen). The input data is in charset fromcode
344 * and is converted into a charset chosen from charsets.
345 * Return 1 if the conversion to UTF-8 failed, 2 if conversion from UTF-8
346 * failed, otherwise 0. If conversion failed, fromcode is assumed to be
347 * compatible with us-ascii and the original data is used.
348 * The input data is assumed to be a single line starting at column col;
349 * if col is non-zero, the preceding character was a space.
351 static int rfc2047_encode (ICONV_CONST char *d, size_t dlen, int col,
352 const char *fromcode, const char *charsets,
353 char **e, size_t * elen, char *specials)
357 size_t bufpos, buflen;
358 char *u, *t0, *t1, *t;
360 size_t ulen, r, n, wlen;
364 char *icode = "UTF-8";
366 /* Try to convert to UTF-8. */
367 if (convert_string (d, dlen, fromcode, icode, &u, &ulen)) {
370 u = safe_malloc ((ulen = dlen) + 1);
375 /* Find earliest and latest things we must encode. */
376 s0 = s1 = t0 = t1 = 0;
377 for (t = u; t < u + ulen; t++) {
379 (*t == '=' && t[1] == '?' && (t == u || HSPACE (*(t - 1))))) {
384 else if (specials && strchr (specials, *t)) {
391 /* If we have something to encode, include RFC822 specials */
392 if (t0 && s0 && s0 < t0)
394 if (t1 && s1 && s1 > t1)
398 /* No encoding is required. */
404 /* Choose target charset. */
407 if ((tocode1 = mutt_choose_charset (icode, charsets, u, ulen, 0, 0)))
413 /* Hack to avoid labelling 8-bit data as us-ascii. */
414 if (!icode && mutt_is_us_ascii (tocode))
415 tocode = "unknown-8bit";
417 /* Adjust t0 for maximum length of line. */
418 t = u + (ENCWORD_LEN_MAX + 1) - col - ENCWORD_LEN_MIN;
425 /* Adjust t0 until we can encode a character after a space. */
426 for (; t0 > u; t0--) {
427 if (!HSPACE (*(t0 - 1)))
431 while (t < u + ulen && CONTINUATION_BYTE (*t))
433 if (!try_block (t0, t - t0, icode, tocode, &encoder, &wlen) &&
434 col + (t0 - u) + wlen <= ENCWORD_LEN_MAX + 1)
438 /* Adjust t1 until we can encode a character before a space. */
439 for (; t1 < u + ulen; t1++) {
444 while (CONTINUATION_BYTE (*t))
446 if (!try_block (t, t1 - t, icode, tocode, &encoder, &wlen) &&
447 1 + wlen + (u + ulen - t1) <= ENCWORD_LEN_MAX + 1)
451 /* We shall encode the region [t0,t1). */
453 /* Initialise the output buffer with the us-ascii prefix. */
455 buf = safe_malloc (buflen);
457 memcpy (buf, u, t0 - u);
463 /* Find how much we can encode. */
464 n = choose_block (t, t1 - t, col, icode, tocode, &encoder, &wlen);
466 /* See if we can fit the us-ascii suffix, too. */
467 if (col + wlen + (u + ulen - t1) <= ENCWORD_LEN_MAX + 1)
471 while (CONTINUATION_BYTE (t[n]))
475 /* This should only happen in the really stupid case where the
476 only word that needs encoding is one character long, but
477 there is too much us-ascii stuff after it to use a single
478 encoded word. We add the next word to the encoded region
480 assert (t1 < u + ulen);
481 for (t1++; t1 < u + ulen && !HSPACE (*t1); t1++);
484 n = choose_block (t, n, col, icode, tocode, &encoder, &wlen);
487 /* Add to output buffer. */
488 #define LINEBREAK "\n\t"
489 if (bufpos + wlen + strlen (LINEBREAK) > buflen) {
490 buflen = bufpos + wlen + strlen (LINEBREAK);
491 safe_realloc (&buf, buflen);
493 r = encode_block (buf + bufpos, t, n, icode, tocode, encoder);
496 memcpy (buf + bufpos, LINEBREAK, strlen (LINEBREAK));
497 bufpos += strlen (LINEBREAK);
505 /* Add last encoded word and us-ascii suffix to buffer. */
506 buflen = bufpos + wlen + (u + ulen - t1);
507 safe_realloc (&buf, buflen + 1);
508 r = encode_block (buf + bufpos, t, t1 - t, icode, tocode, encoder);
511 memcpy (buf + bufpos, t1, u + ulen - t1);
523 void _rfc2047_encode_string (char **pd, int encode_specials, int col)
529 if (!Charset || !*pd)
532 charsets = SendCharset;
533 if (!charsets || !*charsets)
536 rfc2047_encode (*pd, strlen (*pd), col,
537 Charset, charsets, &e, &elen,
538 encode_specials ? RFC822Specials : NULL);
544 void rfc2047_encode_adrlist (ADDRESS * addr, const char *tag)
547 int col = tag ? strlen (tag) + 2 : 32;
551 _rfc2047_encode_string (&ptr->personal, 1, col);
554 _rfc2047_encode_string (&ptr->val, 1, col);
560 static int rfc2047_decode_word (char *d, const char *s, size_t len)
562 const char *pp, *pp1;
565 int enc = 0, count = 0;
566 char *charset = NULL;
568 pd = d0 = safe_malloc (strlen (s));
570 for (pp = s; (pp1 = strchr (pp, '?')); pp = pp1 + 1) {
574 /* ignore language specification a la RFC 2231 */
576 if ((t1 = memchr (pp, '*', t - pp)))
578 charset = safe_malloc (t - pp + 1);
579 memcpy (charset, pp, t - pp);
580 charset[t - pp] = '\0';
583 if (toupper ((unsigned char) *pp) == 'Q')
584 enc = ENCQUOTEDPRINTABLE;
585 else if (toupper ((unsigned char) *pp) == 'B')
594 if (enc == ENCQUOTEDPRINTABLE) {
595 for (; pp < pp1; pp++) {
598 else if (*pp == '=' &&
599 (!(pp[1] & ~127) && hexval (pp[1]) != -1) &&
600 (!(pp[2] & ~127) && hexval (pp[2]) != -1)) {
601 *pd++ = (hexval (pp[1]) << 4) | hexval (pp[2]);
609 else if (enc == ENCBASE64) {
612 for (; pp < pp1; pp++) {
615 if ((*pp & ~127) || (c = base64val (*pp)) == -1)
619 *pd++ = b | (c >> k);
634 mutt_convert_string (&d0, charset, Charset, M_ICONV_HOOK_FROM);
635 strfcpy (d, d0, len);
642 * Find the start and end of the first encoded word in the string.
643 * We use the grammar in section 2 of RFC 2047, but the "encoding"
644 * must be B or Q. Also, we don't require the encoded word to be
645 * separated by linear-white-space (section 5(1)).
647 static const char *find_encoded_word (const char *s, const char **x)
652 while ((p = strstr (q, "=?"))) {
654 0x20 < *q && *q < 0x7f && !strchr ("()<>@,;:\"/[]?.=", *q); q++);
655 if (q[0] != '?' || !strchr ("BbQq", q[1]) || q[2] != '?')
657 for (q = q + 3; 0x20 <= *q && *q < 0x7f && *q != '?'; q++);
658 if (q[0] != '?' || q[1] != '=') {
670 /* return length of linear white space */
671 static size_t lwslen (const char *s, size_t n)
679 for (; p < s + n; p++)
680 if (!strchr (" \t\r\n", *p)) {
681 len = (size_t) (p - s);
684 if (strchr ("\r\n", *(p - 1))) /* LWS doesn't end with CRLF */
689 /* return length of linear white space : reverse */
690 static size_t lwsrlen (const char *s, size_t n)
692 const char *p = s + n - 1;
698 if (strchr ("\r\n", *p)) /* LWS doesn't end with CRLF */
702 if (!strchr (" \t\r\n", *p)) {
703 len = (size_t) (s + n - 1 - p);
709 /* try to decode anything that looks like a valid RFC2047 encoded
710 * header field, ignoring RFC822 parsing rules
712 void rfc2047_decode (char **pd)
716 int found_encoded = 0;
724 dlen = 4 * strlen (s); /* should be enough */
725 d = d0 = safe_malloc (dlen + 1);
727 while (*s && dlen > 0) {
728 if (!(p = find_encoded_word (s, &q))) {
729 /* no encoded words */
730 if (!option (OPTSTRICTMIME)) {
732 if (found_encoded && (m = lwslen (s, n)) != 0) {
734 *d = ' ', d++, dlen--;
737 if (ascii_strcasecmp (AssumedCharset, "us-ascii")) {
741 t = safe_malloc (n + 1);
742 strfcpy (t, s, n + 1);
743 if (mutt_convert_nonmime_string (&t) == 0) {
744 tlen = mutt_strlen (t);
745 strncpy (d, t, tlen);
756 strncpy (d, s, dlen);
762 n = (size_t) (p - s);
763 /* ignore spaces between encoded words
764 * and linear white spaces between encoded word and *text */
765 if (!option (OPTSTRICTMIME)) {
766 if (found_encoded && (m = lwslen (s, n)) != 0) {
768 *d = ' ', d++, dlen--;
772 if ((m = n - lwsrlen (s, n)) != 0) {
779 *d = ' ', d++, dlen--;
782 else if (!found_encoded || strspn (s, " \t\r\n") != n) {
791 rfc2047_decode_word (d, p, dlen);
802 mutt_str_adjust (pd);
805 void rfc2047_decode_adrlist (ADDRESS * a)
809 rfc2047_decode (&a->personal);
811 if (a->val && strstr (a->val, "=?") != NULL)
812 rfc2047_decode (&a->val);