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.
 
 
 

440 lines
16 KiB

  1. #! /usr/bin/env python
  2. '''XML Canonicalization
  3. Patches Applied to xml.dom.ext.c14n:
  4. http://sourceforge.net/projects/pyxml/
  5. [ 1444526 ] c14n.py: http://www.w3.org/TR/xml-exc-c14n/ fix
  6. -- includes [ 829905 ] c14n.py fix for bug #825115,
  7. Date Submitted: 2003-10-24 23:43
  8. -- include dependent namespace declarations declared in ancestor nodes
  9. (checking attributes and tags),
  10. -- handle InclusiveNamespaces PrefixList parameter
  11. This module generates canonical XML of a document or element.
  12. http://www.w3.org/TR/2001/REC-xml-c14n-20010315
  13. and includes a prototype of exclusive canonicalization
  14. http://www.w3.org/Signature/Drafts/xml-exc-c14n
  15. Requires PyXML 0.7.0 or later.
  16. Known issues if using Ft.Lib.pDomlette:
  17. 1. Unicode
  18. 2. does not white space normalize attributes of type NMTOKEN and ID?
  19. 3. seems to be include "\n" after importing external entities?
  20. Note, this version processes a DOM tree, and consequently it processes
  21. namespace nodes as attributes, not from a node's namespace axis. This
  22. permits simple document and element canonicalization without
  23. XPath. When XPath is used, the XPath result node list is passed and used to
  24. determine if the node is in the XPath result list, but little else.
  25. Authors:
  26. "Joseph M. Reagle Jr." <reagle@w3.org>
  27. "Rich Salz" <rsalz@zolera.com>
  28. $Date$ by $Author$
  29. '''
  30. _copyright = '''Copyright 2001, Zolera Systems Inc. All Rights Reserved.
  31. Copyright 2001, MIT. All Rights Reserved.
  32. Distributed under the terms of:
  33. Python 2.0 License or later.
  34. http://www.python.org/2.0.1/license.html
  35. or
  36. W3C Software License
  37. http://www.w3.org/Consortium/Legal/copyright-software-19980720
  38. '''
  39. import string
  40. from xml.dom import Node
  41. try:
  42. from xml.ns import XMLNS
  43. except:
  44. class XMLNS:
  45. BASE = "http://www.w3.org/2000/xmlns/"
  46. XML = "http://www.w3.org/XML/1998/namespace"
  47. import io
  48. _attrs = lambda E: (E.attributes and list(E.attributes.values())) or []
  49. _children = lambda E: E.childNodes or []
  50. _IN_XML_NS = lambda n: n.name.startswith("xmlns")
  51. _inclusive = lambda n: n.unsuppressedPrefixes is None
  52. # Does a document/PI has lesser/greater document order than the
  53. # first element?
  54. _LesserElement, _Element, _GreaterElement = list(range(3))
  55. def _sorter(n1, n2):
  56. '''_sorter(n1,n2) -> int
  57. Sorting predicate for non-NS attributes.'''
  58. i = cmp(n1.namespaceURI, n2.namespaceURI)
  59. if i:
  60. return i
  61. return cmp(n1.localName, n2.localName)
  62. def _sorter_ns(n1, n2):
  63. '''_sorter_ns((n,v),(n,v)) -> int
  64. "(an empty namespace URI is lexicographically least)."'''
  65. if n1[0] == 'xmlns':
  66. return -1
  67. if n2[0] == 'xmlns':
  68. return 1
  69. return cmp(n1[0], n2[0])
  70. def _utilized(n, node, other_attrs, unsuppressedPrefixes):
  71. '''_utilized(n, node, other_attrs, unsuppressedPrefixes) -> boolean
  72. Return true if that nodespace is utilized within the node'''
  73. if n.startswith('xmlns:'):
  74. n = n[6:]
  75. elif n.startswith('xmlns'):
  76. n = n[5:]
  77. if (n == "" and node.prefix in ["#default", None]) or \
  78. n == node.prefix or n in unsuppressedPrefixes:
  79. return 1
  80. for attr in other_attrs:
  81. if n == attr.prefix:
  82. return 1
  83. # For exclusive need to look at attributes
  84. if unsuppressedPrefixes is not None:
  85. for attr in _attrs(node):
  86. if n == attr.prefix:
  87. return 1
  88. return 0
  89. def _inclusiveNamespacePrefixes(node, context, unsuppressedPrefixes):
  90. '''http://www.w3.org/TR/xml-exc-c14n/
  91. InclusiveNamespaces PrefixList parameter, which lists namespace prefixes that
  92. are handled in the manner described by the Canonical XML Recommendation'''
  93. inclusive = []
  94. if node.prefix:
  95. usedPrefixes = ['xmlns:%s' % node.prefix]
  96. else:
  97. usedPrefixes = ['xmlns']
  98. for a in _attrs(node):
  99. if a.nodeName.startswith('xmlns') or not a.prefix:
  100. continue
  101. usedPrefixes.append('xmlns:%s' % a.prefix)
  102. unused_namespace_dict = {}
  103. for attr in context:
  104. n = attr.nodeName
  105. if n in unsuppressedPrefixes:
  106. inclusive.append(attr)
  107. elif n.startswith('xmlns:') and n[6:] in unsuppressedPrefixes:
  108. inclusive.append(attr)
  109. elif n.startswith('xmlns') and n[5:] in unsuppressedPrefixes:
  110. inclusive.append(attr)
  111. elif attr.nodeName in usedPrefixes:
  112. inclusive.append(attr)
  113. elif n.startswith('xmlns:'):
  114. unused_namespace_dict[n] = attr.value
  115. return inclusive, unused_namespace_dict
  116. #_in_subset = lambda subset, node: not subset or node in subset
  117. _in_subset = lambda subset, node: subset is None or node in subset # rich's tweak
  118. class _implementation:
  119. '''Implementation class for C14N. This accompanies a node during it's
  120. processing and includes the parameters and processing state.'''
  121. # Handler for each node type; populated during module instantiation.
  122. handlers = {}
  123. def __init__(self, node, write, **kw):
  124. '''Create and run the implementation.'''
  125. self.write = write
  126. self.subset = kw.get('subset')
  127. self.comments = kw.get('comments', 0)
  128. self.unsuppressedPrefixes = kw.get('unsuppressedPrefixes')
  129. nsdict = kw.get('nsdict', {'xml': XMLNS.XML, 'xmlns': XMLNS.BASE})
  130. # Processing state.
  131. self.state = (nsdict, {'xml': ''}, {}, {}) # 0422
  132. if node.nodeType == Node.DOCUMENT_NODE:
  133. self._do_document(node)
  134. elif node.nodeType == Node.ELEMENT_NODE:
  135. self.documentOrder = _Element # At document element
  136. if not _inclusive(self):
  137. inherited, unused = _inclusiveNamespacePrefixes(node, self._inherit_context(node),
  138. self.unsuppressedPrefixes)
  139. self._do_element(node, inherited, unused=unused)
  140. else:
  141. inherited = self._inherit_context(node)
  142. self._do_element(node, inherited)
  143. elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
  144. pass
  145. else:
  146. raise TypeError(str(node))
  147. def _inherit_context(self, node):
  148. '''_inherit_context(self, node) -> list
  149. Scan ancestors of attribute and namespace context. Used only
  150. for single element node canonicalization, not for subset
  151. canonicalization.'''
  152. # Collect the initial list of xml:foo attributes.
  153. xmlattrs = list(filter(_IN_XML_NS, _attrs(node)))
  154. # Walk up and get all xml:XXX attributes we inherit.
  155. inherited, parent = [], node.parentNode
  156. while parent and parent.nodeType == Node.ELEMENT_NODE:
  157. for a in filter(_IN_XML_NS, _attrs(parent)):
  158. n = a.localName
  159. if n not in xmlattrs:
  160. xmlattrs.append(n)
  161. inherited.append(a)
  162. parent = parent.parentNode
  163. return inherited
  164. def _do_document(self, node):
  165. '''_do_document(self, node) -> None
  166. Process a document node. documentOrder holds whether the document
  167. element has been encountered such that PIs/comments can be written
  168. as specified.'''
  169. self.documentOrder = _LesserElement
  170. for child in node.childNodes:
  171. if child.nodeType == Node.ELEMENT_NODE:
  172. self.documentOrder = _Element # At document element
  173. self._do_element(child)
  174. self.documentOrder = _GreaterElement # After document element
  175. elif child.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
  176. self._do_pi(child)
  177. elif child.nodeType == Node.COMMENT_NODE:
  178. self._do_comment(child)
  179. elif child.nodeType == Node.DOCUMENT_TYPE_NODE:
  180. pass
  181. else:
  182. raise TypeError(str(child))
  183. handlers[Node.DOCUMENT_NODE] = _do_document
  184. def _do_text(self, node):
  185. '''_do_text(self, node) -> None
  186. Process a text or CDATA node. Render various special characters
  187. as their C14N entity representations.'''
  188. if not _in_subset(self.subset, node):
  189. return
  190. s = string.replace(node.data, "&", "&amp;")
  191. s = string.replace(s, "<", "&lt;")
  192. s = string.replace(s, ">", "&gt;")
  193. s = string.replace(s, "\015", "&#xD;")
  194. if s:
  195. self.write(s)
  196. handlers[Node.TEXT_NODE] = _do_text
  197. handlers[Node.CDATA_SECTION_NODE] = _do_text
  198. def _do_pi(self, node):
  199. '''_do_pi(self, node) -> None
  200. Process a PI node. Render a leading or trailing #xA if the
  201. document order of the PI is greater or lesser (respectively)
  202. than the document element.
  203. '''
  204. if not _in_subset(self.subset, node):
  205. return
  206. W = self.write
  207. if self.documentOrder == _GreaterElement:
  208. W('\n')
  209. W('<?')
  210. W(node.nodeName)
  211. s = node.data
  212. if s:
  213. W(' ')
  214. W(s)
  215. W('?>')
  216. if self.documentOrder == _LesserElement:
  217. W('\n')
  218. handlers[Node.PROCESSING_INSTRUCTION_NODE] = _do_pi
  219. def _do_comment(self, node):
  220. '''_do_comment(self, node) -> None
  221. Process a comment node. Render a leading or trailing #xA if the
  222. document order of the comment is greater or lesser (respectively)
  223. than the document element.
  224. '''
  225. if not _in_subset(self.subset, node):
  226. return
  227. if self.comments:
  228. W = self.write
  229. if self.documentOrder == _GreaterElement:
  230. W('\n')
  231. W('<!--')
  232. W(node.data)
  233. W('-->')
  234. if self.documentOrder == _LesserElement:
  235. W('\n')
  236. handlers[Node.COMMENT_NODE] = _do_comment
  237. def _do_attr(self, n, value):
  238. ''''_do_attr(self, node) -> None
  239. Process an attribute.'''
  240. W = self.write
  241. W(' ')
  242. W(n)
  243. W('="')
  244. s = string.replace(value, "&", "&amp;")
  245. s = string.replace(s, "<", "&lt;")
  246. s = string.replace(s, '"', '&quot;')
  247. s = string.replace(s, '\011', '&#x9')
  248. s = string.replace(s, '\012', '&#xA')
  249. s = string.replace(s, '\015', '&#xD')
  250. W(s)
  251. W('"')
  252. def _do_element(self, node, initial_other_attrs=[], unused=None):
  253. '''_do_element(self, node, initial_other_attrs = [], unused = {}) -> None
  254. Process an element (and its children).'''
  255. # Get state (from the stack) make local copies.
  256. # ns_parent -- NS declarations in parent
  257. # ns_rendered -- NS nodes rendered by ancestors
  258. # ns_local -- NS declarations relevant to this element
  259. # xml_attrs -- Attributes in XML namespace from parent
  260. # xml_attrs_local -- Local attributes in XML namespace.
  261. # ns_unused_inherited -- not rendered namespaces, used for exclusive
  262. ns_parent, ns_rendered, xml_attrs = \
  263. self.state[0], self.state[1].copy(), self.state[2].copy() # 0422
  264. ns_unused_inherited = unused
  265. if unused is None:
  266. ns_unused_inherited = self.state[3].copy()
  267. ns_local = ns_parent.copy()
  268. inclusive = _inclusive(self)
  269. xml_attrs_local = {}
  270. # Divide attributes into NS, XML, and others.
  271. other_attrs = []
  272. in_subset = _in_subset(self.subset, node)
  273. for a in initial_other_attrs + _attrs(node):
  274. if a.namespaceURI == XMLNS.BASE:
  275. n = a.nodeName
  276. if n == "xmlns:":
  277. n = "xmlns" # DOM bug workaround
  278. ns_local[n] = a.nodeValue
  279. elif a.namespaceURI == XMLNS.XML:
  280. if inclusive or (in_subset and _in_subset(self.subset, a)): # 020925 Test to see if attribute node in subset
  281. xml_attrs_local[a.nodeName] = a # 0426
  282. else:
  283. if _in_subset(self.subset, a): # 020925 Test to see if attribute node in subset
  284. other_attrs.append(a)
  285. # # TODO: exclusive, might need to define xmlns:prefix here
  286. # if not inclusive and a.prefix is not None and not ns_rendered.has_key('xmlns:%s' %a.prefix):
  287. # ns_local['xmlns:%s' %a.prefix] = ??
  288. #add local xml:foo attributes to ancestor's xml:foo attributes
  289. xml_attrs.update(xml_attrs_local)
  290. # Render the node
  291. W, name = self.write, None
  292. if in_subset:
  293. name = node.nodeName
  294. if not inclusive:
  295. if node.prefix is not None:
  296. prefix = 'xmlns:%s' % node.prefix
  297. else:
  298. prefix = 'xmlns'
  299. if prefix not in ns_rendered and prefix not in ns_local:
  300. if not prefix in ns_unused_inherited:
  301. raise RuntimeError('For exclusive c14n, unable to map prefix "%s" in %s' % (
  302. prefix, node))
  303. ns_local[prefix] = ns_unused_inherited[prefix]
  304. del ns_unused_inherited[prefix]
  305. W('<')
  306. W(name)
  307. # Create list of NS attributes to render.
  308. ns_to_render = []
  309. for n, v in list(ns_local.items()):
  310. # If default namespace is XMLNS.BASE or empty,
  311. # and if an ancestor was the same
  312. if n == "xmlns" and v in [XMLNS.BASE, ''] \
  313. and ns_rendered.get('xmlns') in [XMLNS.BASE, '', None]:
  314. continue
  315. # "omit namespace node with local name xml, which defines
  316. # the xml prefix, if its string value is
  317. # http://www.w3.org/XML/1998/namespace."
  318. if n in ["xmlns:xml", "xml"] \
  319. and v in ['http://www.w3.org/XML/1998/namespace']:
  320. continue
  321. # If not previously rendered
  322. # and it's inclusive or utilized
  323. if (n, v) not in list(ns_rendered.items()):
  324. if inclusive or _utilized(n, node, other_attrs, self.unsuppressedPrefixes):
  325. ns_to_render.append((n, v))
  326. elif not inclusive:
  327. ns_unused_inherited[n] = v
  328. # Sort and render the ns, marking what was rendered.
  329. ns_to_render.sort(_sorter_ns)
  330. for n, v in ns_to_render:
  331. self._do_attr(n, v)
  332. ns_rendered[n] = v # 0417
  333. # If exclusive or the parent is in the subset, add the local xml attributes
  334. # Else, add all local and ancestor xml attributes
  335. # Sort and render the attributes.
  336. if not inclusive or _in_subset(self.subset, node.parentNode): # 0426
  337. other_attrs.extend(list(xml_attrs_local.values()))
  338. else:
  339. other_attrs.extend(list(xml_attrs.values()))
  340. other_attrs.sort(_sorter)
  341. for a in other_attrs:
  342. self._do_attr(a.nodeName, a.value)
  343. W('>')
  344. # Push state, recurse, pop state.
  345. state, self.state = self.state, (ns_local, ns_rendered, xml_attrs, ns_unused_inherited)
  346. for c in _children(node):
  347. _implementation.handlers[c.nodeType](self, c)
  348. self.state = state
  349. if name:
  350. W('</%s>' % name)
  351. handlers[Node.ELEMENT_NODE] = _do_element
  352. def Canonicalize(node, output=None, **kw):
  353. '''Canonicalize(node, output=None, **kw) -> UTF-8
  354. Canonicalize a DOM document/element node and all descendents.
  355. Return the text; if output is specified then output.write will
  356. be called to output the text and None will be returned
  357. Keyword parameters:
  358. nsdict: a dictionary of prefix:uri namespace entries
  359. assumed to exist in the surrounding context
  360. comments: keep comments if non-zero (default is 0)
  361. subset: Canonical XML subsetting resulting from XPath
  362. (default is [])
  363. unsuppressedPrefixes: do exclusive C14N, and this specifies the
  364. prefixes that should be inherited.
  365. '''
  366. if output:
  367. _implementation(*(node, output.write), **kw)
  368. else:
  369. s = StringIO.StringIO()
  370. _implementation(*(node, s.write), **kw)
  371. return s.getvalue()