charset.py 17 KB

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