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