xmlrpc.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. # -*- test-case-name: twisted.web.test.test_xmlrpc -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. A generic resource for publishing objects via XML-RPC.
  6. Maintainer: Itamar Shtull-Trauring
  7. @var Fault: See L{xmlrpclib.Fault}
  8. @type Fault: L{xmlrpclib.Fault}
  9. """
  10. from __future__ import division, absolute_import
  11. from twisted.python.compat import _PY3, intToBytes, nativeString, urllib_parse
  12. from twisted.python.compat import unicode
  13. # System Imports
  14. import base64
  15. if _PY3:
  16. import xmlrpc.client as xmlrpclib
  17. else:
  18. import xmlrpclib
  19. # Sibling Imports
  20. from twisted.web import resource, server, http
  21. from twisted.internet import defer, protocol, reactor
  22. from twisted.python import log, reflect, failure
  23. # These are deprecated, use the class level definitions
  24. NOT_FOUND = 8001
  25. FAILURE = 8002
  26. # Useful so people don't need to import xmlrpclib directly
  27. Fault = xmlrpclib.Fault
  28. Binary = xmlrpclib.Binary
  29. Boolean = xmlrpclib.Boolean
  30. DateTime = xmlrpclib.DateTime
  31. def withRequest(f):
  32. """
  33. Decorator to cause the request to be passed as the first argument
  34. to the method.
  35. If an I{xmlrpc_} method is wrapped with C{withRequest}, the
  36. request object is passed as the first argument to that method.
  37. For example::
  38. @withRequest
  39. def xmlrpc_echo(self, request, s):
  40. return s
  41. @since: 10.2
  42. """
  43. f.withRequest = True
  44. return f
  45. class NoSuchFunction(Fault):
  46. """
  47. There is no function by the given name.
  48. """
  49. class Handler:
  50. """
  51. Handle a XML-RPC request and store the state for a request in progress.
  52. Override the run() method and return result using self.result,
  53. a Deferred.
  54. We require this class since we're not using threads, so we can't
  55. encapsulate state in a running function if we're going to have
  56. to wait for results.
  57. For example, lets say we want to authenticate against twisted.cred,
  58. run a LDAP query and then pass its result to a database query, all
  59. as a result of a single XML-RPC command. We'd use a Handler instance
  60. to store the state of the running command.
  61. """
  62. def __init__(self, resource, *args):
  63. self.resource = resource # the XML-RPC resource we are connected to
  64. self.result = defer.Deferred()
  65. self.run(*args)
  66. def run(self, *args):
  67. # event driven equivalent of 'raise UnimplementedError'
  68. self.result.errback(
  69. NotImplementedError("Implement run() in subclasses"))
  70. class XMLRPC(resource.Resource):
  71. """
  72. A resource that implements XML-RPC.
  73. You probably want to connect this to '/RPC2'.
  74. Methods published can return XML-RPC serializable results, Faults,
  75. Binary, Boolean, DateTime, Deferreds, or Handler instances.
  76. By default methods beginning with 'xmlrpc_' are published.
  77. Sub-handlers for prefixed methods (e.g., system.listMethods)
  78. can be added with putSubHandler. By default, prefixes are
  79. separated with a '.'. Override self.separator to change this.
  80. @ivar allowNone: Permit XML translating of Python constant None.
  81. @type allowNone: C{bool}
  82. @ivar useDateTime: Present C{datetime} values as C{datetime.datetime}
  83. objects?
  84. @type useDateTime: C{bool}
  85. """
  86. # Error codes for Twisted, if they conflict with yours then
  87. # modify them at runtime.
  88. NOT_FOUND = 8001
  89. FAILURE = 8002
  90. isLeaf = 1
  91. separator = '.'
  92. allowedMethods = (b'POST',)
  93. def __init__(self, allowNone=False, useDateTime=False):
  94. resource.Resource.__init__(self)
  95. self.subHandlers = {}
  96. self.allowNone = allowNone
  97. self.useDateTime = useDateTime
  98. def __setattr__(self, name, value):
  99. self.__dict__[name] = value
  100. def putSubHandler(self, prefix, handler):
  101. self.subHandlers[prefix] = handler
  102. def getSubHandler(self, prefix):
  103. return self.subHandlers.get(prefix, None)
  104. def getSubHandlerPrefixes(self):
  105. return list(self.subHandlers.keys())
  106. def render_POST(self, request):
  107. request.content.seek(0, 0)
  108. request.setHeader(b"content-type", b"text/xml; charset=utf-8")
  109. try:
  110. args, functionPath = xmlrpclib.loads(request.content.read(),
  111. use_datetime=self.useDateTime)
  112. except Exception as e:
  113. f = Fault(self.FAILURE, "Can't deserialize input: %s" % (e,))
  114. self._cbRender(f, request)
  115. else:
  116. try:
  117. function = self.lookupProcedure(functionPath)
  118. except Fault as f:
  119. self._cbRender(f, request)
  120. else:
  121. # Use this list to track whether the response has failed or not.
  122. # This will be used later on to decide if the result of the
  123. # Deferred should be written out and Request.finish called.
  124. responseFailed = []
  125. request.notifyFinish().addErrback(responseFailed.append)
  126. if getattr(function, 'withRequest', False):
  127. d = defer.maybeDeferred(function, request, *args)
  128. else:
  129. d = defer.maybeDeferred(function, *args)
  130. d.addErrback(self._ebRender)
  131. d.addCallback(self._cbRender, request, responseFailed)
  132. return server.NOT_DONE_YET
  133. def _cbRender(self, result, request, responseFailed=None):
  134. if responseFailed:
  135. return
  136. if isinstance(result, Handler):
  137. result = result.result
  138. if not isinstance(result, Fault):
  139. result = (result,)
  140. try:
  141. try:
  142. content = xmlrpclib.dumps(
  143. result, methodresponse=True,
  144. allow_none=self.allowNone)
  145. except Exception as e:
  146. f = Fault(self.FAILURE, "Can't serialize output: %s" % (e,))
  147. content = xmlrpclib.dumps(f, methodresponse=True,
  148. allow_none=self.allowNone)
  149. if isinstance(content, unicode):
  150. content = content.encode('utf8')
  151. request.setHeader(
  152. b"content-length", intToBytes(len(content)))
  153. request.write(content)
  154. except:
  155. log.err()
  156. request.finish()
  157. def _ebRender(self, failure):
  158. if isinstance(failure.value, Fault):
  159. return failure.value
  160. log.err(failure)
  161. return Fault(self.FAILURE, "error")
  162. def lookupProcedure(self, procedurePath):
  163. """
  164. Given a string naming a procedure, return a callable object for that
  165. procedure or raise NoSuchFunction.
  166. The returned object will be called, and should return the result of the
  167. procedure, a Deferred, or a Fault instance.
  168. Override in subclasses if you want your own policy. The base
  169. implementation that given C{'foo'}, C{self.xmlrpc_foo} will be returned.
  170. If C{procedurePath} contains C{self.separator}, the sub-handler for the
  171. initial prefix is used to search for the remaining path.
  172. If you override C{lookupProcedure}, you may also want to override
  173. C{listProcedures} to accurately report the procedures supported by your
  174. resource, so that clients using the I{system.listMethods} procedure
  175. receive accurate results.
  176. @since: 11.1
  177. """
  178. if procedurePath.find(self.separator) != -1:
  179. prefix, procedurePath = procedurePath.split(self.separator, 1)
  180. handler = self.getSubHandler(prefix)
  181. if handler is None:
  182. raise NoSuchFunction(self.NOT_FOUND,
  183. "no such subHandler %s" % prefix)
  184. return handler.lookupProcedure(procedurePath)
  185. f = getattr(self, "xmlrpc_%s" % procedurePath, None)
  186. if not f:
  187. raise NoSuchFunction(self.NOT_FOUND,
  188. "procedure %s not found" % procedurePath)
  189. elif not callable(f):
  190. raise NoSuchFunction(self.NOT_FOUND,
  191. "procedure %s not callable" % procedurePath)
  192. else:
  193. return f
  194. def listProcedures(self):
  195. """
  196. Return a list of the names of all xmlrpc procedures.
  197. @since: 11.1
  198. """
  199. return reflect.prefixedMethodNames(self.__class__, 'xmlrpc_')
  200. class XMLRPCIntrospection(XMLRPC):
  201. """
  202. Implement the XML-RPC Introspection API.
  203. By default, the methodHelp method returns the 'help' method attribute,
  204. if it exists, otherwise the __doc__ method attribute, if it exists,
  205. otherwise the empty string.
  206. To enable the methodSignature method, add a 'signature' method attribute
  207. containing a list of lists. See methodSignature's documentation for the
  208. format. Note the type strings should be XML-RPC types, not Python types.
  209. """
  210. def __init__(self, parent):
  211. """
  212. Implement Introspection support for an XMLRPC server.
  213. @param parent: the XMLRPC server to add Introspection support to.
  214. @type parent: L{XMLRPC}
  215. """
  216. XMLRPC.__init__(self)
  217. self._xmlrpc_parent = parent
  218. def xmlrpc_listMethods(self):
  219. """
  220. Return a list of the method names implemented by this server.
  221. """
  222. functions = []
  223. todo = [(self._xmlrpc_parent, '')]
  224. while todo:
  225. obj, prefix = todo.pop(0)
  226. functions.extend([prefix + name for name in obj.listProcedures()])
  227. todo.extend([ (obj.getSubHandler(name),
  228. prefix + name + obj.separator)
  229. for name in obj.getSubHandlerPrefixes() ])
  230. return functions
  231. xmlrpc_listMethods.signature = [['array']]
  232. def xmlrpc_methodHelp(self, method):
  233. """
  234. Return a documentation string describing the use of the given method.
  235. """
  236. method = self._xmlrpc_parent.lookupProcedure(method)
  237. return (getattr(method, 'help', None)
  238. or getattr(method, '__doc__', None) or '')
  239. xmlrpc_methodHelp.signature = [['string', 'string']]
  240. def xmlrpc_methodSignature(self, method):
  241. """
  242. Return a list of type signatures.
  243. Each type signature is a list of the form [rtype, type1, type2, ...]
  244. where rtype is the return type and typeN is the type of the Nth
  245. argument. If no signature information is available, the empty
  246. string is returned.
  247. """
  248. method = self._xmlrpc_parent.lookupProcedure(method)
  249. return getattr(method, 'signature', None) or ''
  250. xmlrpc_methodSignature.signature = [['array', 'string'],
  251. ['string', 'string']]
  252. def addIntrospection(xmlrpc):
  253. """
  254. Add Introspection support to an XMLRPC server.
  255. @param parent: the XMLRPC server to add Introspection support to.
  256. @type parent: L{XMLRPC}
  257. """
  258. xmlrpc.putSubHandler('system', XMLRPCIntrospection(xmlrpc))
  259. class QueryProtocol(http.HTTPClient):
  260. def connectionMade(self):
  261. self._response = None
  262. self.sendCommand(b'POST', self.factory.path)
  263. self.sendHeader(b'User-Agent', b'Twisted/XMLRPClib')
  264. self.sendHeader(b'Host', self.factory.host)
  265. self.sendHeader(b'Content-type', b'text/xml; charset=utf-8')
  266. payload = self.factory.payload
  267. self.sendHeader(b'Content-length', intToBytes(len(payload)))
  268. if self.factory.user:
  269. auth = b':'.join([self.factory.user, self.factory.password])
  270. authHeader = b''.join([b'Basic ', base64.b64encode(auth)])
  271. self.sendHeader(b'Authorization', authHeader)
  272. self.endHeaders()
  273. self.transport.write(payload)
  274. def handleStatus(self, version, status, message):
  275. if status != b'200':
  276. self.factory.badStatus(status, message)
  277. def handleResponse(self, contents):
  278. """
  279. Handle the XML-RPC response received from the server.
  280. Specifically, disconnect from the server and store the XML-RPC
  281. response so that it can be properly handled when the disconnect is
  282. finished.
  283. """
  284. self.transport.loseConnection()
  285. self._response = contents
  286. def connectionLost(self, reason):
  287. """
  288. The connection to the server has been lost.
  289. If we have a full response from the server, then parse it and fired a
  290. Deferred with the return value or C{Fault} that the server gave us.
  291. """
  292. http.HTTPClient.connectionLost(self, reason)
  293. if self._response is not None:
  294. response, self._response = self._response, None
  295. self.factory.parseResponse(response)
  296. payloadTemplate = """<?xml version="1.0"?>
  297. <methodCall>
  298. <methodName>%s</methodName>
  299. %s
  300. </methodCall>
  301. """
  302. class _QueryFactory(protocol.ClientFactory):
  303. """
  304. XML-RPC Client Factory
  305. @ivar path: The path portion of the URL to which to post method calls.
  306. @type path: L{bytes}
  307. @ivar host: The value to use for the Host HTTP header.
  308. @type host: L{bytes}
  309. @ivar user: The username with which to authenticate with the server
  310. when making calls.
  311. @type user: L{bytes} or L{None}
  312. @ivar password: The password with which to authenticate with the server
  313. when making calls.
  314. @type password: L{bytes} or L{None}
  315. @ivar useDateTime: Accept datetime values as datetime.datetime objects.
  316. also passed to the underlying xmlrpclib implementation. Defaults to
  317. C{False}.
  318. @type useDateTime: C{bool}
  319. """
  320. deferred = None
  321. protocol = QueryProtocol
  322. def __init__(self, path, host, method, user=None, password=None,
  323. allowNone=False, args=(), canceller=None, useDateTime=False):
  324. """
  325. @param method: The name of the method to call.
  326. @type method: C{str}
  327. @param allowNone: allow the use of None values in parameters. It's
  328. passed to the underlying xmlrpclib implementation. Defaults to
  329. C{False}.
  330. @type allowNone: C{bool} or L{None}
  331. @param args: the arguments to pass to the method.
  332. @type args: C{tuple}
  333. @param canceller: A 1-argument callable passed to the deferred as the
  334. canceller callback.
  335. @type canceller: callable or L{None}
  336. """
  337. self.path, self.host = path, host
  338. self.user, self.password = user, password
  339. self.payload = payloadTemplate % (method,
  340. xmlrpclib.dumps(args, allow_none=allowNone))
  341. if isinstance(self.payload, unicode):
  342. self.payload = self.payload.encode('utf8')
  343. self.deferred = defer.Deferred(canceller)
  344. self.useDateTime = useDateTime
  345. def parseResponse(self, contents):
  346. if not self.deferred:
  347. return
  348. try:
  349. response = xmlrpclib.loads(contents,
  350. use_datetime=self.useDateTime)[0][0]
  351. except:
  352. deferred, self.deferred = self.deferred, None
  353. deferred.errback(failure.Failure())
  354. else:
  355. deferred, self.deferred = self.deferred, None
  356. deferred.callback(response)
  357. def clientConnectionLost(self, _, reason):
  358. if self.deferred is not None:
  359. deferred, self.deferred = self.deferred, None
  360. deferred.errback(reason)
  361. clientConnectionFailed = clientConnectionLost
  362. def badStatus(self, status, message):
  363. deferred, self.deferred = self.deferred, None
  364. deferred.errback(ValueError(status, message))
  365. class Proxy:
  366. """
  367. A Proxy for making remote XML-RPC calls.
  368. Pass the URL of the remote XML-RPC server to the constructor.
  369. Use C{proxy.callRemote('foobar', *args)} to call remote method
  370. 'foobar' with *args.
  371. @ivar user: The username with which to authenticate with the server
  372. when making calls. If specified, overrides any username information
  373. embedded in C{url}. If not specified, a value may be taken from
  374. C{url} if present.
  375. @type user: L{bytes} or L{None}
  376. @ivar password: The password with which to authenticate with the server
  377. when making calls. If specified, overrides any password information
  378. embedded in C{url}. If not specified, a value may be taken from
  379. C{url} if present.
  380. @type password: L{bytes} or L{None}
  381. @ivar allowNone: allow the use of None values in parameters. It's
  382. passed to the underlying L{xmlrpclib} implementation. Defaults to
  383. C{False}.
  384. @type allowNone: C{bool} or L{None}
  385. @ivar useDateTime: Accept datetime values as datetime.datetime objects.
  386. also passed to the underlying L{xmlrpclib} implementation. Defaults to
  387. C{False}.
  388. @type useDateTime: C{bool}
  389. @ivar connectTimeout: Number of seconds to wait before assuming the
  390. connection has failed.
  391. @type connectTimeout: C{float}
  392. @ivar _reactor: The reactor used to create connections.
  393. @type _reactor: Object providing L{twisted.internet.interfaces.IReactorTCP}
  394. @ivar queryFactory: Object returning a factory for XML-RPC protocol. Mainly
  395. useful for tests.
  396. """
  397. queryFactory = _QueryFactory
  398. def __init__(self, url, user=None, password=None, allowNone=False,
  399. useDateTime=False, connectTimeout=30.0, reactor=reactor):
  400. """
  401. @param url: The URL to which to post method calls. Calls will be made
  402. over SSL if the scheme is HTTPS. If netloc contains username or
  403. password information, these will be used to authenticate, as long as
  404. the C{user} and C{password} arguments are not specified.
  405. @type url: L{bytes}
  406. """
  407. scheme, netloc, path, params, query, fragment = urllib_parse.urlparse(
  408. url)
  409. netlocParts = netloc.split(b'@')
  410. if len(netlocParts) == 2:
  411. userpass = netlocParts.pop(0).split(b':')
  412. self.user = userpass.pop(0)
  413. try:
  414. self.password = userpass.pop(0)
  415. except:
  416. self.password = None
  417. else:
  418. self.user = self.password = None
  419. hostport = netlocParts[0].split(b':')
  420. self.host = hostport.pop(0)
  421. try:
  422. self.port = int(hostport.pop(0))
  423. except:
  424. self.port = None
  425. self.path = path
  426. if self.path in [b'', None]:
  427. self.path = b'/'
  428. self.secure = (scheme == b'https')
  429. if user is not None:
  430. self.user = user
  431. if password is not None:
  432. self.password = password
  433. self.allowNone = allowNone
  434. self.useDateTime = useDateTime
  435. self.connectTimeout = connectTimeout
  436. self._reactor = reactor
  437. def callRemote(self, method, *args):
  438. """
  439. Call remote XML-RPC C{method} with given arguments.
  440. @return: a L{defer.Deferred} that will fire with the method response,
  441. or a failure if the method failed. Generally, the failure type will
  442. be L{Fault}, but you can also have an C{IndexError} on some buggy
  443. servers giving empty responses.
  444. If the deferred is cancelled before the request completes, the
  445. connection is closed and the deferred will fire with a
  446. L{defer.CancelledError}.
  447. """
  448. def cancel(d):
  449. factory.deferred = None
  450. connector.disconnect()
  451. factory = self.queryFactory(
  452. self.path, self.host, method, self.user,
  453. self.password, self.allowNone, args, cancel, self.useDateTime)
  454. if self.secure:
  455. from twisted.internet import ssl
  456. connector = self._reactor.connectSSL(
  457. nativeString(self.host), self.port or 443,
  458. factory, ssl.ClientContextFactory(),
  459. timeout=self.connectTimeout)
  460. else:
  461. connector = self._reactor.connectTCP(
  462. nativeString(self.host), self.port or 80, factory,
  463. timeout=self.connectTimeout)
  464. return factory.deferred
  465. __all__ = [
  466. "XMLRPC", "Handler", "NoSuchFunction", "Proxy",
  467. "Fault", "Binary", "Boolean", "DateTime"]