]>
diplodocus.org Git - nmh/blob - sbr/encode_rfc2047.c
823fd824940becd9995e0b5fc5d7e55bb66e0f7f
1 /* encode_rfc2047.c -- encode message headers using RFC 2047 encoding.
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
9 #include "check_charset.h"
11 #include "h/mhparse.h"
12 #include "h/addrsbr.h"
18 * List of headers that contain addresses and as a result require special
22 static char *address_headers
[] = {
39 * Macros we use for parsing headers
42 #define is_fws(c) (c == '\t' || c == ' ' || c == '\n')
44 #define qphrasevalid(c) ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || \
45 (c >= 'a' && c <= 'z') || \
46 c == '!' || c == '*' || c == '+' || c == '-' || \
47 c == '/' || c == '=' || c == '_')
48 #define qpspecial(c) (c < ' ' || c == '=' || c == '?' || c == '_')
50 #define base64len(n) ((((n) + 2) / 3 ) * 4) /* String len to base64 len */
51 #define strbase64(n) ((n) / 4 * 3) /* Chars that fit in base64 */
53 #define ENCODELINELIMIT 76
55 static void unfold_header(char **, int);
56 static int field_encode_address(const char *, char **, int, const char *);
57 static int field_encode_quoted(const char *, char **, const char *, int,
59 static int field_encode_base64(const char *, char **, const char *);
60 static int scanstring(const char *, int *, int *, int *);
61 static int utf8len(const char *);
62 static int pref_encoding(int, int, int);
65 * Encode a message header using RFC 2047 encoding. We make the assumption
66 * that all characters < 128 are ASCII and as a consequence don't need any
71 encode_rfc2047(const char *name
, char **value
, int encoding
,
74 int i
, asciicount
= 0, eightbitcount
= 0, qpspecialcount
= 0;
78 * First, check to see if we even need to encode the header
81 for (p
= *value
; *p
!= '\0'; p
++) {
82 if (isascii((unsigned char) *p
)) {
84 if (qpspecial((unsigned char) *p
))
90 if (eightbitcount
== 0)
94 * Some rules from RFC 2047:
96 * - Encoded words cannot be more than 75 characters long
97 * - Multiple "long" encoded words must be on new lines.
99 * Also, we're not permitted to encode email addresses, so
100 * we need to actually _parse_ email addresses and only encode
105 * If charset was NULL, then get the value from the locale. But
106 * we reject it if it returns US-ASCII
110 charset
= write_charset_8bit();
112 if (strcasecmp(charset
, "US-ASCII") == 0) {
113 inform("Cannot use US-ASCII with 8 bit characters in header");
118 * If we have an address header, then we need to parse the addresses
119 * and only encode the names or comments. Otherwise, handle it normally.
122 for (i
= 0; address_headers
[i
]; i
++) {
123 if (strcasecmp(name
, address_headers
[i
]) == 0)
124 return field_encode_address(name
, value
, encoding
, charset
);
128 * On the encoding we choose, and the specifics of encoding:
130 * - If a specified encoding is passed in, we use that.
131 * - Otherwise, pick which encoding is shorter.
133 * We don't quite handle continuation right here, but it should be
137 if (encoding
== CE_UNKNOWN
)
138 encoding
= pref_encoding(asciicount
, qpspecialcount
, eightbitcount
);
140 unfold_header(value
, asciicount
+ eightbitcount
);
145 return field_encode_base64(name
, value
, charset
);
148 return field_encode_quoted(name
, value
, charset
, asciicount
,
149 eightbitcount
+ qpspecialcount
, 0);
152 inform("Internal error: unknown RFC-2047 encoding type");
158 * Encode our specified header (or field) using quoted-printable
162 field_encode_quoted(const char *name
, char **value
, const char *charset
,
163 int ascii
, int encoded
, int phraserules
)
165 int prefixlen
= name
? strlen(name
) + 2: 0, outlen
= 0, column
;
166 int charsetlen
= strlen(charset
), utf8
;
167 char *output
= NULL
, *p
, *q
= NULL
;
170 * Right now we just encode the whole thing. Maybe later on we'll
171 * only encode things on a per-atom basis.
176 column
= prefixlen
+ 2; /* Header name plus ": " */
178 utf8
= strcasecmp(charset
, "UTF-8") == 0;
183 * Start a new line, if it's time
187 * If it's the start of the header, we don't need to pad it
189 * The length of the output string is ...
190 * =?charset?Q?...?= so that's 7+strlen(charset) + 2 for \n NUL
192 * plus 1 for every ASCII character and 3 for every eight bit
193 * or special character (eight bit characters are written as =XX).
199 outlen
+= 9 + charsetlen
+ ascii
+ 3 * encoded
;
202 * If output is set, then we're continuing the header. Otherwise
203 * do the initial allocation.
207 int curlen
= q
- output
, i
;
208 outlen
+= prefixlen
+ 1; /* Header plus \n ": " */
209 output
= mh_xrealloc(output
, outlen
);
214 for (i
= 0; i
< prefixlen
; i
++)
218 * A bit of a hack here; the header can contain multiple
219 * spaces (probably at least one) until we get to the
220 * actual text. Copy until we get to a non-space.
222 output
= mh_xmalloc(outlen
);
228 tokenlen
= snprintf(q
, outlen
- (q
- output
), "=?%s?Q?", charset
);
230 column
= prefixlen
+ tokenlen
;
235 * Process each character, encoding if necessary
237 * Note that we have a different set of rules if we're processing
238 * RFC 5322 'phrase' (something you'd see in an address header).
246 } else if (isascii((unsigned char) *p
) &&
247 (phraserules
? qphrasevalid((unsigned char) *p
) :
248 !qpspecial((unsigned char) *p
))) {
252 snprintf(q
, outlen
- (q
- output
), "=%02X", (unsigned char) *p
);
254 column
+= 2; /* column already incremented by 1 above */
261 * We're not allowed more than ENCODELINELIMIT characters per line,
262 * so reserve some room for the final ?=.
264 * If prefixlen == 0, we haven't been passed in a header name, so
265 * don't ever wrap the field (we're likely doing an address).
271 if (column
>= ENCODELINELIMIT
- 2) {
275 * Okay, this is a bit weird, but to explain a bit more ...
277 * RFC 2047 prohibits the splitting of multibyte characters
278 * across encoded words. Right now we only handle the case
279 * of UTF-8, the most common multibyte encoding.
281 * p is now pointing at the next input character. If we're
282 * using UTF-8 _and_ we'd go over ENCODELINELIMIT given the
283 * length of the complete character, then trigger a newline
284 * now. Note that we check the length * 3 since we have to
285 * allow for the encoded output.
287 if (column
+ (utf8len(p
) * 3) > ENCODELINELIMIT
- 2) {
294 /* This should never happen, but just in case. Found by
295 clang static analyzer. */
296 inform("null output encoding for %s, continuing...", *value
);
315 * Encode our specified header (or field) using base64.
317 * This is a little easier since every character gets encoded, we can
318 * calculate the line wrap up front.
322 field_encode_base64(const char *name
, char **value
, const char *charset
)
324 int prefixlen
= name
? strlen(name
) + 2 : 0, charsetlen
= strlen(charset
);
325 int outlen
= 0, numencode
, curlen
;
326 char *output
= NULL
, *p
= *value
, *q
= NULL
, *linestart
= NULL
;
329 * Skip over any leading white space.
332 while (*p
== ' ' || *p
== '\t')
336 * If we had a zero-length prefix, then just encode the whole field
337 * as-is, without line wrapping. Note that in addition to the encoding
339 * The added length we need is =? + charset + ?B? ... ?=
341 * That's 7 + strlen(charset) + 2 (for \n NUL).
344 while (prefixlen
&& ((base64len(strlen(p
)) + 7 + charsetlen
+
345 prefixlen
) > ENCODELINELIMIT
)) {
348 * Our very first time, don't pad the line in the front
350 * Note ENCODELINELIMIT is + 2 because of \n \0
355 outlen
+= ENCODELINELIMIT
+ 2;
356 output
= q
= mh_xmalloc(outlen
);
357 linestart
= q
- prefixlen
; /* Yes, this is intentional */
359 int curstart
= linestart
- output
;
362 outlen
+= ENCODELINELIMIT
+ 2;
363 output
= mh_xrealloc(output
, outlen
);
365 linestart
= output
+ curstart
;
369 * We should have enough space now, so prepend the encoding markers
370 * and character set information. The leading space is intentional.
373 q
+= snprintf(q
, outlen
- (q
- output
), " =?%s?B?", charset
);
376 * Find out how much room we have left on the line and see how
377 * many characters we can stuff in. The start of our line
378 * is marked by "linestart", so use that to figure out how
379 * many characters are left out of ENCODELINELIMIT. Reserve
380 * 2 characters for the end markers and calculate how many
381 * characters we can fit into that space given the base64
382 * encoding expansion.
385 numencode
= strbase64(ENCODELINELIMIT
- (q
- linestart
) - 2);
387 if (numencode
<= 0) {
388 inform("Internal error: tried to encode %d characters "
389 "in base64", numencode
);
394 * RFC 2047 prohibits spanning multibyte characters across tokens.
395 * Right now we only check for UTF-8.
397 * So note the key here ... we want to make sure the character BEYOND
398 * our last character is not a continuation byte. If it's the start
399 * of a new multibyte character or a single-byte character, that's ok.
402 if (strcasecmp(charset
, "UTF-8") == 0) {
404 * p points to the start of our current buffer, so p + numencode
405 * is one past the last character to encode
408 while (numencode
> 0 && ((*(p
+ numencode
) & 0xc0) == 0x80))
411 if (numencode
== 0) {
412 inform("Internal error: could not find start of "
413 "UTF-8 character when base64 encoding header");
418 if (writeBase64raw((unsigned char *) p
, numencode
,
419 (unsigned char *) q
) != OK
) {
420 inform("Internal error: base64 encoding of header failed");
425 q
+= base64len(numencode
);
428 * This will point us at the beginning of the new line (trust me).
434 * What's going on here? Well, we know we're continuing to the next
435 * line, so we want to add continuation padding. We also add the
436 * trailing marker for the RFC 2047 token at this time as well.
437 * This uses a trick of snprintf(); we tell it to print a zero-length
438 * string, but pad it out to prefixlen - 1 characters; that ends
439 * up always printing out the requested number of spaces. We use
440 * prefixlen - 1 because we always add a space on the starting
441 * token marker; this makes things work out correctly for the first
442 * line, which should have a space between the ':' and the start
445 * It's okay if you don't follow all of that.
448 q
+= snprintf(q
, outlen
- (q
- output
), "?=\n%*s", prefixlen
- 1, "");
452 * We're here if there is either no prefix, or we can fit it in less
453 * than ENCODELINELIMIT characters. Encode the whole thing.
456 outlen
+= prefixlen
+ 9 + charsetlen
+ base64len(strlen(p
));
459 output
= mh_xrealloc(output
, outlen
);
462 q
+= snprintf(q
, outlen
- (q
- output
), "%s=?%s?B?",
463 prefixlen
? " " : "", charset
);
465 if (writeBase64raw((unsigned char *) p
, strlen(p
),
466 (unsigned char *) q
) != OK
) {
467 inform("Internal error: base64 encoding of header failed");
484 * Calculate the length of a UTF-8 character.
486 * If it's not a UTF-8 character (or we're in the middle of a multibyte
487 * character) then simply return 0.
491 utf8len(const char *p
)
498 if (isascii((unsigned char) *p
) || (((unsigned char) *p
) & 0xc0) == 0x80)
502 while ((((unsigned char) *p
++) & 0xc0) == 0x80)
509 * "Unfold" a header, making it a single line (without continuation)
511 * We cheat a bit here; we never make the string longer, so using the
512 * original length here is fine.
516 unfold_header(char **value
, int len
)
518 char *str
= mh_xmalloc(len
+ 1);
519 char *p
= str
, *q
= *value
;
524 * When we get a newline, skip to the next non-whitespace
525 * character and add a space to replace all of the whitespace
527 * This has the side effect of stripping off the final newline
528 * for the header; we put it back in the encoding routine.
548 * Decode a header containing addresses. This means we have to parse
549 * each address and only encode the display-name or comment field.
553 field_encode_address(const char *name
, char **value
, int encoding
,
556 int prefixlen
= strlen(name
) + 2, column
= prefixlen
, groupflag
;
560 bool reformat
= false;
561 bool errflag
= false;
563 char *mp
, *cp
= NULL
, *output
= NULL
;
565 size_t tmpbufsize
= 0;
570 * Because these are addresses, we need to handle them individually.
572 * Break them down and process them one by one. This means we have to
573 * rewrite the whole header, but that's unavoidable.
577 * The output headers always have to start with a space first; this
578 * is just the way the API works right now.
581 output
= add(" ", output
);
583 for (groupflag
= 0; (mp
= getname(*value
)); ) {
584 if ((mn
= getm(mp
, NULL
, 0, errbuf
, sizeof(errbuf
))) == NULL
) {
585 inform("%s: %s", errbuf
, mp
);
593 * We only care if the phrase (m_pers) or any trailing comment
594 * (m_note) have 8-bit characters. If doing q-p, we also need
595 * to encode anything marked as qspecial(). Unquote it first
596 * so the specialchars count is right.
602 if ((len
= strlen(mn
->m_pers
)) + 1 > tmpbufsize
) {
603 tmpbuf
= mh_xrealloc(tmpbuf
, tmpbufsize
= len
+ 1);
606 unquote_string(mn
->m_pers
, tmpbuf
);
608 if (scanstring(tmpbuf
, &asciichars
, &eightbitchars
,
611 * If we have 8-bit characters, encode it.
614 if (encoding
== CE_UNKNOWN
)
615 encoding
= pref_encoding(asciichars
, specialchars
,
619 * This is okay, because the output of unquote_string will be either
620 * equal or shorter than the original.
623 strcpy(mn
->m_pers
, tmpbuf
);
628 if (field_encode_base64(NULL
, &mn
->m_pers
, charset
)) {
635 if (field_encode_quoted(NULL
, &mn
->m_pers
, charset
, asciichars
,
636 eightbitchars
+ specialchars
, 1)) {
643 inform("Internal error: unknown RFC-2047 encoding type");
654 * The "note" field is generally a comment at the end of the address,
655 * at least as how it's implemented here. Notes are always surrounded
656 * by parenthesis (since they're comments). Strip them out and
657 * then put them back when we format the final field, but they do
664 if ((len
= strlen(mn
->m_note
)) + 1 > tmpbufsize
) {
665 tmpbuf
= mh_xrealloc(tmpbuf
, tmpbufsize
= len
+ 1);
668 if (mn
->m_note
[0] != '(' || mn
->m_note
[len
- 1] != ')') {
669 inform("Internal error: Invalid note field \"%s\"",
675 strncpy(tmpbuf
, mn
->m_note
+ 1, len
- 1);
676 tmpbuf
[len
- 2] = '\0';
678 if (scanstring(tmpbuf
, &asciichars
, &eightbitchars
,
681 * If we have 8-bit characters, encode it.
684 if (encoding
== CE_UNKNOWN
)
685 encoding
= pref_encoding(asciichars
, specialchars
,
691 if (field_encode_base64(NULL
, &tmpbuf
, charset
)) {
698 if (field_encode_quoted(NULL
, &tmpbuf
, charset
, asciichars
,
699 eightbitchars
+ specialchars
, 1)) {
706 inform("Internal error: unknown RFC-2047 encoding type");
714 * Make sure the size of tmpbuf is correct (it always gets
715 * reallocated in the above functions).
718 tmpbufsize
= strlen(tmpbuf
) + 1;
721 * Put the note field back surrounded by parenthesis.
724 mn
->m_note
= mh_xrealloc(mn
->m_note
, tmpbufsize
+ 2);
726 snprintf(mn
->m_note
, tmpbufsize
+ 2, "(%s)", tmpbuf
);
732 * So, some explanation is in order.
734 * We know we need to rewrite at least one address in the header,
735 * otherwise we wouldn't be here. If we had to reformat this
736 * particular address, then run it through adrformat(). Otherwise
737 * we can use m_text directly.
741 * If we were in a group but are no longer, make sure we add a
742 * semicolon (which needs to be FIRST, as it needs to be at the end
743 * of the last address).
746 if (groupflag
&& ! mn
->m_ingrp
) {
747 output
= add(";", output
);
751 groupflag
= mn
->m_ingrp
;
754 cp
= mh_xstrdup(mn
->m_gname
);
758 cp
= add(adrformat(mn
), cp
);
760 cp
= add(mn
->m_text
, cp
);
766 * If we're not at the beginning of the line, add a command and
767 * either a space or a newline.
770 if (column
!= prefixlen
) {
771 if (len
+ column
+ 2 > OUTPUTLINELEN
) {
773 if ((size_t) (prefixlen
+ 3) < tmpbufsize
)
774 tmpbuf
= mh_xrealloc(tmpbuf
, tmpbufsize
= prefixlen
+ 3);
776 snprintf(tmpbuf
, tmpbufsize
, ",\n%*s", column
= prefixlen
, "");
777 output
= add(tmpbuf
, output
);
779 output
= add(", ", output
);
785 * Finally add the address
788 output
= add(cp
, output
);
795 * Just in case we're at the end of a list
799 output
= add(";", output
);
802 output
= add("\n", output
);
816 * Scan a string, check for characters that need to be encoded
820 scanstring(const char *string
, int *asciilen
, int *eightbitchars
,
827 for (; *string
!= '\0'; string
++) {
828 if ((isascii((unsigned char) *string
))) {
831 * So, a space is not a valid phrase character, but we're counting
832 * an exception here, because in q-p a space can be directly
833 * encoded as an underscore.
835 if (!qphrasevalid((unsigned char) *string
) && *string
!= ' ')
842 return *eightbitchars
> 0;
846 * This function is to be used to decide which encoding algorithm we should
847 * use if one is not given. Basically, we pick whichever one is the shorter
852 * ascii - Number of ASCII characters in to-be-encoded string.
853 * specials - Number of ASCII characters in to-be-encoded string that
854 * still require encoding under quoted-printable. Note that
855 * these are included in the "ascii" total.
856 * eightbit - Eight-bit characters in the to-be-encoded string.
858 * Returns one of CE_BASE64 or CE_QUOTED.
862 pref_encoding(int ascii
, int specials
, int eightbits
)
865 * The length of the q-p encoding is:
867 * ascii - specials + (specials + eightbits) * 3.
869 * The length of the base64 encoding is:
871 * base64len(ascii + eightbits) (See macro for details)
874 return base64len(ascii
+ eightbits
) < (ascii
- specials
+
875 (specials
+ eightbits
) * 3) ? CE_BASE64
: CE_QUOTED
;