generator.py 20 KB

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