464 lines
16 KiB

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