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.
 
 
 

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