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.
 
 
 

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