]> diplodocus.org Git - nmh/blob - sbr/encode_rfc2047.c
fcb1c10457921825cd18da2d0d0415413a28f103
[nmh] / sbr / encode_rfc2047.c
1 /*
2 * Routines to encode message headers using RFC 2047-encoding.
3 *
4 * This code is Copyright (c) 2002, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <h/mhparse.h>
11 #include <h/utils.h>
12
13 /*
14 * List of headers that contain addresses and as a result require special
15 * handling
16 */
17
18 static char *address_headers[] = {
19 "To",
20 "From",
21 "cc",
22 "Bcc",
23 "Reply-To",
24 "Sender",
25 "Resent-To",
26 "Resent-From",
27 "Resent-cc",
28 "Resent-Bcc",
29 "Resent-Reply-To",
30 "Resent-Sender",
31 NULL,
32 };
33
34 /*
35 * Macros we use for parsing headers
36 */
37
38 #define is_fws(c) (c == '\t' || c == ' ' || c == '\n')
39
40 #define qphrasevalid(c) ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || \
41 (c >= 'a' && c <= 'z') || \
42 c == '!' || c == '*' || c == '+' || c == '-' || \
43 c == '/' || c == '=' || c == '_')
44 #define qpspecial(c) (c < ' ' || c == '=' || c == '?' || c == '_')
45
46 #define base64len(n) (((n + 2) / 3 ) * 4) /* String len to base64 len */
47 #define strbase64(n) (n * 3 / 4) /* Chars that fit in base64 */
48
49 #define ENCODELINELIMIT 76
50
51 static void unfold_header(char **, int);
52 static int field_encode_address(const char *, char **, int, const char *);
53 static int field_encode_quoted(const char *, char **, const char *, int, int);
54 static int field_encode_base64(const char *, char **, const char *);
55 static int utf8len(const char *);
56
57 /*
58 * Encode a message header using RFC 2047 encoding. We make the assumption
59 * that all characters < 128 are ASCII and as a consequence don't need any
60 * encoding.
61 */
62
63 int
64 encode_rfc2047(const char *name, char **value, int encoding,
65 const char *charset)
66 {
67 int i, asciicount = 0, eightbitcount = 0, qpspecialcount = 0;
68 char *p;
69
70 /*
71 * First, check to see if we even need to encode the header
72 */
73
74 for (p = *value; *p != '\0'; p++) {
75 if (isascii((unsigned char) *p)) {
76 asciicount++;
77 if (qpspecial((unsigned char) *p))
78 qpspecialcount++;
79 } else
80 eightbitcount++;
81 }
82
83 if (eightbitcount == 0)
84 return 0;
85
86 /*
87 * Some rules from RFC 2047:
88 *
89 * - Encoded words cannot be more than 75 characters long
90 * - Multiple "long" encoded words must be on new lines.
91 *
92 * Also, we're not permitted to encode email addresses, so
93 * we need to actually _parse_ email addresses and only encode
94 * the right bits.
95 */
96
97 /*
98 * If charset was NULL, then get the value from the locale. But
99 * we reject it if it returns US-ASCII
100 */
101
102 if (charset == NULL)
103 charset = write_charset_8bit();
104
105 if (strcasecmp(charset, "US-ASCII") == 0) {
106 advise(NULL, "Cannot use US-ASCII with 8 bit characters in header");
107 return 1;
108 }
109
110 /*
111 * If we have an address header, then we need to parse the addresses
112 * and only encode the names or comments. Otherwise, handle it normally.
113 */
114
115 for (i = 0; address_headers[i]; i++) {
116 if (strcasecmp(name, address_headers[i]) == 0)
117 return field_encode_address(name, value, encoding, charset);
118 }
119
120 /*
121 * On the encoding we choose, and the specifics of encoding:
122 *
123 * - If a specified encoding is passed in, we use that.
124 * - If more than 50% of the characters are high-bit, we use base64
125 * and encode the whole field as one atom (possibly split).
126 * - Otherwise, we use quoted-printable.
127 */
128
129 if (encoding == CE_UNKNOWN)
130 encoding = (eightbitcount * 10 / (asciicount + eightbitcount) > 5) ?
131 CE_BASE64 : CE_QUOTED;
132
133 unfold_header(value, asciicount + eightbitcount);
134
135 switch (encoding) {
136
137 case CE_BASE64:
138 return field_encode_base64(name, value, charset);
139
140 case CE_QUOTED:
141 return field_encode_quoted(name, value, charset, asciicount,
142 eightbitcount + qpspecialcount);
143
144 default:
145 advise(NULL, "Internal error: unknown RFC-2047 encoding type");
146 return 1;
147 }
148 }
149
150 /*
151 * Encode our specified header (or field) using quoted-printable
152 */
153
154 static int
155 field_encode_quoted(const char *name, char **value, const char *charset,
156 int ascii, int encoded)
157 {
158 int prefixlen = name ? strlen(name) + 2: 0, outlen = 0, column, newline = 1;
159 int charsetlen = strlen(charset), utf8;
160 char *output = NULL, *p, *q;
161
162 /*
163 * Right now we just encode the whole thing. Maybe later on we'll
164 * only encode things on a per-atom basis.
165 */
166
167 p = *value;
168
169 column = prefixlen + 2; /* Header name plus ": " */
170
171 utf8 = strcasecmp(charset, "UTF-8") == 0;
172
173 while (*p != '\0') {
174 /*
175 * Start a new line, if it's time
176 */
177 if (newline) {
178 /*
179 * If it's the start of the header, we don't need to pad it
180 *
181 * The length of the output string is ...
182 * =?charset?Q?...?= so that's 7+strlen(charset) + 2 for \n NUL
183 *
184 * plus 1 for every ASCII character and 3 for every eight bit
185 * or special character (eight bit characters are written as =XX).
186 *
187 */
188
189 int tokenlen;
190
191 outlen += 9 + charsetlen + ascii + 3 * encoded;
192
193 /*
194 * If output is set, then we're continuing the header. Otherwise
195 * do the initial allocation.
196 */
197
198 if (output) {
199 int curlen = q - output, i;
200 outlen += prefixlen + 1; /* Header plus \n ": " */
201 output = mh_xrealloc(output, outlen);
202 q = output + curlen;
203 *q++ = '?';
204 *q++ = '=';
205 *q++ = '\n';
206 for (i = 0; i < prefixlen; i++)
207 *q++ = ' ';
208 } else {
209 /*
210 * A bit of a hack here; the header can contain multiple
211 * spaces (probably at least one) until we get to the
212 * actual text. Copy until we get to a non-space.
213 */
214 output = mh_xmalloc(outlen);
215 q = output;
216 while (is_fws(*p))
217 *q++ = *p++;
218 }
219
220 tokenlen = snprintf(q, outlen - (q - output), "=?%s?Q?", charset);
221 q += tokenlen;
222 column = prefixlen + tokenlen;
223 newline = 0;
224 }
225
226 /*
227 * Process each character, encoding if necessary
228 */
229
230 column++;
231
232 if (*p == ' ') {
233 *q++ = '_';
234 ascii--;
235 } else if (isascii((int) *p) && !qpspecial((int) *p)) {
236 *q++ = *p;
237 ascii--;
238 } else {
239 snprintf(q, outlen - (q - output), "=%02X", (unsigned char) *p);
240 q += 3;
241 column += 2; /* column already incremented by 1 above */
242 encoded--;
243 }
244
245 p++;
246
247 /*
248 * We're not allowed more than ENCODELINELIMIT characters per line,
249 * so reserve some room for the final ?=.
250 *
251 * If prefixlen == 0, we haven't been passed in a header name, so
252 * don't ever wrap the field (we're likely doing an address).
253 */
254
255 if (prefixlen == 0)
256 continue;
257
258 if (column >= ENCODELINELIMIT - 2) {
259 newline = 1;
260 } else if (utf8) {
261 /*
262 * Okay, this is a bit weird, but to explain a bit more ...
263 *
264 * RFC 2047 prohibits the splitting of multibyte characters
265 * across encoded words. Right now we only handle the case
266 * of UTF-8, the most common multibyte encoding.
267 *
268 * p is now pointing at the next input character. If we're
269 * using UTF-8 _and_ we'd go over ENCODELINELIMIT given the
270 * length of the complete character, then trigger a newline
271 * now. Note that we check the length * 3 since we have to
272 * allow for the encoded output.
273 */
274 if (column + (utf8len(p) * 3) > ENCODELINELIMIT - 2) {
275 newline = 1;
276 }
277 }
278 }
279
280 strcat(q, "?=\n");
281
282 free(*value);
283
284 *value = output;
285
286 return 0;
287 }
288
289 /*
290 * Encode our specified header (or field) using base64.
291 *
292 * This is a little easier since every character gets encoded, we can
293 * calculate the line wrap up front.
294 */
295
296 static int
297 field_encode_base64(const char *name, char **value, const char *charset)
298 {
299 int prefixlen = name ? strlen(name) + 2 : 0, charsetlen = strlen(charset);
300 int outlen = 0, numencode;
301 char *output = NULL, *p = *value, *q, *linestart;
302
303 /*
304 * If we had a zero-length prefix, then just encode the whole field
305 * as-is, without line wrapping. Note that in addition to the encoding
306 *
307 * The added length we need is =? + charset + ?B? ... ?=
308 *
309 * That's 7 + strlen(charset) + 2 (for \n NUL).
310 */
311
312 while (prefixlen && ((base64len(strlen(p)) + 7 + charsetlen +
313 prefixlen) > ENCODELINELIMIT)) {
314
315 /*
316 * Our very first time, don't pad the line in the front
317 */
318
319
320 if (! output) {
321 outlen += ENCODELINELIMIT - prefixlen + 1;
322 output = q = mh_xmalloc(outlen);
323 linestart = q - prefixlen; /* Yes, this is intentional */
324 } else {
325 int curlen = q - output;
326
327 outlen += ENCODELINELIMIT + 1;
328 output = mh_xrealloc(output, outlen);
329 linestart = q = output + curlen;
330 q += snprintf(q, outlen - (q - output), "%*s", prefixlen, "");
331 }
332
333 /*
334 * We should have enough space now, so prepend the encoding markers
335 * and character set information
336 */
337
338 q += snprintf(q, outlen - (q - output), "=?%s?B?", charset);
339
340 /*
341 * Find out how much room we have left on the line and see how many
342 * characters we can stuff in. The start of our line is marked
343 * by "linestart", so use that to figure out how many characters
344 * are left out of ENCODELINELIMIT. Reserve 2 characters for the
345 * end markers, and calculate how many characters we can fit into
346 * that space given the base64 encoding expansion.
347 */
348
349 numencode = strbase64(ENCODELINELIMIT - (q - linestart) - 2);
350
351 if (numencode <= 0) {
352 advise(NULL, "Internal error: tried to encode %d characters "
353 "in base64", numencode);
354 return 1;
355 }
356
357 /*
358 * RFC 2047 prohibits spanning multibyte characters across tokens.
359 * Right now we only check for UTF-8.
360 */
361 }
362
363 return 0;
364 }
365
366 /*
367 * Calculate the length of a UTF-8 character.
368 *
369 * If it's not a UTF-8 character (or we're in the middle of a multibyte
370 * character) then simply return 0.
371 */
372
373 static int
374 utf8len(const char *p)
375 {
376 int len = 1;
377
378 if (*p == '\0')
379 return 0;
380
381 if (isascii((unsigned char) *p) || (((unsigned char) *p) & 0xc0) == 0x80)
382 return 0;
383
384 p++;
385 while ((((unsigned char) *p++) & 0xc0) == 0x80)
386 len++;
387
388 return len;
389 }
390
391 /*
392 * "Unfold" a header, making it a single line (without continuation)
393 *
394 * We cheat a bit here; we never make the string longer, so using the
395 * original length here is fine.
396 */
397
398 static void
399 unfold_header(char **value, int len)
400 {
401 char *str = mh_xmalloc(len + 1);
402 char *p = str, *q = *value;
403
404 while (*q != '\0') {
405 if (*q == '\n') {
406 /*
407 * When we get a newline, skip to the next non-whitespace
408 * character and add a space to replace all of the whitespace
409 *
410 * This has the side effect of stripping off the final newline
411 * for the header; we put it back in the encoding routine.
412 */
413 while (is_fws(*q++))
414 ;
415 if (*q == '\0')
416 break;
417
418 *p++ = ' ';
419 } else {
420 *p++ = *q++;
421 }
422 }
423
424 *p = '\0';
425
426 free(*value);
427 *value = str;
428 }
429
430 static int
431 field_encode_address(const char *name, char **value, int encoding,
432 const char *charset)
433 {
434 return 0;
435 }