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