generator.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. # Copyright (C) 2001-2010 Python Software Foundation
  2. # Author: Barry Warsaw
  3. # Contact: email-sig@python.org
  4. """Classes to generate plain text from a message object tree."""
  5. from __future__ import print_function
  6. from __future__ import unicode_literals
  7. from __future__ import division
  8. from __future__ import absolute_import
  9. from future.builtins import super
  10. from future.builtins import str
  11. __all__ = ['Generator', 'DecodedGenerator', 'BytesGenerator']
  12. import re
  13. import sys
  14. import time
  15. import random
  16. import warnings
  17. from io import StringIO, BytesIO
  18. from future.backports.email._policybase import compat32
  19. from future.backports.email.header import Header
  20. from future.backports.email.utils import _has_surrogates
  21. import future.backports.email.charset as _charset
  22. UNDERSCORE = '_'
  23. NL = '\n' # XXX: no longer used by the code below.
  24. fcre = re.compile(r'^From ', re.MULTILINE)
  25. class Generator(object):
  26. """Generates output from a Message object tree.
  27. This basic generator writes the message to the given file object as plain
  28. text.
  29. """
  30. #
  31. # Public interface
  32. #
  33. def __init__(self, outfp, mangle_from_=True, maxheaderlen=None, **_3to2kwargs):
  34. if 'policy' in _3to2kwargs: policy = _3to2kwargs['policy']; del _3to2kwargs['policy']
  35. else: policy = None
  36. """Create the generator for message flattening.
  37. outfp is the output file-like object for writing the message to. It
  38. must have a write() method.
  39. Optional mangle_from_ is a flag that, when True (the default), escapes
  40. From_ lines in the body of the message by putting a `>' in front of
  41. them.
  42. Optional maxheaderlen specifies the longest length for a non-continued
  43. header. When a header line is longer (in characters, with tabs
  44. expanded to 8 spaces) than maxheaderlen, the header will split as
  45. defined in the Header class. Set maxheaderlen to zero to disable
  46. header wrapping. The default is 78, as recommended (but not required)
  47. by RFC 2822.
  48. The policy keyword specifies a policy object that controls a number of
  49. aspects of the generator's operation. The default policy maintains
  50. backward compatibility.
  51. """
  52. self._fp = outfp
  53. self._mangle_from_ = mangle_from_
  54. self.maxheaderlen = maxheaderlen
  55. self.policy = policy
  56. def write(self, s):
  57. # Just delegate to the file object
  58. self._fp.write(s)
  59. def flatten(self, msg, unixfrom=False, linesep=None):
  60. r"""Print the message object tree rooted at msg to the output file
  61. specified when the Generator instance was created.
  62. unixfrom is a flag that forces the printing of a Unix From_ delimiter
  63. before the first object in the message tree. If the original message
  64. has no From_ delimiter, a `standard' one is crafted. By default, this
  65. is False to inhibit the printing of any From_ delimiter.
  66. Note that for subobjects, no From_ line is printed.
  67. linesep specifies the characters used to indicate a new line in
  68. the output. The default value is determined by the policy.
  69. """
  70. # We use the _XXX constants for operating on data that comes directly
  71. # from the msg, and _encoded_XXX constants for operating on data that
  72. # has already been converted (to bytes in the BytesGenerator) and
  73. # inserted into a temporary buffer.
  74. policy = msg.policy if self.policy is None else self.policy
  75. if linesep is not None:
  76. policy = policy.clone(linesep=linesep)
  77. if self.maxheaderlen is not None:
  78. policy = policy.clone(max_line_length=self.maxheaderlen)
  79. self._NL = policy.linesep
  80. self._encoded_NL = self._encode(self._NL)
  81. self._EMPTY = ''
  82. self._encoded_EMTPY = self._encode('')
  83. # Because we use clone (below) when we recursively process message
  84. # subparts, and because clone uses the computed policy (not None),
  85. # submessages will automatically get set to the computed policy when
  86. # they are processed by this code.
  87. old_gen_policy = self.policy
  88. old_msg_policy = msg.policy
  89. try:
  90. self.policy = policy
  91. msg.policy = policy
  92. if unixfrom:
  93. ufrom = msg.get_unixfrom()
  94. if not ufrom:
  95. ufrom = 'From nobody ' + time.ctime(time.time())
  96. self.write(ufrom + self._NL)
  97. self._write(msg)
  98. finally:
  99. self.policy = old_gen_policy
  100. msg.policy = old_msg_policy
  101. def clone(self, fp):
  102. """Clone this generator with the exact same options."""
  103. return self.__class__(fp,
  104. self._mangle_from_,
  105. None, # Use policy setting, which we've adjusted
  106. policy=self.policy)
  107. #
  108. # Protected interface - undocumented ;/
  109. #
  110. # Note that we use 'self.write' when what we are writing is coming from
  111. # the source, and self._fp.write when what we are writing is coming from a
  112. # buffer (because the Bytes subclass has already had a chance to transform
  113. # the data in its write method in that case). This is an entirely
  114. # pragmatic split determined by experiment; we could be more general by
  115. # always using write and having the Bytes subclass write method detect when
  116. # it has already transformed the input; but, since this whole thing is a
  117. # hack anyway this seems good enough.
  118. # Similarly, we have _XXX and _encoded_XXX attributes that are used on
  119. # source and buffer data, respectively.
  120. _encoded_EMPTY = ''
  121. def _new_buffer(self):
  122. # BytesGenerator overrides this to return BytesIO.
  123. return StringIO()
  124. def _encode(self, s):
  125. # BytesGenerator overrides this to encode strings to bytes.
  126. return s
  127. def _write_lines(self, lines):
  128. # We have to transform the line endings.
  129. if not lines:
  130. return
  131. lines = lines.splitlines(True)
  132. for line in lines[:-1]:
  133. self.write(line.rstrip('\r\n'))
  134. self.write(self._NL)
  135. laststripped = lines[-1].rstrip('\r\n')
  136. self.write(laststripped)
  137. if len(lines[-1]) != len(laststripped):
  138. self.write(self._NL)
  139. def _write(self, msg):
  140. # We can't write the headers yet because of the following scenario:
  141. # say a multipart message includes the boundary string somewhere in
  142. # its body. We'd have to calculate the new boundary /before/ we write
  143. # the headers so that we can write the correct Content-Type:
  144. # parameter.
  145. #
  146. # The way we do this, so as to make the _handle_*() methods simpler,
  147. # is to cache any subpart writes into a buffer. The we write the
  148. # headers and the buffer contents. That way, subpart handlers can
  149. # Do The Right Thing, and can still modify the Content-Type: header if
  150. # necessary.
  151. oldfp = self._fp
  152. try:
  153. self._fp = sfp = self._new_buffer()
  154. self._dispatch(msg)
  155. finally:
  156. self._fp = oldfp
  157. # Write the headers. First we see if the message object wants to
  158. # handle that itself. If not, we'll do it generically.
  159. meth = getattr(msg, '_write_headers', None)
  160. if meth is None:
  161. self._write_headers(msg)
  162. else:
  163. meth(self)
  164. self._fp.write(sfp.getvalue())
  165. def _dispatch(self, msg):
  166. # Get the Content-Type: for the message, then try to dispatch to
  167. # self._handle_<maintype>_<subtype>(). If there's no handler for the
  168. # full MIME type, then dispatch to self._handle_<maintype>(). If
  169. # that's missing too, then dispatch to self._writeBody().
  170. main = msg.get_content_maintype()
  171. sub = msg.get_content_subtype()
  172. specific = UNDERSCORE.join((main, sub)).replace('-', '_')
  173. meth = getattr(self, '_handle_' + specific, None)
  174. if meth is None:
  175. generic = main.replace('-', '_')
  176. meth = getattr(self, '_handle_' + generic, None)
  177. if meth is None:
  178. meth = self._writeBody
  179. meth(msg)
  180. #
  181. # Default handlers
  182. #
  183. def _write_headers(self, msg):
  184. for h, v in msg.raw_items():
  185. self.write(self.policy.fold(h, v))
  186. # A blank line always separates headers from body
  187. self.write(self._NL)
  188. #
  189. # Handlers for writing types and subtypes
  190. #
  191. def _handle_text(self, msg):
  192. payload = msg.get_payload()
  193. if payload is None:
  194. return
  195. if not isinstance(payload, str):
  196. raise TypeError('string payload expected: %s' % type(payload))
  197. if _has_surrogates(msg._payload):
  198. charset = msg.get_param('charset')
  199. if charset is not None:
  200. del msg['content-transfer-encoding']
  201. msg.set_payload(payload, charset)
  202. payload = msg.get_payload()
  203. if self._mangle_from_:
  204. payload = fcre.sub('>From ', payload)
  205. self._write_lines(payload)
  206. # Default body handler
  207. _writeBody = _handle_text
  208. def _handle_multipart(self, msg):
  209. # The trick here is to write out each part separately, merge them all
  210. # together, and then make sure that the boundary we've chosen isn't
  211. # present in the payload.
  212. msgtexts = []
  213. subparts = msg.get_payload()
  214. if subparts is None:
  215. subparts = []
  216. elif isinstance(subparts, str):
  217. # e.g. a non-strict parse of a message with no starting boundary.
  218. self.write(subparts)
  219. return
  220. elif not isinstance(subparts, list):
  221. # Scalar payload
  222. subparts = [subparts]
  223. for part in subparts:
  224. s = self._new_buffer()
  225. g = self.clone(s)
  226. g.flatten(part, unixfrom=False, linesep=self._NL)
  227. msgtexts.append(s.getvalue())
  228. # BAW: What about boundaries that are wrapped in double-quotes?
  229. boundary = msg.get_boundary()
  230. if not boundary:
  231. # Create a boundary that doesn't appear in any of the
  232. # message texts.
  233. alltext = self._encoded_NL.join(msgtexts)
  234. boundary = self._make_boundary(alltext)
  235. msg.set_boundary(boundary)
  236. # If there's a preamble, write it out, with a trailing CRLF
  237. if msg.preamble is not None:
  238. if self._mangle_from_:
  239. preamble = fcre.sub('>From ', msg.preamble)
  240. else:
  241. preamble = msg.preamble
  242. self._write_lines(preamble)
  243. self.write(self._NL)
  244. # dash-boundary transport-padding CRLF
  245. self.write('--' + boundary + self._NL)
  246. # body-part
  247. if msgtexts:
  248. self._fp.write(msgtexts.pop(0))
  249. # *encapsulation
  250. # --> delimiter transport-padding
  251. # --> CRLF body-part
  252. for body_part in msgtexts:
  253. # delimiter transport-padding CRLF
  254. self.write(self._NL + '--' + boundary + self._NL)
  255. # body-part
  256. self._fp.write(body_part)
  257. # close-delimiter transport-padding
  258. self.write(self._NL + '--' + boundary + '--')
  259. if msg.epilogue is not None:
  260. self.write(self._NL)
  261. if self._mangle_from_:
  262. epilogue = fcre.sub('>From ', msg.epilogue)
  263. else:
  264. epilogue = msg.epilogue
  265. self._write_lines(epilogue)
  266. def _handle_multipart_signed(self, msg):
  267. # The contents of signed parts has to stay unmodified in order to keep
  268. # the signature intact per RFC1847 2.1, so we disable header wrapping.
  269. # RDM: This isn't enough to completely preserve the part, but it helps.
  270. p = self.policy
  271. self.policy = p.clone(max_line_length=0)
  272. try:
  273. self._handle_multipart(msg)
  274. finally:
  275. self.policy = p
  276. def _handle_message_delivery_status(self, msg):
  277. # We can't just write the headers directly to self's file object
  278. # because this will leave an extra newline between the last header
  279. # block and the boundary. Sigh.
  280. blocks = []
  281. for part in msg.get_payload():
  282. s = self._new_buffer()
  283. g = self.clone(s)
  284. g.flatten(part, unixfrom=False, linesep=self._NL)
  285. text = s.getvalue()
  286. lines = text.split(self._encoded_NL)
  287. # Strip off the unnecessary trailing empty line
  288. if lines and lines[-1] == self._encoded_EMPTY:
  289. blocks.append(self._encoded_NL.join(lines[:-1]))
  290. else:
  291. blocks.append(text)
  292. # Now join all the blocks with an empty line. This has the lovely
  293. # effect of separating each block with an empty line, but not adding
  294. # an extra one after the last one.
  295. self._fp.write(self._encoded_NL.join(blocks))
  296. def _handle_message(self, msg):
  297. s = self._new_buffer()
  298. g = self.clone(s)
  299. # The payload of a message/rfc822 part should be a multipart sequence
  300. # of length 1. The zeroth element of the list should be the Message
  301. # object for the subpart. Extract that object, stringify it, and
  302. # write it out.
  303. # Except, it turns out, when it's a string instead, which happens when
  304. # and only when HeaderParser is used on a message of mime type
  305. # message/rfc822. Such messages are generated by, for example,
  306. # Groupwise when forwarding unadorned messages. (Issue 7970.) So
  307. # in that case we just emit the string body.
  308. payload = msg._payload
  309. if isinstance(payload, list):
  310. g.flatten(msg.get_payload(0), unixfrom=False, linesep=self._NL)
  311. payload = s.getvalue()
  312. else:
  313. payload = self._encode(payload)
  314. self._fp.write(payload)
  315. # This used to be a module level function; we use a classmethod for this
  316. # and _compile_re so we can continue to provide the module level function
  317. # for backward compatibility by doing
  318. # _make_boudary = Generator._make_boundary
  319. # at the end of the module. It *is* internal, so we could drop that...
  320. @classmethod
  321. def _make_boundary(cls, text=None):
  322. # Craft a random boundary. If text is given, ensure that the chosen
  323. # boundary doesn't appear in the text.
  324. token = random.randrange(sys.maxsize)
  325. boundary = ('=' * 15) + (_fmt % token) + '=='
  326. if text is None:
  327. return boundary
  328. b = boundary
  329. counter = 0
  330. while True:
  331. cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
  332. if not cre.search(text):
  333. break
  334. b = boundary + '.' + str(counter)
  335. counter += 1
  336. return b
  337. @classmethod
  338. def _compile_re(cls, s, flags):
  339. return re.compile(s, flags)
  340. class BytesGenerator(Generator):
  341. """Generates a bytes version of a Message object tree.
  342. Functionally identical to the base Generator except that the output is
  343. bytes and not string. When surrogates were used in the input to encode
  344. bytes, these are decoded back to bytes for output. If the policy has
  345. cte_type set to 7bit, then the message is transformed such that the
  346. non-ASCII bytes are properly content transfer encoded, using the charset
  347. unknown-8bit.
  348. The outfp object must accept bytes in its write method.
  349. """
  350. # Bytes versions of this constant for use in manipulating data from
  351. # the BytesIO buffer.
  352. _encoded_EMPTY = b''
  353. def write(self, s):
  354. self._fp.write(str(s).encode('ascii', 'surrogateescape'))
  355. def _new_buffer(self):
  356. return BytesIO()
  357. def _encode(self, s):
  358. return s.encode('ascii')
  359. def _write_headers(self, msg):
  360. # This is almost the same as the string version, except for handling
  361. # strings with 8bit bytes.
  362. for h, v in msg.raw_items():
  363. self._fp.write(self.policy.fold_binary(h, v))
  364. # A blank line always separates headers from body
  365. self.write(self._NL)
  366. def _handle_text(self, msg):
  367. # If the string has surrogates the original source was bytes, so
  368. # just write it back out.
  369. if msg._payload is None:
  370. return
  371. if _has_surrogates(msg._payload) and not self.policy.cte_type=='7bit':
  372. if self._mangle_from_:
  373. msg._payload = fcre.sub(">From ", msg._payload)
  374. self._write_lines(msg._payload)
  375. else:
  376. super(BytesGenerator,self)._handle_text(msg)
  377. # Default body handler
  378. _writeBody = _handle_text
  379. @classmethod
  380. def _compile_re(cls, s, flags):
  381. return re.compile(s.encode('ascii'), flags)
  382. _FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]'
  383. class DecodedGenerator(Generator):
  384. """Generates a text representation of a message.
  385. Like the Generator base class, except that non-text parts are substituted
  386. with a format string representing the part.
  387. """
  388. def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None):
  389. """Like Generator.__init__() except that an additional optional
  390. argument is allowed.
  391. Walks through all subparts of a message. If the subpart is of main
  392. type `text', then it prints the decoded payload of the subpart.
  393. Otherwise, fmt is a format string that is used instead of the message
  394. payload. fmt is expanded with the following keywords (in
  395. %(keyword)s format):
  396. type : Full MIME type of the non-text part
  397. maintype : Main MIME type of the non-text part
  398. subtype : Sub-MIME type of the non-text part
  399. filename : Filename of the non-text part
  400. description: Description associated with the non-text part
  401. encoding : Content transfer encoding of the non-text part
  402. The default value for fmt is None, meaning
  403. [Non-text (%(type)s) part of message omitted, filename %(filename)s]
  404. """
  405. Generator.__init__(self, outfp, mangle_from_, maxheaderlen)
  406. if fmt is None:
  407. self._fmt = _FMT
  408. else:
  409. self._fmt = fmt
  410. def _dispatch(self, msg):
  411. for part in msg.walk():
  412. maintype = part.get_content_maintype()
  413. if maintype == 'text':
  414. print(part.get_payload(decode=False), file=self)
  415. elif maintype == 'multipart':
  416. # Just skip this
  417. pass
  418. else:
  419. print(self._fmt % {
  420. 'type' : part.get_content_type(),
  421. 'maintype' : part.get_content_maintype(),
  422. 'subtype' : part.get_content_subtype(),
  423. 'filename' : part.get_filename('[no filename]'),
  424. 'description': part.get('Content-Description',
  425. '[no description]'),
  426. 'encoding' : part.get('Content-Transfer-Encoding',
  427. '[no encoding]'),
  428. }, file=self)
  429. # Helper used by Generator._make_boundary
  430. _width = len(repr(sys.maxsize-1))
  431. _fmt = '%%0%dd' % _width
  432. # Backward compatibility
  433. _make_boundary = Generator._make_boundary