generator.py 20 KB

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