]>
diplodocus.org Git - nmh/blob - sbr/encode_rfc2047.c
e48d7f31ab8f935949ef22d04f3ccfd4e18d8b74
2 * Routines to encode message headers using RFC 2047-encoding.
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.
10 #include <h/mhparse.h>
11 #include <h/addrsbr.h>
15 * List of headers that contain addresses and as a result require special
19 static char *address_headers
[] = {
36 * Macros we use for parsing headers
39 #define is_fws(c) (c == '\t' || c == ' ' || c == '\n')
41 #define qphrasevalid(c) ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || \
42 (c >= 'a' && c <= 'z') || \
43 c == '!' || c == '*' || c == '+' || c == '-' || \
44 c == '/' || c == '=' || c == '_')
45 #define qpspecial(c) (c < ' ' || c == '=' || c == '?' || c == '_')
47 #define base64len(n) ((((n) + 2) / 3 ) * 4) /* String len to base64 len */
48 #define strbase64(n) ((n) / 4 * 3) /* Chars that fit in base64 */
50 #define ENCODELINELIMIT 76
52 static void unfold_header(char **, int);
53 static int field_encode_address(const char *, char **, int, const char *);
54 static int field_encode_quoted(const char *, char **, const char *, int,
56 static int field_encode_base64(const char *, char **, const char *);
57 static int scanstring(const char *, int *, int *, int *);
58 static int utf8len(const char *);
59 static int pref_encoding(int, int, int);
62 * Encode a message header using RFC 2047 encoding. We make the assumption
63 * that all characters < 128 are ASCII and as a consequence don't need any
68 encode_rfc2047(const char *name
, char **value
, int encoding
,
71 int i
, asciicount
= 0, eightbitcount
= 0, qpspecialcount
= 0;
75 * First, check to see if we even need to encode the header
78 for (p
= *value
; *p
!= '\0'; p
++) {
79 if (isascii((unsigned char) *p
)) {
81 if (qpspecial((unsigned char) *p
))
87 if (eightbitcount
== 0)
91 * Some rules from RFC 2047:
93 * - Encoded words cannot be more than 75 characters long
94 * - Multiple "long" encoded words must be on new lines.
96 * Also, we're not permitted to encode email addresses, so
97 * we need to actually _parse_ email addresses and only encode
102 * If charset was NULL, then get the value from the locale. But
103 * we reject it if it returns US-ASCII
107 charset
= write_charset_8bit();
109 if (strcasecmp(charset
, "US-ASCII") == 0) {
110 advise(NULL
, "Cannot use US-ASCII with 8 bit characters in header");
115 * If we have an address header, then we need to parse the addresses
116 * and only encode the names or comments. Otherwise, handle it normally.
119 for (i
= 0; address_headers
[i
]; i
++) {
120 if (strcasecmp(name
, address_headers
[i
]) == 0)
121 return field_encode_address(name
, value
, encoding
, charset
);
125 * On the encoding we choose, and the specifics of encoding:
127 * - If a specified encoding is passed in, we use that.
128 * - If more than 50% of the characters are high-bit, we use base64
129 * and encode the whole field as one atom (possibly split).
130 * - Otherwise, we use quoted-printable.
133 if (encoding
== CE_UNKNOWN
)
134 encoding
= (eightbitcount
* 10 / (asciicount
+ eightbitcount
) > 5) ?
135 CE_BASE64
: CE_QUOTED
;
137 unfold_header(value
, asciicount
+ eightbitcount
);
142 return field_encode_base64(name
, value
, charset
);
145 return field_encode_quoted(name
, value
, charset
, asciicount
,
146 eightbitcount
+ qpspecialcount
, 0);
149 advise(NULL
, "Internal error: unknown RFC-2047 encoding type");
155 * Encode our specified header (or field) using quoted-printable
159 field_encode_quoted(const char *name
, char **value
, const char *charset
,
160 int ascii
, int encoded
, int phraserules
)
162 int prefixlen
= name
? strlen(name
) + 2: 0, outlen
= 0, column
, newline
= 1;
163 int charsetlen
= strlen(charset
), utf8
;
164 char *output
= NULL
, *p
, *q
;
167 * Right now we just encode the whole thing. Maybe later on we'll
168 * only encode things on a per-atom basis.
173 column
= prefixlen
+ 2; /* Header name plus ": " */
175 utf8
= strcasecmp(charset
, "UTF-8") == 0;
179 * Start a new line, if it's time
183 * If it's the start of the header, we don't need to pad it
185 * The length of the output string is ...
186 * =?charset?Q?...?= so that's 7+strlen(charset) + 2 for \n NUL
188 * plus 1 for every ASCII character and 3 for every eight bit
189 * or special character (eight bit characters are written as =XX).
195 outlen
+= 9 + charsetlen
+ ascii
+ 3 * encoded
;
198 * If output is set, then we're continuing the header. Otherwise
199 * do the initial allocation.
203 int curlen
= q
- output
, i
;
204 outlen
+= prefixlen
+ 1; /* Header plus \n ": " */
205 output
= mh_xrealloc(output
, outlen
);
210 for (i
= 0; i
< prefixlen
; i
++)
214 * A bit of a hack here; the header can contain multiple
215 * spaces (probably at least one) until we get to the
216 * actual text. Copy until we get to a non-space.
218 output
= mh_xmalloc(outlen
);
224 tokenlen
= snprintf(q
, outlen
- (q
- output
), "=?%s?Q?", charset
);
226 column
= prefixlen
+ tokenlen
;
231 * Process each character, encoding if necessary
233 * Note that we have a different set of rules if we're processing
234 * RFC 5322 'phrase' (something you'd see in an address header).
242 } else if (isascii((unsigned char) *p
) &&
243 (phraserules
? qphrasevalid((unsigned char) *p
) :
244 !qpspecial((unsigned char) *p
))) {
248 snprintf(q
, outlen
- (q
- output
), "=%02X", (unsigned char) *p
);
250 column
+= 2; /* column already incremented by 1 above */
257 * We're not allowed more than ENCODELINELIMIT characters per line,
258 * so reserve some room for the final ?=.
260 * If prefixlen == 0, we haven't been passed in a header name, so
261 * don't ever wrap the field (we're likely doing an address).
267 if (column
>= ENCODELINELIMIT
- 2) {
271 * Okay, this is a bit weird, but to explain a bit more ...
273 * RFC 2047 prohibits the splitting of multibyte characters
274 * across encoded words. Right now we only handle the case
275 * of UTF-8, the most common multibyte encoding.
277 * p is now pointing at the next input character. If we're
278 * using UTF-8 _and_ we'd go over ENCODELINELIMIT given the
279 * length of the complete character, then trigger a newline
280 * now. Note that we check the length * 3 since we have to
281 * allow for the encoded output.
283 if (column
+ (utf8len(p
) * 3) > ENCODELINELIMIT
- 2) {
302 * Encode our specified header (or field) using base64.
304 * This is a little easier since every character gets encoded, we can
305 * calculate the line wrap up front.
309 field_encode_base64(const char *name
, char **value
, const char *charset
)
311 int prefixlen
= name
? strlen(name
) + 2 : 0, charsetlen
= strlen(charset
);
312 int outlen
= 0, numencode
, curlen
;
313 char *output
= NULL
, *p
= *value
, *q
= NULL
, *linestart
;
316 * Skip over any leading white space.
319 while (*p
== ' ' || *p
== '\t')
323 * If we had a zero-length prefix, then just encode the whole field
324 * as-is, without line wrapping. Note that in addition to the encoding
326 * The added length we need is =? + charset + ?B? ... ?=
328 * That's 7 + strlen(charset) + 2 (for \n NUL).
331 while (prefixlen
&& ((base64len(strlen(p
)) + 7 + charsetlen
+
332 prefixlen
) > ENCODELINELIMIT
)) {
335 * Our very first time, don't pad the line in the front
337 * Note ENCODELINELIMIT is + 2 because of \n \0
342 outlen
+= ENCODELINELIMIT
+ 2;
343 output
= q
= mh_xmalloc(outlen
);
344 linestart
= q
- prefixlen
; /* Yes, this is intentional */
346 int curstart
= linestart
- output
;
349 outlen
+= ENCODELINELIMIT
+ 2;
350 output
= mh_xrealloc(output
, outlen
);
352 linestart
= output
+ curstart
;
356 * We should have enough space now, so prepend the encoding markers
357 * and character set information. The leading space is intentional.
360 q
+= snprintf(q
, outlen
- (q
- output
), " =?%s?B?", charset
);
363 * Find out how much room we have left on the line and see how
364 * many characters we can stuff in. The start of our line
365 * is marked by "linestart", so use that to figure out how
366 * many characters are left out of ENCODELINELIMIT. Reserve
367 * 2 characters for the end markers and calculate how many
368 * characters we can fit into that space given the base64
369 * encoding expansion.
372 numencode
= strbase64(ENCODELINELIMIT
- (q
- linestart
) - 2);
374 if (numencode
<= 0) {
375 advise(NULL
, "Internal error: tried to encode %d characters "
376 "in base64", numencode
);
381 * RFC 2047 prohibits spanning multibyte characters across tokens.
382 * Right now we only check for UTF-8.
384 * So note the key here ... we want to make sure the character BEYOND
385 * our last character is not a continuation byte. If it's the start
386 * of a new multibyte character or a single-byte character, that's ok.
389 if (strcasecmp(charset
, "UTF-8") == 0) {
391 * p points to the start of our current buffer, so p + numencode
392 * is one past the last character to encode
395 while (numencode
> 0 && ((*(p
+ numencode
) & 0xc0) == 0x80))
398 if (numencode
== 0) {
399 advise(NULL
, "Internal error: could not find start of "
400 "UTF-8 character when base64 encoding header");
405 if (writeBase64raw((unsigned char *) p
, numencode
,
406 (unsigned char *) q
) != OK
) {
407 advise(NULL
, "Internal error: base64 encoding of header failed");
412 q
+= base64len(numencode
);
415 * This will point us at the beginning of the new line (trust me).
421 * What's going on here? Well, we know we're continuing to the next
422 * line, so we want to add continuation padding. We also add the
423 * trailing marker for the RFC 2047 token at this time as well.
424 * This uses a trick of snprintf(); we tell it to print a zero-length
425 * string, but pad it out to prefixlen - 1 characters; that ends
426 * up always printing out the requested number of spaces. We use
427 * prefixlen - 1 because we always add a space on the starting
428 * token marker; this makes things work out correctly for the first
429 * line, which should have a space between the ':' and the start
432 * It's okay if you don't follow all of that.
435 q
+= snprintf(q
, outlen
- (q
- output
), "?=\n%*s", prefixlen
- 1, "");
439 * We're here if there is either no prefix, or we can fit it in less
440 * than ENCODELINELIMIT characters. Encode the whole thing.
443 outlen
+= prefixlen
+ 9 + charsetlen
+ base64len(strlen(p
));
446 output
= mh_xrealloc(output
, outlen
);
449 q
+= snprintf(q
, outlen
- (q
- output
), "%s=?%s?B?",
450 prefixlen
? " " : "", charset
);
452 if (writeBase64raw((unsigned char *) p
, strlen(p
),
453 (unsigned char *) q
) != OK
) {
454 advise(NULL
, "Internal error: base64 encoding of header failed");
471 * Calculate the length of a UTF-8 character.
473 * If it's not a UTF-8 character (or we're in the middle of a multibyte
474 * character) then simply return 0.
478 utf8len(const char *p
)
485 if (isascii((unsigned char) *p
) || (((unsigned char) *p
) & 0xc0) == 0x80)
489 while ((((unsigned char) *p
++) & 0xc0) == 0x80)
496 * "Unfold" a header, making it a single line (without continuation)
498 * We cheat a bit here; we never make the string longer, so using the
499 * original length here is fine.
503 unfold_header(char **value
, int len
)
505 char *str
= mh_xmalloc(len
+ 1);
506 char *p
= str
, *q
= *value
;
511 * When we get a newline, skip to the next non-whitespace
512 * character and add a space to replace all of the whitespace
514 * This has the side effect of stripping off the final newline
515 * for the header; we put it back in the encoding routine.
535 * Decode a header containing addresses. This means we have to parse
536 * each address and only encode the display-name or comment field.
540 field_encode_address(const char *name
, char **value
, int encoding
,
543 int prefixlen
= strlen(name
) + 2, column
= prefixlen
, groupflag
, errflag
;
544 int asciichars
, specialchars
, eightbitchars
, reformat
, len
, retval
;
545 char *mp
, *output
= NULL
;
547 size_t tmpbufsize
= 0;
551 * Because these are addresses, we need to handle them individually.
553 * Break them down and process them one by one. This means we have to
554 * rewrite the whole header, but that's unavoidable.
558 * The output headers always have to start with a space first; this
559 * is just the way the API works right now.
562 output
= add(" ", output
);
564 for (groupflag
= 0; (mp
= getname(*value
)); ) {
565 if ((mn
= getm(mp
, NULL
, 0, AD_HOST
, NULL
)) == NULL
) {
571 * We only care if the phrase (m_pers) or any trailing comment
572 * (m_note) have 8-bit characters. If doing q-p, we also need
573 * to encode anything marked as qspecial(). Unquote it first
574 * so the specialchars count is right.
577 if ((len
= strlen(mn
->m_pers
)) + 1 > tmpbufsize
) {
578 tmpbuf
= mh_xrealloc(tmpbuf
, tmpbufsize
= len
+ 1);
581 unquote_string(mn
->m_pers
, tmpbuf
);
583 if (scanstring(tmpbuf
, &asciichars
, &eightbitchars
,
586 * If we have 8-bit characters, encode it.
589 if (encoding
== CE_UNKNOWN
)
590 encoding
= prefencoding(asciichars
, specialchars
,
593 strcpy(mn
->m_pers
, tmpbuf
);
598 retval
= field_encode_base64(NULL
, &mn
->m_pers
, charset
);
602 retval
= field_encode_quoted(NULL
, &mn
->m_pers
, charset
,
604 eightbitchars
+ specialchars
, 1);
608 advise(NULL
, "Internal error: unknown RFC-2047 encoding type");
616 * Scan a string, check for characters that need to be encoded
620 scanstring(const char *string
, int *asciilen
, int *eightbitchars
,
627 for (; *string
!= '\0'; string
++) {
628 if ((isascii((unsigned char) *string
))) {
630 if (!qphrasevalid((unsigned char) *string
))
637 return eightbitchars
> 0;
641 * This function is to be used to decide which encoding algorithm we should
642 * use if one is not given. Basically, we pick whichever one is the shorter
647 * ascii - Number of ASCII characters in to-be-encoded string.
648 * specials - Number of ASCII characters in to-be-encoded string that
649 * still require encoding under quoted-printable. Note that
650 * these are included in the "ascii" total.
651 * eightbit - Eight-bit characters in the to-be-encoded string.
653 * Returns one of CE_BASE64 or CE_QUOTED.
657 prefencoding(int ascii
, int specials
, int eightbits
)
660 * The length of the q-p encoding is:
662 * ascii - specials + (specials + eightbits) * 3.
664 * The length of the base64 encoding is:
666 * base64len(ascii + eightbits) (See macro for details)
669 return base64len(ascii
+ eightbits
) < (ascii
- specials
+
670 (specials
+ eightbits
) * 3) ? CE_BASE64
: CE_QUOTED
;