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