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