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.
 
 
 

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