PageRenderTime 64ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/email/header.py

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