quoprimime.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. from __future__ import unicode_literals
  23. from __future__ import division
  24. from __future__ import absolute_import
  25. from future.builtins import bytes, chr, dict, int, range, super
  26. __all__ = [
  27. 'body_decode',
  28. 'body_encode',
  29. 'body_length',
  30. 'decode',
  31. 'decodestring',
  32. 'header_decode',
  33. 'header_encode',
  34. 'header_length',
  35. 'quote',
  36. 'unquote',
  37. ]
  38. import re
  39. import io
  40. from string import ascii_letters, digits, hexdigits
  41. CRLF = '\r\n'
  42. NL = '\n'
  43. EMPTYSTRING = ''
  44. # Build a mapping of octets to the expansion of that octet. Since we're only
  45. # going to have 256 of these things, this isn't terribly inefficient
  46. # space-wise. Remember that headers and bodies have different sets of safe
  47. # characters. Initialize both maps with the full expansion, and then override
  48. # the safe bytes with the more compact form.
  49. _QUOPRI_HEADER_MAP = dict((c, '=%02X' % c) for c in range(256))
  50. _QUOPRI_BODY_MAP = _QUOPRI_HEADER_MAP.copy()
  51. # Safe header bytes which need no encoding.
  52. for c in bytes(b'-!*+/' + ascii_letters.encode('ascii') + digits.encode('ascii')):
  53. _QUOPRI_HEADER_MAP[c] = chr(c)
  54. # Headers have one other special encoding; spaces become underscores.
  55. _QUOPRI_HEADER_MAP[ord(' ')] = '_'
  56. # Safe body bytes which need no encoding.
  57. for c in bytes(b' !"#$%&\'()*+,-./0123456789:;<>'
  58. b'?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`'
  59. b'abcdefghijklmnopqrstuvwxyz{|}~\t'):
  60. _QUOPRI_BODY_MAP[c] = chr(c)
  61. # Helpers
  62. def header_check(octet):
  63. """Return True if the octet should be escaped with header quopri."""
  64. return chr(octet) != _QUOPRI_HEADER_MAP[octet]
  65. def body_check(octet):
  66. """Return True if the octet should be escaped with body quopri."""
  67. return chr(octet) != _QUOPRI_BODY_MAP[octet]
  68. def header_length(bytearray):
  69. """Return a header quoted-printable encoding length.
  70. Note that this does not include any RFC 2047 chrome added by
  71. `header_encode()`.
  72. :param bytearray: An array of bytes (a.k.a. octets).
  73. :return: The length in bytes of the byte array when it is encoded with
  74. quoted-printable for headers.
  75. """
  76. return sum(len(_QUOPRI_HEADER_MAP[octet]) for octet in bytearray)
  77. def body_length(bytearray):
  78. """Return a body quoted-printable encoding length.
  79. :param bytearray: An array of bytes (a.k.a. octets).
  80. :return: The length in bytes of the byte array when it is encoded with
  81. quoted-printable for bodies.
  82. """
  83. return sum(len(_QUOPRI_BODY_MAP[octet]) for octet in bytearray)
  84. def _max_append(L, s, maxlen, extra=''):
  85. if not isinstance(s, str):
  86. s = chr(s)
  87. if not L:
  88. L.append(s.lstrip())
  89. elif len(L[-1]) + len(s) <= maxlen:
  90. L[-1] += extra + s
  91. else:
  92. L.append(s.lstrip())
  93. def unquote(s):
  94. """Turn a string in the form =AB to the ASCII character with value 0xab"""
  95. return chr(int(s[1:3], 16))
  96. def quote(c):
  97. return '=%02X' % ord(c)
  98. def header_encode(header_bytes, charset='iso-8859-1'):
  99. """Encode a single header line with quoted-printable (like) encoding.
  100. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but
  101. used specifically for email header fields to allow charsets with mostly 7
  102. bit characters (and some 8 bit) to remain more or less readable in non-RFC
  103. 2045 aware mail clients.
  104. charset names the character set to use in the RFC 2046 header. It
  105. defaults to iso-8859-1.
  106. """
  107. # Return empty headers as an empty string.
  108. if not header_bytes:
  109. return ''
  110. # Iterate over every byte, encoding if necessary.
  111. encoded = []
  112. for octet in header_bytes:
  113. encoded.append(_QUOPRI_HEADER_MAP[octet])
  114. # Now add the RFC chrome to each encoded chunk and glue the chunks
  115. # together.
  116. return '=?%s?q?%s?=' % (charset, EMPTYSTRING.join(encoded))
  117. class _body_accumulator(io.StringIO):
  118. def __init__(self, maxlinelen, eol, *args, **kw):
  119. super().__init__(*args, **kw)
  120. self.eol = eol
  121. self.maxlinelen = self.room = maxlinelen
  122. def write_str(self, s):
  123. """Add string s to the accumulated body."""
  124. self.write(s)
  125. self.room -= len(s)
  126. def newline(self):
  127. """Write eol, then start new line."""
  128. self.write_str(self.eol)
  129. self.room = self.maxlinelen
  130. def write_soft_break(self):
  131. """Write a soft break, then start a new line."""
  132. self.write_str('=')
  133. self.newline()
  134. def write_wrapped(self, s, extra_room=0):
  135. """Add a soft line break if needed, then write s."""
  136. if self.room < len(s) + extra_room:
  137. self.write_soft_break()
  138. self.write_str(s)
  139. def write_char(self, c, is_last_char):
  140. if not is_last_char:
  141. # Another character follows on this line, so we must leave
  142. # extra room, either for it or a soft break, and whitespace
  143. # need not be quoted.
  144. self.write_wrapped(c, extra_room=1)
  145. elif c not in ' \t':
  146. # For this and remaining cases, no more characters follow,
  147. # so there is no need to reserve extra room (since a hard
  148. # break will immediately follow).
  149. self.write_wrapped(c)
  150. elif self.room >= 3:
  151. # It's a whitespace character at end-of-line, and we have room
  152. # for the three-character quoted encoding.
  153. self.write(quote(c))
  154. elif self.room == 2:
  155. # There's room for the whitespace character and a soft break.
  156. self.write(c)
  157. self.write_soft_break()
  158. else:
  159. # There's room only for a soft break. The quoted whitespace
  160. # will be the only content on the subsequent line.
  161. self.write_soft_break()
  162. self.write(quote(c))
  163. def body_encode(body, maxlinelen=76, eol=NL):
  164. """Encode with quoted-printable, wrapping at maxlinelen characters.
  165. Each line of encoded text will end with eol, which defaults to "\\n". Set
  166. this to "\\r\\n" if you will be using the result of this function directly
  167. in an email.
  168. Each line will be wrapped at, at most, maxlinelen characters before the
  169. eol string (maxlinelen defaults to 76 characters, the maximum value
  170. permitted by RFC 2045). Long lines will have the 'soft line break'
  171. quoted-printable character "=" appended to them, so the decoded text will
  172. be identical to the original text.
  173. The minimum maxlinelen is 4 to have room for a quoted character ("=XX")
  174. followed by a soft line break. Smaller values will generate a
  175. ValueError.
  176. """
  177. if maxlinelen < 4:
  178. raise ValueError("maxlinelen must be at least 4")
  179. if not body:
  180. return body
  181. # The last line may or may not end in eol, but all other lines do.
  182. last_has_eol = (body[-1] in '\r\n')
  183. # This accumulator will make it easier to build the encoded body.
  184. encoded_body = _body_accumulator(maxlinelen, eol)
  185. lines = body.splitlines()
  186. last_line_no = len(lines) - 1
  187. for line_no, line in enumerate(lines):
  188. last_char_index = len(line) - 1
  189. for i, c in enumerate(line):
  190. if body_check(ord(c)):
  191. c = quote(c)
  192. encoded_body.write_char(c, i==last_char_index)
  193. # Add an eol if input line had eol. All input lines have eol except
  194. # possibly the last one.
  195. if line_no < last_line_no or last_has_eol:
  196. encoded_body.newline()
  197. return encoded_body.getvalue()
  198. # BAW: I'm not sure if the intent was for the signature of this function to be
  199. # the same as base64MIME.decode() or not...
  200. def decode(encoded, eol=NL):
  201. """Decode a quoted-printable string.
  202. Lines are separated with eol, which defaults to \\n.
  203. """
  204. if not encoded:
  205. return encoded
  206. # BAW: see comment in encode() above. Again, we're building up the
  207. # decoded string with string concatenation, which could be done much more
  208. # efficiently.
  209. decoded = ''
  210. for line in encoded.splitlines():
  211. line = line.rstrip()
  212. if not line:
  213. decoded += eol
  214. continue
  215. i = 0
  216. n = len(line)
  217. while i < n:
  218. c = line[i]
  219. if c != '=':
  220. decoded += c
  221. i += 1
  222. # Otherwise, c == "=". Are we at the end of the line? If so, add
  223. # a soft line break.
  224. elif i+1 == n:
  225. i += 1
  226. continue
  227. # Decode if in form =AB
  228. elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits:
  229. decoded += unquote(line[i:i+3])
  230. i += 3
  231. # Otherwise, not in form =AB, pass literally
  232. else:
  233. decoded += c
  234. i += 1
  235. if i == n:
  236. decoded += eol
  237. # Special case if original string did not end with eol
  238. if encoded[-1] not in '\r\n' and decoded.endswith(eol):
  239. decoded = decoded[:-1]
  240. return decoded
  241. # For convenience and backwards compatibility w/ standard base64 module
  242. body_decode = decode
  243. decodestring = decode
  244. def _unquote_match(match):
  245. """Turn a match in the form =AB to the ASCII character with value 0xab"""
  246. s = match.group(0)
  247. return unquote(s)
  248. # Header decoding is done a bit differently
  249. def header_decode(s):
  250. """Decode a string encoded with RFC 2045 MIME header `Q' encoding.
  251. This function does not parse a full MIME header value encoded with
  252. quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use
  253. the high level email.header class for that functionality.
  254. """
  255. s = s.replace('_', ' ')
  256. return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s, re.ASCII)