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