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.
 
 
 

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