* docs/MAIL.FILTERING: added note on removing procmail -f or
[mmh] / sbr / fmt_rfc2047.c
1
2 /*
3  * fmt_rfc2047.c -- decode RFC-2047 header format 
4  *
5  * $Id$
6  *
7  * This code is Copyright (c) 2002, by the authors of nmh.  See the
8  * COPYRIGHT file in the root directory of the nmh distribution for
9  * complete copyright information.
10  */
11
12 #include <h/mh.h>
13 #include <h/utils.h>
14 #ifdef HAVE_ICONV
15 #  include <iconv.h>
16 #  include <errno.h>
17 #endif
18
19 static signed char hexindex[] = {
20     -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
21     -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
22     -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
23      0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
24     -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25     -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
26     -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
27     -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
28 };
29
30 static signed char index_64[128] = {
31     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
32     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
33     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
34     52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1,
35     -1, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
36     15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
37     -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
38     41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
39 };
40
41 #define char64(c) (((unsigned char) (c) > 127) ? -1 : index_64[(unsigned char) (c)])
42
43 static int
44 unqp (unsigned char byte1, unsigned char byte2)
45 {
46     if (hexindex[byte1] == -1 || hexindex[byte2] == -1)
47         return -1;
48     return (hexindex[byte1] << 4 | hexindex[byte2]);
49 }
50
51 /* Check if character is linear whitespace */
52 #define is_lws(c)  ((c) == ' ' || (c) == '\t' || (c) == '\n')
53
54
55 /*
56  * Decode the string as a RFC-2047 header field
57  */
58
59 /* Add character to the destination buffer, and bomb out if it fills up */
60 #define ADDCHR(C) do { *q++ = (C); dstlen--; if (!dstlen) goto buffull; } while (0)
61
62 int
63 decode_rfc2047 (char *str, char *dst, size_t dstlen)
64 {
65     char *p, *q, *pp;
66     char *startofmime, *endofmime;
67     int c, quoted_printable;
68     int encoding_found = 0;     /* did we decode anything?                */
69     int between_encodings = 0;  /* are we between two encodings?          */
70     int equals_pending = 0;     /* is there a '=' pending?                */
71     int whitespace = 0;         /* how much whitespace between encodings? */
72 #ifdef HAVE_ICONV
73     int use_iconv = 0;          /* are we converting encoding with iconv? */
74     iconv_t cd;
75     int fromutf8 = 0;
76     char *saveq, *convbuf = NULL;
77     size_t savedstlen;
78 #endif
79
80     if (!str)
81         return 0;
82
83     /*
84      * Do a quick and dirty check for the '=' character.
85      * This should quickly eliminate many cases.
86      */
87     if (!strchr (str, '='))
88         return 0;
89
90     for (p = str, q = dst; *p; p++) {
91
92         /* reset iconv */
93 #ifdef HAVE_ICONV
94         if (use_iconv) {
95             iconv_close(cd);
96             use_iconv = 0;
97         }
98 #endif
99         /*
100          * If we had an '=' character pending from
101          * last iteration, then add it first.
102          */
103         if (equals_pending) {
104             ADDCHR('=');
105             equals_pending = 0;
106             between_encodings = 0;      /* we have added non-whitespace text */
107         }
108
109         if (*p != '=') {
110             /* count linear whitespace while between encodings */
111             if (between_encodings && is_lws(*p))
112                 whitespace++;
113             else
114                 between_encodings = 0;  /* we have added non-whitespace text */
115             ADDCHR(*p);
116             continue;
117         }
118
119         equals_pending = 1;     /* we have a '=' pending */
120
121         /* Check for initial =? */
122         if (*p == '=' && p[1] && p[1] == '?' && p[2]) {
123             startofmime = p + 2;
124
125             /* Scan ahead for the next '?' character */
126             for (pp = startofmime; *pp && *pp != '?'; pp++)
127                 ;
128
129             if (!*pp)
130                 continue;
131
132             /* Check if character set can be handled natively */
133             if (!check_charset(startofmime, pp - startofmime)) {
134 #ifdef HAVE_ICONV
135                 /* .. it can't. We'll use iconv then. */
136                 *pp = '\0';
137                 cd = iconv_open(get_charset(), startofmime);
138                 fromutf8 = !mh_strcasecmp(startofmime, "UTF-8");
139                 *pp = '?';
140                 if (cd == (iconv_t)-1) continue;
141                 use_iconv = 1;
142 #else
143                 continue;
144 #endif
145             }
146
147             startofmime = pp + 1;
148
149             /* Check for valid encoding type */
150             if (*startofmime != 'B' && *startofmime != 'b' &&
151                 *startofmime != 'Q' && *startofmime != 'q')
152                 continue;
153
154             /* Is encoding quoted printable or base64? */
155             quoted_printable = (*startofmime == 'Q' || *startofmime == 'q');
156             startofmime++;
157
158             /* Check for next '?' character */
159             if (*startofmime != '?')
160                 continue;
161             startofmime++;
162
163             /*
164              * Scan ahead for the ending ?=
165              *
166              * While doing this, we will also check if encoded
167              * word has any embedded linear whitespace.
168              */
169             endofmime = NULL;
170             for (pp = startofmime; *pp && *(pp+1); pp++) {
171                 if (is_lws(*pp)) {
172                     break;
173                 } else if (*pp == '?' && pp[1] == '=') {
174                     endofmime = pp;
175                     break;
176                 }
177             }
178             if (is_lws(*pp) || endofmime == NULL)
179                 continue;
180
181             /*
182              * We've found an encoded word, so we can drop
183              * the '=' that was pending
184              */
185             equals_pending = 0;
186
187             /*
188              * If we are between two encoded words separated only by
189              * linear whitespace, then we ignore the whitespace.
190              * We will roll back the buffer the number of whitespace
191              * characters we've seen since last encoded word.
192              */
193             if (between_encodings) {
194                 q -= whitespace;
195                 dstlen += whitespace;
196             }
197
198 #ifdef HAVE_ICONV
199             /*
200              * empty encoded text. This ensures that we don't
201              * malloc 0 bytes but skip on to the end
202              */
203             if (endofmime == startofmime && use_iconv) {
204                 use_iconv = 0;
205                 iconv_close(cd);
206             }
207
208             if (use_iconv) {
209                 saveq = q;
210                 savedstlen = dstlen;
211                 q = convbuf = (char *) mh_xmalloc(endofmime - startofmime);
212             }
213 /* ADDCHR2 is for adding characters when q is or might be convbuf:
214  * in this case on buffer-full we want to run iconv before returning.
215  * I apologise for the dreadful name.
216  */
217 #define ADDCHR2(C) do { *q++ = (C); dstlen--; if (!dstlen) goto iconvbuffull; } while (0)
218 #else
219 #define ADDCHR2(C) ADDCHR(C)
220 #endif
221
222             /* Now decode the text */
223             if (quoted_printable) {
224                 for (pp = startofmime; pp < endofmime; pp++) {
225                     if (*pp == '=') {
226                         c = unqp (pp[1], pp[2]);
227                         if (c == -1)
228                             continue;
229                         if (c != 0)
230                             *q++ = c;
231                         pp += 2;
232                     } else if (*pp == '_') {
233                         ADDCHR2(' ');
234                     } else {
235                         ADDCHR2(*pp);
236                     }
237                 }
238             } else {
239                 /* base64 */
240                 int c1, c2, c3, c4;
241
242                 pp = startofmime;
243                 while (pp < endofmime) {
244                     /* 6 + 2 bits */
245                     while ((pp < endofmime) &&
246                            ((c1 = char64(*pp)) == -1)) {
247                         pp++;
248                     }
249                     if (pp < endofmime) {
250                         pp++;
251                     }
252                     while ((pp < endofmime) &&
253                            ((c2 = char64(*pp)) == -1)) {
254                         pp++;
255                     }
256                     if (pp < endofmime && c1 != -1 && c2 != -1) {
257                         ADDCHR2((c1 << 2) | (c2 >> 4));
258                         pp++;
259                     }
260                     /* 4 + 4 bits */
261                     while ((pp < endofmime) &&
262                            ((c3 = char64(*pp)) == -1)) {
263                         pp++;
264                     }
265                     if (pp < endofmime && c2 != -1 && c3 != -1) {
266                         ADDCHR2(((c2 & 0xF) << 4) | (c3 >> 2));
267                         pp++;
268                     }
269                     /* 2 + 6 bits */
270                     while ((pp < endofmime) &&
271                            ((c4 = char64(*pp)) == -1)) {
272                         pp++;
273                     }
274                     if (pp < endofmime && c3 != -1 && c4 != -1) {
275                         ADDCHR2(((c3 & 0x3) << 6) | (c4));
276                         pp++;
277                     }
278                 }
279             }
280
281 #ifdef HAVE_ICONV
282         iconvbuffull:
283             /* NB that the string at convbuf is not necessarily NUL terminated here:
284              * q points to the first byte after the valid part.
285              */
286             /* Convert to native character set */
287             if (use_iconv) {
288                 size_t inbytes = q - convbuf;
289                 ICONV_CONST char *start = convbuf;
290                 
291                 while (inbytes) {
292                     if (iconv(cd, &start, &inbytes, &saveq, &savedstlen) ==
293                             (size_t)-1) {
294                         if (errno != EILSEQ) break;
295                         /* character couldn't be converted. we output a `?'
296                          * and try to carry on which won't work if
297                          * either encoding was stateful */
298                         iconv (cd, 0, 0, &saveq, &savedstlen);
299                         if (!savedstlen)
300                             break;
301                         *saveq++ = '?';
302                         savedstlen--;
303                         if (!savedstlen)
304                             break;
305                         /* skip to next input character */
306                         if (fromutf8) {
307                             for (start++;(start < q) && ((*start & 192) == 128);start++)
308                                 inbytes--;
309                         } else
310                             start++, inbytes--;
311                         if (start >= q)
312                             break;
313                     }
314                 }
315                 q = saveq;
316                 /* Stop now if (1) we hit the end of the buffer trying to do
317                  * MIME decoding and have just iconv-converted a partial string
318                  * or (2) our iconv-conversion hit the end of the buffer.
319                  */
320                 if (!dstlen || !savedstlen)
321                     goto buffull;
322                 dstlen = savedstlen;
323                 free(convbuf);
324             }
325 #endif
326             
327             /*
328              * Now that we are done decoding this particular
329              * encoded word, advance string to trailing '='.
330              */
331             p = endofmime + 1;
332
333             encoding_found = 1;         /* we found (at least 1) encoded word */
334             between_encodings = 1;      /* we have just decoded something     */
335             whitespace = 0;             /* re-initialize amount of whitespace */
336         }
337     }
338 #ifdef HAVE_ICONV
339     if (use_iconv) iconv_close(cd);
340 #endif
341
342     /* If an equals was pending at end of string, add it now. */
343     if (equals_pending)
344         ADDCHR('=');
345     *q = '\0';
346
347     return encoding_found;
348
349   buffull:
350     /* q is currently just off the end of the buffer, so rewind to NUL terminate */
351     q--;
352     *q = '\0';
353     return encoding_found;
354 }