parser.pxi 83 KB

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