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.
 
 
 
 

2060 line
83 KiB

  1. # Parsers for XML and HTML
  2. from lxml.includes cimport xmlparser
  3. from lxml.includes cimport htmlparser
  4. cdef object _GenericAlias
  5. try:
  6. from types import GenericAlias as _GenericAlias
  7. except ImportError:
  8. # Python 3.8 - we only need this as return value from "__class_getitem__"
  9. def _GenericAlias(cls, item):
  10. return f"{cls.__name__}[{item.__name__}]"
  11. class ParseError(LxmlSyntaxError):
  12. """Syntax error while parsing an XML document.
  13. For compatibility with ElementTree 1.3 and later.
  14. """
  15. def __init__(self, message, code, line, column, filename=None):
  16. super(_ParseError, self).__init__(message)
  17. self.lineno, self.offset = (line, column - 1)
  18. self.code = code
  19. self.filename = filename
  20. @property
  21. def position(self):
  22. return self.lineno, self.offset + 1
  23. @position.setter
  24. def position(self, new_pos):
  25. self.lineno, column = new_pos
  26. self.offset = column - 1
  27. cdef object _ParseError = ParseError
  28. class XMLSyntaxError(ParseError):
  29. """Syntax error while parsing an XML document.
  30. """
  31. cdef class ParserError(LxmlError):
  32. """Internal lxml parser error.
  33. """
  34. @cython.final
  35. @cython.internal
  36. cdef class _ParserDictionaryContext:
  37. # Global parser context to share the string dictionary.
  38. #
  39. # This class is a delegate singleton!
  40. #
  41. # It creates _ParserDictionaryContext objects for each thread to keep thread state,
  42. # but those must never be used directly. Always stick to using the static
  43. # __GLOBAL_PARSER_CONTEXT as defined below the class.
  44. #
  45. cdef tree.xmlDict* _c_dict
  46. cdef _BaseParser _default_parser
  47. cdef list _implied_parser_contexts
  48. def __cinit__(self):
  49. self._implied_parser_contexts = []
  50. def __dealloc__(self):
  51. if self._c_dict is not NULL:
  52. xmlparser.xmlDictFree(self._c_dict)
  53. cdef int initMainParserContext(self) except -1:
  54. """Put the global context into the thread dictionary of the main
  55. thread. To be called once and only in the main thread."""
  56. thread_dict = python.PyThreadState_GetDict()
  57. if thread_dict is not NULL:
  58. (<dict>thread_dict)["_ParserDictionaryContext"] = self
  59. cdef _ParserDictionaryContext _findThreadParserContext(self):
  60. "Find (or create) the _ParserDictionaryContext object for the current thread"
  61. cdef _ParserDictionaryContext context
  62. thread_dict = python.PyThreadState_GetDict()
  63. if thread_dict is NULL:
  64. return self
  65. d = <dict>thread_dict
  66. result = python.PyDict_GetItem(d, "_ParserDictionaryContext")
  67. if result is not NULL:
  68. return <object>result
  69. context = <_ParserDictionaryContext>_ParserDictionaryContext.__new__(_ParserDictionaryContext)
  70. d["_ParserDictionaryContext"] = context
  71. return context
  72. cdef int setDefaultParser(self, _BaseParser parser) except -1:
  73. "Set the default parser for the current thread"
  74. cdef _ParserDictionaryContext context
  75. context = self._findThreadParserContext()
  76. context._default_parser = parser
  77. cdef _BaseParser getDefaultParser(self):
  78. "Return (or create) the default parser of the current thread"
  79. cdef _ParserDictionaryContext context
  80. context = self._findThreadParserContext()
  81. if context._default_parser is None:
  82. if self._default_parser is None:
  83. self._default_parser = __DEFAULT_XML_PARSER._copy()
  84. if context is not self:
  85. context._default_parser = self._default_parser._copy()
  86. return context._default_parser
  87. cdef tree.xmlDict* _getThreadDict(self, tree.xmlDict* default):
  88. "Return the thread-local dict or create a new one if necessary."
  89. cdef _ParserDictionaryContext context
  90. context = self._findThreadParserContext()
  91. if context._c_dict is NULL:
  92. # thread dict not yet set up => use default or create a new one
  93. if default is not NULL:
  94. context._c_dict = default
  95. xmlparser.xmlDictReference(default)
  96. return default
  97. if self._c_dict is NULL:
  98. self._c_dict = xmlparser.xmlDictCreate()
  99. if context is not self:
  100. context._c_dict = xmlparser.xmlDictCreateSub(self._c_dict)
  101. return context._c_dict
  102. cdef int initThreadDictRef(self, tree.xmlDict** c_dict_ref) except -1:
  103. c_dict = c_dict_ref[0]
  104. c_thread_dict = self._getThreadDict(c_dict)
  105. if c_dict is c_thread_dict:
  106. return 0
  107. if c_dict is not NULL:
  108. xmlparser.xmlDictFree(c_dict)
  109. c_dict_ref[0] = c_thread_dict
  110. xmlparser.xmlDictReference(c_thread_dict)
  111. cdef int initParserDict(self, xmlparser.xmlParserCtxt* pctxt) except -1:
  112. "Assure we always use the same string dictionary."
  113. self.initThreadDictRef(&pctxt.dict)
  114. pctxt.dictNames = 1
  115. cdef int initXPathParserDict(self, xpath.xmlXPathContext* pctxt) except -1:
  116. "Assure we always use the same string dictionary."
  117. self.initThreadDictRef(&pctxt.dict)
  118. cdef int initDocDict(self, xmlDoc* result) except -1:
  119. "Store dict of last object parsed if no shared dict yet"
  120. # XXX We also free the result dict here if there already was one.
  121. # This case should only occur for new documents with empty dicts,
  122. # otherwise we'd free data that's in use => segfault
  123. self.initThreadDictRef(&result.dict)
  124. cdef _ParserContext findImpliedContext(self):
  125. """Return any current implied xml parser context for the current
  126. thread. This is used when the resolver functions are called
  127. with an xmlParserCtxt that was generated from within libxml2
  128. (i.e. without a _ParserContext) - which happens when parsing
  129. schema and xinclude external references."""
  130. cdef _ParserDictionaryContext context
  131. cdef _ParserContext implied_context
  132. # see if we have a current implied parser
  133. context = self._findThreadParserContext()
  134. if context._implied_parser_contexts:
  135. implied_context = context._implied_parser_contexts[-1]
  136. return implied_context
  137. return None
  138. cdef int pushImpliedContextFromParser(self, _BaseParser parser) except -1:
  139. "Push a new implied context object taken from the parser."
  140. if parser is not None:
  141. self.pushImpliedContext(parser._getParserContext())
  142. else:
  143. self.pushImpliedContext(None)
  144. cdef int pushImpliedContext(self, _ParserContext parser_context) except -1:
  145. "Push a new implied context object."
  146. cdef _ParserDictionaryContext context
  147. context = self._findThreadParserContext()
  148. context._implied_parser_contexts.append(parser_context)
  149. cdef int popImpliedContext(self) except -1:
  150. "Pop the current implied context object."
  151. cdef _ParserDictionaryContext context
  152. context = self._findThreadParserContext()
  153. context._implied_parser_contexts.pop()
  154. cdef _ParserDictionaryContext __GLOBAL_PARSER_CONTEXT = _ParserDictionaryContext()
  155. __GLOBAL_PARSER_CONTEXT.initMainParserContext()
  156. ############################################################
  157. ## support for Python unicode I/O
  158. ############################################################
  159. # name of Python Py_UNICODE encoding as known to libxml2
  160. cdef const_char* _PY_UNICODE_ENCODING = NULL
  161. cdef int _setupPythonUnicode() except -1:
  162. """Sets _PY_UNICODE_ENCODING to the internal encoding name of Python unicode
  163. strings if libxml2 supports reading native Python unicode. This depends
  164. on iconv and the local Python installation, so we simply check if we find
  165. a matching encoding handler.
  166. """
  167. cdef tree.xmlCharEncodingHandler* enchandler
  168. cdef Py_ssize_t l
  169. cdef const_char* enc
  170. cdef Py_UNICODE *uchars = [c'<', c't', c'e', c's', c't', c'/', c'>']
  171. cdef const_xmlChar* buffer = <const_xmlChar*>uchars
  172. # apparently, libxml2 can't detect UTF-16 on some systems
  173. if (buffer[0] == c'<' and buffer[1] == c'\0' and
  174. buffer[2] == c't' and buffer[3] == c'\0'):
  175. enc = "UTF-16LE"
  176. elif (buffer[0] == c'\0' and buffer[1] == c'<' and
  177. buffer[2] == c'\0' and buffer[3] == c't'):
  178. enc = "UTF-16BE"
  179. else:
  180. # let libxml2 give it a try
  181. enc = _findEncodingName(buffer, sizeof(Py_UNICODE) * 7)
  182. if enc is NULL:
  183. # not my fault, it's YOUR broken system :)
  184. return 0
  185. enchandler = tree.xmlFindCharEncodingHandler(enc)
  186. if enchandler is not NULL:
  187. global _PY_UNICODE_ENCODING
  188. tree.xmlCharEncCloseFunc(enchandler)
  189. _PY_UNICODE_ENCODING = enc
  190. return 0
  191. cdef const_char* _findEncodingName(const_xmlChar* buffer, int size):
  192. "Work around bug in libxml2: find iconv name of encoding on our own."
  193. cdef tree.xmlCharEncoding enc
  194. enc = tree.xmlDetectCharEncoding(buffer, size)
  195. if enc == tree.XML_CHAR_ENCODING_UTF16LE:
  196. if size >= 4 and (buffer[0] == <const_xmlChar> b'\xFF' and
  197. buffer[1] == <const_xmlChar> b'\xFE' and
  198. buffer[2] == 0 and buffer[3] == 0):
  199. return "UTF-32LE" # according to BOM
  200. else:
  201. return "UTF-16LE"
  202. elif enc == tree.XML_CHAR_ENCODING_UTF16BE:
  203. return "UTF-16BE"
  204. elif enc == tree.XML_CHAR_ENCODING_UCS4LE:
  205. return "UCS-4LE"
  206. elif enc == tree.XML_CHAR_ENCODING_UCS4BE:
  207. return "UCS-4BE"
  208. elif enc == tree.XML_CHAR_ENCODING_NONE:
  209. return NULL
  210. else:
  211. # returns a constant char*, no need to free it
  212. return tree.xmlGetCharEncodingName(enc)
  213. # Python 3.12 removed support for "Py_UNICODE".
  214. if python.PY_VERSION_HEX < 0x030C0000:
  215. _setupPythonUnicode()
  216. cdef unicode _find_PyUCS4EncodingName():
  217. """
  218. Find a suitable encoding for Py_UCS4 PyUnicode strings in libxml2.
  219. """
  220. ustring = "<xml>\U0001F92A</xml>"
  221. cdef const xmlChar* buffer = <const xmlChar*> python.PyUnicode_DATA(ustring)
  222. cdef Py_ssize_t py_buffer_len = python.PyUnicode_GET_LENGTH(ustring)
  223. encoding_name = ''
  224. cdef tree.xmlCharEncoding enc = tree.xmlDetectCharEncoding(buffer, py_buffer_len)
  225. enchandler = tree.xmlGetCharEncodingHandler(enc)
  226. if enchandler is not NULL:
  227. try:
  228. if enchandler.name:
  229. encoding_name = enchandler.name.decode('UTF-8')
  230. finally:
  231. tree.xmlCharEncCloseFunc(enchandler)
  232. else:
  233. c_name = tree.xmlGetCharEncodingName(enc)
  234. if c_name:
  235. encoding_name = c_name.decode('UTF-8')
  236. if encoding_name and not encoding_name.endswith('LE') and not encoding_name.endswith('BE'):
  237. encoding_name += 'BE' if python.PY_BIG_ENDIAN else 'LE'
  238. return encoding_name or None
  239. _pyucs4_encoding_name = _find_PyUCS4EncodingName()
  240. ############################################################
  241. ## support for file-like objects
  242. ############################################################
  243. @cython.final
  244. @cython.internal
  245. cdef class _FileReaderContext:
  246. cdef object _filelike
  247. cdef object _encoding
  248. cdef object _url
  249. cdef object _bytes
  250. cdef _ExceptionContext _exc_context
  251. cdef Py_ssize_t _bytes_read
  252. cdef char* _c_url
  253. cdef bint _close_file_after_read
  254. def __cinit__(self, filelike, exc_context not None, url, encoding=None, bint close_file=False):
  255. self._exc_context = exc_context
  256. self._filelike = filelike
  257. self._close_file_after_read = close_file
  258. self._encoding = encoding
  259. if url is not None:
  260. url = _encodeFilename(url)
  261. self._c_url = _cstr(url)
  262. self._url = url
  263. self._bytes = b''
  264. self._bytes_read = 0
  265. cdef _close_file(self):
  266. if self._filelike is None or not self._close_file_after_read:
  267. return
  268. try:
  269. close = self._filelike.close
  270. except AttributeError:
  271. close = None
  272. finally:
  273. self._filelike = None
  274. if close is not None:
  275. close()
  276. cdef xmlparser.xmlParserInputBuffer* _createParserInputBuffer(self) noexcept:
  277. cdef xmlparser.xmlParserInputBuffer* c_buffer = xmlparser.xmlAllocParserInputBuffer(0)
  278. if c_buffer:
  279. c_buffer.readcallback = _readFilelikeParser
  280. c_buffer.context = <python.PyObject*> self
  281. return c_buffer
  282. cdef xmlparser.xmlParserInput* _createParserInput(
  283. self, xmlparser.xmlParserCtxt* ctxt) noexcept:
  284. cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer()
  285. if not c_buffer:
  286. return NULL
  287. return xmlparser.xmlNewIOInputStream(ctxt, c_buffer, 0)
  288. cdef tree.xmlDtd* _readDtd(self) noexcept:
  289. cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer()
  290. if not c_buffer:
  291. return NULL
  292. with nogil:
  293. return xmlparser.xmlIOParseDTD(NULL, c_buffer, 0)
  294. cdef xmlDoc* _readDoc(self, xmlparser.xmlParserCtxt* ctxt, int options) noexcept:
  295. cdef xmlDoc* result
  296. cdef void* c_callback_context = <python.PyObject*> self
  297. cdef char* c_encoding = _cstr(self._encoding) if self._encoding is not None else NULL
  298. orig_options = ctxt.options
  299. with nogil:
  300. if ctxt.html:
  301. result = htmlparser.htmlCtxtReadIO(
  302. ctxt, _readFilelikeParser, NULL, c_callback_context,
  303. self._c_url, c_encoding, options)
  304. if result is not NULL:
  305. if _fixHtmlDictNames(ctxt.dict, result) < 0:
  306. tree.xmlFreeDoc(result)
  307. result = NULL
  308. else:
  309. result = xmlparser.xmlCtxtReadIO(
  310. ctxt, _readFilelikeParser, NULL, c_callback_context,
  311. self._c_url, c_encoding, options)
  312. ctxt.options = orig_options # work around libxml2 problem
  313. try:
  314. self._close_file()
  315. except:
  316. self._exc_context._store_raised()
  317. finally:
  318. return result # swallow any exceptions
  319. cdef int copyToBuffer(self, char* c_buffer, int c_requested) noexcept:
  320. cdef int c_byte_count = 0
  321. cdef char* c_start
  322. cdef Py_ssize_t byte_count, remaining
  323. if self._bytes_read < 0:
  324. return 0
  325. try:
  326. byte_count = python.PyBytes_GET_SIZE(self._bytes)
  327. remaining = byte_count - self._bytes_read
  328. while c_requested > remaining:
  329. c_start = _cstr(self._bytes) + self._bytes_read
  330. cstring_h.memcpy(c_buffer, c_start, remaining)
  331. c_byte_count += remaining
  332. c_buffer += remaining
  333. c_requested -= remaining
  334. self._bytes = self._filelike.read(c_requested)
  335. if not isinstance(self._bytes, bytes):
  336. if isinstance(self._bytes, unicode):
  337. if self._encoding is None:
  338. self._bytes = (<unicode>self._bytes).encode('utf8')
  339. else:
  340. self._bytes = python.PyUnicode_AsEncodedString(
  341. self._bytes, _cstr(self._encoding), NULL)
  342. else:
  343. self._close_file()
  344. raise TypeError, \
  345. "reading from file-like objects must return byte strings or unicode strings"
  346. remaining = python.PyBytes_GET_SIZE(self._bytes)
  347. if remaining == 0:
  348. self._bytes_read = -1
  349. self._close_file()
  350. return c_byte_count
  351. self._bytes_read = 0
  352. if c_requested > 0:
  353. c_start = _cstr(self._bytes) + self._bytes_read
  354. cstring_h.memcpy(c_buffer, c_start, c_requested)
  355. c_byte_count += c_requested
  356. self._bytes_read += c_requested
  357. except:
  358. c_byte_count = -1
  359. self._exc_context._store_raised()
  360. try:
  361. self._close_file()
  362. except:
  363. self._exc_context._store_raised()
  364. finally:
  365. return c_byte_count # swallow any exceptions
  366. cdef int _readFilelikeParser(void* ctxt, char* c_buffer, int c_size) noexcept with gil:
  367. return (<_FileReaderContext>ctxt).copyToBuffer(c_buffer, c_size)
  368. ############################################################
  369. ## support for custom document loaders
  370. ############################################################
  371. cdef xmlparser.xmlParserInput* _local_resolver(const_char* c_url, const_char* c_pubid,
  372. xmlparser.xmlParserCtxt* c_context) noexcept with gil:
  373. cdef _ResolverContext context
  374. cdef xmlparser.xmlParserInput* c_input
  375. cdef _InputDocument doc_ref
  376. cdef _FileReaderContext file_context
  377. # if there is no _ParserContext associated with the xmlParserCtxt
  378. # passed, check to see if the thread state object has an implied
  379. # context.
  380. if c_context._private is not NULL:
  381. context = <_ResolverContext>c_context._private
  382. else:
  383. context = __GLOBAL_PARSER_CONTEXT.findImpliedContext()
  384. if context is None:
  385. if __DEFAULT_ENTITY_LOADER is NULL:
  386. return NULL
  387. with nogil:
  388. # free the GIL as we might do serious I/O here (e.g. HTTP)
  389. c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
  390. return c_input
  391. try:
  392. if c_url is NULL:
  393. url = None
  394. else:
  395. # parsing a related document (DTD etc.) => UTF-8 encoded URL?
  396. url = _decodeFilename(<const_xmlChar*>c_url)
  397. if c_pubid is NULL:
  398. pubid = None
  399. else:
  400. pubid = funicode(<const_xmlChar*>c_pubid) # always UTF-8
  401. doc_ref = context._resolvers.resolve(url, pubid, context)
  402. except:
  403. context._store_raised()
  404. return NULL
  405. if doc_ref is not None:
  406. if doc_ref._type == PARSER_DATA_STRING:
  407. data = doc_ref._data_bytes
  408. filename = doc_ref._filename
  409. if not filename:
  410. filename = None
  411. elif not isinstance(filename, bytes):
  412. # most likely a text URL
  413. filename = filename.encode('utf8')
  414. if not isinstance(filename, bytes):
  415. filename = None
  416. c_input = xmlparser.xmlNewInputStream(c_context)
  417. if c_input is not NULL:
  418. if filename is not None:
  419. c_input.filename = <char *>tree.xmlStrdup(_xcstr(filename))
  420. c_input.base = _xcstr(data)
  421. c_input.length = python.PyBytes_GET_SIZE(data)
  422. c_input.cur = c_input.base
  423. c_input.end = c_input.base + c_input.length
  424. elif doc_ref._type == PARSER_DATA_FILENAME:
  425. data = None
  426. c_filename = _cstr(doc_ref._filename)
  427. with nogil:
  428. # free the GIL as we might do serious I/O here
  429. c_input = xmlparser.xmlNewInputFromFile(
  430. c_context, c_filename)
  431. elif doc_ref._type == PARSER_DATA_FILE:
  432. file_context = _FileReaderContext(doc_ref._file, context, url,
  433. None, doc_ref._close_file)
  434. c_input = file_context._createParserInput(c_context)
  435. data = file_context
  436. else:
  437. data = None
  438. c_input = NULL
  439. if data is not None:
  440. context._storage.add(data)
  441. if c_input is not NULL:
  442. return c_input
  443. if __DEFAULT_ENTITY_LOADER is NULL:
  444. return NULL
  445. with nogil:
  446. # free the GIL as we might do serious I/O here (e.g. HTTP)
  447. c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
  448. return c_input
  449. cdef xmlparser.xmlExternalEntityLoader __DEFAULT_ENTITY_LOADER
  450. __DEFAULT_ENTITY_LOADER = xmlparser.xmlGetExternalEntityLoader()
  451. cdef xmlparser.xmlExternalEntityLoader _register_document_loader() noexcept nogil:
  452. cdef xmlparser.xmlExternalEntityLoader old = xmlparser.xmlGetExternalEntityLoader()
  453. xmlparser.xmlSetExternalEntityLoader(<xmlparser.xmlExternalEntityLoader>_local_resolver)
  454. return old
  455. cdef void _reset_document_loader(xmlparser.xmlExternalEntityLoader old) noexcept nogil:
  456. xmlparser.xmlSetExternalEntityLoader(old)
  457. ############################################################
  458. ## Parsers
  459. ############################################################
  460. @cython.no_gc_clear # May have to call "self._validator.disconnect()" on dealloc.
  461. @cython.internal
  462. cdef class _ParserContext(_ResolverContext):
  463. cdef _ErrorLog _error_log
  464. cdef _ParserSchemaValidationContext _validator
  465. cdef xmlparser.xmlParserCtxt* _c_ctxt
  466. cdef xmlparser.xmlExternalEntityLoader _orig_loader
  467. cdef python.PyThread_type_lock _lock
  468. cdef _Document _doc
  469. cdef bint _collect_ids
  470. def __cinit__(self):
  471. self._collect_ids = True
  472. if config.ENABLE_THREADING:
  473. self._lock = python.PyThread_allocate_lock()
  474. self._error_log = _ErrorLog()
  475. def __dealloc__(self):
  476. if config.ENABLE_THREADING and self._lock is not NULL:
  477. python.PyThread_free_lock(self._lock)
  478. self._lock = NULL
  479. if self._c_ctxt is not NULL:
  480. if <void*>self._validator is not NULL and self._validator is not None:
  481. # If the parser was not closed correctly (e.g. interrupted iterparse()),
  482. # and the schema validator wasn't freed and cleaned up yet, the libxml2 SAX
  483. # validator plug might still be in place, which will make xmlFreeParserCtxt()
  484. # crash when trying to xmlFree() a static SAX handler.
  485. # Thus, make sure we disconnect the handler interceptor here at the latest.
  486. self._validator.disconnect()
  487. xmlparser.xmlFreeParserCtxt(self._c_ctxt)
  488. cdef _ParserContext _copy(self):
  489. cdef _ParserContext context
  490. context = self.__class__()
  491. context._collect_ids = self._collect_ids
  492. context._validator = self._validator.copy()
  493. _initParserContext(context, self._resolvers._copy(), NULL)
  494. return context
  495. cdef void _initParserContext(self, xmlparser.xmlParserCtxt* c_ctxt) noexcept:
  496. """
  497. Connects the libxml2-level context to the lxml-level parser context.
  498. """
  499. self._c_ctxt = c_ctxt
  500. c_ctxt._private = <void*>self
  501. cdef void _resetParserContext(self) noexcept:
  502. if self._c_ctxt is not NULL:
  503. if self._c_ctxt.html:
  504. htmlparser.htmlCtxtReset(self._c_ctxt)
  505. self._c_ctxt.disableSAX = 0 # work around bug in libxml2
  506. else:
  507. xmlparser.xmlClearParserCtxt(self._c_ctxt)
  508. # work around bug in libxml2 [2.9.10 .. 2.9.14]:
  509. # https://gitlab.gnome.org/GNOME/libxml2/-/issues/378
  510. self._c_ctxt.nsNr = 0
  511. cdef int prepare(self, bint set_document_loader=True) except -1:
  512. cdef int result
  513. if config.ENABLE_THREADING and self._lock is not NULL:
  514. with nogil:
  515. result = python.PyThread_acquire_lock(
  516. self._lock, python.WAIT_LOCK)
  517. if result == 0:
  518. raise ParserError, "parser locking failed"
  519. self._error_log.clear()
  520. self._doc = None
  521. # Connect the lxml error log with libxml2's error handling. In the case of parsing
  522. # HTML, ctxt->sax is not set to null, so this always works. The libxml2 function
  523. # that does this is htmlInitParserCtxt in HTMLparser.c. For HTML (and possibly XML
  524. # too), libxml2's SAX's serror is set to be the place where errors are sent when
  525. # schannel is set to ctxt->sax->serror in xmlCtxtErrMemory in libxml2's
  526. # parserInternals.c.
  527. # Need a cast here because older libxml2 releases do not use 'const' in the functype.
  528. self._c_ctxt.sax.serror = <xmlerror.xmlStructuredErrorFunc> _receiveParserError
  529. self._orig_loader = _register_document_loader() if set_document_loader else NULL
  530. if self._validator is not None:
  531. self._validator.connect(self._c_ctxt, self._error_log)
  532. return 0
  533. cdef int cleanup(self) except -1:
  534. if self._orig_loader is not NULL:
  535. _reset_document_loader(self._orig_loader)
  536. try:
  537. if self._validator is not None:
  538. self._validator.disconnect()
  539. self._resetParserContext()
  540. self.clear()
  541. self._doc = None
  542. self._c_ctxt.sax.serror = NULL
  543. finally:
  544. if config.ENABLE_THREADING and self._lock is not NULL:
  545. python.PyThread_release_lock(self._lock)
  546. return 0
  547. cdef object _handleParseResult(self, _BaseParser parser,
  548. xmlDoc* result, filename):
  549. c_doc = self._handleParseResultDoc(parser, result, filename)
  550. if self._doc is not None and self._doc._c_doc is c_doc:
  551. return self._doc
  552. else:
  553. return _documentFactory(c_doc, parser)
  554. cdef xmlDoc* _handleParseResultDoc(self, _BaseParser parser,
  555. xmlDoc* result, filename) except NULL:
  556. recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER
  557. return _handleParseResult(self, self._c_ctxt, result,
  558. filename, recover,
  559. free_doc=self._doc is None)
  560. cdef _initParserContext(_ParserContext context,
  561. _ResolverRegistry resolvers,
  562. xmlparser.xmlParserCtxt* c_ctxt):
  563. _initResolverContext(context, resolvers)
  564. if c_ctxt is not NULL:
  565. context._initParserContext(c_ctxt)
  566. cdef void _forwardParserError(xmlparser.xmlParserCtxt* _parser_context, const xmlerror.xmlError* error) noexcept with gil:
  567. """
  568. Add an error created by libxml2 to the lxml-level error_log.
  569. """
  570. (<_ParserContext>_parser_context._private)._error_log._receive(error)
  571. cdef void _receiveParserError(void* c_context, const xmlerror.xmlError* error) noexcept nogil:
  572. if __DEBUG:
  573. if c_context is NULL or (<xmlparser.xmlParserCtxt*>c_context)._private is NULL:
  574. _forwardError(NULL, error)
  575. else:
  576. _forwardParserError(<xmlparser.xmlParserCtxt*>c_context, error)
  577. cdef int _raiseParseError(xmlparser.xmlParserCtxt* ctxt, filename,
  578. _ErrorLog error_log) except -1:
  579. if filename is not None and \
  580. ctxt.lastError.domain == xmlerror.XML_FROM_IO:
  581. if isinstance(filename, bytes):
  582. filename = _decodeFilenameWithLength(
  583. <bytes>filename, len(<bytes>filename))
  584. if ctxt.lastError.message is not NULL:
  585. try:
  586. message = ctxt.lastError.message.decode('utf-8')
  587. except UnicodeDecodeError:
  588. # the filename may be in there => play it safe
  589. message = ctxt.lastError.message.decode('iso8859-1')
  590. message = f"Error reading file '{filename}': {message.strip()}"
  591. else:
  592. message = f"Error reading '{filename}'"
  593. raise IOError, message
  594. elif error_log:
  595. raise error_log._buildParseException(
  596. XMLSyntaxError, "Document is not well formed")
  597. elif ctxt.lastError.message is not NULL:
  598. message = ctxt.lastError.message.strip()
  599. code = ctxt.lastError.code
  600. line = ctxt.lastError.line
  601. column = ctxt.lastError.int2
  602. if ctxt.lastError.line > 0:
  603. message = f"line {line}: {message}"
  604. raise XMLSyntaxError(message, code, line, column, filename)
  605. else:
  606. raise XMLSyntaxError(None, xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0,
  607. filename)
  608. cdef xmlDoc* _handleParseResult(_ParserContext context,
  609. xmlparser.xmlParserCtxt* c_ctxt,
  610. xmlDoc* result, filename,
  611. bint recover, bint free_doc) except NULL:
  612. # The C-level argument xmlDoc* result is passed in as NULL if the parser was not able
  613. # to parse the document.
  614. cdef bint well_formed
  615. if result is not NULL:
  616. __GLOBAL_PARSER_CONTEXT.initDocDict(result)
  617. if c_ctxt.myDoc is not NULL:
  618. if c_ctxt.myDoc is not result:
  619. __GLOBAL_PARSER_CONTEXT.initDocDict(c_ctxt.myDoc)
  620. tree.xmlFreeDoc(c_ctxt.myDoc)
  621. c_ctxt.myDoc = NULL
  622. if result is not NULL:
  623. # "wellFormed" in libxml2 is 0 if the parser found fatal errors. It still returns a
  624. # parse result document if 'recover=True'. Here, we determine if we can present
  625. # the document to the user or consider it incorrect or broken enough to raise an error.
  626. if (context._validator is not None and
  627. not context._validator.isvalid()):
  628. well_formed = 0 # actually not 'valid', but anyway ...
  629. elif (not c_ctxt.wellFormed and not c_ctxt.html and
  630. c_ctxt.charset == tree.XML_CHAR_ENCODING_8859_1 and
  631. [1 for error in context._error_log
  632. if error.type == ErrorTypes.ERR_INVALID_CHAR]):
  633. # An encoding error occurred and libxml2 switched from UTF-8
  634. # input to (undecoded) Latin-1, at some arbitrary point in the
  635. # document. Better raise an error than allowing for a broken
  636. # tree with mixed encodings. This is fixed in libxml2 2.12.
  637. well_formed = 0
  638. elif recover or (c_ctxt.wellFormed and
  639. c_ctxt.lastError.level < xmlerror.XML_ERR_ERROR):
  640. well_formed = 1
  641. elif not c_ctxt.replaceEntities and not c_ctxt.validate \
  642. and context is not None:
  643. # in this mode, we ignore errors about undefined entities
  644. for error in context._error_log.filter_from_errors():
  645. if error.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \
  646. error.type != ErrorTypes.ERR_UNDECLARED_ENTITY:
  647. well_formed = 0
  648. break
  649. else:
  650. well_formed = 1
  651. else:
  652. well_formed = 0
  653. if not well_formed:
  654. if free_doc:
  655. tree.xmlFreeDoc(result)
  656. result = NULL
  657. if context is not None and context._has_raised():
  658. if result is not NULL:
  659. if free_doc:
  660. tree.xmlFreeDoc(result)
  661. result = NULL
  662. context._raise_if_stored()
  663. if result is NULL:
  664. if context is not None:
  665. _raiseParseError(c_ctxt, filename, context._error_log)
  666. else:
  667. _raiseParseError(c_ctxt, filename, None)
  668. else:
  669. if result.URL is NULL and filename is not None:
  670. result.URL = tree.xmlStrdup(_xcstr(filename))
  671. if result.encoding is NULL:
  672. result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
  673. if context._validator is not None and \
  674. context._validator._add_default_attributes:
  675. # we currently need to do this here as libxml2 does not
  676. # support inserting default attributes during parse-time
  677. # validation
  678. context._validator.inject_default_attributes(result)
  679. return result
  680. cdef int _fixHtmlDictNames(tree.xmlDict* c_dict, xmlDoc* c_doc) noexcept nogil:
  681. cdef xmlNode* c_node
  682. if c_doc is NULL:
  683. return 0
  684. c_node = c_doc.children
  685. tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
  686. if c_node.type == tree.XML_ELEMENT_NODE:
  687. if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
  688. return -1
  689. tree.END_FOR_EACH_ELEMENT_FROM(c_node)
  690. return 0
  691. cdef int _fixHtmlDictSubtreeNames(tree.xmlDict* c_dict, xmlDoc* c_doc,
  692. xmlNode* c_start_node) noexcept nogil:
  693. """
  694. Move names to the dict, iterating in document order, starting at
  695. c_start_node. This is used in incremental parsing after each chunk.
  696. """
  697. cdef xmlNode* c_node
  698. if not c_doc:
  699. return 0
  700. if not c_start_node:
  701. return _fixHtmlDictNames(c_dict, c_doc)
  702. c_node = c_start_node
  703. tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
  704. if c_node.type == tree.XML_ELEMENT_NODE:
  705. if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
  706. return -1
  707. tree.END_FOR_EACH_ELEMENT_FROM(c_node)
  708. return 0
  709. cdef inline int _fixHtmlDictNodeNames(tree.xmlDict* c_dict,
  710. xmlNode* c_node) noexcept nogil:
  711. cdef xmlNode* c_attr
  712. c_name = tree.xmlDictLookup(c_dict, c_node.name, -1)
  713. if c_name is NULL:
  714. return -1
  715. if c_name is not c_node.name:
  716. tree.xmlFree(<char*>c_node.name)
  717. c_node.name = c_name
  718. c_attr = <xmlNode*>c_node.properties
  719. while c_attr is not NULL:
  720. c_name = tree.xmlDictLookup(c_dict, c_attr.name, -1)
  721. if c_name is NULL:
  722. return -1
  723. if c_name is not c_attr.name:
  724. tree.xmlFree(<char*>c_attr.name)
  725. c_attr.name = c_name
  726. c_attr = c_attr.next
  727. return 0
  728. @cython.internal
  729. cdef class _BaseParser:
  730. cdef ElementClassLookup _class_lookup
  731. cdef _ResolverRegistry _resolvers
  732. cdef _ParserContext _parser_context
  733. cdef _ParserContext _push_parser_context
  734. cdef int _parse_options
  735. cdef bint _for_html
  736. cdef bint _remove_comments
  737. cdef bint _remove_pis
  738. cdef bint _strip_cdata
  739. cdef bint _collect_ids
  740. cdef bint _resolve_external_entities
  741. cdef XMLSchema _schema
  742. cdef bytes _filename
  743. cdef readonly object target
  744. cdef object _default_encoding
  745. cdef tuple _events_to_collect # (event_types, tag)
  746. def __init__(self, int parse_options, bint for_html, XMLSchema schema,
  747. remove_comments, remove_pis, strip_cdata, collect_ids,
  748. target, encoding, bint resolve_external_entities=True):
  749. cdef tree.xmlCharEncodingHandler* enchandler
  750. cdef int c_encoding
  751. if not isinstance(self, (XMLParser, HTMLParser)):
  752. raise TypeError, "This class cannot be instantiated"
  753. self._parse_options = parse_options
  754. self.target = target
  755. self._for_html = for_html
  756. self._remove_comments = remove_comments
  757. self._remove_pis = remove_pis
  758. self._strip_cdata = strip_cdata
  759. self._collect_ids = collect_ids
  760. self._resolve_external_entities = resolve_external_entities
  761. self._schema = schema
  762. self._resolvers = _ResolverRegistry()
  763. if encoding is None:
  764. self._default_encoding = None
  765. else:
  766. encoding = _utf8(encoding)
  767. enchandler = tree.xmlFindCharEncodingHandler(_cstr(encoding))
  768. if enchandler is NULL:
  769. raise LookupError, f"unknown encoding: '{encoding}'"
  770. tree.xmlCharEncCloseFunc(enchandler)
  771. self._default_encoding = encoding
  772. cdef _setBaseURL(self, base_url):
  773. self._filename = _encodeFilename(base_url)
  774. cdef _collectEvents(self, event_types, tag):
  775. if event_types is None:
  776. event_types = ()
  777. else:
  778. event_types = tuple(set(event_types))
  779. _buildParseEventFilter(event_types) # purely for validation
  780. self._events_to_collect = (event_types, tag)
  781. cdef _ParserContext _getParserContext(self):
  782. cdef xmlparser.xmlParserCtxt* pctxt
  783. if self._parser_context is None:
  784. self._parser_context = self._createContext(self.target, None)
  785. self._parser_context._collect_ids = self._collect_ids
  786. if self._schema is not None:
  787. self._parser_context._validator = \
  788. self._schema._newSaxValidator(
  789. self._parse_options & xmlparser.XML_PARSE_DTDATTR)
  790. pctxt = self._newParserCtxt()
  791. _initParserContext(self._parser_context, self._resolvers, pctxt)
  792. self._configureSaxContext(pctxt)
  793. return self._parser_context
  794. cdef _ParserContext _getPushParserContext(self):
  795. cdef xmlparser.xmlParserCtxt* pctxt
  796. if self._push_parser_context is None:
  797. self._push_parser_context = self._createContext(
  798. self.target, self._events_to_collect)
  799. self._push_parser_context._collect_ids = self._collect_ids
  800. if self._schema is not None:
  801. self._push_parser_context._validator = \
  802. self._schema._newSaxValidator(
  803. self._parse_options & xmlparser.XML_PARSE_DTDATTR)
  804. pctxt = self._newPushParserCtxt()
  805. _initParserContext(
  806. self._push_parser_context, self._resolvers, pctxt)
  807. self._configureSaxContext(pctxt)
  808. return self._push_parser_context
  809. cdef _ParserContext _createContext(self, target, events_to_collect):
  810. """
  811. This method creates and configures the lxml-level parser.
  812. """
  813. cdef _SaxParserContext sax_context
  814. if target is not None:
  815. sax_context = _TargetParserContext(self)
  816. (<_TargetParserContext>sax_context)._setTarget(target)
  817. elif events_to_collect:
  818. sax_context = _SaxParserContext(self)
  819. else:
  820. # nothing special to configure
  821. return _ParserContext()
  822. if events_to_collect:
  823. events, tag = events_to_collect
  824. sax_context._setEventFilter(events, tag)
  825. return sax_context
  826. @cython.final
  827. cdef int _configureSaxContext(self, xmlparser.xmlParserCtxt* pctxt) except -1:
  828. if self._remove_comments:
  829. pctxt.sax.comment = NULL
  830. if self._remove_pis:
  831. pctxt.sax.processingInstruction = NULL
  832. if self._strip_cdata:
  833. # hard switch-off for CDATA nodes => makes them plain text
  834. pctxt.sax.cdataBlock = NULL
  835. if not self._resolve_external_entities:
  836. pctxt.sax.getEntity = _getInternalEntityOnly
  837. cdef int _registerHtmlErrorHandler(self, xmlparser.xmlParserCtxt* c_ctxt) except -1:
  838. cdef xmlparser.xmlSAXHandler* sax = c_ctxt.sax
  839. if sax is not NULL and sax.initialized and sax.initialized != xmlparser.XML_SAX2_MAGIC:
  840. # need to extend SAX1 context to SAX2 to get proper error reports
  841. if <xmlparser.xmlSAXHandlerV1*>sax is &htmlparser.htmlDefaultSAXHandler:
  842. sax = <xmlparser.xmlSAXHandler*> tree.xmlMalloc(sizeof(xmlparser.xmlSAXHandler))
  843. if sax is NULL:
  844. raise MemoryError()
  845. cstring_h.memcpy(sax, &htmlparser.htmlDefaultSAXHandler,
  846. sizeof(htmlparser.htmlDefaultSAXHandler))
  847. c_ctxt.sax = sax
  848. sax.initialized = xmlparser.XML_SAX2_MAGIC
  849. # Need a cast here because older libxml2 releases do not use 'const' in the functype.
  850. sax.serror = <xmlerror.xmlStructuredErrorFunc> _receiveParserError
  851. sax.startElementNs = NULL
  852. sax.endElementNs = NULL
  853. sax._private = NULL
  854. return 0
  855. cdef xmlparser.xmlParserCtxt* _newParserCtxt(self) except NULL:
  856. """
  857. Create and initialise a libxml2-level parser context.
  858. """
  859. cdef xmlparser.xmlParserCtxt* c_ctxt
  860. if self._for_html:
  861. c_ctxt = htmlparser.htmlCreateMemoryParserCtxt('dummy', 5)
  862. if c_ctxt is not NULL:
  863. self._registerHtmlErrorHandler(c_ctxt)
  864. else:
  865. c_ctxt = xmlparser.xmlNewParserCtxt()
  866. if c_ctxt is NULL:
  867. raise MemoryError
  868. c_ctxt.sax.startDocument = _initSaxDocument
  869. return c_ctxt
  870. cdef xmlparser.xmlParserCtxt* _newPushParserCtxt(self) except NULL:
  871. cdef xmlparser.xmlParserCtxt* c_ctxt
  872. cdef char* c_filename = _cstr(self._filename) if self._filename is not None else NULL
  873. if self._for_html:
  874. c_ctxt = htmlparser.htmlCreatePushParserCtxt(
  875. NULL, NULL, NULL, 0, c_filename, tree.XML_CHAR_ENCODING_NONE)
  876. if c_ctxt is not NULL:
  877. self._registerHtmlErrorHandler(c_ctxt)
  878. htmlparser.htmlCtxtUseOptions(c_ctxt, self._parse_options)
  879. else:
  880. c_ctxt = xmlparser.xmlCreatePushParserCtxt(
  881. NULL, NULL, NULL, 0, c_filename)
  882. if c_ctxt is not NULL:
  883. xmlparser.xmlCtxtUseOptions(c_ctxt, self._parse_options)
  884. if c_ctxt is NULL:
  885. raise MemoryError()
  886. c_ctxt.sax.startDocument = _initSaxDocument
  887. return c_ctxt
  888. @property
  889. def error_log(self):
  890. """The error log of the last parser run.
  891. """
  892. cdef _ParserContext context
  893. context = self._getParserContext()
  894. return context._error_log.copy()
  895. @property
  896. def resolvers(self):
  897. """The custom resolver registry of this parser."""
  898. return self._resolvers
  899. @property
  900. def version(self):
  901. """The version of the underlying XML parser."""
  902. return "libxml2 %d.%d.%d" % LIBXML_VERSION
  903. def set_element_class_lookup(self, ElementClassLookup lookup = None):
  904. """set_element_class_lookup(self, lookup = None)
  905. Set a lookup scheme for element classes generated from this parser.
  906. Reset it by passing None or nothing.
  907. """
  908. self._class_lookup = lookup
  909. cdef _BaseParser _copy(self):
  910. "Create a new parser with the same configuration."
  911. cdef _BaseParser parser
  912. parser = self.__class__()
  913. parser._parse_options = self._parse_options
  914. parser._for_html = self._for_html
  915. parser._remove_comments = self._remove_comments
  916. parser._remove_pis = self._remove_pis
  917. parser._strip_cdata = self._strip_cdata
  918. parser._filename = self._filename
  919. parser._resolvers = self._resolvers
  920. parser.target = self.target
  921. parser._class_lookup = self._class_lookup
  922. parser._default_encoding = self._default_encoding
  923. parser._schema = self._schema
  924. parser._events_to_collect = self._events_to_collect
  925. return parser
  926. def copy(self):
  927. """copy(self)
  928. Create a new parser with the same configuration.
  929. """
  930. return self._copy()
  931. def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
  932. """makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
  933. Creates a new element associated with this parser.
  934. """
  935. return _makeElement(_tag, NULL, None, self, None, None,
  936. attrib, nsmap, _extra)
  937. # internal parser methods
  938. cdef xmlDoc* _parseUnicodeDoc(self, utext, char* c_filename) except NULL:
  939. """Parse unicode document, share dictionary if possible.
  940. """
  941. cdef _ParserContext context
  942. cdef xmlDoc* result
  943. cdef xmlparser.xmlParserCtxt* pctxt
  944. cdef Py_ssize_t py_buffer_len
  945. cdef int buffer_len, c_kind
  946. cdef const_char* c_text
  947. cdef const_char* c_encoding = _PY_UNICODE_ENCODING
  948. if python.PyUnicode_IS_READY(utext):
  949. # PEP-393 string
  950. c_text = <const_char*>python.PyUnicode_DATA(utext)
  951. py_buffer_len = python.PyUnicode_GET_LENGTH(utext)
  952. c_kind = python.PyUnicode_KIND(utext)
  953. if c_kind == 1:
  954. if python.PyUnicode_MAX_CHAR_VALUE(utext) <= 127:
  955. c_encoding = 'UTF-8'
  956. else:
  957. c_encoding = 'ISO-8859-1'
  958. elif c_kind == 2:
  959. py_buffer_len *= 2
  960. if python.PY_BIG_ENDIAN:
  961. c_encoding = 'UTF-16BE' # actually UCS-2
  962. else:
  963. c_encoding = 'UTF-16LE' # actually UCS-2
  964. elif c_kind == 4:
  965. py_buffer_len *= 4
  966. if python.PY_BIG_ENDIAN:
  967. c_encoding = 'UTF-32BE' # actually UCS-4
  968. else:
  969. c_encoding = 'UTF-32LE' # actually UCS-4
  970. else:
  971. assert False, f"Illegal Unicode kind {c_kind}"
  972. else:
  973. # old Py_UNICODE string
  974. py_buffer_len = python.PyUnicode_GET_DATA_SIZE(utext)
  975. c_text = python.PyUnicode_AS_DATA(utext)
  976. assert 0 <= py_buffer_len <= limits.INT_MAX
  977. buffer_len = py_buffer_len
  978. context = self._getParserContext()
  979. context.prepare()
  980. try:
  981. pctxt = context._c_ctxt
  982. __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
  983. orig_options = pctxt.options
  984. with nogil:
  985. if self._for_html:
  986. result = htmlparser.htmlCtxtReadMemory(
  987. pctxt, c_text, buffer_len, c_filename, c_encoding,
  988. self._parse_options)
  989. if result is not NULL:
  990. if _fixHtmlDictNames(pctxt.dict, result) < 0:
  991. tree.xmlFreeDoc(result)
  992. result = NULL
  993. else:
  994. result = xmlparser.xmlCtxtReadMemory(
  995. pctxt, c_text, buffer_len, c_filename, c_encoding,
  996. self._parse_options)
  997. pctxt.options = orig_options # work around libxml2 problem
  998. return context._handleParseResultDoc(self, result, None)
  999. finally:
  1000. context.cleanup()
  1001. cdef xmlDoc* _parseDoc(self, const char* c_text, int c_len, char* c_filename) except NULL:
  1002. """Parse document, share dictionary if possible.
  1003. """
  1004. cdef _ParserContext context
  1005. cdef xmlDoc* result
  1006. cdef xmlparser.xmlParserCtxt* pctxt
  1007. cdef char* c_encoding
  1008. cdef tree.xmlCharEncoding enc
  1009. context = self._getParserContext()
  1010. context.prepare()
  1011. try:
  1012. pctxt = context._c_ctxt
  1013. __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
  1014. if self._default_encoding is None:
  1015. c_encoding = NULL
  1016. # libxml2 (at least 2.9.3) does not recognise UTF-32 BOMs
  1017. # NOTE: limit to problematic cases because it changes character offsets
  1018. if c_len >= 4 and (c_text[0] == b'\xFF' and c_text[1] == b'\xFE' and
  1019. c_text[2] == 0 and c_text[3] == 0):
  1020. c_encoding = "UTF-32LE"
  1021. c_text += 4
  1022. c_len -= 4
  1023. elif c_len >= 4 and (c_text[0] == 0 and c_text[1] == 0 and
  1024. c_text[2] == b'\xFE' and c_text[3] == b'\xFF'):
  1025. c_encoding = "UTF-32BE"
  1026. c_text += 4
  1027. c_len -= 4
  1028. else:
  1029. # no BOM => try to determine encoding
  1030. enc = tree.xmlDetectCharEncoding(<const_xmlChar*>c_text, c_len)
  1031. if enc == tree.XML_CHAR_ENCODING_UCS4LE:
  1032. c_encoding = 'UTF-32LE'
  1033. elif enc == tree.XML_CHAR_ENCODING_UCS4BE:
  1034. c_encoding = 'UTF-32BE'
  1035. else:
  1036. c_encoding = _cstr(self._default_encoding)
  1037. orig_options = pctxt.options
  1038. with nogil:
  1039. if self._for_html:
  1040. result = htmlparser.htmlCtxtReadMemory(
  1041. pctxt, c_text, c_len, c_filename,
  1042. c_encoding, self._parse_options)
  1043. if result is not NULL:
  1044. if _fixHtmlDictNames(pctxt.dict, result) < 0:
  1045. tree.xmlFreeDoc(result)
  1046. result = NULL
  1047. else:
  1048. result = xmlparser.xmlCtxtReadMemory(
  1049. pctxt, c_text, c_len, c_filename,
  1050. c_encoding, self._parse_options)
  1051. pctxt.options = orig_options # work around libxml2 problem
  1052. return context._handleParseResultDoc(self, result, None)
  1053. finally:
  1054. context.cleanup()
  1055. cdef xmlDoc* _parseDocFromFile(self, char* c_filename) except NULL:
  1056. cdef _ParserContext context
  1057. cdef xmlDoc* result
  1058. cdef xmlparser.xmlParserCtxt* pctxt
  1059. cdef char* c_encoding
  1060. result = NULL
  1061. context = self._getParserContext()
  1062. context.prepare()
  1063. try:
  1064. pctxt = context._c_ctxt
  1065. __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
  1066. if self._default_encoding is None:
  1067. c_encoding = NULL
  1068. else:
  1069. c_encoding = _cstr(self._default_encoding)
  1070. orig_options = pctxt.options
  1071. with nogil:
  1072. if self._for_html:
  1073. result = htmlparser.htmlCtxtReadFile(
  1074. pctxt, c_filename, c_encoding, self._parse_options)
  1075. if result is not NULL:
  1076. if _fixHtmlDictNames(pctxt.dict, result) < 0:
  1077. tree.xmlFreeDoc(result)
  1078. result = NULL
  1079. else:
  1080. result = xmlparser.xmlCtxtReadFile(
  1081. pctxt, c_filename, c_encoding, self._parse_options)
  1082. pctxt.options = orig_options # work around libxml2 problem
  1083. return context._handleParseResultDoc(self, result, c_filename)
  1084. finally:
  1085. context.cleanup()
  1086. cdef xmlDoc* _parseDocFromFilelike(self, filelike, filename,
  1087. encoding) except NULL:
  1088. cdef _ParserContext context
  1089. cdef _FileReaderContext file_context
  1090. cdef xmlDoc* result
  1091. cdef xmlparser.xmlParserCtxt* pctxt
  1092. cdef char* c_filename
  1093. if not filename:
  1094. filename = None
  1095. context = self._getParserContext()
  1096. context.prepare()
  1097. try:
  1098. pctxt = context._c_ctxt
  1099. __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
  1100. file_context = _FileReaderContext(
  1101. filelike, context, filename,
  1102. encoding or self._default_encoding)
  1103. result = file_context._readDoc(pctxt, self._parse_options)
  1104. return context._handleParseResultDoc(
  1105. self, result, filename)
  1106. finally:
  1107. context.cleanup()
  1108. cdef tree.xmlEntity* _getInternalEntityOnly(void* ctxt, const_xmlChar* name) noexcept nogil:
  1109. """
  1110. Callback function to intercept the entity resolution when external entity loading is disabled.
  1111. """
  1112. cdef tree.xmlEntity* entity = xmlparser.xmlSAX2GetEntity(ctxt, name)
  1113. if not entity:
  1114. return NULL
  1115. if entity.etype not in (
  1116. tree.xmlEntityType.XML_EXTERNAL_GENERAL_PARSED_ENTITY,
  1117. tree.xmlEntityType.XML_EXTERNAL_GENERAL_UNPARSED_ENTITY,
  1118. tree.xmlEntityType.XML_EXTERNAL_PARAMETER_ENTITY):
  1119. return entity
  1120. # Reject all external entities and fail the parsing instead. There is currently
  1121. # no way in libxml2 to just prevent the entity resolution in this case.
  1122. cdef xmlerror.xmlError c_error
  1123. cdef xmlerror.xmlStructuredErrorFunc err_func
  1124. cdef xmlparser.xmlParserInput* parser_input
  1125. cdef void* err_context
  1126. c_ctxt = <xmlparser.xmlParserCtxt *> ctxt
  1127. err_func = xmlerror.xmlStructuredError
  1128. if err_func:
  1129. parser_input = c_ctxt.input
  1130. # Copied from xmlVErrParser() in libxml2: get current input from stack.
  1131. if parser_input and parser_input.filename is NULL and c_ctxt.inputNr > 1:
  1132. parser_input = c_ctxt.inputTab[c_ctxt.inputNr - 2]
  1133. c_error = xmlerror.xmlError(
  1134. domain=xmlerror.xmlErrorDomain.XML_FROM_PARSER,
  1135. code=xmlerror.xmlParserErrors.XML_ERR_EXT_ENTITY_STANDALONE,
  1136. level=xmlerror.xmlErrorLevel.XML_ERR_FATAL,
  1137. message=b"External entity resolution is disabled for security reasons "
  1138. b"when resolving '&%s;'. Use 'XMLParser(resolve_entities=True)' "
  1139. b"if you consider it safe to enable it.",
  1140. file=parser_input.filename,
  1141. node=entity,
  1142. str1=<char*> name,
  1143. str2=NULL,
  1144. str3=NULL,
  1145. line=parser_input.line if parser_input else 0,
  1146. int1=0,
  1147. int2=parser_input.col if parser_input else 0,
  1148. )
  1149. err_context = xmlerror.xmlStructuredErrorContext
  1150. err_func(err_context, &c_error)
  1151. c_ctxt.wellFormed = 0
  1152. # The entity was looked up and does not need to be freed.
  1153. return NULL
  1154. cdef void _initSaxDocument(void* ctxt) noexcept with gil:
  1155. xmlparser.xmlSAX2StartDocument(ctxt)
  1156. c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
  1157. c_doc = c_ctxt.myDoc
  1158. # set up document dict
  1159. if c_doc and c_ctxt.dict and not c_doc.dict:
  1160. # I have no idea why libxml2 disables this - we need it
  1161. c_ctxt.dictNames = 1
  1162. c_doc.dict = c_ctxt.dict
  1163. xmlparser.xmlDictReference(c_ctxt.dict)
  1164. # set up XML ID hash table
  1165. if c_ctxt._private:
  1166. context = <_ParserContext>c_ctxt._private
  1167. if context._collect_ids:
  1168. # keep the global parser dict from filling up with XML IDs
  1169. if c_doc and not c_doc.ids:
  1170. # memory errors are not fatal here
  1171. c_dict = xmlparser.xmlDictCreate()
  1172. if c_dict:
  1173. c_doc.ids = tree.xmlHashCreateDict(0, c_dict)
  1174. xmlparser.xmlDictFree(c_dict)
  1175. else:
  1176. c_doc.ids = tree.xmlHashCreate(0)
  1177. else:
  1178. c_ctxt.loadsubset |= xmlparser.XML_SKIP_IDS
  1179. if c_doc and c_doc.ids and not tree.xmlHashSize(c_doc.ids):
  1180. # already initialised but empty => clear
  1181. tree.xmlHashFree(c_doc.ids, NULL)
  1182. c_doc.ids = NULL
  1183. ############################################################
  1184. ## ET feed parser
  1185. ############################################################
  1186. cdef class _FeedParser(_BaseParser):
  1187. cdef bint _feed_parser_running
  1188. @property
  1189. def feed_error_log(self):
  1190. """The error log of the last (or current) run of the feed parser.
  1191. Note that this is local to the feed parser and thus is
  1192. different from what the ``error_log`` property returns.
  1193. """
  1194. return self._getPushParserContext()._error_log.copy()
  1195. cpdef feed(self, data):
  1196. """feed(self, data)
  1197. Feeds data to the parser. The argument should be an 8-bit string
  1198. buffer containing encoded data, although Unicode is supported as long
  1199. as both string types are not mixed.
  1200. This is the main entry point to the consumer interface of a
  1201. parser. The parser will parse as much of the XML stream as it
  1202. can on each call. To finish parsing or to reset the parser,
  1203. call the ``close()`` method. Both methods may raise
  1204. ParseError if errors occur in the input data. If an error is
  1205. raised, there is no longer a need to call ``close()``.
  1206. The feed parser interface is independent of the normal parser
  1207. usage. You can use the same parser as a feed parser and in
  1208. the ``parse()`` function concurrently.
  1209. """
  1210. cdef _ParserContext context
  1211. cdef bytes bstring
  1212. cdef xmlparser.xmlParserCtxt* pctxt
  1213. cdef Py_ssize_t py_buffer_len, ustart
  1214. cdef const_char* char_data
  1215. cdef const_char* c_encoding
  1216. cdef int buffer_len
  1217. cdef int error
  1218. cdef bint recover = self._parse_options & xmlparser.XML_PARSE_RECOVER
  1219. if isinstance(data, bytes):
  1220. if self._default_encoding is None:
  1221. c_encoding = NULL
  1222. else:
  1223. c_encoding = self._default_encoding
  1224. char_data = _cstr(data)
  1225. py_buffer_len = python.PyBytes_GET_SIZE(data)
  1226. ustart = 0
  1227. elif isinstance(data, unicode):
  1228. c_encoding = b"UTF-8"
  1229. char_data = NULL
  1230. py_buffer_len = len(<unicode> data)
  1231. ustart = 0
  1232. else:
  1233. raise TypeError, "Parsing requires string data"
  1234. context = self._getPushParserContext()
  1235. pctxt = context._c_ctxt
  1236. error = 0
  1237. if not self._feed_parser_running:
  1238. context.prepare(set_document_loader=False)
  1239. self._feed_parser_running = 1
  1240. c_filename = (_cstr(self._filename)
  1241. if self._filename is not None else NULL)
  1242. # We have to give *mlCtxtResetPush() enough input to figure
  1243. # out the character encoding (at least four bytes),
  1244. # however if we give it all we got, we'll have nothing for
  1245. # *mlParseChunk() and things go wrong.
  1246. buffer_len = 0
  1247. if char_data is not NULL:
  1248. buffer_len = 4 if py_buffer_len > 4 else <int>py_buffer_len
  1249. orig_loader = _register_document_loader()
  1250. if self._for_html:
  1251. error = _htmlCtxtResetPush(
  1252. pctxt, char_data, buffer_len, c_filename, c_encoding,
  1253. self._parse_options)
  1254. else:
  1255. xmlparser.xmlCtxtUseOptions(pctxt, self._parse_options)
  1256. error = xmlparser.xmlCtxtResetPush(
  1257. pctxt, char_data, buffer_len, c_filename, c_encoding)
  1258. _reset_document_loader(orig_loader)
  1259. py_buffer_len -= buffer_len
  1260. char_data += buffer_len
  1261. if error:
  1262. raise MemoryError()
  1263. __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
  1264. #print pctxt.charset, 'NONE' if c_encoding is NULL else c_encoding
  1265. fixup_error = 0
  1266. while py_buffer_len > 0 and (error == 0 or recover):
  1267. if char_data is NULL:
  1268. # Unicode parsing by converting chunks to UTF-8
  1269. buffer_len = 2**19 # len(bytes) <= 4 * (2**19) == 2 MiB
  1270. bstring = (<unicode> data)[ustart : ustart+buffer_len].encode('UTF-8')
  1271. ustart += buffer_len
  1272. py_buffer_len -= buffer_len # may end up < 0
  1273. error, fixup_error = _parse_data_chunk(pctxt, <const char*> bstring, <int> len(bstring))
  1274. else:
  1275. # Direct byte string parsing.
  1276. buffer_len = <int>py_buffer_len if py_buffer_len <= limits.INT_MAX else limits.INT_MAX
  1277. error, fixup_error = _parse_data_chunk(pctxt, char_data, buffer_len)
  1278. py_buffer_len -= buffer_len
  1279. char_data += buffer_len
  1280. if fixup_error:
  1281. context.store_exception(MemoryError())
  1282. if context._has_raised():
  1283. # propagate Python exceptions immediately
  1284. recover = 0
  1285. error = 1
  1286. break
  1287. if error and not pctxt.replaceEntities and not pctxt.validate:
  1288. # in this mode, we ignore errors about undefined entities
  1289. for entry in context._error_log.filter_from_errors():
  1290. if entry.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \
  1291. entry.type != ErrorTypes.ERR_UNDECLARED_ENTITY:
  1292. break
  1293. else:
  1294. error = 0
  1295. if not pctxt.wellFormed and xmlparser.xmlCtxtIsStopped(pctxt) and context._has_raised():
  1296. # propagate Python exceptions immediately
  1297. recover = 0
  1298. error = 1
  1299. if fixup_error or not recover and (error or not pctxt.wellFormed):
  1300. self._feed_parser_running = 0
  1301. try:
  1302. context._handleParseResult(self, pctxt.myDoc, None)
  1303. finally:
  1304. context.cleanup()
  1305. cpdef close(self):
  1306. """close(self)
  1307. Terminates feeding data to this parser. This tells the parser to
  1308. process any remaining data in the feed buffer, and then returns the
  1309. root Element of the tree that was parsed.
  1310. This method must be called after passing the last chunk of data into
  1311. the ``feed()`` method. It should only be called when using the feed
  1312. parser interface, all other usage is undefined.
  1313. """
  1314. if not self._feed_parser_running:
  1315. raise XMLSyntaxError("no element found",
  1316. xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0,
  1317. self._filename)
  1318. context = self._getPushParserContext()
  1319. pctxt = context._c_ctxt
  1320. self._feed_parser_running = 0
  1321. if self._for_html:
  1322. htmlparser.htmlParseChunk(pctxt, NULL, 0, 1)
  1323. else:
  1324. xmlparser.xmlParseChunk(pctxt, NULL, 0, 1)
  1325. if (pctxt.recovery and not xmlparser.xmlCtxtIsStopped(pctxt) and
  1326. isinstance(context, _SaxParserContext)):
  1327. # apply any left-over 'end' events
  1328. (<_SaxParserContext>context).flushEvents()
  1329. try:
  1330. result = context._handleParseResult(self, pctxt.myDoc, None)
  1331. finally:
  1332. context.cleanup()
  1333. if isinstance(result, _Document):
  1334. return (<_Document>result).getroot()
  1335. else:
  1336. return result
  1337. cdef (int, int) _parse_data_chunk(xmlparser.xmlParserCtxt* c_ctxt,
  1338. const char* char_data, int buffer_len):
  1339. fixup_error = 0
  1340. with nogil:
  1341. if c_ctxt.html:
  1342. c_node = c_ctxt.node # last node where the parser stopped
  1343. orig_loader = _register_document_loader()
  1344. error = htmlparser.htmlParseChunk(c_ctxt, char_data, buffer_len, 0)
  1345. _reset_document_loader(orig_loader)
  1346. # and now for the fun part: move node names to the dict
  1347. if c_ctxt.myDoc:
  1348. fixup_error = _fixHtmlDictSubtreeNames(
  1349. c_ctxt.dict, c_ctxt.myDoc, c_node)
  1350. if c_ctxt.myDoc.dict and c_ctxt.myDoc.dict is not c_ctxt.dict:
  1351. xmlparser.xmlDictFree(c_ctxt.myDoc.dict)
  1352. c_ctxt.myDoc.dict = c_ctxt.dict
  1353. xmlparser.xmlDictReference(c_ctxt.dict)
  1354. else:
  1355. orig_loader = _register_document_loader()
  1356. error = xmlparser.xmlParseChunk(c_ctxt, char_data, buffer_len, 0)
  1357. _reset_document_loader(orig_loader)
  1358. return (error, fixup_error)
  1359. cdef int _htmlCtxtResetPush(xmlparser.xmlParserCtxt* c_ctxt,
  1360. const_char* c_data, int buffer_len,
  1361. const_char* c_filename, const_char* c_encoding,
  1362. int parse_options) except -1:
  1363. cdef xmlparser.xmlParserInput* c_input_stream
  1364. # libxml2 lacks an HTML push parser setup function
  1365. error = xmlparser.xmlCtxtResetPush(
  1366. c_ctxt, c_data, buffer_len, c_filename, c_encoding)
  1367. if error:
  1368. return error
  1369. # fix libxml2 setup for HTML
  1370. if tree.LIBXML_VERSION < 21400:
  1371. c_ctxt.progressive = 1 # TODO: remove
  1372. c_ctxt.html = 1
  1373. htmlparser.htmlCtxtUseOptions(c_ctxt, parse_options)
  1374. return 0
  1375. ############################################################
  1376. ## XML parser
  1377. ############################################################
  1378. cdef int _XML_DEFAULT_PARSE_OPTIONS
  1379. _XML_DEFAULT_PARSE_OPTIONS = (
  1380. xmlparser.XML_PARSE_NOENT |
  1381. xmlparser.XML_PARSE_NOCDATA |
  1382. xmlparser.XML_PARSE_NONET |
  1383. xmlparser.XML_PARSE_COMPACT |
  1384. xmlparser.XML_PARSE_BIG_LINES
  1385. )
  1386. cdef class XMLParser(_FeedParser):
  1387. """XMLParser(self, encoding=None, attribute_defaults=False, dtd_validation=False, \
  1388. load_dtd=False, no_network=True, decompress=False, ns_clean=False, \
  1389. recover=False, schema: XMLSchema =None, huge_tree=False, \
  1390. remove_blank_text=False, resolve_entities=True, \
  1391. remove_comments=False, remove_pis=False, strip_cdata=True, \
  1392. collect_ids=True, target=None, compact=True)
  1393. The XML parser.
  1394. Parsers can be supplied as additional argument to various parse
  1395. functions of the lxml API. A default parser is always available
  1396. and can be replaced by a call to the global function
  1397. 'set_default_parser'. New parsers can be created at any time
  1398. without a major run-time overhead.
  1399. The keyword arguments in the constructor are mainly based on the
  1400. libxml2 parser configuration. A DTD will also be loaded if DTD
  1401. validation or attribute default values are requested (unless you
  1402. additionally provide an XMLSchema from which the default
  1403. attributes can be read).
  1404. Available boolean keyword arguments:
  1405. - attribute_defaults - inject default attributes from DTD or XMLSchema
  1406. - dtd_validation - validate against a DTD referenced by the document
  1407. - load_dtd - use DTD for parsing
  1408. - no_network - prevent network access for related files (default: True)
  1409. - decompress - automatically decompress gzip input
  1410. (default: False, changed in lxml 6.0, disabling only affects libxml2 2.15+)
  1411. - ns_clean - clean up redundant namespace declarations
  1412. - recover - try hard to parse through broken XML
  1413. - remove_blank_text - discard blank text nodes that appear ignorable
  1414. - remove_comments - discard comments
  1415. - remove_pis - discard processing instructions
  1416. - strip_cdata - replace CDATA sections by normal text content (default: True)
  1417. - compact - save memory for short text content (default: True)
  1418. - collect_ids - use a hash table of XML IDs for fast access
  1419. (default: True, always True with DTD validation)
  1420. - huge_tree - disable security restrictions and support very deep trees
  1421. and very long text content
  1422. Other keyword arguments:
  1423. - resolve_entities - replace entities by their text value: False for keeping the
  1424. entity references, True for resolving them, and 'internal' for resolving
  1425. internal definitions only (no external file/URL access).
  1426. The default used to be True and was changed to 'internal' in lxml 5.0.
  1427. - encoding - override the document encoding (note: libiconv encoding name)
  1428. - target - a parser target object that will receive the parse events
  1429. - schema - an XMLSchema to validate against
  1430. Note that you should avoid sharing parsers between threads. While this is
  1431. not harmful, it is more efficient to use separate parsers. This does not
  1432. apply to the default parser.
  1433. """
  1434. def __init__(self, *, encoding=None, attribute_defaults=False,
  1435. dtd_validation=False, load_dtd=False, no_network=True, decompress=False,
  1436. ns_clean=False, recover=False, XMLSchema schema=None,
  1437. huge_tree=False, remove_blank_text=False, resolve_entities='internal',
  1438. remove_comments=False, remove_pis=False, strip_cdata=True,
  1439. collect_ids=True, target=None, compact=True):
  1440. cdef int parse_options
  1441. cdef bint resolve_external = True
  1442. parse_options = _XML_DEFAULT_PARSE_OPTIONS
  1443. if load_dtd:
  1444. parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD
  1445. if dtd_validation:
  1446. parse_options = parse_options | xmlparser.XML_PARSE_DTDVALID | \
  1447. xmlparser.XML_PARSE_DTDLOAD
  1448. if attribute_defaults:
  1449. parse_options = parse_options | xmlparser.XML_PARSE_DTDATTR
  1450. if schema is None:
  1451. parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD
  1452. if ns_clean:
  1453. parse_options = parse_options | xmlparser.XML_PARSE_NSCLEAN
  1454. if recover:
  1455. parse_options = parse_options | xmlparser.XML_PARSE_RECOVER
  1456. if remove_blank_text:
  1457. parse_options = parse_options | xmlparser.XML_PARSE_NOBLANKS
  1458. if huge_tree:
  1459. parse_options = parse_options | xmlparser.XML_PARSE_HUGE
  1460. if not no_network:
  1461. parse_options = parse_options ^ xmlparser.XML_PARSE_NONET
  1462. if not compact:
  1463. parse_options = parse_options ^ xmlparser.XML_PARSE_COMPACT
  1464. if not resolve_entities:
  1465. parse_options = parse_options ^ xmlparser.XML_PARSE_NOENT
  1466. elif resolve_entities == 'internal':
  1467. resolve_external = False
  1468. if not strip_cdata:
  1469. parse_options = parse_options ^ xmlparser.XML_PARSE_NOCDATA
  1470. _BaseParser.__init__(self, parse_options, False, schema,
  1471. remove_comments, remove_pis, strip_cdata,
  1472. collect_ids, target, encoding, resolve_external)
  1473. # Allow subscripting XMLParser in type annotions (PEP 560)
  1474. def __class_getitem__(cls, item):
  1475. return _GenericAlias(cls, item)
  1476. cdef class XMLPullParser(XMLParser):
  1477. """XMLPullParser(self, events=None, *, tag=None, **kwargs)
  1478. XML parser that collects parse events in an iterator.
  1479. The collected events are the same as for iterparse(), but the
  1480. parser itself is non-blocking in the sense that it receives
  1481. data chunks incrementally through its .feed() method, instead
  1482. of reading them directly from a file(-like) object all by itself.
  1483. By default, it collects Element end events. To change that,
  1484. pass any subset of the available events into the ``events``
  1485. argument: ``'start'``, ``'end'``, ``'start-ns'``,
  1486. ``'end-ns'``, ``'comment'``, ``'pi'``.
  1487. To support loading external dependencies relative to the input
  1488. source, you can pass the ``base_url``.
  1489. """
  1490. def __init__(self, events=None, *, tag=None, base_url=None, **kwargs):
  1491. XMLParser.__init__(self, **kwargs)
  1492. if events is None:
  1493. events = ('end',)
  1494. self._setBaseURL(base_url)
  1495. self._collectEvents(events, tag)
  1496. def read_events(self):
  1497. return (<_SaxParserContext?>self._getPushParserContext()).events_iterator
  1498. cdef class ETCompatXMLParser(XMLParser):
  1499. """ETCompatXMLParser(self, encoding=None, attribute_defaults=False, \
  1500. dtd_validation=False, load_dtd=False, no_network=True, decompress=False, \
  1501. ns_clean=False, recover=False, schema=None, \
  1502. huge_tree=False, remove_blank_text=False, resolve_entities=True, \
  1503. remove_comments=True, remove_pis=True, strip_cdata=True, \
  1504. target=None, compact=True)
  1505. An XML parser with an ElementTree compatible default setup.
  1506. See the XMLParser class for details.
  1507. This parser has ``remove_comments`` and ``remove_pis`` enabled by default
  1508. and thus ignores comments and processing instructions.
  1509. """
  1510. def __init__(self, *, encoding=None, attribute_defaults=False,
  1511. dtd_validation=False, load_dtd=False, no_network=True, decompress=False,
  1512. ns_clean=False, recover=False, schema=None,
  1513. huge_tree=False, remove_blank_text=False, resolve_entities=True,
  1514. remove_comments=True, remove_pis=True, strip_cdata=True,
  1515. target=None, compact=True):
  1516. XMLParser.__init__(self,
  1517. attribute_defaults=attribute_defaults,
  1518. dtd_validation=dtd_validation,
  1519. load_dtd=load_dtd,
  1520. no_network=no_network,
  1521. decompress=decompress,
  1522. ns_clean=ns_clean,
  1523. recover=recover,
  1524. remove_blank_text=remove_blank_text,
  1525. huge_tree=huge_tree,
  1526. compact=compact,
  1527. resolve_entities=resolve_entities,
  1528. remove_comments=remove_comments,
  1529. remove_pis=remove_pis,
  1530. strip_cdata=strip_cdata,
  1531. target=target,
  1532. encoding=encoding,
  1533. schema=schema,
  1534. )
  1535. # ET 1.2 compatible name
  1536. XMLTreeBuilder = ETCompatXMLParser
  1537. cdef XMLParser __DEFAULT_XML_PARSER
  1538. __DEFAULT_XML_PARSER = XMLParser()
  1539. __GLOBAL_PARSER_CONTEXT.setDefaultParser(__DEFAULT_XML_PARSER)
  1540. def set_default_parser(_BaseParser parser=None):
  1541. """set_default_parser(parser=None)
  1542. Set a default parser for the current thread. This parser is used
  1543. globally whenever no parser is supplied to the various parse functions of
  1544. the lxml API. If this function is called without a parser (or if it is
  1545. None), the default parser is reset to the original configuration.
  1546. Note that the pre-installed default parser is not thread-safe. Avoid the
  1547. default parser in multi-threaded environments. You can create a separate
  1548. parser for each thread explicitly or use a parser pool.
  1549. """
  1550. if parser is None:
  1551. parser = __DEFAULT_XML_PARSER
  1552. __GLOBAL_PARSER_CONTEXT.setDefaultParser(parser)
  1553. def get_default_parser():
  1554. "get_default_parser()"
  1555. return __GLOBAL_PARSER_CONTEXT.getDefaultParser()
  1556. ############################################################
  1557. ## HTML parser
  1558. ############################################################
  1559. cdef int _HTML_DEFAULT_PARSE_OPTIONS
  1560. _HTML_DEFAULT_PARSE_OPTIONS = (
  1561. htmlparser.HTML_PARSE_RECOVER |
  1562. htmlparser.HTML_PARSE_NONET |
  1563. htmlparser.HTML_PARSE_COMPACT
  1564. )
  1565. cdef object _UNUSED = object()
  1566. cdef class HTMLParser(_FeedParser):
  1567. """HTMLParser(self, encoding=None, remove_blank_text=False, \
  1568. remove_comments=False, remove_pis=False, \
  1569. no_network=True, decompress=False, target=None, schema: XMLSchema =None, \
  1570. recover=True, compact=True, collect_ids=True, huge_tree=False)
  1571. The HTML parser.
  1572. This parser allows reading HTML into a normal XML tree. By
  1573. default, it can read broken (non well-formed) HTML, depending on
  1574. the capabilities of libxml2. Use the 'recover' option to switch
  1575. this off.
  1576. Available boolean keyword arguments:
  1577. - recover - try hard to parse through broken HTML (default: True)
  1578. - no_network - prevent network access for related files (default: True)
  1579. - decompress - automatically decompress gzip input
  1580. (default: False, changed in lxml 6.0, disabling only affects libxml2 2.15+)
  1581. - remove_blank_text - discard empty text nodes that are ignorable (i.e. not actual text content)
  1582. - remove_comments - discard comments
  1583. - remove_pis - discard processing instructions
  1584. - compact - save memory for short text content (default: True)
  1585. - default_doctype - add a default doctype even if it is not found in the HTML (default: True)
  1586. - collect_ids - use a hash table of XML IDs for fast access (default: True)
  1587. - huge_tree - disable security restrictions and support very deep trees
  1588. and very long text content
  1589. Other keyword arguments:
  1590. - encoding - override the document encoding (note: libiconv encoding name)
  1591. - target - a parser target object that will receive the parse events
  1592. - schema - an XMLSchema to validate against
  1593. Note that you should avoid sharing parsers between threads for performance
  1594. reasons.
  1595. """
  1596. def __init__(self, *, encoding=None, remove_blank_text=False,
  1597. remove_comments=False, remove_pis=False, strip_cdata=_UNUSED,
  1598. no_network=True, decompress=False, target=None, XMLSchema schema=None,
  1599. recover=True, compact=True, default_doctype=True,
  1600. collect_ids=True, huge_tree=False):
  1601. cdef int parse_options
  1602. parse_options = _HTML_DEFAULT_PARSE_OPTIONS
  1603. if remove_blank_text:
  1604. parse_options = parse_options | htmlparser.HTML_PARSE_NOBLANKS
  1605. if not recover:
  1606. parse_options = parse_options ^ htmlparser.HTML_PARSE_RECOVER
  1607. if not no_network:
  1608. parse_options = parse_options ^ htmlparser.HTML_PARSE_NONET
  1609. if not compact:
  1610. parse_options = parse_options ^ htmlparser.HTML_PARSE_COMPACT
  1611. if not default_doctype:
  1612. parse_options = parse_options ^ htmlparser.HTML_PARSE_NODEFDTD
  1613. if huge_tree:
  1614. parse_options = parse_options | xmlparser.XML_PARSE_HUGE
  1615. if strip_cdata is not _UNUSED:
  1616. import warnings
  1617. warnings.warn(
  1618. "The 'strip_cdata' option of HTMLParser() has never done anything and will eventually be removed.",
  1619. DeprecationWarning)
  1620. _BaseParser.__init__(self, parse_options, True, schema,
  1621. remove_comments, remove_pis, strip_cdata,
  1622. collect_ids, target, encoding)
  1623. # Allow subscripting HTMLParser in type annotions (PEP 560)
  1624. def __class_getitem__(cls, item):
  1625. return _GenericAlias(cls, item)
  1626. cdef HTMLParser __DEFAULT_HTML_PARSER
  1627. __DEFAULT_HTML_PARSER = HTMLParser()
  1628. cdef class HTMLPullParser(HTMLParser):
  1629. """HTMLPullParser(self, events=None, *, tag=None, base_url=None, **kwargs)
  1630. HTML parser that collects parse events in an iterator.
  1631. The collected events are the same as for iterparse(), but the
  1632. parser itself is non-blocking in the sense that it receives
  1633. data chunks incrementally through its .feed() method, instead
  1634. of reading them directly from a file(-like) object all by itself.
  1635. By default, it collects Element end events. To change that,
  1636. pass any subset of the available events into the ``events``
  1637. argument: ``'start'``, ``'end'``, ``'start-ns'``,
  1638. ``'end-ns'``, ``'comment'``, ``'pi'``.
  1639. To support loading external dependencies relative to the input
  1640. source, you can pass the ``base_url``.
  1641. """
  1642. def __init__(self, events=None, *, tag=None, base_url=None, **kwargs):
  1643. HTMLParser.__init__(self, **kwargs)
  1644. if events is None:
  1645. events = ('end',)
  1646. self._setBaseURL(base_url)
  1647. self._collectEvents(events, tag)
  1648. def read_events(self):
  1649. return (<_SaxParserContext?>self._getPushParserContext()).events_iterator
  1650. ############################################################
  1651. ## helper functions for document creation
  1652. ############################################################
  1653. cdef xmlDoc* _parseDoc(text, filename, _BaseParser parser) except NULL:
  1654. cdef char* c_filename
  1655. if parser is None:
  1656. parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
  1657. if not filename:
  1658. c_filename = NULL
  1659. else:
  1660. filename_utf = _encodeFilenameUTF8(filename)
  1661. c_filename = _cstr(filename_utf)
  1662. if isinstance(text, bytes):
  1663. return _parseDoc_bytes(<bytes> text, filename, c_filename, parser)
  1664. elif isinstance(text, unicode):
  1665. return _parseDoc_unicode(<unicode> text, filename, c_filename, parser)
  1666. else:
  1667. return _parseDoc_charbuffer(text, filename, c_filename, parser)
  1668. cdef xmlDoc* _parseDoc_unicode(unicode text, filename, char* c_filename, _BaseParser parser) except NULL:
  1669. cdef Py_ssize_t c_len
  1670. if python.PyUnicode_IS_READY(text):
  1671. # PEP-393 Unicode string
  1672. c_len = python.PyUnicode_GET_LENGTH(text) * python.PyUnicode_KIND(text)
  1673. else:
  1674. # old Py_UNICODE string
  1675. c_len = python.PyUnicode_GET_DATA_SIZE(text)
  1676. if c_len > limits.INT_MAX:
  1677. return parser._parseDocFromFilelike(
  1678. StringIO(text), filename, None)
  1679. return parser._parseUnicodeDoc(text, c_filename)
  1680. cdef xmlDoc* _parseDoc_bytes(bytes text, filename, char* c_filename, _BaseParser parser) except NULL:
  1681. cdef Py_ssize_t c_len = len(text)
  1682. if c_len > limits.INT_MAX:
  1683. return parser._parseDocFromFilelike(BytesIO(text), filename, None)
  1684. return parser._parseDoc(text, c_len, c_filename)
  1685. cdef xmlDoc* _parseDoc_charbuffer(text, filename, char* c_filename, _BaseParser parser) except NULL:
  1686. cdef const unsigned char[::1] data = memoryview(text).cast('B') # cast to 'unsigned char' buffer
  1687. cdef Py_ssize_t c_len = len(data)
  1688. if c_len > limits.INT_MAX:
  1689. return parser._parseDocFromFilelike(BytesIO(text), filename, None)
  1690. return parser._parseDoc(<const char*>&data[0], c_len, c_filename)
  1691. cdef xmlDoc* _parseDocFromFile(filename8, _BaseParser parser) except NULL:
  1692. if parser is None:
  1693. parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
  1694. return (<_BaseParser>parser)._parseDocFromFile(_cstr(filename8))
  1695. cdef xmlDoc* _parseDocFromFilelike(source, filename,
  1696. _BaseParser parser) except NULL:
  1697. if parser is None:
  1698. parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
  1699. return (<_BaseParser>parser)._parseDocFromFilelike(source, filename, None)
  1700. cdef xmlDoc* _newXMLDoc() except NULL:
  1701. cdef xmlDoc* result
  1702. result = tree.xmlNewDoc(NULL)
  1703. if result is NULL:
  1704. raise MemoryError()
  1705. if result.encoding is NULL:
  1706. result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
  1707. __GLOBAL_PARSER_CONTEXT.initDocDict(result)
  1708. return result
  1709. cdef xmlDoc* _newHTMLDoc() except NULL:
  1710. cdef xmlDoc* result
  1711. result = tree.htmlNewDoc(NULL, NULL)
  1712. if result is NULL:
  1713. raise MemoryError()
  1714. __GLOBAL_PARSER_CONTEXT.initDocDict(result)
  1715. return result
  1716. cdef xmlDoc* _copyDoc(xmlDoc* c_doc, int recursive) except NULL:
  1717. cdef xmlDoc* result
  1718. if recursive:
  1719. with nogil:
  1720. result = tree.xmlCopyDoc(c_doc, recursive)
  1721. else:
  1722. result = tree.xmlCopyDoc(c_doc, 0)
  1723. if result is NULL:
  1724. raise MemoryError()
  1725. __GLOBAL_PARSER_CONTEXT.initDocDict(result)
  1726. return result
  1727. cdef xmlDoc* _copyDocRoot(xmlDoc* c_doc, xmlNode* c_new_root) except NULL:
  1728. "Recursively copy the document and make c_new_root the new root node."
  1729. cdef xmlDoc* result
  1730. cdef xmlNode* c_node
  1731. result = tree.xmlCopyDoc(c_doc, 0) # non recursive
  1732. __GLOBAL_PARSER_CONTEXT.initDocDict(result)
  1733. with nogil:
  1734. c_node = tree.xmlDocCopyNode(c_new_root, result, 1) # recursive
  1735. if c_node is NULL:
  1736. raise MemoryError()
  1737. tree.xmlDocSetRootElement(result, c_node)
  1738. _copyTail(c_new_root.next, c_node)
  1739. return result
  1740. cdef xmlNode* _copyNodeToDoc(xmlNode* c_node, xmlDoc* c_doc) except NULL:
  1741. "Recursively copy the element into the document. c_doc is not modified."
  1742. cdef xmlNode* c_root
  1743. c_root = tree.xmlDocCopyNode(c_node, c_doc, 1) # recursive
  1744. if c_root is NULL:
  1745. raise MemoryError()
  1746. _copyTail(c_node.next, c_root)
  1747. return c_root
  1748. ############################################################
  1749. ## API level helper functions for _Document creation
  1750. ############################################################
  1751. cdef _Document _parseDocument(source, _BaseParser parser, base_url):
  1752. cdef _Document doc
  1753. source = _getFSPathOrObject(source)
  1754. if _isString(source):
  1755. # parse the file directly from the filesystem
  1756. doc = _parseDocumentFromURL(_encodeFilename(source), parser)
  1757. # fix base URL if requested
  1758. if base_url is not None:
  1759. base_url = _encodeFilenameUTF8(base_url)
  1760. if doc._c_doc.URL is not NULL:
  1761. tree.xmlFree(<char*>doc._c_doc.URL)
  1762. doc._c_doc.URL = tree.xmlStrdup(_xcstr(base_url))
  1763. return doc
  1764. if base_url is not None:
  1765. url = base_url
  1766. else:
  1767. url = _getFilenameForFile(source)
  1768. if hasattr(source, 'getvalue') and hasattr(source, 'tell'):
  1769. # StringIO - reading from start?
  1770. if source.tell() == 0:
  1771. return _parseMemoryDocument(source.getvalue(), url, parser)
  1772. # Support for file-like objects (urlgrabber.urlopen, ...)
  1773. if hasattr(source, 'read'):
  1774. return _parseFilelikeDocument(source, url, parser)
  1775. raise TypeError, f"cannot parse from '{python._fqtypename(source).decode('UTF-8')}'"
  1776. cdef _Document _parseDocumentFromURL(url, _BaseParser parser):
  1777. c_doc = _parseDocFromFile(url, parser)
  1778. return _documentFactory(c_doc, parser)
  1779. cdef _Document _parseMemoryDocument(text, url, _BaseParser parser):
  1780. if isinstance(text, unicode):
  1781. if _hasEncodingDeclaration(text):
  1782. raise ValueError(
  1783. "Unicode strings with encoding declaration are not supported. "
  1784. "Please use bytes input or XML fragments without declaration.")
  1785. c_doc = _parseDoc(text, url, parser)
  1786. return _documentFactory(c_doc, parser)
  1787. cdef _Document _parseFilelikeDocument(source, url, _BaseParser parser):
  1788. c_doc = _parseDocFromFilelike(source, url, parser)
  1789. return _documentFactory(c_doc, parser)