Debian Codegraph @

cpython27/Lib/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']
23
24 import re
25
26 from email import errors
27 from email import message
28
29 NLCRE = re.compile('\r\n|\r|\n')
30 NLCRE_bol = re.compile('(\r\n|\r|\n)')
31 NLCRE_eol = re.compile('(\r\n|\r|\n)\Z')
32 NLCRE_crack = re.compile('(\r\n|\r|\n)')
33 # RFC 2822 $3.6.8 Optional fields. ftext is %d33-57 / %d59-126, Any character
34 # except controls, SP, and ":".
35 headerRE = re.compile(r'^(From |[\041-\071\073-\176]{1,}:|[\t ])')
36 EMPTYSTRING = ''
37 NL = '\n'
38
39 NeedMoreData = object()
40
41
42
43 class BufferedSubFile(object):
44 """A file-ish object that can have new data loaded into it.
45
46 You can also push and pop line-matching predicates onto a stack. When the
47 current predicate matches the current line, a false EOF response
48 (i.e. empty string) is returned instead. This lets the parser adhere to a
49 simple abstraction -- it parses until EOF closes the current message.
50 """
51 def __init__(self):
52 # Chunks of the last partial line pushed into this object.
53 self._partial = []
54 # The list of full, pushed lines, in reverse order
55 self._lines = []
56 # The stack of false-EOF checking predicates.
57 self._eofstack = []
58 # A flag indicating whether the file has been closed or not.
59 self._closed = False
60
61 def push_eof_matcher(self, pred):
62 self._eofstack.append(pred)
63
64 def pop_eof_matcher(self):
65 return self._eofstack.pop()
66
67 def close(self):
68 # Don't forget any trailing partial line.
69 self.pushlines(''.join(self._partial).splitlines(True))
70 self._partial = []
71 self._closed = True
72
73 def readline(self):
74 if not self._lines:
75 if self._closed:
76 return ''
77 return NeedMoreData
78 # Pop the line off the stack and see if it matches the current
79 # false-EOF predicate.
80 line = self._lines.pop()
81 # RFC 2046, section 5.1.2 requires us to recognize outer level
82 # boundaries at any level of inner nesting. Do this, but be sure it's
83 # in the order of most to least nested.
84 for ateof in self._eofstack[::-1]:
85 if ateof(line):
86 # We're at the false EOF. But push the last line back first.
87 self._lines.append(line)
88 return ''
89 return line
90
91 def unreadline(self, line):
92 # Let the consumer push a line back into the buffer.
93 assert line is not NeedMoreData
94 self._lines.append(line)
95
96 def push(self, data):
97 """Push some new data into this object."""
98 # Crack into lines, but preserve the linesep characters on the end of each
99 parts = data.splitlines(True)
100
101 if not parts or not parts[0].endswith(('\n', '\r')):
102 # No new complete lines, so just accumulate partials
103 self._partial += parts
104 return
105
106 if self._partial:
107 # If there are previous leftovers, complete them now
108 self._partial.append(parts[0])
109 parts[0:1] = ''.join(self._partial).splitlines(True)
110 del self._partial[:]
111
112 # If the last element of the list does not end in a newline, then treat
113 # it as a partial line. We only check for '\n' here because a line
114 # ending with '\r' might be a line that was split in the middle of a
115 # '\r\n' sequence (see bugs 1555570 and 1721862).
116 if not parts[-1].endswith('\n'):
117 self._partial = [parts.pop()]
118 self.pushlines(parts)
119
120 def pushlines(self, lines):
121 # Reverse and insert at the front of the lines.
122 self._lines[:0] = lines[::-1]
123
124 def is_closed(self):
125 return self._closed
126
127 def __iter__(self):
128 return self
129
130 def next(self):
131 line = self.readline()
132 if line == '':
133 raise StopIteration
134 return line
135
136
137
138 class FeedParser:
139 """A feed-style parser of email."""
140
141 def __init__(self, _factory=message.Message):
142 """_factory is called with no arguments to create a new message obj"""
143 self._factory = _factory
144 self._input = BufferedSubFile()
145 self._msgstack = []
146 self._parse = self._parsegen().next
147 self._cur = None
148 self._last = None
149 self._headersonly = False
150
151 # Non-public interface for supporting Parser's headersonly flag
152 def _set_headersonly(self):
153 self._headersonly = True
154
155 def feed(self, data):
156 """Push more data into the parser."""
157 self._input.push(data)
158 self._call_parse()
159
160 def _call_parse(self):
161 try:
162 self._parse()
163 except StopIteration:
164 pass
165
166 def close(self):
167 """Parse all remaining data and return the root message object."""
168 self._input.close()
169 self._call_parse()
170 root = self._pop_message()
171 assert not self._msgstack
172 # Look for final set of defects
173 if root.get_content_maintype() == 'multipart' \
174 and not root.is_multipart():
175 root.defects.append(errors.MultipartInvariantViolationDefect())
176 return root
177
178 def _new_message(self):
179 msg = self._factory()
180 if self._cur and self._cur.get_content_type() == 'multipart/digest':
181 msg.set_default_type('message/rfc822')
182 if self._msgstack:
183 self._msgstack[-1].attach(msg)
184 self._msgstack.append(msg)
185 self._cur = msg
186 self._last = msg
187
188 def _pop_message(self):
189 retval = self._msgstack.pop()
190 if self._msgstack:
191 self._cur = self._msgstack[-1]
192 else:
193 self._cur = None
194 return retval
195
196 def _parsegen(self):
197 # Create a new message and start by parsing headers.
198 self._new_message()
199 headers = []
200 # Collect the headers, searching for a line that doesn't match the RFC
201 # 2822 header or continuation pattern (including an empty line).
202 for line in self._input:
203 if line is NeedMoreData:
204 yield NeedMoreData
205 continue
206 if not headerRE.match(line):
207 # If we saw the RFC defined header/body separator
208 # (i.e. newline), just throw it away. Otherwise the line is
209 # part of the body so push it back.
210 if not NLCRE.match(line):
211 self._input.unreadline(line)
212 break
213 headers.append(line)
214 # Done with the headers, so parse them and figure out what we're
215 # supposed to see in the body of the message.
216 self._parse_headers(headers)
217 # Headers-only parsing is a backwards compatibility hack, which was
218 # necessary in the older parser, which could raise errors. All
219 # remaining lines in the input are thrown into the message body.
220 if self._headersonly:
221 lines = []
222 while True:
223 line = self._input.readline()
224 if line is NeedMoreData:
225 yield NeedMoreData
226 continue
227 if line == '':
228 break
229 lines.append(line)
230 self._cur.set_payload(EMPTYSTRING.join(lines))
231 return
232 if self._cur.get_content_type() == 'message/delivery-status':
233 # message/delivery-status contains blocks of headers separated by
234 # a blank line. We'll represent each header block as a separate
235 # nested message object, but the processing is a bit different
236 # than standard message/* types because there is no body for the
237 # nested messages. A blank line separates the subparts.
238 while True:
239 self._input.push_eof_matcher(NLCRE.match)
240 for retval in self._parsegen():
241 if retval is NeedMoreData:
242 yield NeedMoreData
243 continue
244 break
245 msg = self._pop_message()
246 # We need to pop the EOF matcher in order to tell if we're at
247 # the end of the current file, not the end of the last block
248 # of message headers.
249 self._input.pop_eof_matcher()
250 # The input stream must be sitting at the newline or at the
251 # EOF. We want to see if we're at the end of this subpart, so
252 # first consume the blank line, then test the next line to see
253 # if we're at this subpart's EOF.
254 while True:
255 line = self._input.readline()
256 if line is NeedMoreData:
257 yield NeedMoreData
258 continue
259 break
260 while True:
261 line = self._input.readline()
262 if line is NeedMoreData:
263 yield NeedMoreData
264 continue
265 break
266 if line == '':
267 break
268 # Not at EOF so this is a line we're going to need.
269 self._input.unreadline(line)
270 return
271 if self._cur.get_content_maintype() == 'message':
272 # The message claims to be a message/* type, then what follows is
273 # another RFC 2822 message.
274 for retval in self._parsegen():
275 if retval is NeedMoreData:
276 yield NeedMoreData
277 continue
278 break
279 self._pop_message()
280 return
281 if self._cur.get_content_maintype() == 'multipart':
282 boundary = self._cur.get_boundary()
283 if boundary is None:
284 # The message /claims/ to be a multipart but it has not
285 # defined a boundary. That's a problem which we'll handle by
286 # reading everything until the EOF and marking the message as
287 # defective.
288 self._cur.defects.append(errors.NoBoundaryInMultipartDefect())
289 lines = []
290 for line in self._input:
291 if line is NeedMoreData:
292 yield NeedMoreData
293 continue
294 lines.append(line)
295 self._cur.set_payload(EMPTYSTRING.join(lines))
296 return
297 # Create a line match predicate which matches the inter-part
298 # boundary as well as the end-of-multipart boundary. Don't push
299 # this onto the input stream until we've scanned past the
300 # preamble.
301 separator = '--' + boundary
302 boundaryre = re.compile(
303 '(?P<sep>' + re.escape(separator) +
304 r')(?P<end>--)?(?P<ws>[ \t]*)(?P<linesep>\r\n|\r|\n)?$')
305 capturing_preamble = True
306 preamble = []
307 linesep = False
308 while True:
309 line = self._input.readline()
310 if line is NeedMoreData:
311 yield NeedMoreData
312 continue
313 if line == '':
314 break
315 mo = boundaryre.match(line)
316 if mo:
317 # If we're looking at the end boundary, we're done with
318 # this multipart. If there was a newline at the end of
319 # the closing boundary, then we need to initialize the
320 # epilogue with the empty string (see below).
321 if mo.group('end'):
322 linesep = mo.group('linesep')
323 break
324 # We saw an inter-part boundary. Were we in the preamble?
325 if capturing_preamble:
326 if preamble:
327 # According to RFC 2046, the last newline belongs
328 # to the boundary.
329 lastline = preamble[-1]
330 eolmo = NLCRE_eol.search(lastline)
331 if eolmo:
332 preamble[-1] = lastline[:-len(eolmo.group(0))]
333 self._cur.preamble = EMPTYSTRING.join(preamble)
334 capturing_preamble = False
335 self._input.unreadline(line)
336 continue
337 # We saw a boundary separating two parts. Consume any
338 # multiple boundary lines that may be following. Our
339 # interpretation of RFC 2046 BNF grammar does not produce
340 # body parts within such double boundaries.
341 while True:
342 line = self._input.readline()
343 if line is NeedMoreData:
344 yield NeedMoreData
345 continue
346 mo = boundaryre.match(line)
347 if not mo:
348 self._input.unreadline(line)
349 break
350 # Recurse to parse this subpart; the input stream points
351 # at the subpart's first line.
352 self._input.push_eof_matcher(boundaryre.match)
353 for retval in self._parsegen():
354 if retval is NeedMoreData:
355 yield NeedMoreData
356 continue
357 break
358 # Because of RFC 2046, the newline preceding the boundary
359 # separator actually belongs to the boundary, not the
360 # previous subpart's payload (or epilogue if the previous
361 # part is a multipart).
362 if self._last.get_content_maintype() == 'multipart':
363 epilogue = self._last.epilogue
364 if epilogue == '':
365 self._last.epilogue = None
366 elif epilogue is not None:
367 mo = NLCRE_eol.search(epilogue)
368 if mo:
369 end = len(mo.group(0))
370 self._last.epilogue = epilogue[:-end]
371 else:
372 payload = self._last.get_payload()
373 if isinstance(payload, basestring):
374 mo = NLCRE_eol.search(payload)
375 if mo:
376 payload = payload[:-len(mo.group(0))]
377 self._last.set_payload(payload)
378 self._input.pop_eof_matcher()
379 self._pop_message()
380 # Set the multipart up for newline cleansing, which will
381 # happen if we're in a nested multipart.
382 self._last = self._cur
383 else:
384 # I think we must be in the preamble
385 assert capturing_preamble
386 preamble.append(line)
387 # We've seen either the EOF or the end boundary. If we're still
388 # capturing the preamble, we never saw the start boundary. Note
389 # that as a defect and store the captured text as the payload.
390 # Everything from here to the EOF is epilogue.
391 if capturing_preamble:
392 self._cur.defects.append(errors.StartBoundaryNotFoundDefect())
393 self._cur.set_payload(EMPTYSTRING.join(preamble))
394 epilogue = []
395 for line in self._input:
396 if line is NeedMoreData:
397 yield NeedMoreData
398 continue
399 self._cur.epilogue = EMPTYSTRING.join(epilogue)
400 return
401 # If the end boundary ended in a newline, we'll need to make sure
402 # the epilogue isn't None
403 if linesep:
404 epilogue = ['']
405 else:
406 epilogue = []
407 for line in self._input:
408 if line is NeedMoreData:
409 yield NeedMoreData
410 continue
411 epilogue.append(line)
412 # Any CRLF at the front of the epilogue is not technically part of
413 # the epilogue. Also, watch out for an empty string epilogue,
414 # which means a single newline.
415 if epilogue:
416 firstline = epilogue[0]
417 bolmo = NLCRE_bol.match(firstline)
418 if bolmo:
419 epilogue[0] = firstline[len(bolmo.group(0)):]
420 self._cur.epilogue = EMPTYSTRING.join(epilogue)
421 return
422 # Otherwise, it's some non-multipart type, so the entire rest of the
423 # file contents becomes the payload.
424 lines = []
425 for line in self._input:
426 if line is NeedMoreData:
427 yield NeedMoreData
428 continue
429 lines.append(line)
430 self._cur.set_payload(EMPTYSTRING.join(lines))
431
432 def _parse_headers(self, lines):
433 # Passed a list of lines that make up the headers for the current msg
434 lastheader = ''
435 lastvalue = []
436 for lineno, line in enumerate(lines):
437 # Check for continuation
438 if line[0] in ' \t':
439 if not lastheader:
440 # The first line of the headers was a continuation. This
441 # is illegal, so let's note the defect, store the illegal
442 # line, and ignore it for purposes of headers.
443 defect = errors.FirstHeaderLineIsContinuationDefect(line)
444 self._cur.defects.append(defect)
445 continue
446 lastvalue.append(line)
447 continue
448 if lastheader:
449 # XXX reconsider the joining of folded lines
450 lhdr = EMPTYSTRING.join(lastvalue)[:-1].rstrip('\r\n')
451 self._cur[lastheader] = lhdr
452 lastheader, lastvalue = '', []
453 # Check for envelope header, i.e. unix-from
454 if line.startswith('From '):
455 if lineno == 0:
456 # Strip off the trailing newline
457 mo = NLCRE_eol.search(line)
458 if mo:
459 line = line[:-len(mo.group(0))]
460 self._cur.set_unixfrom(line)
461 continue
462 elif lineno == len(lines) - 1:
463 # Something looking like a unix-from at the end - it's
464 # probably the first line of the body, so push back the
465 # line and stop.
466 self._input.unreadline(line)
467 return
468 else:
469 # Weirdly placed unix-from line. Note this as a defect
470 # and ignore it.
471 defect = errors.MisplacedEnvelopeHeaderDefect(line)
472 self._cur.defects.append(defect)
473 continue
474 # Split the line on the colon separating field name from value.
475 i = line.find(':')
476 if i < 0:
477 defect = errors.MalformedHeaderDefect(line)
478 self._cur.defects.append(defect)
479 continue
480 lastheader = line[:i]
481 lastvalue = [line[i+1:].lstrip()]
482 # Done with all the lines, so handle the last header.
483 if lastheader:
484 # XXX reconsider the joining of folded lines
485 self._cur[lastheader] = EMPTYSTRING.join(lastvalue).rstrip('\r\n')