generator.py 20 KB

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