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.
 
 
 

1493 lines
52 KiB

  1. #!/usr/bin/env python
  2. # Copyright (c) 2003, The Regents of the University of California,
  3. # through Lawrence Berkeley National Laboratory (subject to receipt of
  4. # any required approvals from the U.S. Dept. of Energy). All rights
  5. # reserved.
  6. #
  7. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
  8. #
  9. # This software is subject to the provisions of the Zope Public License,
  10. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
  11. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  12. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  13. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  14. # FOR A PARTICULAR PURPOSE.
  15. ident = "$Id$"
  16. import copy
  17. import types
  18. import six
  19. import socket
  20. import weakref
  21. from os.path import isfile
  22. import urllib.request, urllib.parse, urllib.error
  23. try:
  24. from urllib.parse import urljoin as basejoin # noqa
  25. except ImportError:
  26. from urllib.parse import urljoin as basejoin # noqa
  27. try:
  28. from UserDict import UserDict
  29. from UserDict import DictMixin # noqa
  30. except ImportError:
  31. from collections import UserDict
  32. from collections import MutableMapping as DictMixin # noqa
  33. from .TimeoutSocket import TimeoutSocket, TimeoutError # noqa
  34. try:
  35. from io import StringIO
  36. except ImportError:
  37. from io import StringIO
  38. try:
  39. from urllib.parse import urlparse
  40. except ImportError:
  41. from urllib.parse import urlparse
  42. try:
  43. from http.client import HTTPConnection, HTTPSConnection, FakeSocket, _CS_REQ_SENT
  44. except ImportError:
  45. from http.client import HTTPConnection, HTTPSConnection, _CS_REQ_SENT
  46. import io
  47. class FakeSocket(io.BytesIO):
  48. io_refs = 1
  49. def sendall(self, data):
  50. FakeHTTPConnection.buf = data
  51. def makefile(self, *args, **kwds):
  52. self.io_refs += 1
  53. return self
  54. def read(self, amt=None):
  55. if self.closed:
  56. return b""
  57. return io.BytesIO.read(self, amt)
  58. def readline(self, length=None):
  59. if self.closed:
  60. return b""
  61. return io.BytesIO.readline(self, length)
  62. def close(self):
  63. self.io_refs -= 1
  64. if self.io_refs == 0:
  65. io.BytesIO.close(self)
  66. class FakeHTTPConnection(HTTPConnection):
  67. # buffer to store data for verification in urlopen tests.
  68. buf = None
  69. def connect(self):
  70. self.sock = FakeSocket(self.fakedata)
  71. type(self).fakesock = self.sock
  72. try:
  73. from exceptions import Exception
  74. except:
  75. pass
  76. try:
  77. from ZSI import _get_idstr
  78. except:
  79. def _get_idstr(pyobj):
  80. '''Python 2.3.x generates a FutureWarning for negative IDs, so
  81. we use a different prefix character to ensure uniqueness, and
  82. call abs() to avoid the warning.'''
  83. x = id(pyobj)
  84. if x < 0:
  85. return 'x%x' % abs(x)
  86. return 'o%x' % x
  87. import xml.dom.minidom
  88. from xml.dom import Node
  89. import logging
  90. from .c14n import Canonicalize
  91. from .Namespaces import SCHEMA, SOAP, XMLNS, ZSI_SCHEMA_URI
  92. DEFAULT = "".join
  93. try:
  94. from xml.dom.ext import SplitQName
  95. except:
  96. def SplitQName(qname):
  97. '''SplitQName(qname) -> (string, string)
  98. Split Qualified Name into a tuple of len 2, consisting
  99. of the prefix and the local name.
  100. (prefix, localName)
  101. Special Cases:
  102. xmlns -- (localName, 'xmlns')
  103. None -- (None, localName)
  104. '''
  105. l = qname.split(':')
  106. if len(l) == 1:
  107. l.insert(0, None)
  108. elif len(l) == 2:
  109. if l[0] == 'xmlns':
  110. l.reverse()
  111. else:
  112. return
  113. return tuple(l)
  114. class NamespaceError(Exception):
  115. """Used to indicate a Namespace Error."""
  116. class RecursionError(Exception):
  117. """Used to indicate a HTTP redirect recursion."""
  118. class ParseError(Exception):
  119. """Used to indicate a XML parsing error."""
  120. class DOMException(Exception):
  121. """Used to indicate a problem processing DOM."""
  122. class Base:
  123. """Base class for instance level Logging"""
  124. def __init__(self, logger=None):
  125. self.logger = logger or logging.getLogger(__name__)
  126. class HTTPResponse:
  127. """Captures the information in an HTTP response message."""
  128. def __init__(self, response):
  129. self.status = response.status
  130. self.reason = response.reason
  131. self.headers = response.msg
  132. self.body = response.read() or None
  133. response.close()
  134. class TimeoutHTTP(HTTPConnection):
  135. """A custom http connection object that supports socket timeout."""
  136. def __init__(self, host, port=None, timeout=20):
  137. HTTPConnection.__init__(self, host, port)
  138. self.timeout = timeout
  139. def connect(self):
  140. self.sock = TimeoutSocket(self.timeout)
  141. self.sock.connect((self.host, self.port))
  142. class TimeoutHTTPS(HTTPSConnection):
  143. """A custom https object that supports socket timeout. Note that this
  144. is not really complete. The builtin SSL support in the Python socket
  145. module requires a real socket (type) to be passed in to be hooked to
  146. SSL. That means our fake socket won't work and our timeout hacks are
  147. bypassed for send and recv calls. Since our hack _is_ in place at
  148. connect() time, it should at least provide some timeout protection."""
  149. def __init__(self, host, port=None, timeout=20, **kwargs):
  150. HTTPSConnection.__init__(self, str(host), port, **kwargs)
  151. self.timeout = timeout
  152. def connect(self):
  153. sock = TimeoutSocket(self.timeout)
  154. sock.connect((self.host, self.port))
  155. realsock = getattr(sock.sock, '_sock', sock.sock)
  156. ssl = socket.ssl(realsock, self.key_file, self.cert_file)
  157. self.sock = FakeSocket(sock, ssl)
  158. def urlopen(url, timeout=20, redirects=None):
  159. """A minimal urlopen replacement hack that supports timeouts for http.
  160. Note that this supports GET only."""
  161. scheme, host, path, params, query, frag = urlparse(url)
  162. if scheme not in ('http', 'https'):
  163. return urllib.request.urlopen(url)
  164. if params:
  165. path = '%s;%s' % (path, params)
  166. if query:
  167. path = '%s?%s' % (path, query)
  168. if frag:
  169. path = '%s#%s' % (path, frag)
  170. if scheme == 'https':
  171. # If ssl is not compiled into Python, you will not get an exception
  172. # until a conn.endheaders() call. We need to know sooner, so use
  173. # getattr.
  174. try:
  175. import M2Crypto
  176. except ImportError:
  177. if not hasattr(socket, 'ssl'):
  178. raise RuntimeError('no built-in SSL Support')
  179. conn = TimeoutHTTPS(host, None, timeout)
  180. else:
  181. ctx = M2Crypto.SSL.Context()
  182. ctx.set_session_timeout(timeout)
  183. conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx)
  184. conn.set_debuglevel(1)
  185. else:
  186. conn = TimeoutHTTP(host, None, timeout)
  187. conn.putrequest('GET', path)
  188. conn.putheader('Connection', 'close')
  189. conn.endheaders()
  190. response = None
  191. while 1:
  192. response = conn.getresponse()
  193. if response.status != 100:
  194. break
  195. conn._HTTPConnection__state = _CS_REQ_SENT
  196. conn._HTTPConnection__response = None
  197. status = response.status
  198. # If we get an HTTP redirect, we will follow it automatically.
  199. if status >= 300 and status < 400:
  200. location = response.msg.getheader('location')
  201. if location is not None:
  202. response.close()
  203. if redirects is not None and location in redirects:
  204. raise RecursionError(
  205. 'Circular HTTP redirection detected.'
  206. )
  207. if redirects is None:
  208. redirects = {}
  209. redirects[location] = 1
  210. return urlopen(location, timeout, redirects)
  211. raise HTTPResponse(response)
  212. if not (status >= 200 and status < 300):
  213. raise HTTPResponse(response)
  214. body = StringIO(response.read())
  215. response.close()
  216. return body
  217. class DOM:
  218. """The DOM singleton defines a number of XML related constants and
  219. provides a number of utility methods for DOM related tasks. It
  220. also provides some basic abstractions so that the rest of the
  221. package need not care about actual DOM implementation in use."""
  222. # if can't find a referenced namespace, try the default one
  223. looseNamespaces = False
  224. # Namespace stuff related to the SOAP specification.
  225. NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
  226. NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'
  227. NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
  228. NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'
  229. NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
  230. NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)
  231. NS_SOAP_ENV = NS_SOAP_ENV_1_1
  232. NS_SOAP_ENC = NS_SOAP_ENC_1_1
  233. _soap_uri_mapping = {
  234. NS_SOAP_ENV_1_1: '1.1',
  235. NS_SOAP_ENV_1_2: '1.2',
  236. }
  237. SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
  238. SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
  239. SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
  240. def SOAPUriToVersion(self, uri):
  241. """Return the SOAP version related to an envelope uri."""
  242. value = self._soap_uri_mapping.get(uri)
  243. if value is not None:
  244. return value
  245. raise ValueError(
  246. 'Unsupported SOAP envelope uri: %s' % uri
  247. )
  248. def GetSOAPEnvUri(self, version):
  249. """Return the appropriate SOAP envelope uri for a given
  250. human-friendly SOAP version string (e.g. '1.1')."""
  251. attrname = 'NS_SOAP_ENV_%s' % '_'.join(version.split('.'))
  252. value = getattr(self, attrname, None)
  253. if value is not None:
  254. return value
  255. raise ValueError(
  256. 'Unsupported SOAP version: %s' % version
  257. )
  258. def GetSOAPEncUri(self, version):
  259. """Return the appropriate SOAP encoding uri for a given
  260. human-friendly SOAP version string (e.g. '1.1')."""
  261. attrname = 'NS_SOAP_ENC_%s' % '_'.join(version.split('.'))
  262. value = getattr(self, attrname, None)
  263. if value is not None:
  264. return value
  265. raise ValueError(
  266. 'Unsupported SOAP version: %s' % version
  267. )
  268. def GetSOAPActorNextUri(self, version):
  269. """Return the right special next-actor uri for a given
  270. human-friendly SOAP version string (e.g. '1.1')."""
  271. attrname = 'SOAP_ACTOR_NEXT_%s' % '_'.join(version.split('.'))
  272. value = getattr(self, attrname, None)
  273. if value is not None:
  274. return value
  275. raise ValueError(
  276. 'Unsupported SOAP version: %s' % version
  277. )
  278. # Namespace stuff related to XML Schema.
  279. NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
  280. NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'
  281. NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
  282. NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'
  283. NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
  284. NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'
  285. NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
  286. NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)
  287. NS_XSD = NS_XSD_01
  288. NS_XSI = NS_XSI_01
  289. _xsd_uri_mapping = {
  290. NS_XSD_99: NS_XSI_99,
  291. NS_XSD_00: NS_XSI_00,
  292. NS_XSD_01: NS_XSI_01,
  293. }
  294. for key, value in list(copy.deepcopy(_xsd_uri_mapping).items()):
  295. _xsd_uri_mapping[value] = key
  296. def InstanceUriForSchemaUri(self, uri):
  297. """Return the appropriate matching XML Schema instance uri for
  298. the given XML Schema namespace uri."""
  299. return self._xsd_uri_mapping.get(uri)
  300. def SchemaUriForInstanceUri(self, uri):
  301. """Return the appropriate matching XML Schema namespace uri for
  302. the given XML Schema instance namespace uri."""
  303. return self._xsd_uri_mapping.get(uri)
  304. # Namespace stuff related to WSDL.
  305. NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
  306. NS_WSDL_ALL = (NS_WSDL_1_1,)
  307. NS_WSDL = NS_WSDL_1_1
  308. NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
  309. NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
  310. NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'
  311. NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
  312. NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
  313. NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)
  314. NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
  315. NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
  316. NS_MIME_BINDING = NS_MIME_BINDING_1_1
  317. NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
  318. NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
  319. NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
  320. _wsdl_uri_mapping = {
  321. NS_WSDL_1_1: '1.1',
  322. }
  323. def WSDLUriToVersion(self, uri):
  324. """Return the WSDL version related to a WSDL namespace uri."""
  325. value = self._wsdl_uri_mapping.get(uri)
  326. if value is not None:
  327. return value
  328. raise ValueError(
  329. 'Unsupported SOAP envelope uri: %s' % uri
  330. )
  331. def GetWSDLUri(self, version):
  332. attr = 'NS_WSDL_%s' % '_'.join(version.split('.'))
  333. value = getattr(self, attr, None)
  334. if value is not None:
  335. return value
  336. raise ValueError(
  337. 'Unsupported WSDL version: %s' % version
  338. )
  339. def GetWSDLSoapBindingUri(self, version):
  340. attr = 'NS_SOAP_BINDING_%s' % '_'.join(version.split('.'))
  341. value = getattr(self, attr, None)
  342. if value is not None:
  343. return value
  344. raise ValueError(
  345. 'Unsupported WSDL version: %s' % version
  346. )
  347. def GetWSDLHttpBindingUri(self, version):
  348. attr = 'NS_HTTP_BINDING_%s' % '_'.join(version.split('.'))
  349. value = getattr(self, attr, None)
  350. if value is not None:
  351. return value
  352. raise ValueError(
  353. 'Unsupported WSDL version: %s' % version
  354. )
  355. def GetWSDLMimeBindingUri(self, version):
  356. attr = 'NS_MIME_BINDING_%s' % '_'.join(version.split('.'))
  357. value = getattr(self, attr, None)
  358. if value is not None:
  359. return value
  360. raise ValueError(
  361. 'Unsupported WSDL version: %s' % version
  362. )
  363. def GetWSDLHttpTransportUri(self, version):
  364. attr = 'NS_SOAP_HTTP_%s' % '_'.join(version.split('.'))
  365. value = getattr(self, attr, None)
  366. if value is not None:
  367. return value
  368. raise ValueError(
  369. 'Unsupported WSDL version: %s' % version
  370. )
  371. # Other xml namespace constants.
  372. NS_XMLNS = 'http://www.w3.org/2000/xmlns/'
  373. def isElement(self, node, name, nsuri=None):
  374. """Return true if the given node is an element with the given
  375. name and optional namespace uri."""
  376. if node.nodeType != node.ELEMENT_NODE:
  377. return 0
  378. return node.localName == name and \
  379. (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
  380. def getElement(self, node, name, nsuri=None, default=DEFAULT):
  381. """Return the first child of node with a matching name and
  382. namespace uri, or the default if one is provided."""
  383. nsmatch = self.nsUriMatch
  384. ELEMENT_NODE = node.ELEMENT_NODE
  385. for child in node.childNodes:
  386. if child.nodeType == ELEMENT_NODE:
  387. if ((child.localName == name or name is None) and
  388. (nsuri is None or nsmatch(child.namespaceURI, nsuri))):
  389. return child
  390. if default != DEFAULT:
  391. return default
  392. raise KeyError(name)
  393. def getElementById(self, node, id, default=DEFAULT):
  394. """Return the first child of node matching an id reference."""
  395. attrget = self.getAttr
  396. ELEMENT_NODE = node.ELEMENT_NODE
  397. for child in node.childNodes:
  398. if child.nodeType == ELEMENT_NODE:
  399. if attrget(child, 'id') == id:
  400. return child
  401. if default != DEFAULT:
  402. return default
  403. raise KeyError(node)
  404. def getMappingById(self, document, depth=None, element=None,
  405. mapping=None, level=1):
  406. """Create an id -> element mapping of those elements within a
  407. document that define an id attribute. The depth of the search
  408. may be controlled by using the (1-based) depth argument."""
  409. if document is not None:
  410. element = document.documentElement
  411. mapping = {}
  412. attr = element._attrs.get('id', None)
  413. if attr is not None:
  414. mapping[attr.value] = element
  415. if depth is None or depth > level:
  416. level = level + 1
  417. ELEMENT_NODE = element.ELEMENT_NODE
  418. for child in element.childNodes:
  419. if child.nodeType == ELEMENT_NODE:
  420. self.getMappingById(None, depth, child, mapping, level)
  421. return mapping
  422. def getElements(self, node, name, nsuri=None):
  423. """Return a sequence of the child elements of the given node that
  424. match the given name and optional namespace uri."""
  425. nsmatch = self.nsUriMatch
  426. result = []
  427. ELEMENT_NODE = node.ELEMENT_NODE
  428. for child in node.childNodes:
  429. if child.nodeType == ELEMENT_NODE:
  430. if ((child.localName == name or name is None) and (
  431. (nsuri is None) or nsmatch(child.namespaceURI, nsuri))):
  432. result.append(child)
  433. return result
  434. def hasAttr(self, node, name, nsuri=None):
  435. """Return true if element has attribute with the given name and
  436. optional nsuri. If nsuri is not specified, returns true if an
  437. attribute exists with the given name with any namespace."""
  438. if nsuri is None:
  439. if node.hasAttribute(name):
  440. return True
  441. return False
  442. return node.hasAttributeNS(nsuri, name)
  443. def getAttr(self, node, name, nsuri=None, default=DEFAULT):
  444. """Return the value of the attribute named 'name' with the
  445. optional nsuri, or the default if one is specified. If
  446. nsuri is not specified, an attribute that matches the
  447. given name will be returned regardless of namespace."""
  448. if nsuri is None:
  449. if node._attrs is None:
  450. result = None
  451. else:
  452. result = node._attrs.get(name, None)
  453. if result is None:
  454. if node._attrsNS is None:
  455. result = None
  456. else:
  457. for item in list(node._attrsNS.keys()):
  458. if item[1] == name:
  459. result = node._attrsNS[item]
  460. break
  461. else:
  462. if node._attrsNS is None:
  463. result = None
  464. else:
  465. if node._attrsNS is None:
  466. result = None
  467. else:
  468. result = node._attrsNS.get((nsuri, name), None)
  469. if result is not None:
  470. return result.value
  471. if default != DEFAULT:
  472. return default
  473. return ''
  474. def getAttrs(self, node):
  475. """Return a Collection of all attributes
  476. """
  477. attrs = {}
  478. for k, v in list(node._attrs.items()):
  479. attrs[k] = v.value
  480. return attrs
  481. def getElementText(self, node, preserve_ws=None):
  482. """Return the text value of an xml element node. Leading and trailing
  483. whitespace is stripped from the value unless the preserve_ws flag
  484. is passed with a true value."""
  485. result = []
  486. for child in node.childNodes:
  487. nodetype = child.nodeType
  488. if nodetype == child.TEXT_NODE or \
  489. nodetype == child.CDATA_SECTION_NODE:
  490. result.append(child.nodeValue)
  491. value = ''.join(result)
  492. if preserve_ws is None:
  493. value = value.strip()
  494. return value
  495. def findNamespaceURI(self, prefix, node):
  496. """Find a namespace uri given a prefix and a context node."""
  497. attrkey = (self.NS_XMLNS, prefix)
  498. DOCUMENT_NODE = node.DOCUMENT_NODE
  499. ELEMENT_NODE = node.ELEMENT_NODE
  500. orig_node = node
  501. while 1:
  502. if node is None:
  503. raise DOMException('Value for prefix %s not found.' % prefix)
  504. if node.nodeType != ELEMENT_NODE:
  505. node = node.parentNode
  506. continue
  507. result = node._attrsNS.get(attrkey, None)
  508. if result is not None:
  509. return result.value
  510. if hasattr(node, '__imported__'):
  511. raise DOMException('Value for prefix %s not found.' % prefix)
  512. node = node.parentNode
  513. if node.nodeType == DOCUMENT_NODE:
  514. if DOM.looseNamespaces:
  515. return self.findTargetNS(orig_node)
  516. else:
  517. raise DOMException('Value for prefix %s not found.'
  518. % prefix)
  519. def findDefaultNS(self, node):
  520. """Return the current default namespace uri for the given node."""
  521. attrkey = (self.NS_XMLNS, 'xmlns')
  522. DOCUMENT_NODE = node.DOCUMENT_NODE
  523. ELEMENT_NODE = node.ELEMENT_NODE
  524. while 1:
  525. if node.nodeType != ELEMENT_NODE:
  526. node = node.parentNode
  527. continue
  528. result = node._attrsNS.get(attrkey, None)
  529. if result is not None:
  530. return result.value
  531. if hasattr(node, '__imported__'):
  532. raise DOMException('Cannot determine default namespace.')
  533. node = node.parentNode
  534. if node.nodeType == DOCUMENT_NODE:
  535. raise DOMException('Cannot determine default namespace.')
  536. def findTargetNS(self, node):
  537. """Return the defined target namespace uri for the given node."""
  538. attrget = self.getAttr
  539. # attrkey = (self.NS_XMLNS, 'xmlns')
  540. DOCUMENT_NODE = node.DOCUMENT_NODE
  541. ELEMENT_NODE = node.ELEMENT_NODE
  542. while 1:
  543. if node.nodeType != ELEMENT_NODE:
  544. node = node.parentNode
  545. continue
  546. result = attrget(node, 'targetNamespace', default=None)
  547. if result is not None:
  548. return result
  549. node = node.parentNode
  550. if node.nodeType == DOCUMENT_NODE:
  551. raise DOMException('Cannot determine target namespace.')
  552. def getTypeRef(self, element):
  553. """Return (namespaceURI, name) for a type attribue of the given
  554. element, or None if the element does not have a type attribute."""
  555. typeattr = self.getAttr(element, 'type', default=None)
  556. if typeattr is None:
  557. return None
  558. parts = typeattr.split(':', 1)
  559. if len(parts) == 2:
  560. nsuri = self.findNamespaceURI(parts[0], element)
  561. else:
  562. nsuri = self.findDefaultNS(element)
  563. return (nsuri, parts[1])
  564. def importNode(self, document, node, deep=0):
  565. """Implements (well enough for our purposes) DOM node import."""
  566. nodetype = node.nodeType
  567. if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
  568. raise DOMException('Illegal node type for importNode')
  569. if nodetype == node.ENTITY_REFERENCE_NODE:
  570. deep = 0
  571. clone = node.cloneNode(deep)
  572. self._setOwnerDoc(document, clone)
  573. clone.__imported__ = 1
  574. return clone
  575. def _setOwnerDoc(self, document, node):
  576. node.ownerDocument = document
  577. for child in node.childNodes:
  578. self._setOwnerDoc(document, child)
  579. def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
  580. """Return a true value if two namespace uri values match."""
  581. if value == wanted or (type(wanted) is tt) and value in wanted:
  582. return 1
  583. if not strict and value is not None:
  584. wanted = type(wanted) is tt and wanted or (wanted,)
  585. value = value[-1:] != '/' and value or value[:-1]
  586. for item in wanted:
  587. if item == value or item[:-1] == value:
  588. return 1
  589. return 0
  590. def createDocument(self, nsuri, qname, doctype=None):
  591. """Create a new writable DOM document object."""
  592. impl = xml.dom.minidom.getDOMImplementation()
  593. return impl.createDocument(nsuri, qname, doctype)
  594. def loadDocument(self, data):
  595. """Load an xml file from a file-like object and return a DOM
  596. document instance."""
  597. return xml.dom.minidom.parse(data)
  598. def loadFromURL(self, url):
  599. """Load an xml file from a URL and return a DOM document."""
  600. if isfile(url) is True:
  601. file = open(url, 'r')
  602. else:
  603. file = urlopen(url)
  604. try:
  605. result = self.loadDocument(file)
  606. except Exception as ex:
  607. file.close()
  608. raise ParseError(('Failed to load document %s' % url,) + ex.args)
  609. else:
  610. file.close()
  611. return result
  612. DOM = DOM()
  613. class MessageInterface:
  614. '''Higher Level Interface, delegates to DOM singleton, must
  615. be subclassed and implement all methods that throw NotImplementedError.
  616. '''
  617. def __init__(self, sw):
  618. '''Constructor, May be extended, do not override.
  619. sw -- soapWriter instance
  620. '''
  621. self.sw = None
  622. if type(sw) != weakref.ReferenceType and sw is not None:
  623. self.sw = weakref.ref(sw)
  624. else:
  625. self.sw = sw
  626. def AddCallback(self, func, *arglist):
  627. self.sw().AddCallback(func, *arglist)
  628. def Known(self, obj):
  629. return self.sw().Known(obj)
  630. def Forget(self, obj):
  631. return self.sw().Forget(obj)
  632. def canonicalize(self):
  633. '''canonicalize the underlying DOM, and return as string.
  634. '''
  635. raise NotImplementedError('')
  636. def createDocument(self, namespaceURI=SOAP.ENV, localName='Envelope'):
  637. '''create Document
  638. '''
  639. raise NotImplementedError('')
  640. def createAppendElement(self, namespaceURI, localName):
  641. '''create and append element(namespaceURI,localName), and return
  642. the node.
  643. '''
  644. raise NotImplementedError('')
  645. def findNamespaceURI(self, qualifiedName):
  646. raise NotImplementedError('')
  647. def resolvePrefix(self, prefix):
  648. raise NotImplementedError('')
  649. def setAttributeNS(self, namespaceURI, localName, value):
  650. '''set attribute (namespaceURI, localName)=value
  651. '''
  652. raise NotImplementedError('')
  653. def setAttributeType(self, namespaceURI, localName):
  654. '''set attribute xsi:type=(namespaceURI, localName)
  655. '''
  656. raise NotImplementedError('')
  657. def setNamespaceAttribute(self, namespaceURI, prefix):
  658. '''set namespace attribute xmlns:prefix=namespaceURI
  659. '''
  660. raise NotImplementedError('')
  661. class ElementProxy(Base, MessageInterface):
  662. _soap_env_prefix = 'SOAP-ENV'
  663. _soap_enc_prefix = 'SOAP-ENC'
  664. _zsi_prefix = 'ZSI'
  665. _xsd_prefix = 'xsd'
  666. _xsi_prefix = 'xsi'
  667. _xml_prefix = 'xml'
  668. _xmlns_prefix = 'xmlns'
  669. _soap_env_nsuri = SOAP.ENV
  670. _soap_enc_nsuri = SOAP.ENC
  671. _zsi_nsuri = ZSI_SCHEMA_URI
  672. _xsd_nsuri = SCHEMA.XSD3
  673. _xsi_nsuri = SCHEMA.XSI3
  674. _xml_nsuri = XMLNS.XML
  675. _xmlns_nsuri = XMLNS.BASE
  676. standard_ns = {
  677. _xml_prefix: _xml_nsuri,
  678. _xmlns_prefix: _xmlns_nsuri
  679. }
  680. reserved_ns = {
  681. _soap_env_prefix: _soap_env_nsuri,
  682. _soap_enc_prefix: _soap_enc_nsuri,
  683. _zsi_prefix: _zsi_nsuri,
  684. _xsd_prefix: _xsd_nsuri,
  685. _xsi_prefix: _xsi_nsuri,
  686. }
  687. name = None
  688. namespaceURI = None
  689. def __init__(self, sw, message=None):
  690. '''Initialize.
  691. sw -- SoapWriter
  692. '''
  693. self._indx = 0
  694. MessageInterface.__init__(self, sw)
  695. Base.__init__(self)
  696. self._dom = DOM
  697. self.node = None
  698. if type(message) in (bytes, str):
  699. self.loadFromString(message)
  700. elif isinstance(message, ElementProxy):
  701. self.node = message._getNode()
  702. else:
  703. self.node = message
  704. self.processorNss = self.standard_ns.copy()
  705. self.processorNss.update(self.reserved_ns)
  706. def __str__(self):
  707. return self.toString()
  708. def evaluate(self, expression, processorNss=None):
  709. '''expression -- XPath compiled expression
  710. '''
  711. from Ft.Xml import XPath
  712. if not processorNss:
  713. context = XPath.Context.Context(self.node,
  714. processorNss=self.processorNss)
  715. else:
  716. context = XPath.Context.Context(self.node,
  717. processorNss=processorNss)
  718. nodes = expression.evaluate(context)
  719. return [ElementProxy(self.sw, node) for node in nodes]
  720. #############################################
  721. # Methods for checking/setting the
  722. # classes (namespaceURI,name) node.
  723. #############################################
  724. def checkNode(self, namespaceURI=None, localName=None):
  725. '''
  726. namespaceURI -- namespace of element
  727. localName -- local name of element
  728. '''
  729. namespaceURI = namespaceURI or self.namespaceURI
  730. localName = localName or self.name
  731. check = False
  732. if localName and self.node:
  733. check = self._dom.isElement(self.node, localName, namespaceURI)
  734. if not check:
  735. raise NamespaceError('unexpected node type %s, expecting %s'
  736. % (self.node, localName))
  737. def setNode(self, node=None):
  738. if node:
  739. if isinstance(node, ElementProxy):
  740. self.node = node._getNode()
  741. else:
  742. self.node = node
  743. elif self.node:
  744. node = self._dom.getElement(self.node, self.name,
  745. self.namespaceURI, default=None)
  746. if not node:
  747. raise NamespaceError('cant find element (%s, %s)' %
  748. (self.namespaceURI, self.name))
  749. self.node = node
  750. else:
  751. self.createDocument(self.namespaceURI, localName=self.name,
  752. doctype=None)
  753. self.checkNode()
  754. #############################################
  755. # Wrapper Methods for direct DOM Element Node access
  756. #############################################
  757. def _getNode(self):
  758. return self.node
  759. def _getElements(self):
  760. return self._dom.getElements(self.node, name=None)
  761. def _getOwnerDocument(self):
  762. return self.node.ownerDocument or self.node
  763. def _getUniquePrefix(self):
  764. '''I guess we need to resolve all potential prefixes
  765. because when the current node is attached it copies the
  766. namespaces into the parent node.
  767. '''
  768. while 1:
  769. self._indx += 1
  770. prefix = 'ns%d' % self._indx
  771. try:
  772. self._dom.findNamespaceURI(prefix, self._getNode())
  773. except DOMException:
  774. break
  775. return prefix
  776. def _getPrefix(self, node, nsuri):
  777. '''
  778. Keyword arguments:
  779. node -- DOM Element Node
  780. nsuri -- namespace of attribute value
  781. '''
  782. try:
  783. if node and (node.nodeType == node.ELEMENT_NODE) and \
  784. (nsuri == self._dom.findDefaultNS(node)):
  785. return None
  786. except DOMException:
  787. pass
  788. if nsuri == XMLNS.XML:
  789. return self._xml_prefix
  790. if node.nodeType == Node.ELEMENT_NODE:
  791. for attr in list(node.attributes.values()):
  792. if attr.namespaceURI == XMLNS.BASE \
  793. and nsuri == attr.value:
  794. return attr.localName
  795. else:
  796. if node.parentNode:
  797. return self._getPrefix(node.parentNode, nsuri)
  798. raise NamespaceError('namespaceURI "%s" is not defined' % nsuri)
  799. def _appendChild(self, node):
  800. '''
  801. Keyword arguments:
  802. node -- DOM Element Node
  803. '''
  804. if node is None:
  805. raise TypeError('node is None')
  806. self.node.appendChild(node)
  807. def _insertBefore(self, newChild, refChild):
  808. '''
  809. Keyword arguments:
  810. child -- DOM Element Node to insert
  811. refChild -- DOM Element Node
  812. '''
  813. self.node.insertBefore(newChild, refChild)
  814. def _setAttributeNS(self, namespaceURI, qualifiedName, value):
  815. '''
  816. Keyword arguments:
  817. namespaceURI -- namespace of attribute
  818. qualifiedName -- qualified name of new attribute value
  819. value -- value of attribute
  820. '''
  821. self.node.setAttributeNS(namespaceURI, qualifiedName, value)
  822. #############################################
  823. # General Methods
  824. #############################################
  825. def isFault(self):
  826. '''check to see if this is a soap:fault message.
  827. '''
  828. return False
  829. def getPrefix(self, namespaceURI):
  830. try:
  831. prefix = self._getPrefix(node=self.node, nsuri=namespaceURI)
  832. except NamespaceError:
  833. prefix = self._getUniquePrefix()
  834. self.setNamespaceAttribute(prefix, namespaceURI)
  835. return prefix
  836. def getDocument(self):
  837. return self._getOwnerDocument()
  838. def setDocument(self, document):
  839. self.node = document
  840. def importFromString(self, xmlString):
  841. doc = self._dom.loadDocument(StringIO(xmlString))
  842. node = self._dom.getElement(doc, name=None)
  843. clone = self.importNode(node)
  844. self._appendChild(clone)
  845. def importNode(self, node):
  846. if isinstance(node, ElementProxy):
  847. node = node._getNode()
  848. return self._dom.importNode(self._getOwnerDocument(), node, deep=1)
  849. def loadFromString(self, data):
  850. self.node = self._dom.loadDocument(StringIO(data))
  851. def canonicalize(self):
  852. return Canonicalize(self.node)
  853. def toString(self):
  854. return self.canonicalize()
  855. def createDocument(self, namespaceURI, localName, doctype=None):
  856. '''If specified must be a SOAP envelope, else may contruct an empty
  857. document.
  858. '''
  859. prefix = self._soap_env_prefix
  860. if namespaceURI == self.reserved_ns[prefix]:
  861. qualifiedName = '%s:%s' % (prefix, localName)
  862. elif namespaceURI is localName is None:
  863. self.node = self._dom.createDocument(None, None, None)
  864. return
  865. else:
  866. raise KeyError('only support creation of document in %s' %
  867. self.reserved_ns[prefix])
  868. document = self._dom.createDocument(nsuri=namespaceURI,
  869. qname=qualifiedName,
  870. doctype=doctype)
  871. self.node = document.childNodes[0]
  872. # set up reserved namespace attributes
  873. for prefix, nsuri in list(self.reserved_ns.items()):
  874. self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
  875. qualifiedName='%s:%s' % (self._xmlns_prefix,
  876. prefix),
  877. value=nsuri)
  878. #############################################
  879. # Methods for attributes
  880. #############################################
  881. def hasAttribute(self, namespaceURI, localName):
  882. return self._dom.hasAttr(self._getNode(), name=localName,
  883. nsuri=namespaceURI)
  884. def setAttributeType(self, namespaceURI, localName):
  885. '''set xsi:type
  886. Keyword arguments:
  887. namespaceURI -- namespace of attribute value
  888. localName -- name of new attribute value
  889. '''
  890. self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName)
  891. value = localName
  892. if namespaceURI:
  893. value = '%s:%s' % (self.getPrefix(namespaceURI), localName)
  894. xsi_prefix = self.getPrefix(self._xsi_nsuri)
  895. self._setAttributeNS(self._xsi_nsuri, '%s:type' % xsi_prefix, value)
  896. def createAttributeNS(self, namespace, name, value):
  897. document = self._getOwnerDocument()
  898. # this function doesn't exist!! it has only two arguments
  899. document.createAttributeNS(namespace, name, value)
  900. def setAttributeNS(self, namespaceURI, localName, value):
  901. '''
  902. Keyword arguments:
  903. namespaceURI -- namespace of attribute to create, None is for
  904. attributes in no namespace.
  905. localName -- local name of new attribute
  906. value -- value of new attribute
  907. '''
  908. prefix = None
  909. if namespaceURI:
  910. try:
  911. prefix = self.getPrefix(namespaceURI)
  912. except KeyError:
  913. prefix = 'ns2'
  914. self.setNamespaceAttribute(prefix, namespaceURI)
  915. qualifiedName = localName
  916. if prefix:
  917. qualifiedName = '%s:%s' % (prefix, localName)
  918. self._setAttributeNS(namespaceURI, qualifiedName, value)
  919. def setNamespaceAttribute(self, prefix, namespaceURI):
  920. '''
  921. Keyword arguments:
  922. prefix -- xmlns prefix
  923. namespaceURI -- value of prefix
  924. '''
  925. self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' % prefix, namespaceURI)
  926. #############################################
  927. # Methods for elements
  928. #############################################
  929. def createElementNS(self, namespace, qname):
  930. '''
  931. Keyword arguments:
  932. namespace -- namespace of element to create
  933. qname -- qualified name of new element
  934. '''
  935. document = self._getOwnerDocument()
  936. node = document.createElementNS(namespace, qname)
  937. return ElementProxy(self.sw, node)
  938. def createAppendSetElement(self, namespaceURI, localName, prefix=None):
  939. '''Create a new element (namespaceURI,name), append it
  940. to current node, then set it to be the current node.
  941. Keyword arguments:
  942. namespaceURI -- namespace of element to create
  943. localName -- local name of new element
  944. prefix -- if namespaceURI is not defined, declare prefix. defaults
  945. to 'ns1' if left unspecified.
  946. '''
  947. node = self.createAppendElement(namespaceURI, localName, prefix=None)
  948. node = node._getNode()
  949. self._setNode(node._getNode())
  950. def createAppendElement(self, namespaceURI, localName, prefix=None):
  951. '''Create a new element (namespaceURI,name), append it
  952. to current node, and return the newly created node.
  953. Keyword arguments:
  954. namespaceURI -- namespace of element to create
  955. localName -- local name of new element
  956. prefix -- if namespaceURI is not defined, declare prefix. defaults
  957. to 'ns1' if left unspecified.
  958. '''
  959. declare = False
  960. qualifiedName = localName
  961. if namespaceURI:
  962. try:
  963. prefix = self.getPrefix(namespaceURI)
  964. except:
  965. declare = True
  966. prefix = prefix or self._getUniquePrefix()
  967. if prefix:
  968. qualifiedName = '%s:%s' % (prefix, localName)
  969. node = self.createElementNS(namespaceURI, qualifiedName)
  970. if declare:
  971. node._setAttributeNS(XMLNS.BASE, 'xmlns:%s' % prefix, namespaceURI)
  972. self._appendChild(node=node._getNode())
  973. return node
  974. def createInsertBefore(self, namespaceURI, localName, refChild):
  975. qualifiedName = localName
  976. prefix = self.getPrefix(namespaceURI)
  977. if prefix:
  978. qualifiedName = '%s:%s' % (prefix, localName)
  979. node = self.createElementNS(namespaceURI, qualifiedName)
  980. self._insertBefore(newChild=node._getNode(),
  981. refChild=refChild._getNode())
  982. return node
  983. def getElement(self, namespaceURI, localName):
  984. '''
  985. Keyword arguments:
  986. namespaceURI -- namespace of element
  987. localName -- local name of element
  988. '''
  989. node = self._dom.getElement(self.node, localName, namespaceURI,
  990. default=None)
  991. if node:
  992. return ElementProxy(self.sw, node)
  993. return None
  994. def getAttributeValue(self, namespaceURI, localName):
  995. '''
  996. Keyword arguments:
  997. namespaceURI -- namespace of attribute
  998. localName -- local name of attribute
  999. '''
  1000. if self.hasAttribute(namespaceURI, localName):
  1001. attr = self.node.getAttributeNodeNS(namespaceURI, localName)
  1002. return attr.value
  1003. return None
  1004. def getValue(self):
  1005. return self._dom.getElementText(self.node, preserve_ws=True)
  1006. #############################################
  1007. # Methods for text nodes
  1008. #############################################
  1009. def createAppendTextNode(self, pyobj):
  1010. node = self.createTextNode(pyobj)
  1011. self._appendChild(node=node._getNode())
  1012. return node
  1013. def createTextNode(self, pyobj):
  1014. document = self._getOwnerDocument()
  1015. node = document.createTextNode(pyobj)
  1016. return ElementProxy(self.sw, node)
  1017. #############################################
  1018. # Methods for retrieving namespaceURI's
  1019. #############################################
  1020. def findNamespaceURI(self, qualifiedName):
  1021. parts = SplitQName(qualifiedName)
  1022. element = self._getNode()
  1023. if len(parts) == 1:
  1024. return (self._dom.findTargetNS(element), None)
  1025. return self._dom.findNamespaceURI(parts[0], element)
  1026. def resolvePrefix(self, prefix):
  1027. element = self._getNode()
  1028. return self._dom.findNamespaceURI(prefix, element)
  1029. def getSOAPEnvURI(self):
  1030. return self._soap_env_nsuri
  1031. def isEmpty(self):
  1032. return not self.node
  1033. class Collection(UserDict):
  1034. """Helper class for maintaining ordered named collections."""
  1035. default = lambda self, k: k.name
  1036. def __init__(self, parent, key=None):
  1037. UserDict.__init__(self)
  1038. self.parent = weakref.ref(parent)
  1039. self.list = []
  1040. self._func = key or self.default
  1041. def __getitem__(self, key):
  1042. NumberTypes = six.integer_types
  1043. NumberTypes = NumberTypes + (type(float), type(complex))
  1044. if isinstance(key, NumberTypes):
  1045. return self.list[key]
  1046. return self.data[key]
  1047. def __setitem__(self, key, item):
  1048. item.parent = weakref.ref(self)
  1049. self.list.append(item)
  1050. self.data[key] = item
  1051. def keys(self):
  1052. return [self._func(i) for i in self.list]
  1053. def items(self):
  1054. return [(self._func(i), i) for i in self.list]
  1055. def values(self):
  1056. return self.list
  1057. class CollectionNS(UserDict):
  1058. """Helper class for maintaining ordered named collections."""
  1059. default = lambda self, k: k.name
  1060. def __init__(self, parent, key=None):
  1061. UserDict.__init__(self)
  1062. self.parent = weakref.ref(parent)
  1063. self.targetNamespace = None
  1064. self.list = []
  1065. self._func = key or self.default
  1066. def __getitem__(self, key):
  1067. self.targetNamespace = self.parent().targetNamespace
  1068. if isinstance(key, six.integer_types):
  1069. return self.list[key]
  1070. elif self.__isSequence(key):
  1071. nsuri, name = key
  1072. return self.data[nsuri][name]
  1073. return self.data[self.parent().targetNamespace][key]
  1074. def __setitem__(self, key, item):
  1075. item.parent = weakref.ref(self)
  1076. self.list.append(item)
  1077. targetNamespace = getattr(item, 'targetNamespace',
  1078. self.parent().targetNamespace)
  1079. if targetNamespace not in self.data:
  1080. self.data[targetNamespace] = {}
  1081. self.data[targetNamespace][key] = item
  1082. def __isSequence(self, key):
  1083. return (isinstance(key, (tuple, list))
  1084. and len(key) == 2)
  1085. def keys(self):
  1086. keys = []
  1087. for tns in list(self.data.keys()):
  1088. keys.append([(tns, self._func(i)) for i in list(self.data[tns].values())])
  1089. return keys
  1090. def items(self):
  1091. return [(self._func(i), i) for i in self.list]
  1092. def values(self):
  1093. return self.list
  1094. # This is a runtime guerilla patch for pulldom (used by minidom) so
  1095. # that xml namespace declaration attributes are not lost in parsing.
  1096. # We need them to do correct QName linking for XML Schema and WSDL.
  1097. # The patch has been submitted to SF for the next Python version.
  1098. from xml.dom.pulldom import PullDOM, START_ELEMENT
  1099. if 1:
  1100. def startPrefixMapping(self, prefix, uri):
  1101. if not hasattr(self, '_xmlns_attrs'):
  1102. self._xmlns_attrs = []
  1103. self._xmlns_attrs.append((prefix or 'xmlns', uri))
  1104. self._ns_contexts.append(self._current_context.copy())
  1105. self._current_context[uri] = prefix or ''
  1106. PullDOM.startPrefixMapping = startPrefixMapping
  1107. def startElementNS(self, name, tagName, attrs):
  1108. # Retrieve xml namespace declaration attributes.
  1109. xmlns_uri = 'http://www.w3.org/2000/xmlns/'
  1110. xmlns_attrs = getattr(self, '_xmlns_attrs', None)
  1111. if xmlns_attrs is not None:
  1112. for aname, value in xmlns_attrs:
  1113. attrs._attrs[(xmlns_uri, aname)] = value
  1114. self._xmlns_attrs = []
  1115. uri, localname = name
  1116. if uri:
  1117. # When using namespaces, the reader may or may not
  1118. # provide us with the original name. If not, create
  1119. # *a* valid tagName from the current context.
  1120. if tagName is None:
  1121. prefix = self._current_context[uri]
  1122. if prefix:
  1123. tagName = prefix + ":" + localname
  1124. else:
  1125. tagName = localname
  1126. if self.document:
  1127. node = self.document.createElementNS(uri, tagName)
  1128. else:
  1129. node = self.buildDocument(uri, tagName)
  1130. else:
  1131. # When the tagname is not prefixed, it just appears as
  1132. # localname
  1133. if self.document:
  1134. node = self.document.createElement(localname)
  1135. else:
  1136. node = self.buildDocument(None, localname)
  1137. for aname, value in list(attrs.items()):
  1138. a_uri, a_localname = aname
  1139. if a_uri == xmlns_uri:
  1140. if a_localname == 'xmlns':
  1141. qname = a_localname
  1142. else:
  1143. qname = 'xmlns:' + a_localname
  1144. attr = self.document.createAttributeNS(a_uri, qname)
  1145. node.setAttributeNodeNS(attr)
  1146. elif a_uri:
  1147. prefix = self._current_context[a_uri]
  1148. if prefix:
  1149. qname = prefix + ":" + a_localname
  1150. else:
  1151. qname = a_localname
  1152. attr = self.document.createAttributeNS(a_uri, qname)
  1153. node.setAttributeNodeNS(attr)
  1154. else:
  1155. attr = self.document.createAttribute(a_localname)
  1156. node.setAttributeNode(attr)
  1157. attr.value = value
  1158. self.lastEvent[1] = [(START_ELEMENT, node), None]
  1159. self.lastEvent = self.lastEvent[1]
  1160. self.push(node)
  1161. PullDOM.startElementNS = startElementNS
  1162. #
  1163. # This is a runtime guerilla patch for minidom so
  1164. # that xmlns prefixed attributes dont raise AttributeErrors
  1165. # during cloning.
  1166. #
  1167. # Namespace declarations can appear in any start-tag, must look for xmlns
  1168. # prefixed attribute names during cloning.
  1169. #
  1170. # key (attr.namespaceURI, tag)
  1171. # ('http://www.w3.org/2000/xmlns/', u'xsd')
  1172. # <xml.dom.minidom.Attr instance at 0x82227c4>
  1173. # ('http://www.w3.org/2000/xmlns/', 'xmlns')
  1174. # <xml.dom.minidom.Attr instance at 0x8414b3c>
  1175. #
  1176. # xml.dom.minidom.Attr.nodeName = xmlns:xsd
  1177. # xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
  1178. if 1:
  1179. def _clone_node(node, deep, newOwnerDocument):
  1180. """
  1181. Clone a node and give it the new owner document.
  1182. Called by Node.cloneNode and Document.importNode
  1183. """
  1184. if node.ownerDocument.isSameNode(newOwnerDocument):
  1185. operation = xml.dom.UserDataHandler.NODE_CLONED
  1186. else:
  1187. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1188. if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
  1189. clone = newOwnerDocument.createElementNS(node.namespaceURI,
  1190. node.nodeName)
  1191. for attr in list(node.attributes.values()):
  1192. clone.setAttributeNS(attr.namespaceURI, attr.nodeName,
  1193. attr.value)
  1194. prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
  1195. if prefix == 'xmlns':
  1196. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1197. elif prefix:
  1198. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1199. else:
  1200. a = clone.getAttributeNodeNS(attr.namespaceURI,
  1201. attr.nodeName)
  1202. a.specified = attr.specified
  1203. if deep:
  1204. for child in node.childNodes:
  1205. c = xml.dom.minidom._clone_node(child, deep,
  1206. newOwnerDocument)
  1207. clone.appendChild(c)
  1208. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
  1209. clone = newOwnerDocument.createDocumentFragment()
  1210. if deep:
  1211. for child in node.childNodes:
  1212. c = xml.dom.minidom._clone_node(child, deep,
  1213. newOwnerDocument)
  1214. clone.appendChild(c)
  1215. elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
  1216. clone = newOwnerDocument.createTextNode(node.data)
  1217. elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
  1218. clone = newOwnerDocument.createCDATASection(node.data)
  1219. elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
  1220. clone = newOwnerDocument.createProcessingInstruction(node.target,
  1221. node.data)
  1222. elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
  1223. clone = newOwnerDocument.createComment(node.data)
  1224. elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
  1225. clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
  1226. node.nodeName)
  1227. clone.specified = True
  1228. clone.value = node.value
  1229. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
  1230. assert node.ownerDocument is not newOwnerDocument
  1231. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1232. clone = newOwnerDocument.implementation.createDocumentType(
  1233. node.name, node.publicId, node.systemId)
  1234. clone.ownerDocument = newOwnerDocument
  1235. if deep:
  1236. clone.entities._seq = []
  1237. clone.notations._seq = []
  1238. for n in node.notations._seq:
  1239. notation = xml.dom.minidom.Notation(n.nodeName, n.publicId,
  1240. n.systemId)
  1241. notation.ownerDocument = newOwnerDocument
  1242. clone.notations._seq.append(notation)
  1243. if hasattr(n, '_call_user_data_handler'):
  1244. n._call_user_data_handler(operation, n, notation)
  1245. for e in node.entities._seq:
  1246. entity = xml.dom.minidom.Entity(e.nodeName, e.publicId,
  1247. e.systemId,
  1248. e.notationName)
  1249. entity.actualEncoding = e.actualEncoding
  1250. entity.encoding = e.encoding
  1251. entity.version = e.version
  1252. entity.ownerDocument = newOwnerDocument
  1253. clone.entities._seq.append(entity)
  1254. if hasattr(e, '_call_user_data_handler'):
  1255. e._call_user_data_handler(operation, n, entity)
  1256. else:
  1257. # Note the cloning of Document and DocumentType nodes is
  1258. # implemenetation specific. minidom handles those cases
  1259. # directly in the cloneNode() methods.
  1260. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
  1261. # Check for _call_user_data_handler() since this could conceivably
  1262. # used with other DOM implementations (one of the FourThought
  1263. # DOMs, perhaps?).
  1264. if hasattr(node, '_call_user_data_handler'):
  1265. node._call_user_data_handler(operation, node, clone)
  1266. return clone
  1267. xml.dom.minidom._clone_node = _clone_node