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