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