server.py 36 KB

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