server.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. r"""
  2. Ported using Python-Future from the Python 3.3 standard library.
  3. XML-RPC Servers.
  4. This module can be used to create simple XML-RPC servers
  5. by creating a server and either installing functions, a
  6. class instance, or by extending the SimpleXMLRPCServer
  7. class.
  8. It can also be used to handle XML-RPC requests in a CGI
  9. environment using CGIXMLRPCRequestHandler.
  10. The Doc* classes can be used to create XML-RPC servers that
  11. serve pydoc-style documentation in response to HTTP
  12. GET requests. This documentation is dynamically generated
  13. based on the functions and methods registered with the
  14. server.
  15. A list of possible usage patterns follows:
  16. 1. Install functions:
  17. server = SimpleXMLRPCServer(("localhost", 8000))
  18. server.register_function(pow)
  19. server.register_function(lambda x,y: x+y, 'add')
  20. server.serve_forever()
  21. 2. Install an instance:
  22. class MyFuncs:
  23. def __init__(self):
  24. # make all of the sys functions available through sys.func_name
  25. import sys
  26. self.sys = sys
  27. def _listMethods(self):
  28. # implement this method so that system.listMethods
  29. # knows to advertise the sys methods
  30. return list_public_methods(self) + \
  31. ['sys.' + method for method in list_public_methods(self.sys)]
  32. def pow(self, x, y): return pow(x, y)
  33. def add(self, x, y) : return x + y
  34. server = SimpleXMLRPCServer(("localhost", 8000))
  35. server.register_introspection_functions()
  36. server.register_instance(MyFuncs())
  37. server.serve_forever()
  38. 3. Install an instance with custom dispatch method:
  39. class Math:
  40. def _listMethods(self):
  41. # this method must be present for system.listMethods
  42. # to work
  43. return ['add', 'pow']
  44. def _methodHelp(self, method):
  45. # this method must be present for system.methodHelp
  46. # to work
  47. if method == 'add':
  48. return "add(2,3) => 5"
  49. elif method == 'pow':
  50. return "pow(x, y[, z]) => number"
  51. else:
  52. # By convention, return empty
  53. # string if no help is available
  54. return ""
  55. def _dispatch(self, method, params):
  56. if method == 'pow':
  57. return pow(*params)
  58. elif method == 'add':
  59. return params[0] + params[1]
  60. else:
  61. raise ValueError('bad method')
  62. server = SimpleXMLRPCServer(("localhost", 8000))
  63. server.register_introspection_functions()
  64. server.register_instance(Math())
  65. server.serve_forever()
  66. 4. Subclass SimpleXMLRPCServer:
  67. class MathServer(SimpleXMLRPCServer):
  68. def _dispatch(self, method, params):
  69. try:
  70. # We are forcing the 'export_' prefix on methods that are
  71. # callable through XML-RPC to prevent potential security
  72. # problems
  73. func = getattr(self, 'export_' + method)
  74. except AttributeError:
  75. raise Exception('method "%s" is not supported' % method)
  76. else:
  77. return func(*params)
  78. def export_add(self, x, y):
  79. return x + y
  80. server = MathServer(("localhost", 8000))
  81. server.serve_forever()
  82. 5. CGI script:
  83. server = CGIXMLRPCRequestHandler()
  84. server.register_function(pow)
  85. server.handle_request()
  86. """
  87. from __future__ import absolute_import, division, print_function, unicode_literals
  88. from future.builtins import int, str
  89. # Written by Brian Quinlan (brian@sweetapp.com).
  90. # Based on code written by Fredrik Lundh.
  91. from future.backports.xmlrpc.client import Fault, dumps, loads, gzip_encode, gzip_decode
  92. from future.backports.http.server import BaseHTTPRequestHandler
  93. import future.backports.http.server as http_server
  94. from future.backports import socketserver
  95. import sys
  96. import os
  97. import re
  98. import pydoc
  99. import inspect
  100. import traceback
  101. try:
  102. import fcntl
  103. except ImportError:
  104. fcntl = None
  105. def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
  106. """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
  107. Resolves a dotted attribute name to an object. Raises
  108. an AttributeError if any attribute in the chain starts with a '_'.
  109. If the optional allow_dotted_names argument is false, dots are not
  110. supported and this function operates similar to getattr(obj, attr).
  111. """
  112. if allow_dotted_names:
  113. attrs = attr.split('.')
  114. else:
  115. attrs = [attr]
  116. for i in attrs:
  117. if i.startswith('_'):
  118. raise AttributeError(
  119. 'attempt to access private attribute "%s"' % i
  120. )
  121. else:
  122. obj = getattr(obj,i)
  123. return obj
  124. def list_public_methods(obj):
  125. """Returns a list of attribute strings, found in the specified
  126. object, which represent callable attributes"""
  127. return [member for member in dir(obj)
  128. if not member.startswith('_') and
  129. callable(getattr(obj, member))]
  130. class SimpleXMLRPCDispatcher(object):
  131. """Mix-in class that dispatches XML-RPC requests.
  132. This class is used to register XML-RPC method handlers
  133. and then to dispatch them. This class doesn't need to be
  134. instanced directly when used by SimpleXMLRPCServer but it
  135. can be instanced when used by the MultiPathXMLRPCServer
  136. """
  137. def __init__(self, allow_none=False, encoding=None,
  138. use_builtin_types=False):
  139. self.funcs = {}
  140. self.instance = None
  141. self.allow_none = allow_none
  142. self.encoding = encoding or 'utf-8'
  143. self.use_builtin_types = use_builtin_types
  144. def register_instance(self, instance, allow_dotted_names=False):
  145. """Registers an instance to respond to XML-RPC requests.
  146. Only one instance can be installed at a time.
  147. If the registered instance has a _dispatch method then that
  148. method will be called with the name of the XML-RPC method and
  149. its parameters as a tuple
  150. e.g. instance._dispatch('add',(2,3))
  151. If the registered instance does not have a _dispatch method
  152. then the instance will be searched to find a matching method
  153. and, if found, will be called. Methods beginning with an '_'
  154. are considered private and will not be called by
  155. SimpleXMLRPCServer.
  156. If a registered function matches a XML-RPC request, then it
  157. will be called instead of the registered instance.
  158. If the optional allow_dotted_names argument is true and the
  159. instance does not have a _dispatch method, method names
  160. containing dots are supported and resolved, as long as none of
  161. the name segments start with an '_'.
  162. *** SECURITY WARNING: ***
  163. Enabling the allow_dotted_names options allows intruders
  164. to access your module's global variables and may allow
  165. intruders to execute arbitrary code on your machine. Only
  166. use this option on a secure, closed network.
  167. """
  168. self.instance = instance
  169. self.allow_dotted_names = allow_dotted_names
  170. def register_function(self, function, name=None):
  171. """Registers a function to respond to XML-RPC requests.
  172. The optional name argument can be used to set a Unicode name
  173. for the function.
  174. """
  175. if name is None:
  176. name = function.__name__
  177. self.funcs[name] = function
  178. def register_introspection_functions(self):
  179. """Registers the XML-RPC introspection methods in the system
  180. namespace.
  181. see http://xmlrpc.usefulinc.com/doc/reserved.html
  182. """
  183. self.funcs.update({'system.listMethods' : self.system_listMethods,
  184. 'system.methodSignature' : self.system_methodSignature,
  185. 'system.methodHelp' : self.system_methodHelp})
  186. def register_multicall_functions(self):
  187. """Registers the XML-RPC multicall method in the system
  188. namespace.
  189. see http://www.xmlrpc.com/discuss/msgReader$1208"""
  190. self.funcs.update({'system.multicall' : self.system_multicall})
  191. def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
  192. """Dispatches an XML-RPC method from marshalled (XML) data.
  193. XML-RPC methods are dispatched from the marshalled (XML) data
  194. using the _dispatch method and the result is returned as
  195. marshalled data. For backwards compatibility, a dispatch
  196. function can be provided as an argument (see comment in
  197. SimpleXMLRPCRequestHandler.do_POST) but overriding the
  198. existing method through subclassing is the preferred means
  199. of changing method dispatch behavior.
  200. """
  201. try:
  202. params, method = loads(data, use_builtin_types=self.use_builtin_types)
  203. # generate response
  204. if dispatch_method is not None:
  205. response = dispatch_method(method, params)
  206. else:
  207. response = self._dispatch(method, params)
  208. # wrap response in a singleton tuple
  209. response = (response,)
  210. response = dumps(response, methodresponse=1,
  211. allow_none=self.allow_none, encoding=self.encoding)
  212. except Fault as fault:
  213. response = dumps(fault, allow_none=self.allow_none,
  214. encoding=self.encoding)
  215. except:
  216. # report exception back to server
  217. exc_type, exc_value, exc_tb = sys.exc_info()
  218. response = dumps(
  219. Fault(1, "%s:%s" % (exc_type, exc_value)),
  220. encoding=self.encoding, allow_none=self.allow_none,
  221. )
  222. return response.encode(self.encoding)
  223. def system_listMethods(self):
  224. """system.listMethods() => ['add', 'subtract', 'multiple']
  225. Returns a list of the methods supported by the server."""
  226. methods = set(self.funcs.keys())
  227. if self.instance is not None:
  228. # Instance can implement _listMethod to return a list of
  229. # methods
  230. if hasattr(self.instance, '_listMethods'):
  231. methods |= set(self.instance._listMethods())
  232. # if the instance has a _dispatch method then we
  233. # don't have enough information to provide a list
  234. # of methods
  235. elif not hasattr(self.instance, '_dispatch'):
  236. methods |= set(list_public_methods(self.instance))
  237. return sorted(methods)
  238. def system_methodSignature(self, method_name):
  239. """system.methodSignature('add') => [double, int, int]
  240. Returns a list describing the signature of the method. In the
  241. above example, the add method takes two integers as arguments
  242. and returns a double result.
  243. This server does NOT support system.methodSignature."""
  244. # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
  245. return 'signatures not supported'
  246. def system_methodHelp(self, method_name):
  247. """system.methodHelp('add') => "Adds two integers together"
  248. Returns a string containing documentation for the specified method."""
  249. method = None
  250. if method_name in self.funcs:
  251. method = self.funcs[method_name]
  252. elif self.instance is not None:
  253. # Instance can implement _methodHelp to return help for a method
  254. if hasattr(self.instance, '_methodHelp'):
  255. return self.instance._methodHelp(method_name)
  256. # if the instance has a _dispatch method then we
  257. # don't have enough information to provide help
  258. elif not hasattr(self.instance, '_dispatch'):
  259. try:
  260. method = resolve_dotted_attribute(
  261. self.instance,
  262. method_name,
  263. self.allow_dotted_names
  264. )
  265. except AttributeError:
  266. pass
  267. # Note that we aren't checking that the method actually
  268. # be a callable object of some kind
  269. if method is None:
  270. return ""
  271. else:
  272. return pydoc.getdoc(method)
  273. def system_multicall(self, call_list):
  274. """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
  275. [[4], ...]
  276. Allows the caller to package multiple XML-RPC calls into a single
  277. request.
  278. See http://www.xmlrpc.com/discuss/msgReader$1208
  279. """
  280. results = []
  281. for call in call_list:
  282. method_name = call['methodName']
  283. params = call['params']
  284. try:
  285. # XXX A marshalling error in any response will fail the entire
  286. # multicall. If someone cares they should fix this.
  287. results.append([self._dispatch(method_name, params)])
  288. except Fault as fault:
  289. results.append(
  290. {'faultCode' : fault.faultCode,
  291. 'faultString' : fault.faultString}
  292. )
  293. except:
  294. exc_type, exc_value, exc_tb = sys.exc_info()
  295. results.append(
  296. {'faultCode' : 1,
  297. 'faultString' : "%s:%s" % (exc_type, exc_value)}
  298. )
  299. return results
  300. def _dispatch(self, method, params):
  301. """Dispatches the XML-RPC method.
  302. XML-RPC calls are forwarded to a registered function that
  303. matches the called XML-RPC method name. If no such function
  304. exists then the call is forwarded to the registered instance,
  305. if available.
  306. If the registered instance has a _dispatch method then that
  307. method will be called with the name of the XML-RPC method and
  308. its parameters as a tuple
  309. e.g. instance._dispatch('add',(2,3))
  310. If the registered instance does not have a _dispatch method
  311. then the instance will be searched to find a matching method
  312. and, if found, will be called.
  313. Methods beginning with an '_' are considered private and will
  314. not be called.
  315. """
  316. func = None
  317. try:
  318. # check to see if a matching function has been registered
  319. func = self.funcs[method]
  320. except KeyError:
  321. if self.instance is not None:
  322. # check for a _dispatch method
  323. if hasattr(self.instance, '_dispatch'):
  324. return self.instance._dispatch(method, params)
  325. else:
  326. # call instance method directly
  327. try:
  328. func = resolve_dotted_attribute(
  329. self.instance,
  330. method,
  331. self.allow_dotted_names
  332. )
  333. except AttributeError:
  334. pass
  335. if func is not None:
  336. return func(*params)
  337. else:
  338. raise Exception('method "%s" is not supported' % method)
  339. class SimpleXMLRPCRequestHandler(BaseHTTPRequestHandler):
  340. """Simple XML-RPC request handler class.
  341. Handles all HTTP POST requests and attempts to decode them as
  342. XML-RPC requests.
  343. """
  344. # Class attribute listing the accessible path components;
  345. # paths not on this list will result in a 404 error.
  346. rpc_paths = ('/', '/RPC2')
  347. #if not None, encode responses larger than this, if possible
  348. encode_threshold = 1400 #a common MTU
  349. #Override form StreamRequestHandler: full buffering of output
  350. #and no Nagle.
  351. wbufsize = -1
  352. disable_nagle_algorithm = True
  353. # a re to match a gzip Accept-Encoding
  354. aepattern = re.compile(r"""
  355. \s* ([^\s;]+) \s* #content-coding
  356. (;\s* q \s*=\s* ([0-9\.]+))? #q
  357. """, re.VERBOSE | re.IGNORECASE)
  358. def accept_encodings(self):
  359. r = {}
  360. ae = self.headers.get("Accept-Encoding", "")
  361. for e in ae.split(","):
  362. match = self.aepattern.match(e)
  363. if match:
  364. v = match.group(3)
  365. v = float(v) if v else 1.0
  366. r[match.group(1)] = v
  367. return r
  368. def is_rpc_path_valid(self):
  369. if self.rpc_paths:
  370. return self.path in self.rpc_paths
  371. else:
  372. # If .rpc_paths is empty, just assume all paths are legal
  373. return True
  374. def do_POST(self):
  375. """Handles the HTTP POST request.
  376. Attempts to interpret all HTTP POST requests as XML-RPC calls,
  377. which are forwarded to the server's _dispatch method for handling.
  378. """
  379. # Check that the path is legal
  380. if not self.is_rpc_path_valid():
  381. self.report_404()
  382. return
  383. try:
  384. # Get arguments by reading body of request.
  385. # We read this in chunks to avoid straining
  386. # socket.read(); around the 10 or 15Mb mark, some platforms
  387. # begin to have problems (bug #792570).
  388. max_chunk_size = 10*1024*1024
  389. size_remaining = int(self.headers["content-length"])
  390. L = []
  391. while size_remaining:
  392. chunk_size = min(size_remaining, max_chunk_size)
  393. chunk = self.rfile.read(chunk_size)
  394. if not chunk:
  395. break
  396. L.append(chunk)
  397. size_remaining -= len(L[-1])
  398. data = b''.join(L)
  399. data = self.decode_request_content(data)
  400. if data is None:
  401. return #response has been sent
  402. # In previous versions of SimpleXMLRPCServer, _dispatch
  403. # could be overridden in this class, instead of in
  404. # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
  405. # check to see if a subclass implements _dispatch and dispatch
  406. # using that method if present.
  407. response = self.server._marshaled_dispatch(
  408. data, getattr(self, '_dispatch', None), self.path
  409. )
  410. except Exception as e: # This should only happen if the module is buggy
  411. # internal error, report as HTTP server error
  412. self.send_response(500)
  413. # Send information about the exception if requested
  414. if hasattr(self.server, '_send_traceback_header') and \
  415. self.server._send_traceback_header:
  416. self.send_header("X-exception", str(e))
  417. trace = traceback.format_exc()
  418. trace = str(trace.encode('ASCII', 'backslashreplace'), 'ASCII')
  419. self.send_header("X-traceback", trace)
  420. self.send_header("Content-length", "0")
  421. self.end_headers()
  422. else:
  423. self.send_response(200)
  424. self.send_header("Content-type", "text/xml")
  425. if self.encode_threshold is not None:
  426. if len(response) > self.encode_threshold:
  427. q = self.accept_encodings().get("gzip", 0)
  428. if q:
  429. try:
  430. response = gzip_encode(response)
  431. self.send_header("Content-Encoding", "gzip")
  432. except NotImplementedError:
  433. pass
  434. self.send_header("Content-length", str(len(response)))
  435. self.end_headers()
  436. self.wfile.write(response)
  437. def decode_request_content(self, data):
  438. #support gzip encoding of request
  439. encoding = self.headers.get("content-encoding", "identity").lower()
  440. if encoding == "identity":
  441. return data
  442. if encoding == "gzip":
  443. try:
  444. return gzip_decode(data)
  445. except NotImplementedError:
  446. self.send_response(501, "encoding %r not supported" % encoding)
  447. except ValueError:
  448. self.send_response(400, "error decoding gzip content")
  449. else:
  450. self.send_response(501, "encoding %r not supported" % encoding)
  451. self.send_header("Content-length", "0")
  452. self.end_headers()
  453. def report_404 (self):
  454. # Report a 404 error
  455. self.send_response(404)
  456. response = b'No such page'
  457. self.send_header("Content-type", "text/plain")
  458. self.send_header("Content-length", str(len(response)))
  459. self.end_headers()
  460. self.wfile.write(response)
  461. def log_request(self, code='-', size='-'):
  462. """Selectively log an accepted request."""
  463. if self.server.logRequests:
  464. BaseHTTPRequestHandler.log_request(self, code, size)
  465. class SimpleXMLRPCServer(socketserver.TCPServer,
  466. SimpleXMLRPCDispatcher):
  467. """Simple XML-RPC server.
  468. Simple XML-RPC server that allows functions and a single instance
  469. to be installed to handle requests. The default implementation
  470. attempts to dispatch XML-RPC calls to the functions or instance
  471. installed in the server. Override the _dispatch method inherited
  472. from SimpleXMLRPCDispatcher to change this behavior.
  473. """
  474. allow_reuse_address = True
  475. # Warning: this is for debugging purposes only! Never set this to True in
  476. # production code, as will be sending out sensitive information (exception
  477. # and stack trace details) when exceptions are raised inside
  478. # SimpleXMLRPCRequestHandler.do_POST
  479. _send_traceback_header = False
  480. def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
  481. logRequests=True, allow_none=False, encoding=None,
  482. bind_and_activate=True, use_builtin_types=False):
  483. self.logRequests = logRequests
  484. SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types)
  485. socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
  486. # [Bug #1222790] If possible, set close-on-exec flag; if a
  487. # method spawns a subprocess, the subprocess shouldn't have
  488. # the listening socket open.
  489. if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
  490. flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
  491. flags |= fcntl.FD_CLOEXEC
  492. fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
  493. class MultiPathXMLRPCServer(SimpleXMLRPCServer):
  494. """Multipath XML-RPC Server
  495. This specialization of SimpleXMLRPCServer allows the user to create
  496. multiple Dispatcher instances and assign them to different
  497. HTTP request paths. This makes it possible to run two or more
  498. 'virtual XML-RPC servers' at the same port.
  499. Make sure that the requestHandler accepts the paths in question.
  500. """
  501. def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
  502. logRequests=True, allow_none=False, encoding=None,
  503. bind_and_activate=True, use_builtin_types=False):
  504. SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, allow_none,
  505. encoding, bind_and_activate, use_builtin_types)
  506. self.dispatchers = {}
  507. self.allow_none = allow_none
  508. self.encoding = encoding or 'utf-8'
  509. def add_dispatcher(self, path, dispatcher):
  510. self.dispatchers[path] = dispatcher
  511. return dispatcher
  512. def get_dispatcher(self, path):
  513. return self.dispatchers[path]
  514. def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
  515. try:
  516. response = self.dispatchers[path]._marshaled_dispatch(
  517. data, dispatch_method, path)
  518. except:
  519. # report low level exception back to server
  520. # (each dispatcher should have handled their own
  521. # exceptions)
  522. exc_type, exc_value = sys.exc_info()[:2]
  523. response = dumps(
  524. Fault(1, "%s:%s" % (exc_type, exc_value)),
  525. encoding=self.encoding, allow_none=self.allow_none)
  526. response = response.encode(self.encoding)
  527. return response
  528. class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
  529. """Simple handler for XML-RPC data passed through CGI."""
  530. def __init__(self, allow_none=False, encoding=None, use_builtin_types=False):
  531. SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types)
  532. def handle_xmlrpc(self, request_text):
  533. """Handle a single XML-RPC request"""
  534. response = self._marshaled_dispatch(request_text)
  535. print('Content-Type: text/xml')
  536. print('Content-Length: %d' % len(response))
  537. print()
  538. sys.stdout.flush()
  539. sys.stdout.buffer.write(response)
  540. sys.stdout.buffer.flush()
  541. def handle_get(self):
  542. """Handle a single HTTP GET request.
  543. Default implementation indicates an error because
  544. XML-RPC uses the POST method.
  545. """
  546. code = 400
  547. message, explain = BaseHTTPRequestHandler.responses[code]
  548. response = http_server.DEFAULT_ERROR_MESSAGE % \
  549. {
  550. 'code' : code,
  551. 'message' : message,
  552. 'explain' : explain
  553. }
  554. response = response.encode('utf-8')
  555. print('Status: %d %s' % (code, message))
  556. print('Content-Type: %s' % http_server.DEFAULT_ERROR_CONTENT_TYPE)
  557. print('Content-Length: %d' % len(response))
  558. print()
  559. sys.stdout.flush()
  560. sys.stdout.buffer.write(response)
  561. sys.stdout.buffer.flush()
  562. def handle_request(self, request_text=None):
  563. """Handle a single XML-RPC request passed through a CGI post method.
  564. If no XML data is given then it is read from stdin. The resulting
  565. XML-RPC response is printed to stdout along with the correct HTTP
  566. headers.
  567. """
  568. if request_text is None and \
  569. os.environ.get('REQUEST_METHOD', None) == 'GET':
  570. self.handle_get()
  571. else:
  572. # POST data is normally available through stdin
  573. try:
  574. length = int(os.environ.get('CONTENT_LENGTH', None))
  575. except (ValueError, TypeError):
  576. length = -1
  577. if request_text is None:
  578. request_text = sys.stdin.read(length)
  579. self.handle_xmlrpc(request_text)
  580. # -----------------------------------------------------------------------------
  581. # Self documenting XML-RPC Server.
  582. class ServerHTMLDoc(pydoc.HTMLDoc):
  583. """Class used to generate pydoc HTML document for a server"""
  584. def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
  585. """Mark up some plain text, given a context of symbols to look for.
  586. Each context dictionary maps object names to anchor names."""
  587. escape = escape or self.escape
  588. results = []
  589. here = 0
  590. # XXX Note that this regular expression does not allow for the
  591. # hyperlinking of arbitrary strings being used as method
  592. # names. Only methods with names consisting of word characters
  593. # and '.'s are hyperlinked.
  594. pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
  595. r'RFC[- ]?(\d+)|'
  596. r'PEP[- ]?(\d+)|'
  597. r'(self\.)?((?:\w|\.)+))\b')
  598. while 1:
  599. match = pattern.search(text, here)
  600. if not match: break
  601. start, end = match.span()
  602. results.append(escape(text[here:start]))
  603. all, scheme, rfc, pep, selfdot, name = match.groups()
  604. if scheme:
  605. url = escape(all).replace('"', '"')
  606. results.append('<a href="%s">%s</a>' % (url, url))
  607. elif rfc:
  608. url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  609. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  610. elif pep:
  611. url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
  612. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  613. elif text[end:end+1] == '(':
  614. results.append(self.namelink(name, methods, funcs, classes))
  615. elif selfdot:
  616. results.append('self.<strong>%s</strong>' % name)
  617. else:
  618. results.append(self.namelink(name, classes))
  619. here = end
  620. results.append(escape(text[here:]))
  621. return ''.join(results)
  622. def docroutine(self, object, name, mod=None,
  623. funcs={}, classes={}, methods={}, cl=None):
  624. """Produce HTML documentation for a function or method object."""
  625. anchor = (cl and cl.__name__ or '') + '-' + name
  626. note = ''
  627. title = '<a name="%s"><strong>%s</strong></a>' % (
  628. self.escape(anchor), self.escape(name))
  629. if inspect.ismethod(object):
  630. args = inspect.getfullargspec(object)
  631. # exclude the argument bound to the instance, it will be
  632. # confusing to the non-Python user
  633. argspec = inspect.formatargspec (
  634. args.args[1:],
  635. args.varargs,
  636. args.varkw,
  637. args.defaults,
  638. annotations=args.annotations,
  639. formatvalue=self.formatvalue
  640. )
  641. elif inspect.isfunction(object):
  642. args = inspect.getfullargspec(object)
  643. argspec = inspect.formatargspec(
  644. args.args, args.varargs, args.varkw, args.defaults,
  645. annotations=args.annotations,
  646. formatvalue=self.formatvalue)
  647. else:
  648. argspec = '(...)'
  649. if isinstance(object, tuple):
  650. argspec = object[0] or argspec
  651. docstring = object[1] or ""
  652. else:
  653. docstring = pydoc.getdoc(object)
  654. decl = title + argspec + (note and self.grey(
  655. '<font face="helvetica, arial">%s</font>' % note))
  656. doc = self.markup(
  657. docstring, self.preformat, funcs, classes, methods)
  658. doc = doc and '<dd><tt>%s</tt></dd>' % doc
  659. return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  660. def docserver(self, server_name, package_documentation, methods):
  661. """Produce HTML documentation for an XML-RPC server."""
  662. fdict = {}
  663. for key, value in methods.items():
  664. fdict[key] = '#-' + key
  665. fdict[value] = fdict[key]
  666. server_name = self.escape(server_name)
  667. head = '<big><big><strong>%s</strong></big></big>' % server_name
  668. result = self.heading(head, '#ffffff', '#7799ee')
  669. doc = self.markup(package_documentation, self.preformat, fdict)
  670. doc = doc and '<tt>%s</tt>' % doc
  671. result = result + '<p>%s</p>\n' % doc
  672. contents = []
  673. method_items = sorted(methods.items())
  674. for key, value in method_items:
  675. contents.append(self.docroutine(value, key, funcs=fdict))
  676. result = result + self.bigsection(
  677. 'Methods', '#ffffff', '#eeaa77', ''.join(contents))
  678. return result
  679. class XMLRPCDocGenerator(object):
  680. """Generates documentation for an XML-RPC server.
  681. This class is designed as mix-in and should not
  682. be constructed directly.
  683. """
  684. def __init__(self):
  685. # setup variables used for HTML documentation
  686. self.server_name = 'XML-RPC Server Documentation'
  687. self.server_documentation = \
  688. "This server exports the following methods through the XML-RPC "\
  689. "protocol."
  690. self.server_title = 'XML-RPC Server Documentation'
  691. def set_server_title(self, server_title):
  692. """Set the HTML title of the generated server documentation"""
  693. self.server_title = server_title
  694. def set_server_name(self, server_name):
  695. """Set the name of the generated HTML server documentation"""
  696. self.server_name = server_name
  697. def set_server_documentation(self, server_documentation):
  698. """Set the documentation string for the entire server."""
  699. self.server_documentation = server_documentation
  700. def generate_html_documentation(self):
  701. """generate_html_documentation() => html documentation for the server
  702. Generates HTML documentation for the server using introspection for
  703. installed functions and instances that do not implement the
  704. _dispatch method. Alternatively, instances can choose to implement
  705. the _get_method_argstring(method_name) method to provide the
  706. argument string used in the documentation and the
  707. _methodHelp(method_name) method to provide the help text used
  708. in the documentation."""
  709. methods = {}
  710. for method_name in self.system_listMethods():
  711. if method_name in self.funcs:
  712. method = self.funcs[method_name]
  713. elif self.instance is not None:
  714. method_info = [None, None] # argspec, documentation
  715. if hasattr(self.instance, '_get_method_argstring'):
  716. method_info[0] = self.instance._get_method_argstring(method_name)
  717. if hasattr(self.instance, '_methodHelp'):
  718. method_info[1] = self.instance._methodHelp(method_name)
  719. method_info = tuple(method_info)
  720. if method_info != (None, None):
  721. method = method_info
  722. elif not hasattr(self.instance, '_dispatch'):
  723. try:
  724. method = resolve_dotted_attribute(
  725. self.instance,
  726. method_name
  727. )
  728. except AttributeError:
  729. method = method_info
  730. else:
  731. method = method_info
  732. else:
  733. assert 0, "Could not find method in self.functions and no "\
  734. "instance installed"
  735. methods[method_name] = method
  736. documenter = ServerHTMLDoc()
  737. documentation = documenter.docserver(
  738. self.server_name,
  739. self.server_documentation,
  740. methods
  741. )
  742. return documenter.page(self.server_title, documentation)
  743. class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
  744. """XML-RPC and documentation request handler class.
  745. Handles all HTTP POST requests and attempts to decode them as
  746. XML-RPC requests.
  747. Handles all HTTP GET requests and interprets them as requests
  748. for documentation.
  749. """
  750. def do_GET(self):
  751. """Handles the HTTP GET request.
  752. Interpret all HTTP GET requests as requests for server
  753. documentation.
  754. """
  755. # Check that the path is legal
  756. if not self.is_rpc_path_valid():
  757. self.report_404()
  758. return
  759. response = self.server.generate_html_documentation().encode('utf-8')
  760. self.send_response(200)
  761. self.send_header("Content-type", "text/html")
  762. self.send_header("Content-length", str(len(response)))
  763. self.end_headers()
  764. self.wfile.write(response)
  765. class DocXMLRPCServer( SimpleXMLRPCServer,
  766. XMLRPCDocGenerator):
  767. """XML-RPC and HTML documentation server.
  768. Adds the ability to serve server documentation to the capabilities
  769. of SimpleXMLRPCServer.
  770. """
  771. def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler,
  772. logRequests=True, allow_none=False, encoding=None,
  773. bind_and_activate=True, use_builtin_types=False):
  774. SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests,
  775. allow_none, encoding, bind_and_activate,
  776. use_builtin_types)
  777. XMLRPCDocGenerator.__init__(self)
  778. class DocCGIXMLRPCRequestHandler( CGIXMLRPCRequestHandler,
  779. XMLRPCDocGenerator):
  780. """Handler for XML-RPC data and documentation requests passed through
  781. CGI"""
  782. def handle_get(self):
  783. """Handles the HTTP GET request.
  784. Interpret all HTTP GET requests as requests for server
  785. documentation.
  786. """
  787. response = self.generate_html_documentation().encode('utf-8')
  788. print('Content-Type: text/html')
  789. print('Content-Length: %d' % len(response))
  790. print()
  791. sys.stdout.flush()
  792. sys.stdout.buffer.write(response)
  793. sys.stdout.buffer.flush()
  794. def __init__(self):
  795. CGIXMLRPCRequestHandler.__init__(self)
  796. XMLRPCDocGenerator.__init__(self)
  797. if __name__ == '__main__':
  798. import datetime
  799. class ExampleService:
  800. def getData(self):
  801. return '42'
  802. class currentTime:
  803. @staticmethod
  804. def getCurrentTime():
  805. return datetime.datetime.now()
  806. server = SimpleXMLRPCServer(("localhost", 8000))
  807. server.register_function(pow)
  808. server.register_function(lambda x,y: x+y, 'add')
  809. server.register_instance(ExampleService(), allow_dotted_names=True)
  810. server.register_multicall_functions()
  811. print('Serving XML-RPC on localhost port 8000')
  812. print('It is advisable to run this example server within a secure, closed network.')
  813. try:
  814. server.serve_forever()
  815. except KeyboardInterrupt:
  816. print("\nKeyboard interrupt received, exiting.")
  817. server.server_close()
  818. sys.exit(0)