You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

504 lines
21 KiB

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