SimpleXMLRPCServer.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. """Simple XML-RPC Server.
  2. This module can be used to create simple XML-RPC servers
  3. by creating a server and either installing functions, a
  4. class instance, or by extending the SimpleXMLRPCServer
  5. class.
  6. It can also be used to handle XML-RPC requests in a CGI
  7. environment using CGIXMLRPCRequestHandler.
  8. A list of possible usage patterns follows:
  9. 1. Install functions:
  10. server = SimpleXMLRPCServer(("localhost", 8000))
  11. server.register_function(pow)
  12. server.register_function(lambda x,y: x+y, 'add')
  13. server.serve_forever()
  14. 2. Install an instance:
  15. class MyFuncs:
  16. def __init__(self):
  17. # make all of the string functions available through
  18. # string.func_name
  19. import string
  20. self.string = string
  21. def _listMethods(self):
  22. # implement this method so that system.listMethods
  23. # knows to advertise the strings methods
  24. return list_public_methods(self) + \
  25. ['string.' + method for method in list_public_methods(self.string)]
  26. def pow(self, x, y): return pow(x, y)
  27. def add(self, x, y) : return x + y
  28. server = SimpleXMLRPCServer(("localhost", 8000))
  29. server.register_introspection_functions()
  30. server.register_instance(MyFuncs())
  31. server.serve_forever()
  32. 3. Install an instance with custom dispatch method:
  33. class Math:
  34. def _listMethods(self):
  35. # this method must be present for system.listMethods
  36. # to work
  37. return ['add', 'pow']
  38. def _methodHelp(self, method):
  39. # this method must be present for system.methodHelp
  40. # to work
  41. if method == 'add':
  42. return "add(2,3) => 5"
  43. elif method == 'pow':
  44. return "pow(x, y[, z]) => number"
  45. else:
  46. # By convention, return empty
  47. # string if no help is available
  48. return ""
  49. def _dispatch(self, method, params):
  50. if method == 'pow':
  51. return pow(*params)
  52. elif method == 'add':
  53. return params[0] + params[1]
  54. else:
  55. raise 'bad method'
  56. server = SimpleXMLRPCServer(("localhost", 8000))
  57. server.register_introspection_functions()
  58. server.register_instance(Math())
  59. server.serve_forever()
  60. 4. Subclass SimpleXMLRPCServer:
  61. class MathServer(SimpleXMLRPCServer):
  62. def _dispatch(self, method, params):
  63. try:
  64. # We are forcing the 'export_' prefix on methods that are
  65. # callable through XML-RPC to prevent potential security
  66. # problems
  67. func = getattr(self, 'export_' + method)
  68. except AttributeError:
  69. raise Exception('method "%s" is not supported' % method)
  70. else:
  71. return func(*params)
  72. def export_add(self, x, y):
  73. return x + y
  74. server = MathServer(("localhost", 8000))
  75. server.serve_forever()
  76. 5. CGI script:
  77. server = CGIXMLRPCRequestHandler()
  78. server.register_function(pow)
  79. server.handle_request()
  80. """
  81. # Written by Brian Quinlan ([email protected]).
  82. # Based on code written by Fredrik Lundh.
  83. import xmlrpclib
  84. from xmlrpclib import Fault
  85. import SocketServer
  86. import BaseHTTPServer
  87. import sys
  88. import os
  89. def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
  90. """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
  91. Resolves a dotted attribute name to an object. Raises
  92. an AttributeError if any attribute in the chain starts with a '_'.
  93. If the optional allow_dotted_names argument is false, dots are not
  94. supported and this function operates similar to getattr(obj, attr).
  95. """
  96. if allow_dotted_names:
  97. attrs = attr.split('.')
  98. else:
  99. attrs = [attr]
  100. for i in attrs:
  101. if i.startswith('_'):
  102. raise AttributeError(
  103. 'attempt to access private attribute "%s"' % i
  104. )
  105. else:
  106. obj = getattr(obj,i)
  107. return obj
  108. def list_public_methods(obj):
  109. """Returns a list of attribute strings, found in the specified
  110. object, which represent callable attributes"""
  111. return [member for member in dir(obj)
  112. if not member.startswith('_') and
  113. callable(getattr(obj, member))]
  114. def remove_duplicates(lst):
  115. """remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
  116. Returns a copy of a list without duplicates. Every list
  117. item must be hashable and the order of the items in the
  118. resulting list is not defined.
  119. """
  120. u = {}
  121. for x in lst:
  122. u[x] = 1
  123. return u.keys()
  124. class SimpleXMLRPCDispatcher:
  125. """Mix-in class that dispatches XML-RPC requests.
  126. This class is used to register XML-RPC method handlers
  127. and then to dispatch them. There should never be any
  128. reason to instantiate this class directly.
  129. """
  130. def __init__(self):
  131. self.funcs = {}
  132. self.instance = None
  133. def register_instance(self, instance, allow_dotted_names=False):
  134. """Registers an instance to respond to XML-RPC requests.
  135. Only one instance can be installed at a time.
  136. If the registered instance has a _dispatch method then that
  137. method will be called with the name of the XML-RPC method and
  138. its parameters as a tuple
  139. e.g. instance._dispatch('add',(2,3))
  140. If the registered instance does not have a _dispatch method
  141. then the instance will be searched to find a matching method
  142. and, if found, will be called. Methods beginning with an '_'
  143. are considered private and will not be called by
  144. SimpleXMLRPCServer.
  145. If a registered function matches a XML-RPC request, then it
  146. will be called instead of the registered instance.
  147. If the optional allow_dotted_names argument is true and the
  148. instance does not have a _dispatch method, method names
  149. containing dots are supported and resolved, as long as none of
  150. the name segments start with an '_'.
  151. *** SECURITY WARNING: ***
  152. Enabling the allow_dotted_names options allows intruders
  153. to access your module's global variables and may allow
  154. intruders to execute arbitrary code on your machine. Only
  155. use this option on a secure, closed network.
  156. """
  157. self.instance = instance
  158. self.allow_dotted_names = allow_dotted_names
  159. def register_function(self, function, name = None):
  160. """Registers a function to respond to XML-RPC requests.
  161. The optional name argument can be used to set a Unicode name
  162. for the function.
  163. """
  164. if name is None:
  165. name = function.__name__
  166. self.funcs[name] = function
  167. def register_introspection_functions(self):
  168. """Registers the XML-RPC introspection methods in the system
  169. namespace.
  170. see http://xmlrpc.usefulinc.com/doc/reserved.html
  171. """
  172. self.funcs.update({'system.listMethods' : self.system_listMethods,
  173. 'system.methodSignature' : self.system_methodSignature,
  174. 'system.methodHelp' : self.system_methodHelp})
  175. def register_multicall_functions(self):
  176. """Registers the XML-RPC multicall method in the system
  177. namespace.
  178. see http://www.xmlrpc.com/discuss/msgReader$1208"""
  179. self.funcs.update({'system.multicall' : self.system_multicall})
  180. def _marshaled_dispatch(self, data, dispatch_method = None):
  181. """Dispatches an XML-RPC method from marshalled (XML) data.
  182. XML-RPC methods are dispatched from the marshalled (XML) data
  183. using the _dispatch method and the result is returned as
  184. marshalled data. For backwards compatibility, a dispatch
  185. function can be provided as an argument (see comment in
  186. SimpleXMLRPCRequestHandler.do_POST) but overriding the
  187. existing method through subclassing is the prefered means
  188. of changing method dispatch behavior.
  189. """
  190. params, method = xmlrpclib.loads(data)
  191. # generate response
  192. try:
  193. if dispatch_method is not None:
  194. response = dispatch_method(method, params)
  195. else:
  196. response = self._dispatch(method, params)
  197. # wrap response in a singleton tuple
  198. response = (response,)
  199. response = xmlrpclib.dumps(response, methodresponse=1)
  200. except Fault, fault:
  201. response = xmlrpclib.dumps(fault)
  202. except:
  203. # report exception back to server
  204. response = xmlrpclib.dumps(
  205. xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))
  206. )
  207. return response
  208. def system_listMethods(self):
  209. """system.listMethods() => ['add', 'subtract', 'multiple']
  210. Returns a list of the methods supported by the server."""
  211. methods = self.funcs.keys()
  212. if self.instance is not None:
  213. # Instance can implement _listMethod to return a list of
  214. # methods
  215. if hasattr(self.instance, '_listMethods'):
  216. methods = remove_duplicates(
  217. methods + self.instance._listMethods()
  218. )
  219. # if the instance has a _dispatch method then we
  220. # don't have enough information to provide a list
  221. # of methods
  222. elif not hasattr(self.instance, '_dispatch'):
  223. methods = remove_duplicates(
  224. methods + list_public_methods(self.instance)
  225. )
  226. methods.sort()
  227. return methods
  228. def system_methodSignature(self, method_name):
  229. """system.methodSignature('add') => [double, int, int]
  230. Returns a list describing the signature of the method. In the
  231. above example, the add method takes two integers as arguments
  232. and returns a double result.
  233. This server does NOT support system.methodSignature."""
  234. # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
  235. return 'signatures not supported'
  236. def system_methodHelp(self, method_name):
  237. """system.methodHelp('add') => "Adds two integers together"
  238. Returns a string containing documentation for the specified method."""
  239. method = None
  240. if self.funcs.has_key(method_name):
  241. method = self.funcs[method_name]
  242. elif self.instance is not None:
  243. # Instance can implement _methodHelp to return help for a method
  244. if hasattr(self.instance, '_methodHelp'):
  245. return self.instance._methodHelp(method_name)
  246. # if the instance has a _dispatch method then we
  247. # don't have enough information to provide help
  248. elif not hasattr(self.instance, '_dispatch'):
  249. try:
  250. method = resolve_dotted_attribute(
  251. self.instance,
  252. method_name,
  253. self.allow_dotted_names
  254. )
  255. except AttributeError:
  256. pass
  257. # Note that we aren't checking that the method actually
  258. # be a callable object of some kind
  259. if method is None:
  260. return ""
  261. else:
  262. import pydoc
  263. return pydoc.getdoc(method)
  264. def system_multicall(self, call_list):
  265. """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
  266. [[4], ...]
  267. Allows the caller to package multiple XML-RPC calls into a single
  268. request.
  269. See http://www.xmlrpc.com/discuss/msgReader$1208
  270. """
  271. results = []
  272. for call in call_list:
  273. method_name = call['methodName']
  274. params = call['params']
  275. try:
  276. # XXX A marshalling error in any response will fail the entire
  277. # multicall. If someone cares they should fix this.
  278. results.append([self._dispatch(method_name, params)])
  279. except Fault, fault:
  280. results.append(
  281. {'faultCode' : fault.faultCode,
  282. 'faultString' : fault.faultString}
  283. )
  284. except:
  285. results.append(
  286. {'faultCode' : 1,
  287. 'faultString' : "%s:%s" % (sys.exc_type, sys.exc_value)}
  288. )
  289. return results
  290. def _dispatch(self, method, params):
  291. """Dispatches the XML-RPC method.
  292. XML-RPC calls are forwarded to a registered function that
  293. matches the called XML-RPC method name. If no such function
  294. exists then the call is forwarded to the registered instance,
  295. if available.
  296. If the registered instance has a _dispatch method then that
  297. method will be called with the name of the XML-RPC method and
  298. its parameters as a tuple
  299. e.g. instance._dispatch('add',(2,3))
  300. If the registered instance does not have a _dispatch method
  301. then the instance will be searched to find a matching method
  302. and, if found, will be called.
  303. Methods beginning with an '_' are considered private and will
  304. not be called.
  305. """
  306. func = None
  307. try:
  308. # check to see if a matching function has been registered
  309. func = self.funcs[method]
  310. except KeyError:
  311. if self.instance is not None:
  312. # check for a _dispatch method
  313. if hasattr(self.instance, '_dispatch'):
  314. return self.instance._dispatch(method, params)
  315. else:
  316. # call instance method directly
  317. try:
  318. func = resolve_dotted_attribute(
  319. self.instance,
  320. method,
  321. self.allow_dotted_names
  322. )
  323. except AttributeError:
  324. pass
  325. if func is not None:
  326. return func(*params)
  327. else:
  328. raise Exception('method "%s" is not supported' % method)
  329. class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  330. """Simple XML-RPC request handler class.
  331. Handles all HTTP POST requests and attempts to decode them as
  332. XML-RPC requests.
  333. """
  334. def do_POST(self):
  335. """Handles the HTTP POST request.
  336. Attempts to interpret all HTTP POST requests as XML-RPC calls,
  337. which are forwarded to the server's _dispatch method for handling.
  338. """
  339. try:
  340. # get arguments
  341. data = self.rfile.read(int(self.headers["content-length"]))
  342. # In previous versions of SimpleXMLRPCServer, _dispatch
  343. # could be overridden in this class, instead of in
  344. # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
  345. # check to see if a subclass implements _dispatch and dispatch
  346. # using that method if present.
  347. response = self.server._marshaled_dispatch(
  348. data, getattr(self, '_dispatch', None)
  349. )
  350. except: # This should only happen if the module is buggy
  351. # internal error, report as HTTP server error
  352. self.send_response(500)
  353. self.end_headers()
  354. else:
  355. # got a valid XML RPC response
  356. self.send_response(200)
  357. self.send_header("Content-type", "text/xml")
  358. self.send_header("Content-length", str(len(response)))
  359. self.end_headers()
  360. self.wfile.write(response)
  361. # shut down the connection
  362. self.wfile.flush()
  363. self.connection.shutdown(1)
  364. def log_request(self, code='-', size='-'):
  365. """Selectively log an accepted request."""
  366. if self.server.logRequests:
  367. BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
  368. class SimpleXMLRPCServer(SocketServer.TCPServer,
  369. SimpleXMLRPCDispatcher):
  370. """Simple XML-RPC server.
  371. Simple XML-RPC server that allows functions and a single instance
  372. to be installed to handle requests. The default implementation
  373. attempts to dispatch XML-RPC calls to the functions or instance
  374. installed in the server. Override the _dispatch method inhereted
  375. from SimpleXMLRPCDispatcher to change this behavior.
  376. """
  377. def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
  378. logRequests=1):
  379. self.logRequests = logRequests
  380. SimpleXMLRPCDispatcher.__init__(self)
  381. SocketServer.TCPServer.__init__(self, addr, requestHandler)
  382. class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
  383. """Simple handler for XML-RPC data passed through CGI."""
  384. def __init__(self):
  385. SimpleXMLRPCDispatcher.__init__(self)
  386. def handle_xmlrpc(self, request_text):
  387. """Handle a single XML-RPC request"""
  388. response = self._marshaled_dispatch(request_text)
  389. print 'Content-Type: text/xml'
  390. print 'Content-Length: %d' % len(response)
  391. print
  392. sys.stdout.write(response)
  393. def handle_get(self):
  394. """Handle a single HTTP GET request.
  395. Default implementation indicates an error because
  396. XML-RPC uses the POST method.
  397. """
  398. code = 400
  399. message, explain = \
  400. BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
  401. response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
  402. {
  403. 'code' : code,
  404. 'message' : message,
  405. 'explain' : explain
  406. }
  407. print 'Status: %d %s' % (code, message)
  408. print 'Content-Type: text/html'
  409. print 'Content-Length: %d' % len(response)
  410. print
  411. sys.stdout.write(response)
  412. def handle_request(self, request_text = None):
  413. """Handle a single XML-RPC request passed through a CGI post method.
  414. If no XML data is given then it is read from stdin. The resulting
  415. XML-RPC response is printed to stdout along with the correct HTTP
  416. headers.
  417. """
  418. if request_text is None and \
  419. os.environ.get('REQUEST_METHOD', None) == 'GET':
  420. self.handle_get()
  421. else:
  422. # POST data is normally available through stdin
  423. if request_text is None:
  424. request_text = sys.stdin.read()
  425. self.handle_xmlrpc(request_text)
  426. if __name__ == '__main__':
  427. server = SimpleXMLRPCServer(("localhost", 8000))
  428. server.register_function(pow)
  429. server.register_function(lambda x,y: x+y, 'add')
  430. server.serve_forever()