PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/email/feedparser.py

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