| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
"""FeedParser - An email feed parser. |
| 6 |
|
| 7 |
The feed parser implements an interface for incrementally parsing an email |
| 8 |
message, line by line. This has advantages for certain applications, such as |
| 9 |
those reading email messages off a socket. |
| 10 |
|
| 11 |
FeedParser.feed() is the primary interface for pushing new data into the |
| 12 |
parser. It returns when there's nothing more it can do with the available |
| 13 |
data. When you have no more data to push into the parser, call .close(). |
| 14 |
This completes the parsing and returns the root message object. |
| 15 |
|
| 16 |
The other advantage of this parser is that it will never raise a parsing |
| 17 |
exception. Instead, when it finds something unexpected, it adds a 'defect' to |
| 18 |
the current message. Defects are just instances that live on the message |
| 19 |
object's .defects attribute. |
| 20 |
""" |
| 21 |
|
| 22 |
__all__ = ['FeedParser', 'BytesFeedParser'] |
| 23 |
|
| 24 |
import re |
| 25 |
|
| 26 |
from email import errors |
| 27 |
from email._policybase import compat32 |
| 28 |
from collections import deque |
| 29 |
from io import StringIO |
| 30 |
|
| 31 |
NLCRE = re.compile(r'\r\n|\r|\n') |
| 32 |
NLCRE_bol = re.compile(r'(\r\n|\r|\n)') |
| 33 |
NLCRE_eol = re.compile(r'(\r\n|\r|\n)\Z') |
| 34 |
NLCRE_crack = re.compile(r'(\r\n|\r|\n)') |
| 35 |
|
| 36 |
|
| 37 |
headerRE = re.compile(r'^(From |[\041-\071\073-\176]*:|[\t ])') |
| 38 |
EMPTYSTRING = '' |
| 39 |
NL = '\n' |
| 40 |
boundaryend_re = re.compile(r'(?P<end>--)?(?P<ws>[ \t]*)(?P<linesep>\r\n|\r|\n)?$') |
| 41 |
|
| 42 |
NeedMoreData = object() |
| 43 |
|
| 44 |
|
| 45 |
class BufferedSubFile(object): |
| 46 |
"""A file-ish object that can have new data loaded into it. |
| 47 |
|
| 48 |
You can also push and pop line-matching predicates onto a stack. When the |
| 49 |
current predicate matches the current line, a false EOF response |
| 50 |
(i.e. empty string) is returned instead. This lets the parser adhere to a |
| 51 |
simple abstraction -- it parses until EOF closes the current message. |
| 52 |
""" |
| 53 |
def __init__(self): |
| 54 |
|
| 55 |
|
| 56 |
self._partial = StringIO(newline='') |
| 57 |
|
| 58 |
self._lines = deque() |
| 59 |
|
| 60 |
self._eofstack = [] |
| 61 |
|
| 62 |
self._closed = False |
| 63 |
|
| 64 |
def push_eof_matcher(self, pred): |
| 65 |
self._eofstack.append(pred) |
| 66 |
|
| 67 |
def pop_eof_matcher(self): |
| 68 |
return self._eofstack.pop() |
| 69 |
|
| 70 |
def close(self): |
| 71 |
|
| 72 |
self._partial.seek(0) |
| 73 |
self.pushlines(self._partial.readlines()) |
| 74 |
self._partial.seek(0) |
| 75 |
self._partial.truncate() |
| 76 |
self._closed = True |
| 77 |
|
| 78 |
def readline(self): |
| 79 |
if not self._lines: |
| 80 |
if self._closed: |
| 81 |
return '' |
| 82 |
return NeedMoreData |
| 83 |
|
| 84 |
|
| 85 |
line = self._lines.popleft() |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
for ateof in reversed(self._eofstack): |
| 90 |
if ateof(line): |
| 91 |
|
| 92 |
self._lines.appendleft(line) |
| 93 |
return '' |
| 94 |
return line |
| 95 |
|
| 96 |
def unreadline(self, line): |
| 97 |
|
| 98 |
assert line is not NeedMoreData |
| 99 |
self._lines.appendleft(line) |
| 100 |
|
| 101 |
def push(self, data): |
| 102 |
"""Push some new data into this object.""" |
| 103 |
self._partial.write(data) |
| 104 |
if '\n' not in data and '\r' not in data: |
| 105 |
|
| 106 |
return |
| 107 |
|
| 108 |
|
| 109 |
self._partial.seek(0) |
| 110 |
parts = self._partial.readlines() |
| 111 |
self._partial.seek(0) |
| 112 |
self._partial.truncate() |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
if not parts[-1].endswith('\n'): |
| 119 |
self._partial.write(parts.pop()) |
| 120 |
self.pushlines(parts) |
| 121 |
|
| 122 |
def pushlines(self, lines): |
| 123 |
self._lines.extend(lines) |
| 124 |
|
| 125 |
def __iter__(self): |
| 126 |
return self |
| 127 |
|
| 128 |
def __next__(self): |
| 129 |
line = self.readline() |
| 130 |
if line == '': |
| 131 |
raise StopIteration |
| 132 |
return line |
| 133 |
|
| 134 |
|
| 135 |
class FeedParser: |
| 136 |
"""A feed-style parser of email.""" |
| 137 |
|
| 138 |
def __init__(self, _factory=None, *, policy=compat32): |
| 139 |
"""_factory is called with no arguments to create a new message obj |
| 140 |
|
| 141 |
The policy keyword specifies a policy object that controls a number of |
| 142 |
aspects of the parser's operation. The default policy maintains |
| 143 |
backward compatibility. |
| 144 |
|
| 145 |
""" |
| 146 |
self.policy = policy |
| 147 |
self._old_style_factory = False |
| 148 |
if _factory is None: |
| 149 |
if policy.message_factory is None: |
| 150 |
from email.message import Message |
| 151 |
self._factory = Message |
| 152 |
else: |
| 153 |
self._factory = policy.message_factory |
| 154 |
else: |
| 155 |
self._factory = _factory |
| 156 |
try: |
| 157 |
_factory(policy=self.policy) |
| 158 |
except TypeError: |
| 159 |
|
| 160 |
self._old_style_factory = True |
| 161 |
self._input = BufferedSubFile() |
| 162 |
self._msgstack = [] |
| 163 |
self._parse = self._parsegen().__next__ |
| 164 |
self._cur = None |
| 165 |
self._last = None |
| 166 |
self._headersonly = False |
| 167 |
|
| 168 |
|
| 169 |
def _set_headersonly(self): |
| 170 |
self._headersonly = True |
| 171 |
|
| 172 |
def feed(self, data): |
| 173 |
"""Push more data into the parser.""" |
| 174 |
self._input.push(data) |
| 175 |
self._call_parse() |
| 176 |
|
| 177 |
def _call_parse(self): |
| 178 |
try: |
| 179 |
self._parse() |
| 180 |
except StopIteration: |
| 181 |
pass |
| 182 |
|
| 183 |
def close(self): |
| 184 |
"""Parse all remaining data and return the root message object.""" |
| 185 |
self._input.close() |
| 186 |
self._call_parse() |
| 187 |
root = self._pop_message() |
| 188 |
assert not self._msgstack |
| 189 |
|
| 190 |
if root.get_content_maintype() == 'multipart' \ |
| 191 |
and not root.is_multipart() and not self._headersonly: |
| 192 |
defect = errors.MultipartInvariantViolationDefect() |
| 193 |
self.policy.handle_defect(root, defect) |
| 194 |
return root |
| 195 |
|
| 196 |
def _new_message(self): |
| 197 |
if self._old_style_factory: |
| 198 |
msg = self._factory() |
| 199 |
else: |
| 200 |
msg = self._factory(policy=self.policy) |
| 201 |
if self._cur and self._cur.get_content_type() == 'multipart/digest': |
| 202 |
msg.set_default_type('message/rfc822') |
| 203 |
if self._msgstack: |
| 204 |
self._msgstack[-1].attach(msg) |
| 205 |
self._msgstack.append(msg) |
| 206 |
self._cur = msg |
| 207 |
self._last = msg |
| 208 |
|
| 209 |
def _pop_message(self): |
| 210 |
retval = self._msgstack.pop() |
| 211 |
if self._msgstack: |
| 212 |
self._cur = self._msgstack[-1] |
| 213 |
else: |
| 214 |
self._cur = None |
| 215 |
return retval |
| 216 |
|
| 217 |
def _parsegen(self): |
| 218 |
|
| 219 |
self._new_message() |
| 220 |
headers = [] |
| 221 |
|
| 222 |
|
| 223 |
for line in self._input: |
| 224 |
if line is NeedMoreData: |
| 225 |
yield NeedMoreData |
| 226 |
continue |
| 227 |
if not headerRE.match(line): |
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
if not NLCRE.match(line): |
| 232 |
defect = errors.MissingHeaderBodySeparatorDefect() |
| 233 |
self.policy.handle_defect(self._cur, defect) |
| 234 |
self._input.unreadline(line) |
| 235 |
break |
| 236 |
headers.append(line) |
| 237 |
|
| 238 |
|
| 239 |
self._parse_headers(headers) |
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
if self._headersonly: |
| 244 |
lines = [] |
| 245 |
while True: |
| 246 |
line = self._input.readline() |
| 247 |
if line is NeedMoreData: |
| 248 |
yield NeedMoreData |
| 249 |
continue |
| 250 |
if line == '': |
| 251 |
break |
| 252 |
lines.append(line) |
| 253 |
self._cur.set_payload(EMPTYSTRING.join(lines)) |
| 254 |
return |
| 255 |
if self._cur.get_content_type() == 'message/delivery-status': |
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
while True: |
| 262 |
self._input.push_eof_matcher(NLCRE.match) |
| 263 |
for retval in self._parsegen(): |
| 264 |
if retval is NeedMoreData: |
| 265 |
yield NeedMoreData |
| 266 |
continue |
| 267 |
break |
| 268 |
msg = self._pop_message() |
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
self._input.pop_eof_matcher() |
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
while True: |
| 278 |
line = self._input.readline() |
| 279 |
if line is NeedMoreData: |
| 280 |
yield NeedMoreData |
| 281 |
continue |
| 282 |
break |
| 283 |
while True: |
| 284 |
line = self._input.readline() |
| 285 |
if line is NeedMoreData: |
| 286 |
yield NeedMoreData |
| 287 |
continue |
| 288 |
break |
| 289 |
if line == '': |
| 290 |
break |
| 291 |
|
| 292 |
self._input.unreadline(line) |
| 293 |
return |
| 294 |
if self._cur.get_content_maintype() == 'message': |
| 295 |
|
| 296 |
|
| 297 |
for retval in self._parsegen(): |
| 298 |
if retval is NeedMoreData: |
| 299 |
yield NeedMoreData |
| 300 |
continue |
| 301 |
break |
| 302 |
self._pop_message() |
| 303 |
return |
| 304 |
if self._cur.get_content_maintype() == 'multipart': |
| 305 |
boundary = self._cur.get_boundary() |
| 306 |
if boundary is None: |
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
defect = errors.NoBoundaryInMultipartDefect() |
| 312 |
self.policy.handle_defect(self._cur, defect) |
| 313 |
lines = [] |
| 314 |
for line in self._input: |
| 315 |
if line is NeedMoreData: |
| 316 |
yield NeedMoreData |
| 317 |
continue |
| 318 |
lines.append(line) |
| 319 |
self._cur.set_payload(EMPTYSTRING.join(lines)) |
| 320 |
return |
| 321 |
|
| 322 |
if (str(self._cur.get('content-transfer-encoding', '8bit')).lower() |
| 323 |
not in ('7bit', '8bit', 'binary')): |
| 324 |
defect = errors.InvalidMultipartContentTransferEncodingDefect() |
| 325 |
self.policy.handle_defect(self._cur, defect) |
| 326 |
|
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
separator = '--' + boundary |
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
def boundarymatch(line): |
| 336 |
if not line.startswith(separator): |
| 337 |
return None |
| 338 |
return boundaryend_re.match(line, len(separator)) |
| 339 |
capturing_preamble = True |
| 340 |
preamble = [] |
| 341 |
linesep = False |
| 342 |
close_boundary_seen = False |
| 343 |
while True: |
| 344 |
line = self._input.readline() |
| 345 |
if line is NeedMoreData: |
| 346 |
yield NeedMoreData |
| 347 |
continue |
| 348 |
if line == '': |
| 349 |
break |
| 350 |
mo = boundarymatch(line) |
| 351 |
if mo: |
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
|
| 356 |
if mo.group('end'): |
| 357 |
close_boundary_seen = True |
| 358 |
linesep = mo.group('linesep') |
| 359 |
break |
| 360 |
|
| 361 |
if capturing_preamble: |
| 362 |
if preamble: |
| 363 |
|
| 364 |
|
| 365 |
lastline = preamble[-1] |
| 366 |
eolmo = NLCRE_eol.search(lastline) |
| 367 |
if eolmo: |
| 368 |
preamble[-1] = lastline[:-len(eolmo.group(0))] |
| 369 |
self._cur.preamble = EMPTYSTRING.join(preamble) |
| 370 |
capturing_preamble = False |
| 371 |
self._input.unreadline(line) |
| 372 |
continue |
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
while True: |
| 378 |
line = self._input.readline() |
| 379 |
if line is NeedMoreData: |
| 380 |
yield NeedMoreData |
| 381 |
continue |
| 382 |
mo = boundarymatch(line) |
| 383 |
if not mo: |
| 384 |
self._input.unreadline(line) |
| 385 |
break |
| 386 |
|
| 387 |
|
| 388 |
self._input.push_eof_matcher(boundarymatch) |
| 389 |
for retval in self._parsegen(): |
| 390 |
if retval is NeedMoreData: |
| 391 |
yield NeedMoreData |
| 392 |
continue |
| 393 |
break |
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
if self._last.get_content_maintype() == 'multipart': |
| 399 |
epilogue = self._last.epilogue |
| 400 |
if epilogue == '': |
| 401 |
self._last.epilogue = None |
| 402 |
elif epilogue is not None: |
| 403 |
mo = NLCRE_eol.search(epilogue) |
| 404 |
if mo: |
| 405 |
end = len(mo.group(0)) |
| 406 |
self._last.epilogue = epilogue[:-end] |
| 407 |
else: |
| 408 |
payload = self._last._payload |
| 409 |
if isinstance(payload, str): |
| 410 |
mo = NLCRE_eol.search(payload) |
| 411 |
if mo: |
| 412 |
payload = payload[:-len(mo.group(0))] |
| 413 |
self._last._payload = payload |
| 414 |
self._input.pop_eof_matcher() |
| 415 |
self._pop_message() |
| 416 |
|
| 417 |
|
| 418 |
self._last = self._cur |
| 419 |
else: |
| 420 |
|
| 421 |
assert capturing_preamble |
| 422 |
preamble.append(line) |
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
if capturing_preamble: |
| 427 |
defect = errors.StartBoundaryNotFoundDefect() |
| 428 |
self.policy.handle_defect(self._cur, defect) |
| 429 |
self._cur.set_payload(EMPTYSTRING.join(preamble)) |
| 430 |
epilogue = [] |
| 431 |
for line in self._input: |
| 432 |
if line is NeedMoreData: |
| 433 |
yield NeedMoreData |
| 434 |
continue |
| 435 |
self._cur.epilogue = EMPTYSTRING.join(epilogue) |
| 436 |
return |
| 437 |
|
| 438 |
|
| 439 |
if not close_boundary_seen: |
| 440 |
defect = errors.CloseBoundaryNotFoundDefect() |
| 441 |
self.policy.handle_defect(self._cur, defect) |
| 442 |
return |
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
if linesep: |
| 447 |
epilogue = [''] |
| 448 |
else: |
| 449 |
epilogue = [] |
| 450 |
for line in self._input: |
| 451 |
if line is NeedMoreData: |
| 452 |
yield NeedMoreData |
| 453 |
continue |
| 454 |
epilogue.append(line) |
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
if epilogue: |
| 459 |
firstline = epilogue[0] |
| 460 |
bolmo = NLCRE_bol.match(firstline) |
| 461 |
if bolmo: |
| 462 |
epilogue[0] = firstline[len(bolmo.group(0)):] |
| 463 |
self._cur.epilogue = EMPTYSTRING.join(epilogue) |
| 464 |
return |
| 465 |
|
| 466 |
|
| 467 |
lines = [] |
| 468 |
for line in self._input: |
| 469 |
if line is NeedMoreData: |
| 470 |
yield NeedMoreData |
| 471 |
continue |
| 472 |
lines.append(line) |
| 473 |
self._cur.set_payload(EMPTYSTRING.join(lines)) |
| 474 |
|
| 475 |
def _parse_headers(self, lines): |
| 476 |
|
| 477 |
lastheader = '' |
| 478 |
lastvalue = [] |
| 479 |
for lineno, line in enumerate(lines): |
| 480 |
|
| 481 |
if line[0] in ' \t': |
| 482 |
if not lastheader: |
| 483 |
|
| 484 |
|
| 485 |
|
| 486 |
defect = errors.FirstHeaderLineIsContinuationDefect(line) |
| 487 |
self.policy.handle_defect(self._cur, defect) |
| 488 |
continue |
| 489 |
lastvalue.append(line) |
| 490 |
continue |
| 491 |
if lastheader: |
| 492 |
self._cur.set_raw(*self.policy.header_source_parse(lastvalue)) |
| 493 |
lastheader, lastvalue = '', [] |
| 494 |
|
| 495 |
if line.startswith('From '): |
| 496 |
if lineno == 0: |
| 497 |
|
| 498 |
mo = NLCRE_eol.search(line) |
| 499 |
if mo: |
| 500 |
line = line[:-len(mo.group(0))] |
| 501 |
self._cur.set_unixfrom(line) |
| 502 |
continue |
| 503 |
elif lineno == len(lines) - 1: |
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
self._input.unreadline(line) |
| 508 |
return |
| 509 |
else: |
| 510 |
|
| 511 |
|
| 512 |
defect = errors.MisplacedEnvelopeHeaderDefect(line) |
| 513 |
self._cur.defects.append(defect) |
| 514 |
continue |
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
i = line.find(':') |
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
if i == 0: |
| 524 |
defect = errors.InvalidHeaderDefect("Missing header name.") |
| 525 |
self._cur.defects.append(defect) |
| 526 |
continue |
| 527 |
|
| 528 |
assert i>0, "_parse_headers fed line with no : and no leading WS" |
| 529 |
lastheader = line[:i] |
| 530 |
lastvalue = [line] |
| 531 |
|
| 532 |
if lastheader: |
| 533 |
self._cur.set_raw(*self.policy.header_source_parse(lastvalue)) |
| 534 |
|
| 535 |
|
| 536 |
class BytesFeedParser(FeedParser): |
| 537 |
"""Like FeedParser, but feed accepts bytes.""" |
| 538 |
|
| 539 |
def feed(self, data): |
| 540 |
super().feed(data.decode('ascii', 'surrogateescape')) |