feedparser.py 22 KB

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