PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/python/Lib/email/header.py

https://github.com/vesnican/play
Python | 503 lines | 328 code | 24 blank | 151 comment | 53 complexity | 8f50db99ab1fee6b3fe0787eec1f9be2 MD5 | raw file
  1. # Copyright (C) 2002-2006 Python Software Foundation
  2. # Author: Ben Gertzfield, Barry Warsaw
  3. # Contact: email-sig@python.org
  4. """Header encoding and decoding functionality."""
  5. __all__ = [
  6. 'Header',
  7. 'decode_header',
  8. 'make_header',
  9. ]
  10. import re
  11. import binascii
  12. import email.quoprimime
  13. import email.base64mime
  14. from email.errors import HeaderParseError
  15. from email.charset import Charset
  16. NL = '\n'
  17. SPACE = ' '
  18. USPACE = u' '
  19. SPACE8 = ' ' * 8
  20. UEMPTYSTRING = u''
  21. MAXLINELEN = 76
  22. USASCII = Charset('us-ascii')
  23. UTF8 = Charset('utf-8')
  24. # Match encoded-word strings in the form =?charset?q?Hello_World?=
  25. ecre = re.compile(r'''
  26. =\? # literal =?
  27. (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
  28. \? # literal ?
  29. (?P<encoding>[qb]) # either a "q" or a "b", case insensitive
  30. \? # literal ?
  31. (?P<encoded>.*?) # non-greedy up to the next ?= is the encoded string
  32. \?= # literal ?=
  33. (?=[ \t]|$) # whitespace or the end of the string
  34. ''', re.VERBOSE | re.IGNORECASE | re.MULTILINE)
  35. # Field name regexp, including trailing colon, but not separating whitespace,
  36. # according to RFC 2822. Character range is from tilde to exclamation mark.
  37. # For use with .match()
  38. fcre = re.compile(r'[\041-\176]+:$')
  39. # Helpers
  40. _max_append = email.quoprimime._max_append
  41. def decode_header(header):
  42. """Decode a message header value without converting charset.
  43. Returns a list of (decoded_string, charset) pairs containing each of the
  44. decoded parts of the header. Charset is None for non-encoded parts of the
  45. header, otherwise a lower-case string containing the name of the character
  46. set specified in the encoded string.
  47. An email.Errors.HeaderParseError may be raised when certain decoding error
  48. occurs (e.g. a base64 decoding exception).
  49. """
  50. # If no encoding, just return the header
  51. header = str(header)
  52. if not ecre.search(header):
  53. return [(header, None)]
  54. decoded = []
  55. dec = ''
  56. for line in header.splitlines():
  57. # This line might not have an encoding in it
  58. if not ecre.search(line):
  59. decoded.append((line, None))
  60. continue
  61. parts = ecre.split(line)
  62. while parts:
  63. unenc = parts.pop(0).strip()
  64. if unenc:
  65. # Should we continue a long line?
  66. if decoded and decoded[-1][1] is None:
  67. decoded[-1] = (decoded[-1][0] + SPACE + unenc, None)
  68. else:
  69. decoded.append((unenc, None))
  70. if parts:
  71. charset, encoding = [s.lower() for s in parts[0:2]]
  72. encoded = parts[2]
  73. dec = None
  74. if encoding == 'q':
  75. dec = email.quoprimime.header_decode(encoded)
  76. elif encoding == 'b':
  77. try:
  78. dec = email.base64mime.decode(encoded)
  79. except binascii.Error:
  80. # Turn this into a higher level exception. BAW: Right
  81. # now we throw the lower level exception away but
  82. # when/if we get exception chaining, we'll preserve it.
  83. raise HeaderParseError
  84. if dec is None:
  85. dec = encoded
  86. if decoded and decoded[-1][1] == charset:
  87. decoded[-1] = (decoded[-1][0] + dec, decoded[-1][1])
  88. else:
  89. decoded.append((dec, charset))
  90. del parts[0:3]
  91. return decoded
  92. def make_header(decoded_seq, maxlinelen=None, header_name=None,
  93. continuation_ws=' '):
  94. """Create a Header from a sequence of pairs as returned by decode_header()
  95. decode_header() takes a header value string and returns a sequence of
  96. pairs of the format (decoded_string, charset) where charset is the string
  97. name of the character set.
  98. This function takes one of those sequence of pairs and returns a Header
  99. instance. Optional maxlinelen, header_name, and continuation_ws are as in
  100. the Header constructor.
  101. """
  102. h = Header(maxlinelen=maxlinelen, header_name=header_name,
  103. continuation_ws=continuation_ws)
  104. for s, charset in decoded_seq:
  105. # None means us-ascii but we can simply pass it on to h.append()
  106. if charset is not None and not isinstance(charset, Charset):
  107. charset = Charset(charset)
  108. h.append(s, charset)
  109. return h
  110. class Header:
  111. def __init__(self, s=None, charset=None,
  112. maxlinelen=None, header_name=None,
  113. continuation_ws=' ', errors='strict'):
  114. """Create a MIME-compliant header that can contain many character sets.
  115. Optional s is the initial header value. If None, the initial header
  116. value is not set. You can later append to the header with .append()
  117. method calls. s may be a byte string or a Unicode string, but see the
  118. .append() documentation for semantics.
  119. Optional charset serves two purposes: it has the same meaning as the
  120. charset argument to the .append() method. It also sets the default
  121. character set for all subsequent .append() calls that omit the charset
  122. argument. If charset is not provided in the constructor, the us-ascii
  123. charset is used both as s's initial charset and as the default for
  124. subsequent .append() calls.
  125. The maximum line length can be specified explicit via maxlinelen. For
  126. splitting the first line to a shorter value (to account for the field
  127. header which isn't included in s, e.g. `Subject') pass in the name of
  128. the field in header_name. The default maxlinelen is 76.
  129. continuation_ws must be RFC 2822 compliant folding whitespace (usually
  130. either a space or a hard tab) which will be prepended to continuation
  131. lines.
  132. errors is passed through to the .append() call.
  133. """
  134. if charset is None:
  135. charset = USASCII
  136. if not isinstance(charset, Charset):
  137. charset = Charset(charset)
  138. self._charset = charset
  139. self._continuation_ws = continuation_ws
  140. cws_expanded_len = len(continuation_ws.replace('\t', SPACE8))
  141. # BAW: I believe `chunks' and `maxlinelen' should be non-public.
  142. self._chunks = []
  143. if s is not None:
  144. self.append(s, charset, errors)
  145. if maxlinelen is None:
  146. maxlinelen = MAXLINELEN
  147. if header_name is None:
  148. # We don't know anything about the field header so the first line
  149. # is the same length as subsequent lines.
  150. self._firstlinelen = maxlinelen
  151. else:
  152. # The first line should be shorter to take into account the field
  153. # header. Also subtract off 2 extra for the colon and space.
  154. self._firstlinelen = maxlinelen - len(header_name) - 2
  155. # Second and subsequent lines should subtract off the length in
  156. # columns of the continuation whitespace prefix.
  157. self._maxlinelen = maxlinelen - cws_expanded_len
  158. def __str__(self):
  159. """A synonym for self.encode()."""
  160. return self.encode()
  161. def __unicode__(self):
  162. """Helper for the built-in unicode function."""
  163. uchunks = []
  164. lastcs = None
  165. for s, charset in self._chunks:
  166. # We must preserve spaces between encoded and non-encoded word
  167. # boundaries, which means for us we need to add a space when we go
  168. # from a charset to None/us-ascii, or from None/us-ascii to a
  169. # charset. Only do this for the second and subsequent chunks.
  170. nextcs = charset
  171. if uchunks:
  172. if lastcs not in (None, 'us-ascii'):
  173. if nextcs in (None, 'us-ascii'):
  174. uchunks.append(USPACE)
  175. nextcs = None
  176. elif nextcs not in (None, 'us-ascii'):
  177. uchunks.append(USPACE)
  178. lastcs = nextcs
  179. uchunks.append(unicode(s, str(charset)))
  180. return UEMPTYSTRING.join(uchunks)
  181. # Rich comparison operators for equality only. BAW: does it make sense to
  182. # have or explicitly disable <, <=, >, >= operators?
  183. def __eq__(self, other):
  184. # other may be a Header or a string. Both are fine so coerce
  185. # ourselves to a string, swap the args and do another comparison.
  186. return other == self.encode()
  187. def __ne__(self, other):
  188. return not self == other
  189. def append(self, s, charset=None, errors='strict'):
  190. """Append a string to the MIME header.
  191. Optional charset, if given, should be a Charset instance or the name
  192. of a character set (which will be converted to a Charset instance). A
  193. value of None (the default) means that the charset given in the
  194. constructor is used.
  195. s may be a byte string or a Unicode string. If it is a byte string
  196. (i.e. isinstance(s, str) is true), then charset is the encoding of
  197. that byte string, and a UnicodeError will be raised if the string
  198. cannot be decoded with that charset. If s is a Unicode string, then
  199. charset is a hint specifying the character set of the characters in
  200. the string. In this case, when producing an RFC 2822 compliant header
  201. using RFC 2047 rules, the Unicode string will be encoded using the
  202. following charsets in order: us-ascii, the charset hint, utf-8. The
  203. first character set not to provoke a UnicodeError is used.
  204. Optional `errors' is passed as the third argument to any unicode() or
  205. ustr.encode() call.
  206. """
  207. if charset is None:
  208. charset = self._charset
  209. elif not isinstance(charset, Charset):
  210. charset = Charset(charset)
  211. # If the charset is our faux 8bit charset, leave the string unchanged
  212. if charset != '8bit':
  213. # We need to test that the string can be converted to unicode and
  214. # back to a byte string, given the input and output codecs of the
  215. # charset.
  216. if isinstance(s, str):
  217. # Possibly raise UnicodeError if the byte string can't be
  218. # converted to a unicode with the input codec of the charset.
  219. incodec = charset.input_codec or 'us-ascii'
  220. ustr = unicode(s, incodec, errors)
  221. # Now make sure that the unicode could be converted back to a
  222. # byte string with the output codec, which may be different
  223. # than the iput coded. Still, use the original byte string.
  224. outcodec = charset.output_codec or 'us-ascii'
  225. ustr.encode(outcodec, errors)
  226. elif isinstance(s, unicode):
  227. # Now we have to be sure the unicode string can be converted
  228. # to a byte string with a reasonable output codec. We want to
  229. # use the byte string in the chunk.
  230. for charset in USASCII, charset, UTF8:
  231. try:
  232. outcodec = charset.output_codec or 'us-ascii'
  233. s = s.encode(outcodec, errors)
  234. break
  235. except UnicodeError:
  236. pass
  237. else:
  238. assert False, 'utf-8 conversion failed'
  239. self._chunks.append((s, charset))
  240. def _split(self, s, charset, maxlinelen, splitchars):
  241. # Split up a header safely for use with encode_chunks.
  242. splittable = charset.to_splittable(s)
  243. encoded = charset.from_splittable(splittable, True)
  244. elen = charset.encoded_header_len(encoded)
  245. # If the line's encoded length first, just return it
  246. if elen <= maxlinelen:
  247. return [(encoded, charset)]
  248. # If we have undetermined raw 8bit characters sitting in a byte
  249. # string, we really don't know what the right thing to do is. We
  250. # can't really split it because it might be multibyte data which we
  251. # could break if we split it between pairs. The least harm seems to
  252. # be to not split the header at all, but that means they could go out
  253. # longer than maxlinelen.
  254. if charset == '8bit':
  255. return [(s, charset)]
  256. # BAW: I'm not sure what the right test here is. What we're trying to
  257. # do is be faithful to RFC 2822's recommendation that ($2.2.3):
  258. #
  259. # "Note: Though structured field bodies are defined in such a way that
  260. # folding can take place between many of the lexical tokens (and even
  261. # within some of the lexical tokens), folding SHOULD be limited to
  262. # placing the CRLF at higher-level syntactic breaks."
  263. #
  264. # For now, I can only imagine doing this when the charset is us-ascii,
  265. # although it's possible that other charsets may also benefit from the
  266. # higher-level syntactic breaks.
  267. elif charset == 'us-ascii':
  268. return self._split_ascii(s, charset, maxlinelen, splitchars)
  269. # BAW: should we use encoded?
  270. elif elen == len(s):
  271. # We can split on _maxlinelen boundaries because we know that the
  272. # encoding won't change the size of the string
  273. splitpnt = maxlinelen
  274. first = charset.from_splittable(splittable[:splitpnt], False)
  275. last = charset.from_splittable(splittable[splitpnt:], False)
  276. else:
  277. # Binary search for split point
  278. first, last = _binsplit(splittable, charset, maxlinelen)
  279. # first is of the proper length so just wrap it in the appropriate
  280. # chrome. last must be recursively split.
  281. fsplittable = charset.to_splittable(first)
  282. fencoded = charset.from_splittable(fsplittable, True)
  283. chunk = [(fencoded, charset)]
  284. return chunk + self._split(last, charset, self._maxlinelen, splitchars)
  285. def _split_ascii(self, s, charset, firstlen, splitchars):
  286. chunks = _split_ascii(s, firstlen, self._maxlinelen,
  287. self._continuation_ws, splitchars)
  288. return zip(chunks, [charset]*len(chunks))
  289. def _encode_chunks(self, newchunks, maxlinelen):
  290. # MIME-encode a header with many different charsets and/or encodings.
  291. #
  292. # Given a list of pairs (string, charset), return a MIME-encoded
  293. # string suitable for use in a header field. Each pair may have
  294. # different charsets and/or encodings, and the resulting header will
  295. # accurately reflect each setting.
  296. #
  297. # Each encoding can be email.Utils.QP (quoted-printable, for
  298. # ASCII-like character sets like iso-8859-1), email.Utils.BASE64
  299. # (Base64, for non-ASCII like character sets like KOI8-R and
  300. # iso-2022-jp), or None (no encoding).
  301. #
  302. # Each pair will be represented on a separate line; the resulting
  303. # string will be in the format:
  304. #
  305. # =?charset1?q?Mar=EDa_Gonz=E1lez_Alonso?=\n
  306. # =?charset2?b?SvxyZ2VuIEL2aW5n?="
  307. chunks = []
  308. for header, charset in newchunks:
  309. if not header:
  310. continue
  311. if charset is None or charset.header_encoding is None:
  312. s = header
  313. else:
  314. s = charset.header_encode(header)
  315. # Don't add more folding whitespace than necessary
  316. if chunks and chunks[-1].endswith(' '):
  317. extra = ''
  318. else:
  319. extra = ' '
  320. _max_append(chunks, s, maxlinelen, extra)
  321. joiner = NL + self._continuation_ws
  322. return joiner.join(chunks)
  323. def encode(self, splitchars=';, '):
  324. """Encode a message header into an RFC-compliant format.
  325. There are many issues involved in converting a given string for use in
  326. an email header. Only certain character sets are readable in most
  327. email clients, and as header strings can only contain a subset of
  328. 7-bit ASCII, care must be taken to properly convert and encode (with
  329. Base64 or quoted-printable) header strings. In addition, there is a
  330. 75-character length limit on any given encoded header field, so
  331. line-wrapping must be performed, even with double-byte character sets.
  332. This method will do its best to convert the string to the correct
  333. character set used in email, and encode and line wrap it safely with
  334. the appropriate scheme for that character set.
  335. If the given charset is not known or an error occurs during
  336. conversion, this function will return the header untouched.
  337. Optional splitchars is a string containing characters to split long
  338. ASCII lines on, in rough support of RFC 2822's `highest level
  339. syntactic breaks'. This doesn't affect RFC 2047 encoded lines.
  340. """
  341. newchunks = []
  342. maxlinelen = self._firstlinelen
  343. lastlen = 0
  344. for s, charset in self._chunks:
  345. # The first bit of the next chunk should be just long enough to
  346. # fill the next line. Don't forget the space separating the
  347. # encoded words.
  348. targetlen = maxlinelen - lastlen - 1
  349. if targetlen < charset.encoded_header_len(''):
  350. # Stick it on the next line
  351. targetlen = maxlinelen
  352. newchunks += self._split(s, charset, targetlen, splitchars)
  353. lastchunk, lastcharset = newchunks[-1]
  354. lastlen = lastcharset.encoded_header_len(lastchunk)
  355. return self._encode_chunks(newchunks, maxlinelen)
  356. def _split_ascii(s, firstlen, restlen, continuation_ws, splitchars):
  357. lines = []
  358. maxlen = firstlen
  359. for line in s.splitlines():
  360. # Ignore any leading whitespace (i.e. continuation whitespace) already
  361. # on the line, since we'll be adding our own.
  362. line = line.lstrip()
  363. if len(line) < maxlen:
  364. lines.append(line)
  365. maxlen = restlen
  366. continue
  367. # Attempt to split the line at the highest-level syntactic break
  368. # possible. Note that we don't have a lot of smarts about field
  369. # syntax; we just try to break on semi-colons, then commas, then
  370. # whitespace.
  371. for ch in splitchars:
  372. if ch in line:
  373. break
  374. else:
  375. # There's nothing useful to split the line on, not even spaces, so
  376. # just append this line unchanged
  377. lines.append(line)
  378. maxlen = restlen
  379. continue
  380. # Now split the line on the character plus trailing whitespace
  381. cre = re.compile(r'%s\s*' % ch)
  382. if ch in ';,':
  383. eol = ch
  384. else:
  385. eol = ''
  386. joiner = eol + ' '
  387. joinlen = len(joiner)
  388. wslen = len(continuation_ws.replace('\t', SPACE8))
  389. this = []
  390. linelen = 0
  391. for part in cre.split(line):
  392. curlen = linelen + max(0, len(this)-1) * joinlen
  393. partlen = len(part)
  394. onfirstline = not lines
  395. # We don't want to split after the field name, if we're on the
  396. # first line and the field name is present in the header string.
  397. if ch == ' ' and onfirstline and \
  398. len(this) == 1 and fcre.match(this[0]):
  399. this.append(part)
  400. linelen += partlen
  401. elif curlen + partlen > maxlen:
  402. if this:
  403. lines.append(joiner.join(this) + eol)
  404. # If this part is longer than maxlen and we aren't already
  405. # splitting on whitespace, try to recursively split this line
  406. # on whitespace.
  407. if partlen > maxlen and ch != ' ':
  408. subl = _split_ascii(part, maxlen, restlen,
  409. continuation_ws, ' ')
  410. lines.extend(subl[:-1])
  411. this = [subl[-1]]
  412. else:
  413. this = [part]
  414. linelen = wslen + len(this[-1])
  415. maxlen = restlen
  416. else:
  417. this.append(part)
  418. linelen += partlen
  419. # Put any left over parts on a line by themselves
  420. if this:
  421. lines.append(joiner.join(this))
  422. return lines
  423. def _binsplit(splittable, charset, maxlinelen):
  424. i = 0
  425. j = len(splittable)
  426. while i < j:
  427. # Invariants:
  428. # 1. splittable[:k] fits for all k <= i (note that we *assume*,
  429. # at the start, that splittable[:0] fits).
  430. # 2. splittable[:k] does not fit for any k > j (at the start,
  431. # this means we shouldn't look at any k > len(splittable)).
  432. # 3. We don't know about splittable[:k] for k in i+1..j.
  433. # 4. We want to set i to the largest k that fits, with i <= k <= j.
  434. #
  435. m = (i+j+1) >> 1 # ceiling((i+j)/2); i < m <= j
  436. chunk = charset.from_splittable(splittable[:m], True)
  437. chunklen = charset.encoded_header_len(chunk)
  438. if chunklen <= maxlinelen:
  439. # m is acceptable, so is a new lower bound.
  440. i = m
  441. else:
  442. # m is not acceptable, so final i must be < m.
  443. j = m - 1
  444. # i == j. Invariant #1 implies that splittable[:i] fits, and
  445. # invariant #2 implies that splittable[:i+1] does not fit, so i
  446. # is what we're looking for.
  447. first = charset.from_splittable(splittable[:i], False)
  448. last = charset.from_splittable(splittable[i:], False)
  449. return first, last