PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

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

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