Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 1 | # Copyright (C) 2001-2006 Python Software Foundation |
| 2 | # Author: Ben Gertzfield |
| 3 | # Contact: email-sig@python.org |
| 4 | |
| 5 | """Quoted-printable content transfer encoding per RFCs 2045-2047. |
| 6 | |
| 7 | This module handles the content transfer encoding method defined in RFC 2045 |
| 8 | to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to |
| 9 | safely encode text that is in a character set similar to the 7-bit US ASCII |
| 10 | character set, but that includes some 8-bit characters that are normally not |
| 11 | allowed in email bodies or headers. |
| 12 | |
| 13 | Quoted-printable is very space-inefficient for encoding binary files; use the |
| 14 | email.base64MIME module for that instead. |
| 15 | |
| 16 | This module provides an interface to encode and decode both headers and bodies |
| 17 | with quoted-printable encoding. |
| 18 | |
| 19 | RFC 2045 defines a method for including character set information in an |
| 20 | `encoded-word' in a header. This method is commonly used for 8-bit real names |
| 21 | in To:/From:/Cc: etc. fields, as well as Subject: lines. |
| 22 | |
| 23 | This module does not do the line wrapping or end-of-line character |
| 24 | conversion necessary for proper internationalized headers; it only |
| 25 | does dumb encoding and decoding. To deal with the various line |
| 26 | wrapping issues, use the email.Header module. |
| 27 | """ |
| 28 | |
| 29 | __all__ = [ |
| 30 | 'body_decode', |
| 31 | 'body_encode', |
| 32 | 'body_quopri_check', |
| 33 | 'body_quopri_len', |
| 34 | 'decode', |
| 35 | 'decodestring', |
| 36 | 'encode', |
| 37 | 'encodestring', |
| 38 | 'header_decode', |
| 39 | 'header_encode', |
| 40 | 'header_quopri_check', |
| 41 | 'header_quopri_len', |
| 42 | 'quote', |
| 43 | 'unquote', |
| 44 | ] |
| 45 | |
| 46 | import re |
| 47 | |
| 48 | from string import ascii_letters, digits, hexdigits |
| 49 | from email.utils import fix_eols |
| 50 | |
| 51 | CRLF = '\r\n' |
| 52 | NL = '\n' |
| 53 | EMPTYSTRING = '' |
| 54 | |
| 55 | # See also Charset.py |
| 56 | MISC_LEN = 7 |
| 57 | |
Barry Warsaw | 8b3d659 | 2007-08-30 02:10:49 +0000 | [diff] [blame] | 58 | HEADER_SAFE_BYTES = (b'-!*+/ ' + |
| 59 | ascii_letters.encode('raw-unicode-escape') + |
| 60 | digits.encode('raw-unicode-escape')) |
| 61 | |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 62 | BODY_SAFE_BYTES = (b' !"#$%&\'()*+,-./0123456789:;<>' |
| 63 | b'?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`' |
| 64 | b'abcdefghijklmnopqrstuvwxyz{|}~\t') |
| 65 | |
| 66 | |
| 67 | |
| 68 | # Helpers |
| 69 | def header_quopri_check(c): |
| 70 | """Return True if the character should be escaped with header quopri.""" |
| 71 | return c not in HEADER_SAFE_BYTES |
| 72 | |
| 73 | |
| 74 | def body_quopri_check(c): |
| 75 | """Return True if the character should be escaped with body quopri.""" |
| 76 | return c not in BODY_SAFE_BYTES |
| 77 | |
| 78 | |
| 79 | def header_quopri_len(bytearray): |
| 80 | """Return the length of bytearray when it is encoded with header quopri. |
| 81 | |
| 82 | Note that this does not include any RFC 2047 chrome added by |
| 83 | `header_encode()`. |
| 84 | """ |
| 85 | count = 0 |
| 86 | for c in bytearray: |
| 87 | count += (3 if header_quopri_check(c) else 1) |
| 88 | return count |
| 89 | |
| 90 | |
| 91 | def body_quopri_len(bytearray): |
| 92 | """Return the length of bytearray when it is encoded with body quopri.""" |
| 93 | count = 0 |
| 94 | for c in bytearray: |
| 95 | count += (3 if body_quopri_check(c) else 1) |
| 96 | return count |
| 97 | |
| 98 | |
| 99 | def _max_append(L, s, maxlen, extra=''): |
| 100 | if not isinstance(s, str): |
| 101 | s = chr(s) |
| 102 | if not L: |
| 103 | L.append(s.lstrip()) |
| 104 | elif len(L[-1]) + len(s) <= maxlen: |
| 105 | L[-1] += extra + s |
| 106 | else: |
| 107 | L.append(s.lstrip()) |
| 108 | |
| 109 | |
| 110 | def unquote(s): |
| 111 | """Turn a string in the form =AB to the ASCII character with value 0xab""" |
| 112 | return chr(int(s[1:3], 16)) |
| 113 | |
| 114 | |
| 115 | def quote(c): |
| 116 | return '=%02X' % ord(c) |
| 117 | |
| 118 | |
| 119 | |
| 120 | def header_encode(header_bytes, charset='iso-8859-1'): |
| 121 | """Encode a single header line with quoted-printable (like) encoding. |
| 122 | |
| 123 | Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but |
| 124 | used specifically for email header fields to allow charsets with mostly 7 |
| 125 | bit characters (and some 8 bit) to remain more or less readable in non-RFC |
| 126 | 2045 aware mail clients. |
| 127 | |
| 128 | charset names the character set to use in the RFC 2046 header. It |
| 129 | defaults to iso-8859-1. |
| 130 | """ |
| 131 | # Return empty headers unchanged |
| 132 | if not header_bytes: |
| 133 | return str(header_bytes) |
| 134 | # Iterate over every byte, encoding if necessary. |
| 135 | encoded = [] |
| 136 | for character in header_bytes: |
| 137 | # Space may be represented as _ instead of =20 for readability |
| 138 | if character == ord(' '): |
| 139 | encoded.append('_') |
| 140 | # These characters can be included verbatim. |
| 141 | elif not header_quopri_check(character): |
| 142 | encoded.append(chr(character)) |
| 143 | # Otherwise, replace with hex value like =E2 |
| 144 | else: |
| 145 | encoded.append('=%02X' % character) |
| 146 | # Now add the RFC chrome to each encoded chunk and glue the chunks |
| 147 | # together. |
| 148 | return '=?%s?q?%s?=' % (charset, EMPTYSTRING.join(encoded)) |
| 149 | |
| 150 | |
| 151 | |
| 152 | def encode(body, binary=False, maxlinelen=76, eol=NL): |
| 153 | """Encode with quoted-printable, wrapping at maxlinelen characters. |
| 154 | |
| 155 | If binary is False (the default), end-of-line characters will be converted |
| 156 | to the canonical email end-of-line sequence \\r\\n. Otherwise they will |
| 157 | be left verbatim. |
| 158 | |
| 159 | Each line of encoded text will end with eol, which defaults to "\\n". Set |
| 160 | this to "\\r\\n" if you will be using the result of this function directly |
| 161 | in an email. |
| 162 | |
| 163 | Each line will be wrapped at, at most, maxlinelen characters (defaults to |
| 164 | 76 characters). Long lines will have the `soft linefeed' quoted-printable |
| 165 | character "=" appended to them, so the decoded text will be identical to |
| 166 | the original text. |
| 167 | """ |
| 168 | if not body: |
| 169 | return body |
| 170 | |
| 171 | if not binary: |
| 172 | body = fix_eols(body) |
| 173 | |
| 174 | # BAW: We're accumulating the body text by string concatenation. That |
| 175 | # can't be very efficient, but I don't have time now to rewrite it. It |
| 176 | # just feels like this algorithm could be more efficient. |
| 177 | encoded_body = '' |
| 178 | lineno = -1 |
| 179 | # Preserve line endings here so we can check later to see an eol needs to |
| 180 | # be added to the output later. |
| 181 | lines = body.splitlines(1) |
| 182 | for line in lines: |
| 183 | # But strip off line-endings for processing this line. |
| 184 | if line.endswith(CRLF): |
| 185 | line = line[:-2] |
| 186 | elif line[-1] in CRLF: |
| 187 | line = line[:-1] |
| 188 | |
| 189 | lineno += 1 |
| 190 | encoded_line = '' |
| 191 | prev = None |
| 192 | linelen = len(line) |
| 193 | # Now we need to examine every character to see if it needs to be |
| 194 | # quopri encoded. BAW: again, string concatenation is inefficient. |
| 195 | for j in range(linelen): |
| 196 | c = line[j] |
| 197 | prev = c |
| 198 | if body_quopri_check(c): |
| 199 | c = quote(c) |
| 200 | elif j+1 == linelen: |
| 201 | # Check for whitespace at end of line; special case |
| 202 | if c not in ' \t': |
| 203 | encoded_line += c |
| 204 | prev = c |
| 205 | continue |
| 206 | # Check to see to see if the line has reached its maximum length |
| 207 | if len(encoded_line) + len(c) >= maxlinelen: |
| 208 | encoded_body += encoded_line + '=' + eol |
| 209 | encoded_line = '' |
| 210 | encoded_line += c |
| 211 | # Now at end of line.. |
| 212 | if prev and prev in ' \t': |
| 213 | # Special case for whitespace at end of file |
| 214 | if lineno + 1 == len(lines): |
| 215 | prev = quote(prev) |
| 216 | if len(encoded_line) + len(prev) > maxlinelen: |
| 217 | encoded_body += encoded_line + '=' + eol + prev |
| 218 | else: |
| 219 | encoded_body += encoded_line + prev |
| 220 | # Just normal whitespace at end of line |
| 221 | else: |
| 222 | encoded_body += encoded_line + prev + '=' + eol |
| 223 | encoded_line = '' |
| 224 | # Now look at the line we just finished and it has a line ending, we |
| 225 | # need to add eol to the end of the line. |
| 226 | if lines[lineno].endswith(CRLF) or lines[lineno][-1] in CRLF: |
| 227 | encoded_body += encoded_line + eol |
| 228 | else: |
| 229 | encoded_body += encoded_line |
| 230 | encoded_line = '' |
| 231 | return encoded_body |
| 232 | |
| 233 | |
| 234 | # For convenience and backwards compatibility w/ standard base64 module |
| 235 | body_encode = encode |
| 236 | encodestring = encode |
| 237 | |
| 238 | |
| 239 | |
| 240 | # BAW: I'm not sure if the intent was for the signature of this function to be |
| 241 | # the same as base64MIME.decode() or not... |
| 242 | def decode(encoded, eol=NL): |
| 243 | """Decode a quoted-printable string. |
| 244 | |
| 245 | Lines are separated with eol, which defaults to \\n. |
| 246 | """ |
| 247 | if not encoded: |
| 248 | return encoded |
| 249 | # BAW: see comment in encode() above. Again, we're building up the |
| 250 | # decoded string with string concatenation, which could be done much more |
| 251 | # efficiently. |
| 252 | decoded = '' |
| 253 | |
| 254 | for line in encoded.splitlines(): |
| 255 | line = line.rstrip() |
| 256 | if not line: |
| 257 | decoded += eol |
| 258 | continue |
| 259 | |
| 260 | i = 0 |
| 261 | n = len(line) |
| 262 | while i < n: |
| 263 | c = line[i] |
| 264 | if c != '=': |
| 265 | decoded += c |
| 266 | i += 1 |
| 267 | # Otherwise, c == "=". Are we at the end of the line? If so, add |
| 268 | # a soft line break. |
| 269 | elif i+1 == n: |
| 270 | i += 1 |
| 271 | continue |
| 272 | # Decode if in form =AB |
| 273 | elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits: |
| 274 | decoded += unquote(line[i:i+3]) |
| 275 | i += 3 |
| 276 | # Otherwise, not in form =AB, pass literally |
| 277 | else: |
| 278 | decoded += c |
| 279 | i += 1 |
| 280 | |
| 281 | if i == n: |
| 282 | decoded += eol |
| 283 | # Special case if original string did not end with eol |
| 284 | if not encoded.endswith(eol) and decoded.endswith(eol): |
| 285 | decoded = decoded[:-1] |
| 286 | return decoded |
| 287 | |
| 288 | |
| 289 | # For convenience and backwards compatibility w/ standard base64 module |
| 290 | body_decode = decode |
| 291 | decodestring = decode |
| 292 | |
| 293 | |
| 294 | |
| 295 | def _unquote_match(match): |
| 296 | """Turn a match in the form =AB to the ASCII character with value 0xab""" |
| 297 | s = match.group(0) |
| 298 | return unquote(s) |
| 299 | |
| 300 | |
| 301 | # Header decoding is done a bit differently |
| 302 | def header_decode(s): |
| 303 | """Decode a string encoded with RFC 2045 MIME header `Q' encoding. |
| 304 | |
| 305 | This function does not parse a full MIME header value encoded with |
| 306 | quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use |
| 307 | the high level email.Header class for that functionality. |
| 308 | """ |
| 309 | s = s.replace('_', ' ') |
| 310 | return re.sub(r'=\w{2}', _unquote_match, s) |