charset.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. from __future__ import unicode_literals
  2. from __future__ import division
  3. from __future__ import absolute_import
  4. from future.builtins import str
  5. from future.builtins import next
  6. # Copyright (C) 2001-2007 Python Software Foundation
  7. # Author: Ben Gertzfield, Barry Warsaw
  8. # Contact: email-sig@python.org
  9. __all__ = [
  10. 'Charset',
  11. 'add_alias',
  12. 'add_charset',
  13. 'add_codec',
  14. ]
  15. from functools import partial
  16. from future.backports import email
  17. from future.backports.email import errors
  18. from future.backports.email.encoders import encode_7or8bit
  19. # Flags for types of header encodings
  20. QP = 1 # Quoted-Printable
  21. BASE64 = 2 # Base64
  22. SHORTEST = 3 # the shorter of QP and base64, but only for headers
  23. # In "=?charset?q?hello_world?=", the =?, ?q?, and ?= add up to 7
  24. RFC2047_CHROME_LEN = 7
  25. DEFAULT_CHARSET = 'us-ascii'
  26. UNKNOWN8BIT = 'unknown-8bit'
  27. EMPTYSTRING = ''
  28. # Defaults
  29. CHARSETS = {
  30. # input header enc body enc output conv
  31. 'iso-8859-1': (QP, QP, None),
  32. 'iso-8859-2': (QP, QP, None),
  33. 'iso-8859-3': (QP, QP, None),
  34. 'iso-8859-4': (QP, QP, None),
  35. # iso-8859-5 is Cyrillic, and not especially used
  36. # iso-8859-6 is Arabic, also not particularly used
  37. # iso-8859-7 is Greek, QP will not make it readable
  38. # iso-8859-8 is Hebrew, QP will not make it readable
  39. 'iso-8859-9': (QP, QP, None),
  40. 'iso-8859-10': (QP, QP, None),
  41. # iso-8859-11 is Thai, QP will not make it readable
  42. 'iso-8859-13': (QP, QP, None),
  43. 'iso-8859-14': (QP, QP, None),
  44. 'iso-8859-15': (QP, QP, None),
  45. 'iso-8859-16': (QP, QP, None),
  46. 'windows-1252':(QP, QP, None),
  47. 'viscii': (QP, QP, None),
  48. 'us-ascii': (None, None, None),
  49. 'big5': (BASE64, BASE64, None),
  50. 'gb2312': (BASE64, BASE64, None),
  51. 'euc-jp': (BASE64, None, 'iso-2022-jp'),
  52. 'shift_jis': (BASE64, None, 'iso-2022-jp'),
  53. 'iso-2022-jp': (BASE64, None, None),
  54. 'koi8-r': (BASE64, BASE64, None),
  55. 'utf-8': (SHORTEST, BASE64, 'utf-8'),
  56. }
  57. # Aliases for other commonly-used names for character sets. Map
  58. # them to the real ones used in email.
  59. ALIASES = {
  60. 'latin_1': 'iso-8859-1',
  61. 'latin-1': 'iso-8859-1',
  62. 'latin_2': 'iso-8859-2',
  63. 'latin-2': 'iso-8859-2',
  64. 'latin_3': 'iso-8859-3',
  65. 'latin-3': 'iso-8859-3',
  66. 'latin_4': 'iso-8859-4',
  67. 'latin-4': 'iso-8859-4',
  68. 'latin_5': 'iso-8859-9',
  69. 'latin-5': 'iso-8859-9',
  70. 'latin_6': 'iso-8859-10',
  71. 'latin-6': 'iso-8859-10',
  72. 'latin_7': 'iso-8859-13',
  73. 'latin-7': 'iso-8859-13',
  74. 'latin_8': 'iso-8859-14',
  75. 'latin-8': 'iso-8859-14',
  76. 'latin_9': 'iso-8859-15',
  77. 'latin-9': 'iso-8859-15',
  78. 'latin_10':'iso-8859-16',
  79. 'latin-10':'iso-8859-16',
  80. 'cp949': 'ks_c_5601-1987',
  81. 'euc_jp': 'euc-jp',
  82. 'euc_kr': 'euc-kr',
  83. 'ascii': 'us-ascii',
  84. }
  85. # Map charsets to their Unicode codec strings.
  86. CODEC_MAP = {
  87. 'gb2312': 'eucgb2312_cn',
  88. 'big5': 'big5_tw',
  89. # Hack: We don't want *any* conversion for stuff marked us-ascii, as all
  90. # sorts of garbage might be sent to us in the guise of 7-bit us-ascii.
  91. # Let that stuff pass through without conversion to/from Unicode.
  92. 'us-ascii': None,
  93. }
  94. # Convenience functions for extending the above mappings
  95. def add_charset(charset, header_enc=None, body_enc=None, output_charset=None):
  96. """Add character set properties to the global registry.
  97. charset is the input character set, and must be the canonical name of a
  98. character set.
  99. Optional header_enc and body_enc is either Charset.QP for
  100. quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for
  101. the shortest of qp or base64 encoding, or None for no encoding. SHORTEST
  102. is only valid for header_enc. It describes how message headers and
  103. message bodies in the input charset are to be encoded. Default is no
  104. encoding.
  105. Optional output_charset is the character set that the output should be
  106. in. Conversions will proceed from input charset, to Unicode, to the
  107. output charset when the method Charset.convert() is called. The default
  108. is to output in the same character set as the input.
  109. Both input_charset and output_charset must have Unicode codec entries in
  110. the module's charset-to-codec mapping; use add_codec(charset, codecname)
  111. to add codecs the module does not know about. See the codecs module's
  112. documentation for more information.
  113. """
  114. if body_enc == SHORTEST:
  115. raise ValueError('SHORTEST not allowed for body_enc')
  116. CHARSETS[charset] = (header_enc, body_enc, output_charset)
  117. def add_alias(alias, canonical):
  118. """Add a character set alias.
  119. alias is the alias name, e.g. latin-1
  120. canonical is the character set's canonical name, e.g. iso-8859-1
  121. """
  122. ALIASES[alias] = canonical
  123. def add_codec(charset, codecname):
  124. """Add a codec that map characters in the given charset to/from Unicode.
  125. charset is the canonical name of a character set. codecname is the name
  126. of a Python codec, as appropriate for the second argument to the unicode()
  127. built-in, or to the encode() method of a Unicode string.
  128. """
  129. CODEC_MAP[charset] = codecname
  130. # Convenience function for encoding strings, taking into account
  131. # that they might be unknown-8bit (ie: have surrogate-escaped bytes)
  132. def _encode(string, codec):
  133. string = str(string)
  134. if codec == UNKNOWN8BIT:
  135. return string.encode('ascii', 'surrogateescape')
  136. else:
  137. return string.encode(codec)
  138. class Charset(object):
  139. """Map character sets to their email properties.
  140. This class provides information about the requirements imposed on email
  141. for a specific character set. It also provides convenience routines for
  142. converting between character sets, given the availability of the
  143. applicable codecs. Given a character set, it will do its best to provide
  144. information on how to use that character set in an email in an
  145. RFC-compliant way.
  146. Certain character sets must be encoded with quoted-printable or base64
  147. when used in email headers or bodies. Certain character sets must be
  148. converted outright, and are not allowed in email. Instances of this
  149. module expose the following information about a character set:
  150. input_charset: The initial character set specified. Common aliases
  151. are converted to their `official' email names (e.g. latin_1
  152. is converted to iso-8859-1). Defaults to 7-bit us-ascii.
  153. header_encoding: If the character set must be encoded before it can be
  154. used in an email header, this attribute will be set to
  155. Charset.QP (for quoted-printable), Charset.BASE64 (for
  156. base64 encoding), or Charset.SHORTEST for the shortest of
  157. QP or BASE64 encoding. Otherwise, it will be None.
  158. body_encoding: Same as header_encoding, but describes the encoding for the
  159. mail message's body, which indeed may be different than the
  160. header encoding. Charset.SHORTEST is not allowed for
  161. body_encoding.
  162. output_charset: Some character sets must be converted before they can be
  163. used in email headers or bodies. If the input_charset is
  164. one of them, this attribute will contain the name of the
  165. charset output will be converted to. Otherwise, it will
  166. be None.
  167. input_codec: The name of the Python codec used to convert the
  168. input_charset to Unicode. If no conversion codec is
  169. necessary, this attribute will be None.
  170. output_codec: The name of the Python codec used to convert Unicode
  171. to the output_charset. If no conversion codec is necessary,
  172. this attribute will have the same value as the input_codec.
  173. """
  174. def __init__(self, input_charset=DEFAULT_CHARSET):
  175. # RFC 2046, $4.1.2 says charsets are not case sensitive. We coerce to
  176. # unicode because its .lower() is locale insensitive. If the argument
  177. # is already a unicode, we leave it at that, but ensure that the
  178. # charset is ASCII, as the standard (RFC XXX) requires.
  179. try:
  180. if isinstance(input_charset, str):
  181. input_charset.encode('ascii')
  182. else:
  183. input_charset = str(input_charset, 'ascii')
  184. except UnicodeError:
  185. raise errors.CharsetError(input_charset)
  186. input_charset = input_charset.lower()
  187. # Set the input charset after filtering through the aliases
  188. self.input_charset = ALIASES.get(input_charset, input_charset)
  189. # We can try to guess which encoding and conversion to use by the
  190. # charset_map dictionary. Try that first, but let the user override
  191. # it.
  192. henc, benc, conv = CHARSETS.get(self.input_charset,
  193. (SHORTEST, BASE64, None))
  194. if not conv:
  195. conv = self.input_charset
  196. # Set the attributes, allowing the arguments to override the default.
  197. self.header_encoding = henc
  198. self.body_encoding = benc
  199. self.output_charset = ALIASES.get(conv, conv)
  200. # Now set the codecs. If one isn't defined for input_charset,
  201. # guess and try a Unicode codec with the same name as input_codec.
  202. self.input_codec = CODEC_MAP.get(self.input_charset,
  203. self.input_charset)
  204. self.output_codec = CODEC_MAP.get(self.output_charset,
  205. self.output_charset)
  206. def __str__(self):
  207. return self.input_charset.lower()
  208. __repr__ = __str__
  209. def __eq__(self, other):
  210. return str(self) == str(other).lower()
  211. def __ne__(self, other):
  212. return not self.__eq__(other)
  213. def get_body_encoding(self):
  214. """Return the content-transfer-encoding used for body encoding.
  215. This is either the string `quoted-printable' or `base64' depending on
  216. the encoding used, or it is a function in which case you should call
  217. the function with a single argument, the Message object being
  218. encoded. The function should then set the Content-Transfer-Encoding
  219. header itself to whatever is appropriate.
  220. Returns "quoted-printable" if self.body_encoding is QP.
  221. Returns "base64" if self.body_encoding is BASE64.
  222. Returns conversion function otherwise.
  223. """
  224. assert self.body_encoding != SHORTEST
  225. if self.body_encoding == QP:
  226. return 'quoted-printable'
  227. elif self.body_encoding == BASE64:
  228. return 'base64'
  229. else:
  230. return encode_7or8bit
  231. def get_output_charset(self):
  232. """Return the output character set.
  233. This is self.output_charset if that is not None, otherwise it is
  234. self.input_charset.
  235. """
  236. return self.output_charset or self.input_charset
  237. def header_encode(self, string):
  238. """Header-encode a string by converting it first to bytes.
  239. The type of encoding (base64 or quoted-printable) will be based on
  240. this charset's `header_encoding`.
  241. :param string: A unicode string for the header. It must be possible
  242. to encode this string to bytes using the character set's
  243. output codec.
  244. :return: The encoded string, with RFC 2047 chrome.
  245. """
  246. codec = self.output_codec or 'us-ascii'
  247. header_bytes = _encode(string, codec)
  248. # 7bit/8bit encodings return the string unchanged (modulo conversions)
  249. encoder_module = self._get_encoder(header_bytes)
  250. if encoder_module is None:
  251. return string
  252. return encoder_module.header_encode(header_bytes, codec)
  253. def header_encode_lines(self, string, maxlengths):
  254. """Header-encode a string by converting it first to bytes.
  255. This is similar to `header_encode()` except that the string is fit
  256. into maximum line lengths as given by the argument.
  257. :param string: A unicode string for the header. It must be possible
  258. to encode this string to bytes using the character set's
  259. output codec.
  260. :param maxlengths: Maximum line length iterator. Each element
  261. returned from this iterator will provide the next maximum line
  262. length. This parameter is used as an argument to built-in next()
  263. and should never be exhausted. The maximum line lengths should
  264. not count the RFC 2047 chrome. These line lengths are only a
  265. hint; the splitter does the best it can.
  266. :return: Lines of encoded strings, each with RFC 2047 chrome.
  267. """
  268. # See which encoding we should use.
  269. codec = self.output_codec or 'us-ascii'
  270. header_bytes = _encode(string, codec)
  271. encoder_module = self._get_encoder(header_bytes)
  272. encoder = partial(encoder_module.header_encode, charset=codec)
  273. # Calculate the number of characters that the RFC 2047 chrome will
  274. # contribute to each line.
  275. charset = self.get_output_charset()
  276. extra = len(charset) + RFC2047_CHROME_LEN
  277. # Now comes the hard part. We must encode bytes but we can't split on
  278. # bytes because some character sets are variable length and each
  279. # encoded word must stand on its own. So the problem is you have to
  280. # encode to bytes to figure out this word's length, but you must split
  281. # on characters. This causes two problems: first, we don't know how
  282. # many octets a specific substring of unicode characters will get
  283. # encoded to, and second, we don't know how many ASCII characters
  284. # those octets will get encoded to. Unless we try it. Which seems
  285. # inefficient. In the interest of being correct rather than fast (and
  286. # in the hope that there will be few encoded headers in any such
  287. # message), brute force it. :(
  288. lines = []
  289. current_line = []
  290. maxlen = next(maxlengths) - extra
  291. for character in string:
  292. current_line.append(character)
  293. this_line = EMPTYSTRING.join(current_line)
  294. length = encoder_module.header_length(_encode(this_line, charset))
  295. if length > maxlen:
  296. # This last character doesn't fit so pop it off.
  297. current_line.pop()
  298. # Does nothing fit on the first line?
  299. if not lines and not current_line:
  300. lines.append(None)
  301. else:
  302. separator = (' ' if lines else '')
  303. joined_line = EMPTYSTRING.join(current_line)
  304. header_bytes = _encode(joined_line, codec)
  305. lines.append(encoder(header_bytes))
  306. current_line = [character]
  307. maxlen = next(maxlengths) - extra
  308. joined_line = EMPTYSTRING.join(current_line)
  309. header_bytes = _encode(joined_line, codec)
  310. lines.append(encoder(header_bytes))
  311. return lines
  312. def _get_encoder(self, header_bytes):
  313. if self.header_encoding == BASE64:
  314. return email.base64mime
  315. elif self.header_encoding == QP:
  316. return email.quoprimime
  317. elif self.header_encoding == SHORTEST:
  318. len64 = email.base64mime.header_length(header_bytes)
  319. lenqp = email.quoprimime.header_length(header_bytes)
  320. if len64 < lenqp:
  321. return email.base64mime
  322. else:
  323. return email.quoprimime
  324. else:
  325. return None
  326. def body_encode(self, string):
  327. """Body-encode a string by converting it first to bytes.
  328. The type of encoding (base64 or quoted-printable) will be based on
  329. self.body_encoding. If body_encoding is None, we assume the
  330. output charset is a 7bit encoding, so re-encoding the decoded
  331. string using the ascii codec produces the correct string version
  332. of the content.
  333. """
  334. if not string:
  335. return string
  336. if self.body_encoding is BASE64:
  337. if isinstance(string, str):
  338. string = string.encode(self.output_charset)
  339. return email.base64mime.body_encode(string)
  340. elif self.body_encoding is QP:
  341. # quopromime.body_encode takes a string, but operates on it as if
  342. # it were a list of byte codes. For a (minimal) history on why
  343. # this is so, see changeset 0cf700464177. To correctly encode a
  344. # character set, then, we must turn it into pseudo bytes via the
  345. # latin1 charset, which will encode any byte as a single code point
  346. # between 0 and 255, which is what body_encode is expecting.
  347. if isinstance(string, str):
  348. string = string.encode(self.output_charset)
  349. string = string.decode('latin1')
  350. return email.quoprimime.body_encode(string)
  351. else:
  352. if isinstance(string, str):
  353. string = string.encode(self.output_charset).decode('ascii')
  354. return string