quoprimime.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # Copyright (C) 2001-2006 Python Software Foundation
  2. # Author: Ben Gertzfield
  3. # Contact: email-sig@python.org
  4. """Quoted-printable content transfer encoding per RFCs 2045-2047.
  5. This module handles the content transfer encoding method defined in RFC 2045
  6. to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to
  7. safely encode text that is in a character set similar to the 7-bit US ASCII
  8. character set, but that includes some 8-bit characters that are normally not
  9. allowed in email bodies or headers.
  10. Quoted-printable is very space-inefficient for encoding binary files; use the
  11. email.base64mime module for that instead.
  12. This module provides an interface to encode and decode both headers and bodies
  13. with quoted-printable encoding.
  14. RFC 2045 defines a method for including character set information in an
  15. `encoded-word' in a header. This method is commonly used for 8-bit real names
  16. in To:/From:/Cc: etc. fields, as well as Subject: lines.
  17. This module does not do the line wrapping or end-of-line character
  18. conversion necessary for proper internationalized headers; it only
  19. does dumb encoding and decoding. To deal with the various line
  20. wrapping issues, use the email.header module.
  21. """
  22. __all__ = [
  23. 'body_decode',
  24. 'body_encode',
  25. 'body_length',
  26. 'decode',
  27. 'decodestring',
  28. 'header_decode',
  29. 'header_encode',
  30. 'header_length',
  31. 'quote',
  32. 'unquote',
  33. ]
  34. import re
  35. from string import ascii_letters, digits, hexdigits
  36. CRLF = '\r\n'
  37. NL = '\n'
  38. EMPTYSTRING = ''
  39. # Build a mapping of octets to the expansion of that octet. Since we're only
  40. # going to have 256 of these things, this isn't terribly inefficient
  41. # space-wise. Remember that headers and bodies have different sets of safe
  42. # characters. Initialize both maps with the full expansion, and then override
  43. # the safe bytes with the more compact form.
  44. _QUOPRI_MAP = ['=%02X' % c for c in range(256)]
  45. _QUOPRI_HEADER_MAP = _QUOPRI_MAP[:]
  46. _QUOPRI_BODY_MAP = _QUOPRI_MAP[:]
  47. # Safe header bytes which need no encoding.
  48. for c in b'-!*+/' + ascii_letters.encode('ascii') + digits.encode('ascii'):
  49. _QUOPRI_HEADER_MAP[c] = chr(c)
  50. # Headers have one other special encoding; spaces become underscores.
  51. _QUOPRI_HEADER_MAP[ord(' ')] = '_'
  52. # Safe body bytes which need no encoding.
  53. for c in (b' !"#$%&\'()*+,-./0123456789:;<>'
  54. b'?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`'
  55. b'abcdefghijklmnopqrstuvwxyz{|}~\t'):
  56. _QUOPRI_BODY_MAP[c] = chr(c)
  57. # Helpers
  58. def header_check(octet):
  59. """Return True if the octet should be escaped with header quopri."""
  60. return chr(octet) != _QUOPRI_HEADER_MAP[octet]
  61. def body_check(octet):
  62. """Return True if the octet should be escaped with body quopri."""
  63. return chr(octet) != _QUOPRI_BODY_MAP[octet]
  64. def header_length(bytearray):
  65. """Return a header quoted-printable encoding length.
  66. Note that this does not include any RFC 2047 chrome added by
  67. `header_encode()`.
  68. :param bytearray: An array of bytes (a.k.a. octets).
  69. :return: The length in bytes of the byte array when it is encoded with
  70. quoted-printable for headers.
  71. """
  72. return sum(len(_QUOPRI_HEADER_MAP[octet]) for octet in bytearray)
  73. def body_length(bytearray):
  74. """Return a body quoted-printable encoding length.
  75. :param bytearray: An array of bytes (a.k.a. octets).
  76. :return: The length in bytes of the byte array when it is encoded with
  77. quoted-printable for bodies.
  78. """
  79. return sum(len(_QUOPRI_BODY_MAP[octet]) for octet in bytearray)
  80. def _max_append(L, s, maxlen, extra=''):
  81. if not isinstance(s, str):
  82. s = chr(s)
  83. if not L:
  84. L.append(s.lstrip())
  85. elif len(L[-1]) + len(s) <= maxlen:
  86. L[-1] += extra + s
  87. else:
  88. L.append(s.lstrip())
  89. def unquote(s):
  90. """Turn a string in the form =AB to the ASCII character with value 0xab"""
  91. return chr(int(s[1:3], 16))
  92. def quote(c):
  93. return _QUOPRI_MAP[ord(c)]
  94. def header_encode(header_bytes, charset='iso-8859-1'):
  95. """Encode a single header line with quoted-printable (like) encoding.
  96. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but
  97. used specifically for email header fields to allow charsets with mostly 7
  98. bit characters (and some 8 bit) to remain more or less readable in non-RFC
  99. 2045 aware mail clients.
  100. charset names the character set to use in the RFC 2046 header. It
  101. defaults to iso-8859-1.
  102. """
  103. # Return empty headers as an empty string.
  104. if not header_bytes:
  105. return ''
  106. # Iterate over every byte, encoding if necessary.
  107. encoded = header_bytes.decode('latin1').translate(_QUOPRI_HEADER_MAP)
  108. # Now add the RFC chrome to each encoded chunk and glue the chunks
  109. # together.
  110. return '=?%s?q?%s?=' % (charset, encoded)
  111. _QUOPRI_BODY_ENCODE_MAP = _QUOPRI_BODY_MAP[:]
  112. for c in b'\r\n':
  113. _QUOPRI_BODY_ENCODE_MAP[c] = chr(c)
  114. def body_encode(body, maxlinelen=76, eol=NL):
  115. """Encode with quoted-printable, wrapping at maxlinelen characters.
  116. Each line of encoded text will end with eol, which defaults to "\\n". Set
  117. this to "\\r\\n" if you will be using the result of this function directly
  118. in an email.
  119. Each line will be wrapped at, at most, maxlinelen characters before the
  120. eol string (maxlinelen defaults to 76 characters, the maximum value
  121. permitted by RFC 2045). Long lines will have the 'soft line break'
  122. quoted-printable character "=" appended to them, so the decoded text will
  123. be identical to the original text.
  124. The minimum maxlinelen is 4 to have room for a quoted character ("=XX")
  125. followed by a soft line break. Smaller values will generate a
  126. ValueError.
  127. """
  128. if maxlinelen < 4:
  129. raise ValueError("maxlinelen must be at least 4")
  130. if not body:
  131. return body
  132. # quote special characters
  133. body = body.translate(_QUOPRI_BODY_ENCODE_MAP)
  134. soft_break = '=' + eol
  135. # leave space for the '=' at the end of a line
  136. maxlinelen1 = maxlinelen - 1
  137. encoded_body = []
  138. append = encoded_body.append
  139. for line in body.splitlines():
  140. # break up the line into pieces no longer than maxlinelen - 1
  141. start = 0
  142. laststart = len(line) - 1 - maxlinelen
  143. while start <= laststart:
  144. stop = start + maxlinelen1
  145. # make sure we don't break up an escape sequence
  146. if line[stop - 2] == '=':
  147. append(line[start:stop - 1])
  148. start = stop - 2
  149. elif line[stop - 1] == '=':
  150. append(line[start:stop])
  151. start = stop - 1
  152. else:
  153. append(line[start:stop] + '=')
  154. start = stop
  155. # handle rest of line, special case if line ends in whitespace
  156. if line and line[-1] in ' \t':
  157. room = start - laststart
  158. if room >= 3:
  159. # It's a whitespace character at end-of-line, and we have room
  160. # for the three-character quoted encoding.
  161. q = quote(line[-1])
  162. elif room == 2:
  163. # There's room for the whitespace character and a soft break.
  164. q = line[-1] + soft_break
  165. else:
  166. # There's room only for a soft break. The quoted whitespace
  167. # will be the only content on the subsequent line.
  168. q = soft_break + quote(line[-1])
  169. append(line[start:-1] + q)
  170. else:
  171. append(line[start:])
  172. # add back final newline if present
  173. if body[-1] in CRLF:
  174. append('')
  175. return eol.join(encoded_body)
  176. # BAW: I'm not sure if the intent was for the signature of this function to be
  177. # the same as base64MIME.decode() or not...
  178. def decode(encoded, eol=NL):
  179. """Decode a quoted-printable string.
  180. Lines are separated with eol, which defaults to \\n.
  181. """
  182. if not encoded:
  183. return encoded
  184. # BAW: see comment in encode() above. Again, we're building up the
  185. # decoded string with string concatenation, which could be done much more
  186. # efficiently.
  187. decoded = ''
  188. for line in encoded.splitlines():
  189. line = line.rstrip()
  190. if not line:
  191. decoded += eol
  192. continue
  193. i = 0
  194. n = len(line)
  195. while i < n:
  196. c = line[i]
  197. if c != '=':
  198. decoded += c
  199. i += 1
  200. # Otherwise, c == "=". Are we at the end of the line? If so, add
  201. # a soft line break.
  202. elif i+1 == n:
  203. i += 1
  204. continue
  205. # Decode if in form =AB
  206. elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits:
  207. decoded += unquote(line[i:i+3])
  208. i += 3
  209. # Otherwise, not in form =AB, pass literally
  210. else:
  211. decoded += c
  212. i += 1
  213. if i == n:
  214. decoded += eol
  215. # Special case if original string did not end with eol
  216. if encoded[-1] not in '\r\n' and decoded.endswith(eol):
  217. decoded = decoded[:-1]
  218. return decoded
  219. # For convenience and backwards compatibility w/ standard base64 module
  220. body_decode = decode
  221. decodestring = decode
  222. def _unquote_match(match):
  223. """Turn a match in the form =AB to the ASCII character with value 0xab"""
  224. s = match.group(0)
  225. return unquote(s)
  226. # Header decoding is done a bit differently
  227. def header_decode(s):
  228. """Decode a string encoded with RFC 2045 MIME header `Q' encoding.
  229. This function does not parse a full MIME header value encoded with
  230. quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use
  231. the high level email.header class for that functionality.
  232. """
  233. s = s.replace('_', ' ')
  234. return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s, flags=re.ASCII)