Debian Codegraph @

lib-python/3/email/feedparser.py

raw symbols SCIP
1 # Copyright (C) 2004-2006 Python Software Foundation
2 # Authors: Baxter, Wouters and Warsaw
3 # Contact: [email protected]
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 # RFC 2822 $3.6.8 Optional fields. ftext is %d33-57 / %d59-126, Any character
36 # except controls, SP, and ":".
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 # Text stream of the last partial line pushed into this object.
55 # See issue 22233 for why this is a text stream and not a list.
56 self._partial = StringIO(newline='')
57 # A deque of full, pushed lines
58 self._lines = deque()
59 # The stack of false-EOF checking predicates.
60 self._eofstack = []
61 # A flag indicating whether the file has been closed or not.
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 # Don't forget any trailing partial line.
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 # Pop the line off the stack and see if it matches the current
84 # false-EOF predicate.
85 line = self._lines.popleft()
86 # RFC 2046, section 5.1.2 requires us to recognize outer level
87 # boundaries at any level of inner nesting. Do this, but be sure it's
88 # in the order of most to least nested.
89 for ateof in reversed(self._eofstack):
90 if ateof(line):
91 # We're at the false EOF. But push the last line back first.
92 self._lines.appendleft(line)
93 return ''
94 return line
95
96 def unreadline(self, line):
97 # Let the consumer push a line back into the buffer.
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 # No new complete lines, wait for more.
106 return
107
108 # Crack into lines, preserving the linesep characters.
109 self._partial.seek(0)
110 parts = self._partial.readlines()
111 self._partial.seek(0)
112 self._partial.truncate()
113
114 # If the last element of the list does not end in a newline, then treat
115 # it as a partial line. We only check for '\n' here because a line
116 # ending with '\r' might be a line that was split in the middle of a
117 # '\r\n' sequence (see bugs 1555570 and 1721862).
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 # Assume this is an old-style factory
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 # Non-public interface for supporting Parser's headersonly flag
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 # Look for final set of defects
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 # Create a new message and start by parsing headers.
219 self._new_message()
220 headers = []
221 # Collect the headers, searching for a line that doesn't match the RFC
222 # 2822 header or continuation pattern (including an empty line).
223 for line in self._input:
224 if line is NeedMoreData:
225 yield NeedMoreData
226 continue
227 if not headerRE.match(line):
228 # If we saw the RFC defined header/body separator
229 # (i.e. newline), just throw it away. Otherwise the line is
230 # part of the body so push it back.
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 # Done with the headers, so parse them and figure out what we're
238 # supposed to see in the body of the message.
239 self._parse_headers(headers)
240 # Headers-only parsing is a backwards compatibility hack, which was
241 # necessary in the older parser, which could raise errors. All
242 # remaining lines in the input are thrown into the message body.
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 # message/delivery-status contains blocks of headers separated by
257 # a blank line. We'll represent each header block as a separate
258 # nested message object, but the processing is a bit different
259 # than standard message/* types because there is no body for the
260 # nested messages. A blank line separates the subparts.
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 # We need to pop the EOF matcher in order to tell if we're at
270 # the end of the current file, not the end of the last block
271 # of message headers.
272 self._input.pop_eof_matcher()
273 # The input stream must be sitting at the newline or at the
274 # EOF. We want to see if we're at the end of this subpart, so
275 # first consume the blank line, then test the next line to see
276 # if we're at this subpart's EOF.
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 # Not at EOF so this is a line we're going to need.
292 self._input.unreadline(line)
293 return
294 if self._cur.get_content_maintype() == 'message':
295 # The message claims to be a message/* type, then what follows is
296 # another RFC 2822 message.
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 # The message /claims/ to be a multipart but it has not
308 # defined a boundary. That's a problem which we'll handle by
309 # reading everything until the EOF and marking the message as
310 # defective.
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 # Make sure a valid content type was specified per RFC 2045:6.4.
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 # Create a line match predicate which matches the inter-part
327 # boundary as well as the end-of-multipart boundary. Don't push
328 # this onto the input stream until we've scanned past the
329 # preamble.
330 separator = '--' + boundary
331 # PyPy difference: don't compile a new regular expression for every
332 # single message, instead just use str.startswith and a generic re
333 # this prevents the JIT compiling more and more traces for all the
334 # different (random) boundaries of messages
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 # If we're looking at the end boundary, we're done with
353 # this multipart. If there was a newline at the end of
354 # the closing boundary, then we need to initialize the
355 # epilogue with the empty string (see below).
356 if mo.group('end'):
357 close_boundary_seen = True
358 linesep = mo.group('linesep')
359 break
360 # We saw an inter-part boundary. Were we in the preamble?
361 if capturing_preamble:
362 if preamble:
363 # According to RFC 2046, the last newline belongs
364 # to the boundary.
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 # We saw a boundary separating two parts. Consume any
374 # multiple boundary lines that may be following. Our
375 # interpretation of RFC 2046 BNF grammar does not produce
376 # body parts within such double boundaries.
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 # Recurse to parse this subpart; the input stream points
387 # at the subpart's first line.
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 # Because of RFC 2046, the newline preceding the boundary
395 # separator actually belongs to the boundary, not the
396 # previous subpart's payload (or epilogue if the previous
397 # part is a multipart).
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 # Set the multipart up for newline cleansing, which will
417 # happen if we're in a nested multipart.
418 self._last = self._cur
419 else:
420 # I think we must be in the preamble
421 assert capturing_preamble
422 preamble.append(line)
423 # We've seen either the EOF or the end boundary. If we're still
424 # capturing the preamble, we never saw the start boundary. Note
425 # that as a defect and store the captured text as the payload.
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 # If we're not processing the preamble, then we might have seen
438 # EOF without seeing that end boundary...that is also a defect.
439 if not close_boundary_seen:
440 defect = errors.CloseBoundaryNotFoundDefect()
441 self.policy.handle_defect(self._cur, defect)
442 return
443 # Everything from here to the EOF is epilogue. If the end boundary
444 # ended in a newline, we'll need to make sure the epilogue isn't
445 # None
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 # Any CRLF at the front of the epilogue is not technically part of
456 # the epilogue. Also, watch out for an empty string epilogue,
457 # which means a single newline.
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 # Otherwise, it's some non-multipart type, so the entire rest of the
466 # file contents becomes the payload.
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 # Passed a list of lines that make up the headers for the current msg
477 lastheader = ''
478 lastvalue = []
479 for lineno, line in enumerate(lines):
480 # Check for continuation
481 if line[0] in ' \t':
482 if not lastheader:
483 # The first line of the headers was a continuation. This
484 # is illegal, so let's note the defect, store the illegal
485 # line, and ignore it for purposes of headers.
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 # Check for envelope header, i.e. unix-from
495 if line.startswith('From '):
496 if lineno == 0:
497 # Strip off the trailing newline
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 # Something looking like a unix-from at the end - it's
505 # probably the first line of the body, so push back the
506 # line and stop.
507 self._input.unreadline(line)
508 return
509 else:
510 # Weirdly placed unix-from line. Note this as a defect
511 # and ignore it.
512 defect = errors.MisplacedEnvelopeHeaderDefect(line)
513 self._cur.defects.append(defect)
514 continue
515 # Split the line on the colon separating field name from value.
516 # There will always be a colon, because if there wasn't the part of
517 # the parser that calls us would have started parsing the body.
518 i = line.find(':')
519
520 # If the colon is on the start of the line the header is clearly
521 # malformed, but we might be able to salvage the rest of the
522 # message. Track the error but keep going.
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 # Done with all the lines, so handle the last header.
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'))