]> diplodocus.org Git - nmh/blob - sbr/encode_rfc2047.c
dfa373e36366f28cf1b7b68431dd6bc1f06db0a7
[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, "?=");
281
282 if (prefixlen)
283 strcat(q, "\n");
284
285 free(*value);
286
287 *value = output;
288
289 return 0;
290 }
291
292 /*
293 * Encode our specified header (or field) using base64.
294 *
295 * This is a little easier since every character gets encoded, we can
296 * calculate the line wrap up front.
297 */
298
299 static int
300 field_encode_base64(const char *name, char **value, const char *charset)
301 {
302 int prefixlen = name ? strlen(name) + 2 : 0, charsetlen = strlen(charset);
303 int outlen = 0, numencode, curlen;
304 char *output = NULL, *p = *value, *q = NULL, *linestart;
305
306 /*
307 * If we had a zero-length prefix, then just encode the whole field
308 * as-is, without line wrapping. Note that in addition to the encoding
309 *
310 * The added length we need is =? + charset + ?B? ... ?=
311 *
312 * That's 7 + strlen(charset) + 2 (for \n NUL).
313 */
314
315 while (prefixlen && ((base64len(strlen(p)) + 7 + charsetlen +
316 prefixlen) > ENCODELINELIMIT)) {
317
318 /*
319 * Our very first time, don't pad the line in the front
320 */
321
322
323 if (! output) {
324 outlen += ENCODELINELIMIT - prefixlen + 1;
325 output = q = mh_xmalloc(outlen);
326 linestart = q - prefixlen; /* Yes, this is intentional */
327 } else {
328 curlen = q - output;
329
330 outlen += ENCODELINELIMIT + 1;
331 output = mh_xrealloc(output, outlen);
332 linestart = q = output + curlen;
333 q += snprintf(q, outlen - (q - output), "%*s", prefixlen, "");
334 }
335
336 /*
337 * We should have enough space now, so prepend the encoding markers
338 * and character set information
339 */
340
341 q += snprintf(q, outlen - (q - output), "=?%s?B?", charset);
342
343 /*
344 * Find out how much room we have left on the line and see how many
345 * characters we can stuff in. The start of our line is marked
346 * by "linestart", so use that to figure out how many characters
347 * are left out of ENCODELINELIMIT. Reserve 2 characters for the
348 * end markers, and calculate how many characters we can fit into
349 * that space given the base64 encoding expansion.
350 */
351
352 numencode = strbase64(ENCODELINELIMIT - (q - linestart) - 2);
353
354 if (numencode <= 0) {
355 advise(NULL, "Internal error: tried to encode %d characters "
356 "in base64", numencode);
357 return 1;
358 }
359
360 /*
361 * RFC 2047 prohibits spanning multibyte characters across tokens.
362 * Right now we only check for UTF-8.
363 *
364 * So note the key here ... we want to make sure the character BEYOND
365 * our last character is not a continuation byte. If it's the start
366 * of a new multibyte character or a single-byte character, that's ok.
367 */
368
369 if (strcasecmp(charset, "UTF-8") == 0) {
370 /*
371 * p points to the start of our current buffer, so p + numencode
372 * is one past the last character to encode
373 */
374
375 while (numencode > 0 && ((*(p + numencode) & 0xc0) == 0x80))
376 numencode--;
377
378 if (numencode == 0) {
379 advise(NULL, "Internal error: could not find start of "
380 "UTF-8 character when base64 encoding header");
381 return 1;
382 }
383 }
384
385 if (writeBase64raw((unsigned char *) p, numencode,
386 (unsigned char *) q) != OK) {
387 advise(NULL, "Internal error: base64 encoding of header failed");
388 return 1;
389 }
390
391 p += numencode;
392 q += base64len(numencode);
393 *q++ = '?';
394 *q++ = '=';
395 *q++ = '\n';
396 *q++ = '\0';
397 }
398
399 /*
400 * We're here if there is either no prefix, or we can fit it in less
401 * than ENCODELINELIMIT characters. Encode the whole thing.
402 */
403
404 outlen += prefixlen + 9 + charsetlen + base64len(strlen(p));
405 curlen = q - output;
406
407 output = mh_xrealloc(output, outlen);
408 q = output + curlen;
409
410 q += snprintf(q, outlen - (q - output), "=?%s?B?", charset);
411
412 if (writeBase64raw((unsigned char *) p, strlen(p),
413 (unsigned char *) q) != OK) {
414 advise(NULL, "Internal error: base64 encoding of header failed");
415 return 1;
416 }
417
418 strcat(q, "?=");
419
420 if (prefixlen)
421 strcat(q, "\n");
422
423 free(*value);
424
425 *value = output;
426
427 return 0;
428 }
429
430 /*
431 * Calculate the length of a UTF-8 character.
432 *
433 * If it's not a UTF-8 character (or we're in the middle of a multibyte
434 * character) then simply return 0.
435 */
436
437 static int
438 utf8len(const char *p)
439 {
440 int len = 1;
441
442 if (*p == '\0')
443 return 0;
444
445 if (isascii((unsigned char) *p) || (((unsigned char) *p) & 0xc0) == 0x80)
446 return 0;
447
448 p++;
449 while ((((unsigned char) *p++) & 0xc0) == 0x80)
450 len++;
451
452 return len;
453 }
454
455 /*
456 * "Unfold" a header, making it a single line (without continuation)
457 *
458 * We cheat a bit here; we never make the string longer, so using the
459 * original length here is fine.
460 */
461
462 static void
463 unfold_header(char **value, int len)
464 {
465 char *str = mh_xmalloc(len + 1);
466 char *p = str, *q = *value;
467
468 while (*q != '\0') {
469 if (*q == '\n') {
470 /*
471 * When we get a newline, skip to the next non-whitespace
472 * character and add a space to replace all of the whitespace
473 *
474 * This has the side effect of stripping off the final newline
475 * for the header; we put it back in the encoding routine.
476 */
477 while (is_fws(*q++))
478 ;
479 if (*q == '\0')
480 break;
481
482 *p++ = ' ';
483 } else {
484 *p++ = *q++;
485 }
486 }
487
488 *p = '\0';
489
490 free(*value);
491 *value = str;
492 }
493
494 static int
495 field_encode_address(const char *name, char **value, int encoding,
496 const char *charset)
497 {
498 return 0;
499 }