server.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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 BaseException as exc:
  218. response = dumps(
  219. Fault(1, "%s:%s" % (type(exc), exc)),
  220. encoding=self.encoding, allow_none=self.allow_none,
  221. )
  222. return response.encode(self.encoding, 'xmlcharrefreplace')
  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 BaseException as exc:
  294. results.append(
  295. {'faultCode' : 1,
  296. 'faultString' : "%s:%s" % (type(exc), exc)}
  297. )
  298. return results
  299. def _dispatch(self, method, params):
  300. """Dispatches the XML-RPC method.
  301. XML-RPC calls are forwarded to a registered function that
  302. matches the called XML-RPC method name. If no such function
  303. exists then the call is forwarded to the registered instance,
  304. if available.
  305. If the registered instance has a _dispatch method then that
  306. method will be called with the name of the XML-RPC method and
  307. its parameters as a tuple
  308. e.g. instance._dispatch('add',(2,3))
  309. If the registered instance does not have a _dispatch method
  310. then the instance will be searched to find a matching method
  311. and, if found, will be called.
  312. Methods beginning with an '_' are considered private and will
  313. not be called.
  314. """
  315. try:
  316. # call the matching registered function
  317. func = self.funcs[method]
  318. except KeyError:
  319. pass
  320. else:
  321. if func is not None:
  322. return func(*params)
  323. raise Exception('method "%s" is not supported' % method)
  324. if self.instance is not None:
  325. if hasattr(self.instance, '_dispatch'):
  326. # call the `_dispatch` method on the instance
  327. return self.instance._dispatch(method, params)
  328. # call the instance's method directly
  329. try:
  330. func = resolve_dotted_attribute(
  331. self.instance,
  332. method,
  333. self.allow_dotted_names
  334. )
  335. except AttributeError:
  336. pass
  337. else:
  338. if func is not None:
  339. return func(*params)
  340. raise Exception('method "%s" is not supported' % method)
  341. class SimpleXMLRPCRequestHandler(BaseHTTPRequestHandler):
  342. """Simple XML-RPC request handler class.
  343. Handles all HTTP POST requests and attempts to decode them as
  344. XML-RPC requests.
  345. """
  346. # Class attribute listing the accessible path components;
  347. # paths not on this list will result in a 404 error.
  348. rpc_paths = ('/', '/RPC2', '/pydoc.css')
  349. #if not None, encode responses larger than this, if possible
  350. encode_threshold = 1400 #a common MTU
  351. #Override form StreamRequestHandler: full buffering of output
  352. #and no Nagle.
  353. wbufsize = -1
  354. disable_nagle_algorithm = True
  355. # a re to match a gzip Accept-Encoding
  356. aepattern = re.compile(r"""
  357. \s* ([^\s;]+) \s* #content-coding
  358. (;\s* q \s*=\s* ([0-9\.]+))? #q
  359. """, re.VERBOSE | re.IGNORECASE)
  360. def accept_encodings(self):
  361. r = {}
  362. ae = self.headers.get("Accept-Encoding", "")
  363. for e in ae.split(","):
  364. match = self.aepattern.match(e)
  365. if match:
  366. v = match.group(3)
  367. v = float(v) if v else 1.0
  368. r[match.group(1)] = v
  369. return r
  370. def is_rpc_path_valid(self):
  371. if self.rpc_paths:
  372. return self.path in self.rpc_paths
  373. else:
  374. # If .rpc_paths is empty, just assume all paths are legal
  375. return True
  376. def do_POST(self):
  377. """Handles the HTTP POST request.
  378. Attempts to interpret all HTTP POST requests as XML-RPC calls,
  379. which are forwarded to the server's _dispatch method for handling.
  380. """
  381. # Check that the path is legal
  382. if not self.is_rpc_path_valid():
  383. self.report_404()
  384. return
  385. try:
  386. # Get arguments by reading body of request.
  387. # We read this in chunks to avoid straining
  388. # socket.read(); around the 10 or 15Mb mark, some platforms
  389. # begin to have problems (bug #792570).
  390. max_chunk_size = 10*1024*1024
  391. size_remaining = int(self.headers["content-length"])
  392. L = []
  393. while size_remaining:
  394. chunk_size = min(size_remaining, max_chunk_size)
  395. chunk = self.rfile.read(chunk_size)
  396. if not chunk:
  397. break
  398. L.append(chunk)
  399. size_remaining -= len(L[-1])
  400. data = b''.join(L)
  401. data = self.decode_request_content(data)
  402. if data is None:
  403. return #response has been sent
  404. # In previous versions of SimpleXMLRPCServer, _dispatch
  405. # could be overridden in this class, instead of in
  406. # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
  407. # check to see if a subclass implements _dispatch and dispatch
  408. # using that method if present.
  409. response = self.server._marshaled_dispatch(
  410. data, getattr(self, '_dispatch', None), self.path
  411. )
  412. except Exception as e: # This should only happen if the module is buggy
  413. # internal error, report as HTTP server error
  414. self.send_response(500)
  415. # Send information about the exception if requested
  416. if hasattr(self.server, '_send_traceback_header') and \
  417. self.server._send_traceback_header:
  418. self.send_header("X-exception", str(e))
  419. trace = traceback.format_exc()
  420. trace = str(trace.encode('ASCII', 'backslashreplace'), 'ASCII')
  421. self.send_header("X-traceback", trace)
  422. self.send_header("Content-length", "0")
  423. self.end_headers()
  424. else:
  425. self.send_response(200)
  426. self.send_header("Content-type", "text/xml")
  427. if self.encode_threshold is not None:
  428. if len(response) > self.encode_threshold:
  429. q = self.accept_encodings().get("gzip", 0)
  430. if q:
  431. try:
  432. response = gzip_encode(response)
  433. self.send_header("Content-Encoding", "gzip")
  434. except NotImplementedError:
  435. pass
  436. self.send_header("Content-length", str(len(response)))
  437. self.end_headers()
  438. self.wfile.write(response)
  439. def decode_request_content(self, data):
  440. #support gzip encoding of request
  441. encoding = self.headers.get("content-encoding", "identity").lower()
  442. if encoding == "identity":
  443. return data
  444. if encoding == "gzip":
  445. try:
  446. return gzip_decode(data)
  447. except NotImplementedError:
  448. self.send_response(501, "encoding %r not supported" % encoding)
  449. except ValueError:
  450. self.send_response(400, "error decoding gzip content")
  451. else:
  452. self.send_response(501, "encoding %r not supported" % encoding)
  453. self.send_header("Content-length", "0")
  454. self.end_headers()
  455. def report_404 (self):
  456. # Report a 404 error
  457. self.send_response(404)
  458. response = b'No such page'
  459. self.send_header("Content-type", "text/plain")
  460. self.send_header("Content-length", str(len(response)))
  461. self.end_headers()
  462. self.wfile.write(response)
  463. def log_request(self, code='-', size='-'):
  464. """Selectively log an accepted request."""
  465. if self.server.logRequests:
  466. BaseHTTPRequestHandler.log_request(self, code, size)
  467. class SimpleXMLRPCServer(socketserver.TCPServer,
  468. SimpleXMLRPCDispatcher):
  469. """Simple XML-RPC server.
  470. Simple XML-RPC server that allows functions and a single instance
  471. to be installed to handle requests. The default implementation
  472. attempts to dispatch XML-RPC calls to the functions or instance
  473. installed in the server. Override the _dispatch method inherited
  474. from SimpleXMLRPCDispatcher to change this behavior.
  475. """
  476. allow_reuse_address = True
  477. # Warning: this is for debugging purposes only! Never set this to True in
  478. # production code, as will be sending out sensitive information (exception
  479. # and stack trace details) when exceptions are raised inside
  480. # SimpleXMLRPCRequestHandler.do_POST
  481. _send_traceback_header = False
  482. def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
  483. logRequests=True, allow_none=False, encoding=None,
  484. bind_and_activate=True, use_builtin_types=False):
  485. self.logRequests = logRequests
  486. SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types)
  487. socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
  488. class MultiPathXMLRPCServer(SimpleXMLRPCServer):
  489. """Multipath XML-RPC Server
  490. This specialization of SimpleXMLRPCServer allows the user to create
  491. multiple Dispatcher instances and assign them to different
  492. HTTP request paths. This makes it possible to run two or more
  493. 'virtual XML-RPC servers' at the same port.
  494. Make sure that the requestHandler accepts the paths in question.
  495. """
  496. def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
  497. logRequests=True, allow_none=False, encoding=None,
  498. bind_and_activate=True, use_builtin_types=False):
  499. SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, allow_none,
  500. encoding, bind_and_activate, use_builtin_types)
  501. self.dispatchers = {}
  502. self.allow_none = allow_none
  503. self.encoding = encoding or 'utf-8'
  504. def add_dispatcher(self, path, dispatcher):
  505. self.dispatchers[path] = dispatcher
  506. return dispatcher
  507. def get_dispatcher(self, path):
  508. return self.dispatchers[path]
  509. def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
  510. try:
  511. response = self.dispatchers[path]._marshaled_dispatch(
  512. data, dispatch_method, path)
  513. except BaseException as exc:
  514. # report low level exception back to server
  515. # (each dispatcher should have handled their own
  516. # exceptions)
  517. response = dumps(
  518. Fault(1, "%s:%s" % (type(exc), exc)),
  519. encoding=self.encoding, allow_none=self.allow_none)
  520. response = response.encode(self.encoding, 'xmlcharrefreplace')
  521. return response
  522. class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
  523. """Simple handler for XML-RPC data passed through CGI."""
  524. def __init__(self, allow_none=False, encoding=None, use_builtin_types=False):
  525. SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types)
  526. def handle_xmlrpc(self, request_text):
  527. """Handle a single XML-RPC request"""
  528. response = self._marshaled_dispatch(request_text)
  529. print('Content-Type: text/xml')
  530. print('Content-Length: %d' % len(response))
  531. print()
  532. sys.stdout.flush()
  533. sys.stdout.buffer.write(response)
  534. sys.stdout.buffer.flush()
  535. def handle_get(self):
  536. """Handle a single HTTP GET request.
  537. Default implementation indicates an error because
  538. XML-RPC uses the POST method.
  539. """
  540. code = 400
  541. message, explain = BaseHTTPRequestHandler.responses[code]
  542. response = http.server.DEFAULT_ERROR_MESSAGE % \
  543. {
  544. 'code' : code,
  545. 'message' : message,
  546. 'explain' : explain
  547. }
  548. response = response.encode('utf-8')
  549. print('Status: %d %s' % (code, message))
  550. print('Content-Type: %s' % http.server.DEFAULT_ERROR_CONTENT_TYPE)
  551. print('Content-Length: %d' % len(response))
  552. print()
  553. sys.stdout.flush()
  554. sys.stdout.buffer.write(response)
  555. sys.stdout.buffer.flush()
  556. def handle_request(self, request_text=None):
  557. """Handle a single XML-RPC request passed through a CGI post method.
  558. If no XML data is given then it is read from stdin. The resulting
  559. XML-RPC response is printed to stdout along with the correct HTTP
  560. headers.
  561. """
  562. if request_text is None and \
  563. os.environ.get('REQUEST_METHOD', None) == 'GET':
  564. self.handle_get()
  565. else:
  566. # POST data is normally available through stdin
  567. try:
  568. length = int(os.environ.get('CONTENT_LENGTH', None))
  569. except (ValueError, TypeError):
  570. length = -1
  571. if request_text is None:
  572. request_text = sys.stdin.read(length)
  573. self.handle_xmlrpc(request_text)
  574. # -----------------------------------------------------------------------------
  575. # Self documenting XML-RPC Server.
  576. class ServerHTMLDoc(pydoc.HTMLDoc):
  577. """Class used to generate pydoc HTML document for a server"""
  578. def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
  579. """Mark up some plain text, given a context of symbols to look for.
  580. Each context dictionary maps object names to anchor names."""
  581. escape = escape or self.escape
  582. results = []
  583. here = 0
  584. # XXX Note that this regular expression does not allow for the
  585. # hyperlinking of arbitrary strings being used as method
  586. # names. Only methods with names consisting of word characters
  587. # and '.'s are hyperlinked.
  588. pattern = re.compile(r'\b((http|https|ftp)://\S+[\w/]|'
  589. r'RFC[- ]?(\d+)|'
  590. r'PEP[- ]?(\d+)|'
  591. r'(self\.)?((?:\w|\.)+))\b')
  592. while match := pattern.search(text, here):
  593. start, end = match.span()
  594. results.append(escape(text[here:start]))
  595. all, scheme, rfc, pep, selfdot, name = match.groups()
  596. if scheme:
  597. url = escape(all).replace('"', '"')
  598. results.append('<a href="%s">%s</a>' % (url, url))
  599. elif rfc:
  600. url = 'https://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  601. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  602. elif pep:
  603. url = 'https://peps.python.org/pep-%04d/' % int(pep)
  604. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  605. elif text[end:end+1] == '(':
  606. results.append(self.namelink(name, methods, funcs, classes))
  607. elif selfdot:
  608. results.append('self.<strong>%s</strong>' % name)
  609. else:
  610. results.append(self.namelink(name, classes))
  611. here = end
  612. results.append(escape(text[here:]))
  613. return ''.join(results)
  614. def docroutine(self, object, name, mod=None,
  615. funcs={}, classes={}, methods={}, cl=None):
  616. """Produce HTML documentation for a function or method object."""
  617. anchor = (cl and cl.__name__ or '') + '-' + name
  618. note = ''
  619. title = '<a name="%s"><strong>%s</strong></a>' % (
  620. self.escape(anchor), self.escape(name))
  621. if callable(object):
  622. argspec = str(signature(object))
  623. else:
  624. argspec = '(...)'
  625. if isinstance(object, tuple):
  626. argspec = object[0] or argspec
  627. docstring = object[1] or ""
  628. else:
  629. docstring = pydoc.getdoc(object)
  630. decl = title + argspec + (note and self.grey(
  631. '<font face="helvetica, arial">%s</font>' % note))
  632. doc = self.markup(
  633. docstring, self.preformat, funcs, classes, methods)
  634. doc = doc and '<dd><tt>%s</tt></dd>' % doc
  635. return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  636. def docserver(self, server_name, package_documentation, methods):
  637. """Produce HTML documentation for an XML-RPC server."""
  638. fdict = {}
  639. for key, value in methods.items():
  640. fdict[key] = '#-' + key
  641. fdict[value] = fdict[key]
  642. server_name = self.escape(server_name)
  643. head = '<big><big><strong>%s</strong></big></big>' % server_name
  644. result = self.heading(head)
  645. doc = self.markup(package_documentation, self.preformat, fdict)
  646. doc = doc and '<tt>%s</tt>' % doc
  647. result = result + '<p>%s</p>\n' % doc
  648. contents = []
  649. method_items = sorted(methods.items())
  650. for key, value in method_items:
  651. contents.append(self.docroutine(value, key, funcs=fdict))
  652. result = result + self.bigsection(
  653. 'Methods', 'functions', ''.join(contents))
  654. return result
  655. def page(self, title, contents):
  656. """Format an HTML page."""
  657. css_path = "/pydoc.css"
  658. css_link = (
  659. '<link rel="stylesheet" type="text/css" href="%s">' %
  660. css_path)
  661. return '''\
  662. <!DOCTYPE>
  663. <html lang="en">
  664. <head>
  665. <meta charset="utf-8">
  666. <title>Python: %s</title>
  667. %s</head><body>%s</body></html>''' % (title, css_link, contents)
  668. class XMLRPCDocGenerator:
  669. """Generates documentation for an XML-RPC server.
  670. This class is designed as mix-in and should not
  671. be constructed directly.
  672. """
  673. def __init__(self):
  674. # setup variables used for HTML documentation
  675. self.server_name = 'XML-RPC Server Documentation'
  676. self.server_documentation = \
  677. "This server exports the following methods through the XML-RPC "\
  678. "protocol."
  679. self.server_title = 'XML-RPC Server Documentation'
  680. def set_server_title(self, server_title):
  681. """Set the HTML title of the generated server documentation"""
  682. self.server_title = server_title
  683. def set_server_name(self, server_name):
  684. """Set the name of the generated HTML server documentation"""
  685. self.server_name = server_name
  686. def set_server_documentation(self, server_documentation):
  687. """Set the documentation string for the entire server."""
  688. self.server_documentation = server_documentation
  689. def generate_html_documentation(self):
  690. """generate_html_documentation() => html documentation for the server
  691. Generates HTML documentation for the server using introspection for
  692. installed functions and instances that do not implement the
  693. _dispatch method. Alternatively, instances can choose to implement
  694. the _get_method_argstring(method_name) method to provide the
  695. argument string used in the documentation and the
  696. _methodHelp(method_name) method to provide the help text used
  697. in the documentation."""
  698. methods = {}
  699. for method_name in self.system_listMethods():
  700. if method_name in self.funcs:
  701. method = self.funcs[method_name]
  702. elif self.instance is not None:
  703. method_info = [None, None] # argspec, documentation
  704. if hasattr(self.instance, '_get_method_argstring'):
  705. method_info[0] = self.instance._get_method_argstring(method_name)
  706. if hasattr(self.instance, '_methodHelp'):
  707. method_info[1] = self.instance._methodHelp(method_name)
  708. method_info = tuple(method_info)
  709. if method_info != (None, None):
  710. method = method_info
  711. elif not hasattr(self.instance, '_dispatch'):
  712. try:
  713. method = resolve_dotted_attribute(
  714. self.instance,
  715. method_name
  716. )
  717. except AttributeError:
  718. method = method_info
  719. else:
  720. method = method_info
  721. else:
  722. assert 0, "Could not find method in self.functions and no "\
  723. "instance installed"
  724. methods[method_name] = method
  725. documenter = ServerHTMLDoc()
  726. documentation = documenter.docserver(
  727. self.server_name,
  728. self.server_documentation,
  729. methods
  730. )
  731. return documenter.page(html.escape(self.server_title), documentation)
  732. class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
  733. """XML-RPC and documentation request handler class.
  734. Handles all HTTP POST requests and attempts to decode them as
  735. XML-RPC requests.
  736. Handles all HTTP GET requests and interprets them as requests
  737. for documentation.
  738. """
  739. def _get_css(self, url):
  740. path_here = os.path.dirname(os.path.realpath(__file__))
  741. css_path = os.path.join(path_here, "..", "pydoc_data", "_pydoc.css")
  742. with open(css_path, mode="rb") as fp:
  743. return fp.read()
  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. if self.path.endswith('.css'):
  754. content_type = 'text/css'
  755. response = self._get_css(self.path)
  756. else:
  757. content_type = 'text/html'
  758. response = self.server.generate_html_documentation().encode('utf-8')
  759. self.send_response(200)
  760. self.send_header('Content-Type', '%s; charset=UTF-8' % content_type)
  761. self.send_header("Content-length", str(len(response)))
  762. self.end_headers()
  763. self.wfile.write(response)
  764. class DocXMLRPCServer( SimpleXMLRPCServer,
  765. XMLRPCDocGenerator):
  766. """XML-RPC and HTML documentation server.
  767. Adds the ability to serve server documentation to the capabilities
  768. of SimpleXMLRPCServer.
  769. """
  770. def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler,
  771. logRequests=True, allow_none=False, encoding=None,
  772. bind_and_activate=True, use_builtin_types=False):
  773. SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests,
  774. allow_none, encoding, bind_and_activate,
  775. use_builtin_types)
  776. XMLRPCDocGenerator.__init__(self)
  777. class DocCGIXMLRPCRequestHandler( CGIXMLRPCRequestHandler,
  778. XMLRPCDocGenerator):
  779. """Handler for XML-RPC data and documentation requests passed through
  780. CGI"""
  781. def handle_get(self):
  782. """Handles the HTTP GET request.
  783. Interpret all HTTP GET requests as requests for server
  784. documentation.
  785. """
  786. response = self.generate_html_documentation().encode('utf-8')
  787. print('Content-Type: text/html')
  788. print('Content-Length: %d' % len(response))
  789. print()
  790. sys.stdout.flush()
  791. sys.stdout.buffer.write(response)
  792. sys.stdout.buffer.flush()
  793. def __init__(self):
  794. CGIXMLRPCRequestHandler.__init__(self)
  795. XMLRPCDocGenerator.__init__(self)
  796. if __name__ == '__main__':
  797. import datetime
  798. class ExampleService:
  799. def getData(self):
  800. return '42'
  801. class currentTime:
  802. @staticmethod
  803. def getCurrentTime():
  804. return datetime.datetime.now()
  805. with SimpleXMLRPCServer(("localhost", 8000)) as server:
  806. server.register_function(pow)
  807. server.register_function(lambda x,y: x+y, 'add')
  808. server.register_instance(ExampleService(), allow_dotted_names=True)
  809. server.register_multicall_functions()
  810. print('Serving XML-RPC on localhost port 8000')
  811. print('It is advisable to run this example server within a secure, closed network.')
  812. try:
  813. server.serve_forever()
  814. except KeyboardInterrupt:
  815. print("\nKeyboard interrupt received, exiting.")
  816. sys.exit(0)