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

/python/lib/Lib/email/feedparser.py

http://github.com/JetBrains/intellij-community
Python | 480 lines | 403 code | 9 blank | 68 comment | 54 complexity | 55e31c00d9b7da2a261bb885a98e3743 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0
  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 throw 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)$')
  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. # 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._lines.append(self._partial)
  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. # Handle any previous leftovers
  80. data, self._partial = self._partial + data, ''
  81. # Crack into lines, but preserve the newlines on the end of each
  82. parts = NLCRE_crack.split(data)
  83. # The *ahem* interesting behaviour of re.split when supplied grouping
  84. # parentheses is that the last element of the resulting list is the
  85. # data after the final RE. In the case of a NL/CR terminated string,
  86. # this is the empty string.
  87. self._partial = parts.pop()
  88. # parts is a list of strings, alternating between the line contents
  89. # and the eol character(s). Gather up a list of lines after
  90. # re-attaching the newlines.
  91. lines = []
  92. for i in range(len(parts) // 2):
  93. lines.append(parts[i*2] + parts[i*2+1])
  94. self.pushlines(lines)
  95. def pushlines(self, lines):
  96. # Reverse and insert at the front of the lines.
  97. self._lines[:0] = lines[::-1]
  98. def is_closed(self):
  99. return self._closed
  100. def __iter__(self):
  101. return self
  102. def next(self):
  103. line = self.readline()
  104. if line == '':
  105. raise StopIteration
  106. return line
  107. class FeedParser:
  108. """A feed-style parser of email."""
  109. def __init__(self, _factory=message.Message):
  110. """_factory is called with no arguments to create a new message obj"""
  111. self._factory = _factory
  112. self._input = BufferedSubFile()
  113. self._msgstack = []
  114. self._parse = self._parsegen().next
  115. self._cur = None
  116. self._last = None
  117. self._headersonly = False
  118. # Non-public interface for supporting Parser's headersonly flag
  119. def _set_headersonly(self):
  120. self._headersonly = True
  121. def feed(self, data):
  122. """Push more data into the parser."""
  123. self._input.push(data)
  124. self._call_parse()
  125. def _call_parse(self):
  126. try:
  127. self._parse()
  128. except StopIteration:
  129. pass
  130. def close(self):
  131. """Parse all remaining data and return the root message object."""
  132. self._input.close()
  133. self._call_parse()
  134. root = self._pop_message()
  135. assert not self._msgstack
  136. # Look for final set of defects
  137. if root.get_content_maintype() == 'multipart' \
  138. and not root.is_multipart():
  139. root.defects.append(errors.MultipartInvariantViolationDefect())
  140. return root
  141. def _new_message(self):
  142. msg = self._factory()
  143. if self._cur and self._cur.get_content_type() == 'multipart/digest':
  144. msg.set_default_type('message/rfc822')
  145. if self._msgstack:
  146. self._msgstack[-1].attach(msg)
  147. self._msgstack.append(msg)
  148. self._cur = msg
  149. self._last = msg
  150. def _pop_message(self):
  151. retval = self._msgstack.pop()
  152. if self._msgstack:
  153. self._cur = self._msgstack[-1]
  154. else:
  155. self._cur = None
  156. return retval
  157. def _parsegen(self):
  158. # Create a new message and start by parsing headers.
  159. self._new_message()
  160. headers = []
  161. # Collect the headers, searching for a line that doesn't match the RFC
  162. # 2822 header or continuation pattern (including an empty line).
  163. for line in self._input:
  164. if line is NeedMoreData:
  165. yield NeedMoreData
  166. continue
  167. if not headerRE.match(line):
  168. # If we saw the RFC defined header/body separator
  169. # (i.e. newline), just throw it away. Otherwise the line is
  170. # part of the body so push it back.
  171. if not NLCRE.match(line):
  172. self._input.unreadline(line)
  173. break
  174. headers.append(line)
  175. # Done with the headers, so parse them and figure out what we're
  176. # supposed to see in the body of the message.
  177. self._parse_headers(headers)
  178. # Headers-only parsing is a backwards compatibility hack, which was
  179. # necessary in the older parser, which could throw errors. All
  180. # remaining lines in the input are thrown into the message body.
  181. if self._headersonly:
  182. lines = []
  183. while True:
  184. line = self._input.readline()
  185. if line is NeedMoreData:
  186. yield NeedMoreData
  187. continue
  188. if line == '':
  189. break
  190. lines.append(line)
  191. self._cur.set_payload(EMPTYSTRING.join(lines))
  192. return
  193. if self._cur.get_content_type() == 'message/delivery-status':
  194. # message/delivery-status contains blocks of headers separated by
  195. # a blank line. We'll represent each header block as a separate
  196. # nested message object, but the processing is a bit different
  197. # than standard message/* types because there is no body for the
  198. # nested messages. A blank line separates the subparts.
  199. while True:
  200. self._input.push_eof_matcher(NLCRE.match)
  201. for retval in self._parsegen():
  202. if retval is NeedMoreData:
  203. yield NeedMoreData
  204. continue
  205. break
  206. msg = self._pop_message()
  207. # We need to pop the EOF matcher in order to tell if we're at
  208. # the end of the current file, not the end of the last block
  209. # of message headers.
  210. self._input.pop_eof_matcher()
  211. # The input stream must be sitting at the newline or at the
  212. # EOF. We want to see if we're at the end of this subpart, so
  213. # first consume the blank line, then test the next line to see
  214. # if we're at this subpart's EOF.
  215. while True:
  216. line = self._input.readline()
  217. if line is NeedMoreData:
  218. yield NeedMoreData
  219. continue
  220. break
  221. while True:
  222. line = self._input.readline()
  223. if line is NeedMoreData:
  224. yield NeedMoreData
  225. continue
  226. break
  227. if line == '':
  228. break
  229. # Not at EOF so this is a line we're going to need.
  230. self._input.unreadline(line)
  231. return
  232. if self._cur.get_content_maintype() == 'message':
  233. # The message claims to be a message/* type, then what follows is
  234. # another RFC 2822 message.
  235. for retval in self._parsegen():
  236. if retval is NeedMoreData:
  237. yield NeedMoreData
  238. continue
  239. break
  240. self._pop_message()
  241. return
  242. if self._cur.get_content_maintype() == 'multipart':
  243. boundary = self._cur.get_boundary()
  244. if boundary is None:
  245. # The message /claims/ to be a multipart but it has not
  246. # defined a boundary. That's a problem which we'll handle by
  247. # reading everything until the EOF and marking the message as
  248. # defective.
  249. self._cur.defects.append(errors.NoBoundaryInMultipartDefect())
  250. lines = []
  251. for line in self._input:
  252. if line is NeedMoreData:
  253. yield NeedMoreData
  254. continue
  255. lines.append(line)
  256. self._cur.set_payload(EMPTYSTRING.join(lines))
  257. return
  258. # Create a line match predicate which matches the inter-part
  259. # boundary as well as the end-of-multipart boundary. Don't push
  260. # this onto the input stream until we've scanned past the
  261. # preamble.
  262. separator = '--' + boundary
  263. boundaryre = re.compile(
  264. '(?P<sep>' + re.escape(separator) +
  265. r')(?P<end>--)?(?P<ws>[ \t]*)(?P<linesep>\r\n|\r|\n)?$')
  266. capturing_preamble = True
  267. preamble = []
  268. linesep = False
  269. while True:
  270. line = self._input.readline()
  271. if line is NeedMoreData:
  272. yield NeedMoreData
  273. continue
  274. if line == '':
  275. break
  276. mo = boundaryre.match(line)
  277. if mo:
  278. # If we're looking at the end boundary, we're done with
  279. # this multipart. If there was a newline at the end of
  280. # the closing boundary, then we need to initialize the
  281. # epilogue with the empty string (see below).
  282. if mo.group('end'):
  283. linesep = mo.group('linesep')
  284. break
  285. # We saw an inter-part boundary. Were we in the preamble?
  286. if capturing_preamble:
  287. if preamble:
  288. # According to RFC 2046, the last newline belongs
  289. # to the boundary.
  290. lastline = preamble[-1]
  291. eolmo = NLCRE_eol.search(lastline)
  292. if eolmo:
  293. preamble[-1] = lastline[:-len(eolmo.group(0))]
  294. self._cur.preamble = EMPTYSTRING.join(preamble)
  295. capturing_preamble = False
  296. self._input.unreadline(line)
  297. continue
  298. # We saw a boundary separating two parts. Consume any
  299. # multiple boundary lines that may be following. Our
  300. # interpretation of RFC 2046 BNF grammar does not produce
  301. # body parts within such double boundaries.
  302. while True:
  303. line = self._input.readline()
  304. if line is NeedMoreData:
  305. yield NeedMoreData
  306. continue
  307. mo = boundaryre.match(line)
  308. if not mo:
  309. self._input.unreadline(line)
  310. break
  311. # Recurse to parse this subpart; the input stream points
  312. # at the subpart's first line.
  313. self._input.push_eof_matcher(boundaryre.match)
  314. for retval in self._parsegen():
  315. if retval is NeedMoreData:
  316. yield NeedMoreData
  317. continue
  318. break
  319. # Because of RFC 2046, the newline preceding the boundary
  320. # separator actually belongs to the boundary, not the
  321. # previous subpart's payload (or epilogue if the previous
  322. # part is a multipart).
  323. if self._last.get_content_maintype() == 'multipart':
  324. epilogue = self._last.epilogue
  325. if epilogue == '':
  326. self._last.epilogue = None
  327. elif epilogue is not None:
  328. mo = NLCRE_eol.search(epilogue)
  329. if mo:
  330. end = len(mo.group(0))
  331. self._last.epilogue = epilogue[:-end]
  332. else:
  333. payload = self._last.get_payload()
  334. if isinstance(payload, basestring):
  335. mo = NLCRE_eol.search(payload)
  336. if mo:
  337. payload = payload[:-len(mo.group(0))]
  338. self._last.set_payload(payload)
  339. self._input.pop_eof_matcher()
  340. self._pop_message()
  341. # Set the multipart up for newline cleansing, which will
  342. # happen if we're in a nested multipart.
  343. self._last = self._cur
  344. else:
  345. # I think we must be in the preamble
  346. assert capturing_preamble
  347. preamble.append(line)
  348. # We've seen either the EOF or the end boundary. If we're still
  349. # capturing the preamble, we never saw the start boundary. Note
  350. # that as a defect and store the captured text as the payload.
  351. # Everything from here to the EOF is epilogue.
  352. if capturing_preamble:
  353. self._cur.defects.append(errors.StartBoundaryNotFoundDefect())
  354. self._cur.set_payload(EMPTYSTRING.join(preamble))
  355. epilogue = []
  356. for line in self._input:
  357. if line is NeedMoreData:
  358. yield NeedMoreData
  359. continue
  360. self._cur.epilogue = EMPTYSTRING.join(epilogue)
  361. return
  362. # If the end boundary ended in a newline, we'll need to make sure
  363. # the epilogue isn't None
  364. if linesep:
  365. epilogue = ['']
  366. else:
  367. epilogue = []
  368. for line in self._input:
  369. if line is NeedMoreData:
  370. yield NeedMoreData
  371. continue
  372. epilogue.append(line)
  373. # Any CRLF at the front of the epilogue is not technically part of
  374. # the epilogue. Also, watch out for an empty string epilogue,
  375. # which means a single newline.
  376. if epilogue:
  377. firstline = epilogue[0]
  378. bolmo = NLCRE_bol.match(firstline)
  379. if bolmo:
  380. epilogue[0] = firstline[len(bolmo.group(0)):]
  381. self._cur.epilogue = EMPTYSTRING.join(epilogue)
  382. return
  383. # Otherwise, it's some non-multipart type, so the entire rest of the
  384. # file contents becomes the payload.
  385. lines = []
  386. for line in self._input:
  387. if line is NeedMoreData:
  388. yield NeedMoreData
  389. continue
  390. lines.append(line)
  391. self._cur.set_payload(EMPTYSTRING.join(lines))
  392. def _parse_headers(self, lines):
  393. # Passed a list of lines that make up the headers for the current msg
  394. lastheader = ''
  395. lastvalue = []
  396. for lineno, line in enumerate(lines):
  397. # Check for continuation
  398. if line[0] in ' \t':
  399. if not lastheader:
  400. # The first line of the headers was a continuation. This
  401. # is illegal, so let's note the defect, store the illegal
  402. # line, and ignore it for purposes of headers.
  403. defect = errors.FirstHeaderLineIsContinuationDefect(line)
  404. self._cur.defects.append(defect)
  405. continue
  406. lastvalue.append(line)
  407. continue
  408. if lastheader:
  409. # XXX reconsider the joining of folded lines
  410. lhdr = EMPTYSTRING.join(lastvalue)[:-1].rstrip('\r\n')
  411. self._cur[lastheader] = lhdr
  412. lastheader, lastvalue = '', []
  413. # Check for envelope header, i.e. unix-from
  414. if line.startswith('From '):
  415. if lineno == 0:
  416. # Strip off the trailing newline
  417. mo = NLCRE_eol.search(line)
  418. if mo:
  419. line = line[:-len(mo.group(0))]
  420. self._cur.set_unixfrom(line)
  421. continue
  422. elif lineno == len(lines) - 1:
  423. # Something looking like a unix-from at the end - it's
  424. # probably the first line of the body, so push back the
  425. # line and stop.
  426. self._input.unreadline(line)
  427. return
  428. else:
  429. # Weirdly placed unix-from line. Note this as a defect
  430. # and ignore it.
  431. defect = errors.MisplacedEnvelopeHeaderDefect(line)
  432. self._cur.defects.append(defect)
  433. continue
  434. # Split the line on the colon separating field name from value.
  435. i = line.find(':')
  436. if i < 0:
  437. defect = errors.MalformedHeaderDefect(line)
  438. self._cur.defects.append(defect)
  439. continue
  440. lastheader = line[:i]
  441. lastvalue = [line[i+1:].lstrip()]
  442. # Done with all the lines, so handle the last header.
  443. if lastheader:
  444. # XXX reconsider the joining of folded lines
  445. self._cur[lastheader] = EMPTYSTRING.join(lastvalue).rstrip('\r\n')