blob: 458d4278f8f4765c10f9d1d9de3ec862104b6536 [file] [log] [blame]
Fredrik Lundhb329b712001-09-17 17:35:21 +00001"""Simple XML-RPC Server.
2
3This module can be used to create simple XML-RPC servers
4by creating a server and either installing functions, a
Martin v. Löwisd69663d2003-01-15 11:37:23 +00005class instance, or by extending the SimpleXMLRPCServer
Fredrik Lundhb329b712001-09-17 17:35:21 +00006class.
7
Martin v. Löwisd69663d2003-01-15 11:37:23 +00008It can also be used to handle XML-RPC requests in a CGI
9environment using CGIXMLRPCRequestHandler.
10
Fredrik Lundhb329b712001-09-17 17:35:21 +000011A list of possible usage patterns follows:
12
131. Install functions:
14
15server = SimpleXMLRPCServer(("localhost", 8000))
16server.register_function(pow)
17server.register_function(lambda x,y: x+y, 'add')
18server.serve_forever()
19
202. Install an instance:
21
22class MyFuncs:
23 def __init__(self):
Neal Norwitz9d72bb42007-04-17 08:48:32 +000024 # make all of the sys functions available through sys.func_name
25 import sys
26 self.sys = sys
Martin v. Löwisd69663d2003-01-15 11:37:23 +000027 def _listMethods(self):
28 # implement this method so that system.listMethods
Neal Norwitz9d72bb42007-04-17 08:48:32 +000029 # knows to advertise the sys methods
Martin v. Löwisd69663d2003-01-15 11:37:23 +000030 return list_public_methods(self) + \
Neal Norwitz9d72bb42007-04-17 08:48:32 +000031 ['sys.' + method for method in list_public_methods(self.sys)]
Fredrik Lundhb329b712001-09-17 17:35:21 +000032 def pow(self, x, y): return pow(x, y)
33 def add(self, x, y) : return x + y
Tim Peters2c60f7a2003-01-29 03:49:43 +000034
Fredrik Lundhb329b712001-09-17 17:35:21 +000035server = SimpleXMLRPCServer(("localhost", 8000))
Martin v. Löwisd69663d2003-01-15 11:37:23 +000036server.register_introspection_functions()
Fredrik Lundhb329b712001-09-17 17:35:21 +000037server.register_instance(MyFuncs())
38server.serve_forever()
39
403. Install an instance with custom dispatch method:
41
42class Math:
Martin v. Löwisd69663d2003-01-15 11:37:23 +000043 def _listMethods(self):
44 # this method must be present for system.listMethods
45 # to work
46 return ['add', 'pow']
47 def _methodHelp(self, method):
48 # this method must be present for system.methodHelp
49 # to work
50 if method == 'add':
51 return "add(2,3) => 5"
52 elif method == 'pow':
53 return "pow(x, y[, z]) => number"
54 else:
55 # By convention, return empty
56 # string if no help is available
57 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +000058 def _dispatch(self, method, params):
59 if method == 'pow':
Martin v. Löwisd69663d2003-01-15 11:37:23 +000060 return pow(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +000061 elif method == 'add':
62 return params[0] + params[1]
63 else:
64 raise 'bad method'
Martin v. Löwisd69663d2003-01-15 11:37:23 +000065
Fredrik Lundhb329b712001-09-17 17:35:21 +000066server = SimpleXMLRPCServer(("localhost", 8000))
Martin v. Löwisd69663d2003-01-15 11:37:23 +000067server.register_introspection_functions()
Fredrik Lundhb329b712001-09-17 17:35:21 +000068server.register_instance(Math())
69server.serve_forever()
70
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000714. Subclass SimpleXMLRPCServer:
Fredrik Lundhb329b712001-09-17 17:35:21 +000072
Martin v. Löwisd69663d2003-01-15 11:37:23 +000073class MathServer(SimpleXMLRPCServer):
Fredrik Lundhb329b712001-09-17 17:35:21 +000074 def _dispatch(self, method, params):
75 try:
76 # We are forcing the 'export_' prefix on methods that are
77 # callable through XML-RPC to prevent potential security
78 # problems
79 func = getattr(self, 'export_' + method)
80 except AttributeError:
81 raise Exception('method "%s" is not supported' % method)
82 else:
Martin v. Löwisd69663d2003-01-15 11:37:23 +000083 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +000084
85 def export_add(self, x, y):
86 return x + y
87
Martin v. Löwisd69663d2003-01-15 11:37:23 +000088server = MathServer(("localhost", 8000))
Fredrik Lundhb329b712001-09-17 17:35:21 +000089server.serve_forever()
Martin v. Löwisd69663d2003-01-15 11:37:23 +000090
915. CGI script:
92
93server = CGIXMLRPCRequestHandler()
94server.register_function(pow)
95server.handle_request()
Fredrik Lundhb329b712001-09-17 17:35:21 +000096"""
97
98# Written by Brian Quinlan (brian@sweetapp.com).
99# Based on code written by Fredrik Lundh.
100
101import xmlrpclib
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000102from xmlrpclib import Fault
Fredrik Lundhb329b712001-09-17 17:35:21 +0000103import SocketServer
104import BaseHTTPServer
105import sys
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000106import os
107try:
108 import fcntl
109except ImportError:
110 fcntl = None
Fredrik Lundhb329b712001-09-17 17:35:21 +0000111
Guido van Rossumd0641422005-02-03 15:01:24 +0000112def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000113 """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
Fredrik Lundhb329b712001-09-17 17:35:21 +0000114
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000115 Resolves a dotted attribute name to an object. Raises
116 an AttributeError if any attribute in the chain starts with a '_'.
Guido van Rossumd0641422005-02-03 15:01:24 +0000117
118 If the optional allow_dotted_names argument is false, dots are not
119 supported and this function operates similar to getattr(obj, attr).
Fredrik Lundhb329b712001-09-17 17:35:21 +0000120 """
121
Guido van Rossumd0641422005-02-03 15:01:24 +0000122 if allow_dotted_names:
123 attrs = attr.split('.')
124 else:
125 attrs = [attr]
126
127 for i in attrs:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000128 if i.startswith('_'):
129 raise AttributeError(
130 'attempt to access private attribute "%s"' % i
131 )
132 else:
133 obj = getattr(obj,i)
134 return obj
Fredrik Lundhb329b712001-09-17 17:35:21 +0000135
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000136def list_public_methods(obj):
137 """Returns a list of attribute strings, found in the specified
138 object, which represent callable attributes"""
139
140 return [member for member in dir(obj)
141 if not member.startswith('_') and
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000142 hasattr(getattr(obj, member), '__call__')]
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000143
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000144class SimpleXMLRPCDispatcher:
145 """Mix-in class that dispatches XML-RPC requests.
146
147 This class is used to register XML-RPC method handlers
148 and then to dispatch them. There should never be any
149 reason to instantiate this class directly.
150 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000151
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000152 def __init__(self, allow_none, encoding):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000153 self.funcs = {}
154 self.instance = None
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000155 self.allow_none = allow_none
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000156 self.encoding = encoding
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000157
Guido van Rossumd0641422005-02-03 15:01:24 +0000158 def register_instance(self, instance, allow_dotted_names=False):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000159 """Registers an instance to respond to XML-RPC requests.
160
161 Only one instance can be installed at a time.
162
163 If the registered instance has a _dispatch method then that
164 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000165 its parameters as a tuple
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000166 e.g. instance._dispatch('add',(2,3))
167
168 If the registered instance does not have a _dispatch method
169 then the instance will be searched to find a matching method
170 and, if found, will be called. Methods beginning with an '_'
171 are considered private and will not be called by
172 SimpleXMLRPCServer.
173
174 If a registered function matches a XML-RPC request, then it
175 will be called instead of the registered instance.
Guido van Rossumd0641422005-02-03 15:01:24 +0000176
177 If the optional allow_dotted_names argument is true and the
178 instance does not have a _dispatch method, method names
179 containing dots are supported and resolved, as long as none of
180 the name segments start with an '_'.
181
182 *** SECURITY WARNING: ***
183
184 Enabling the allow_dotted_names options allows intruders
185 to access your module's global variables and may allow
186 intruders to execute arbitrary code on your machine. Only
187 use this option on a secure, closed network.
188
Fredrik Lundhb329b712001-09-17 17:35:21 +0000189 """
190
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000191 self.instance = instance
Guido van Rossumd0641422005-02-03 15:01:24 +0000192 self.allow_dotted_names = allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000193
194 def register_function(self, function, name = None):
195 """Registers a function to respond to XML-RPC requests.
196
197 The optional name argument can be used to set a Unicode name
198 for the function.
199 """
200
201 if name is None:
202 name = function.__name__
203 self.funcs[name] = function
204
205 def register_introspection_functions(self):
206 """Registers the XML-RPC introspection methods in the system
207 namespace.
208
209 see http://xmlrpc.usefulinc.com/doc/reserved.html
210 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000211
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000212 self.funcs.update({'system.listMethods' : self.system_listMethods,
213 'system.methodSignature' : self.system_methodSignature,
214 'system.methodHelp' : self.system_methodHelp})
215
216 def register_multicall_functions(self):
217 """Registers the XML-RPC multicall method in the system
218 namespace.
219
220 see http://www.xmlrpc.com/discuss/msgReader$1208"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000221
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000222 self.funcs.update({'system.multicall' : self.system_multicall})
Tim Peters2c60f7a2003-01-29 03:49:43 +0000223
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000224 def _marshaled_dispatch(self, data, dispatch_method = None):
225 """Dispatches an XML-RPC method from marshalled (XML) data.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000226
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000227 XML-RPC methods are dispatched from the marshalled (XML) data
228 using the _dispatch method and the result is returned as
229 marshalled data. For backwards compatibility, a dispatch
Tim Peters2c60f7a2003-01-29 03:49:43 +0000230 function can be provided as an argument (see comment in
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000231 SimpleXMLRPCRequestHandler.do_POST) but overriding the
232 existing method through subclassing is the prefered means
233 of changing method dispatch behavior.
234 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000235
Fredrik Lundhb329b712001-09-17 17:35:21 +0000236 try:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000237 params, method = xmlrpclib.loads(data)
238
239 # generate response
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000240 if dispatch_method is not None:
241 response = dispatch_method(method, params)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000242 else:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000243 response = self._dispatch(method, params)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000244 # wrap response in a singleton tuple
245 response = (response,)
Tim Peters536cf992005-12-25 23:18:31 +0000246 response = xmlrpclib.dumps(response, methodresponse=1,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000247 allow_none=self.allow_none, encoding=self.encoding)
Guido van Rossumb940e112007-01-10 16:19:56 +0000248 except Fault as fault:
Tim Peters536cf992005-12-25 23:18:31 +0000249 response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000250 encoding=self.encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000251 except:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000252 # report exception back to server
Thomas Wouters89f507f2006-12-13 04:49:30 +0000253 exc_type, exc_value, exc_tb = sys.exc_info()
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000254 response = xmlrpclib.dumps(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000255 xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)),
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000256 encoding=self.encoding, allow_none=self.allow_none,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000257 )
258
259 return response
260
261 def system_listMethods(self):
262 """system.listMethods() => ['add', 'subtract', 'multiple']
263
264 Returns a list of the methods supported by the server."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000265
Hye-Shik Chang96042862007-08-19 10:49:11 +0000266 methods = set(self.funcs.keys())
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000267 if self.instance is not None:
268 # Instance can implement _listMethod to return a list of
269 # methods
270 if hasattr(self.instance, '_listMethods'):
Hye-Shik Chang96042862007-08-19 10:49:11 +0000271 methods |= set(self.instance._listMethods())
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000272 # if the instance has a _dispatch method then we
273 # don't have enough information to provide a list
274 # of methods
275 elif not hasattr(self.instance, '_dispatch'):
Hye-Shik Chang96042862007-08-19 10:49:11 +0000276 methods |= set(list_public_methods(self.instance))
277 return sorted(methods)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000278
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000279 def system_methodSignature(self, method_name):
280 """system.methodSignature('add') => [double, int, int]
281
Brett Cannonb9b5f162004-10-03 23:21:44 +0000282 Returns a list describing the signature of the method. In the
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000283 above example, the add method takes two integers as arguments
284 and returns a double result.
285
286 This server does NOT support system.methodSignature."""
287
288 # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
Tim Peters2c60f7a2003-01-29 03:49:43 +0000289
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000290 return 'signatures not supported'
291
292 def system_methodHelp(self, method_name):
293 """system.methodHelp('add') => "Adds two integers together"
294
295 Returns a string containing documentation for the specified method."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000296
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000297 method = None
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000298 if method_name in self.funcs:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000299 method = self.funcs[method_name]
300 elif self.instance is not None:
301 # Instance can implement _methodHelp to return help for a method
302 if hasattr(self.instance, '_methodHelp'):
303 return self.instance._methodHelp(method_name)
304 # if the instance has a _dispatch method then we
305 # don't have enough information to provide help
306 elif not hasattr(self.instance, '_dispatch'):
307 try:
308 method = resolve_dotted_attribute(
309 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000310 method_name,
311 self.allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000312 )
313 except AttributeError:
314 pass
315
316 # Note that we aren't checking that the method actually
317 # be a callable object of some kind
318 if method is None:
319 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +0000320 else:
Neal Norwitz732911f2003-06-29 04:16:28 +0000321 import pydoc
Neal Norwitz3f401f02003-06-29 04:19:37 +0000322 return pydoc.getdoc(method)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000323
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000324 def system_multicall(self, call_list):
325 """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
326[[4], ...]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000327
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000328 Allows the caller to package multiple XML-RPC calls into a single
329 request.
330
Tim Peters2c60f7a2003-01-29 03:49:43 +0000331 See http://www.xmlrpc.com/discuss/msgReader$1208
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000332 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000333
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000334 results = []
335 for call in call_list:
336 method_name = call['methodName']
337 params = call['params']
338
339 try:
340 # XXX A marshalling error in any response will fail the entire
341 # multicall. If someone cares they should fix this.
342 results.append([self._dispatch(method_name, params)])
Guido van Rossumb940e112007-01-10 16:19:56 +0000343 except Fault as fault:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000344 results.append(
345 {'faultCode' : fault.faultCode,
346 'faultString' : fault.faultString}
347 )
348 except:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000349 exc_type, exc_value, exc_tb = sys.exc_info()
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000350 results.append(
351 {'faultCode' : 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000352 'faultString' : "%s:%s" % (exc_type, exc_value)}
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000353 )
354 return results
Tim Peters2c60f7a2003-01-29 03:49:43 +0000355
Fredrik Lundhb329b712001-09-17 17:35:21 +0000356 def _dispatch(self, method, params):
357 """Dispatches the XML-RPC method.
358
359 XML-RPC calls are forwarded to a registered function that
360 matches the called XML-RPC method name. If no such function
361 exists then the call is forwarded to the registered instance,
362 if available.
363
364 If the registered instance has a _dispatch method then that
365 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000366 its parameters as a tuple
Fredrik Lundhb329b712001-09-17 17:35:21 +0000367 e.g. instance._dispatch('add',(2,3))
368
369 If the registered instance does not have a _dispatch method
370 then the instance will be searched to find a matching method
371 and, if found, will be called.
372
373 Methods beginning with an '_' are considered private and will
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000374 not be called.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000375 """
376
Fredrik Lundhb329b712001-09-17 17:35:21 +0000377 func = None
378 try:
379 # check to see if a matching function has been registered
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000380 func = self.funcs[method]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000381 except KeyError:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000382 if self.instance is not None:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000383 # check for a _dispatch method
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000384 if hasattr(self.instance, '_dispatch'):
385 return self.instance._dispatch(method, params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000386 else:
387 # call instance method directly
388 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000389 func = resolve_dotted_attribute(
390 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000391 method,
392 self.allow_dotted_names
Fredrik Lundhb329b712001-09-17 17:35:21 +0000393 )
394 except AttributeError:
395 pass
396
397 if func is not None:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000398 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000399 else:
400 raise Exception('method "%s" is not supported' % method)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000401
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000402class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
403 """Simple XML-RPC request handler class.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000404
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000405 Handles all HTTP POST requests and attempts to decode them as
406 XML-RPC requests.
407 """
408
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000409 # Class attribute listing the accessible path components;
410 # paths not on this list will result in a 404 error.
411 rpc_paths = ('/', '/RPC2')
412
413 def is_rpc_path_valid(self):
414 if self.rpc_paths:
415 return self.path in self.rpc_paths
416 else:
417 # If .rpc_paths is empty, just assume all paths are legal
418 return True
419
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000420 def do_POST(self):
421 """Handles the HTTP POST request.
422
423 Attempts to interpret all HTTP POST requests as XML-RPC calls,
424 which are forwarded to the server's _dispatch method for handling.
425 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000426
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000427 # Check that the path is legal
428 if not self.is_rpc_path_valid():
429 self.report_404()
430 return
431
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000432 try:
Tim Peters536cf992005-12-25 23:18:31 +0000433 # Get arguments by reading body of request.
434 # We read this in chunks to avoid straining
Andrew M. Kuchlinge63fde72005-12-04 15:36:57 +0000435 # socket.read(); around the 10 or 15Mb mark, some platforms
436 # begin to have problems (bug #792570).
437 max_chunk_size = 10*1024*1024
438 size_remaining = int(self.headers["content-length"])
439 L = []
440 while size_remaining:
441 chunk_size = min(size_remaining, max_chunk_size)
442 L.append(self.rfile.read(chunk_size))
443 size_remaining -= len(L[-1])
Hye-Shik Chang96042862007-08-19 10:49:11 +0000444 data = b''.join(L)
Andrew M. Kuchlinge63fde72005-12-04 15:36:57 +0000445
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000446 # In previous versions of SimpleXMLRPCServer, _dispatch
447 # could be overridden in this class, instead of in
448 # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
449 # check to see if a subclass implements _dispatch and dispatch
450 # using that method if present.
451 response = self.server._marshaled_dispatch(
452 data, getattr(self, '_dispatch', None)
453 )
454 except: # This should only happen if the module is buggy
455 # internal error, report as HTTP server error
456 self.send_response(500)
457 self.end_headers()
458 else:
459 # got a valid XML RPC response
460 self.send_response(200)
461 self.send_header("Content-type", "text/xml")
462 self.send_header("Content-length", str(len(response)))
463 self.end_headers()
464 self.wfile.write(response)
465
466 # shut down the connection
467 self.wfile.flush()
468 self.connection.shutdown(1)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000469
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000470 def report_404 (self):
471 # Report a 404 error
472 self.send_response(404)
473 response = 'No such page'
474 self.send_header("Content-type", "text/plain")
475 self.send_header("Content-length", str(len(response)))
476 self.end_headers()
477 self.wfile.write(response)
478 # shut down the connection
479 self.wfile.flush()
480 self.connection.shutdown(1)
481
Fredrik Lundhb329b712001-09-17 17:35:21 +0000482 def log_request(self, code='-', size='-'):
483 """Selectively log an accepted request."""
484
485 if self.server.logRequests:
486 BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
487
Tim Peters2c60f7a2003-01-29 03:49:43 +0000488class SimpleXMLRPCServer(SocketServer.TCPServer,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000489 SimpleXMLRPCDispatcher):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000490 """Simple XML-RPC server.
491
492 Simple XML-RPC server that allows functions and a single instance
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000493 to be installed to handle requests. The default implementation
494 attempts to dispatch XML-RPC calls to the functions or instance
495 installed in the server. Override the _dispatch method inhereted
496 from SimpleXMLRPCDispatcher to change this behavior.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000497 """
498
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000499 allow_reuse_address = True
500
Fredrik Lundhb329b712001-09-17 17:35:21 +0000501 def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502 logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000503 self.logRequests = logRequests
Tim Peters2c60f7a2003-01-29 03:49:43 +0000504
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000505 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000506 SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000507
Tim Peters536cf992005-12-25 23:18:31 +0000508 # [Bug #1222790] If possible, set close-on-exec flag; if a
509 # method spawns a subprocess, the subprocess shouldn't have
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000510 # the listening socket open.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000511 if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000512 flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
513 flags |= fcntl.FD_CLOEXEC
514 fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
515
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000516class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
517 """Simple handler for XML-RPC data passed through CGI."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000518
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000519 def __init__(self, allow_none=False, encoding=None):
520 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000521
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000522 def handle_xmlrpc(self, request_text):
523 """Handle a single XML-RPC request"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000524
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000525 response = self._marshaled_dispatch(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000526
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000527 print('Content-Type: text/xml')
528 print('Content-Length: %d' % len(response))
529 print()
Martin v. Löwis9c5ea502003-05-01 05:05:09 +0000530 sys.stdout.write(response)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000531
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000532 def handle_get(self):
533 """Handle a single HTTP GET request.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000534
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000535 Default implementation indicates an error because
536 XML-RPC uses the POST method.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000537 """
538
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000539 code = 400
540 message, explain = \
541 BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
Tim Peters2c60f7a2003-01-29 03:49:43 +0000542
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000543 response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
544 {
Tim Peters2c60f7a2003-01-29 03:49:43 +0000545 'code' : code,
546 'message' : message,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000547 'explain' : explain
548 }
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000549 print('Status: %d %s' % (code, message))
550 print('Content-Type: text/html')
551 print('Content-Length: %d' % len(response))
552 print()
Neal Norwitz732911f2003-06-29 04:16:28 +0000553 sys.stdout.write(response)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000554
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000555 def handle_request(self, request_text = None):
556 """Handle a single XML-RPC request passed through a CGI post method.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000557
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000558 If no XML data is given then it is read from stdin. The resulting
559 XML-RPC response is printed to stdout along with the correct HTTP
560 headers.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000561 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000562
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000563 if request_text is None and \
564 os.environ.get('REQUEST_METHOD', None) == 'GET':
565 self.handle_get()
566 else:
567 # POST data is normally available through stdin
568 if request_text is None:
Tim Peters2c60f7a2003-01-29 03:49:43 +0000569 request_text = sys.stdin.read()
Fredrik Lundhb329b712001-09-17 17:35:21 +0000570
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000571 self.handle_xmlrpc(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000572
Fredrik Lundhb329b712001-09-17 17:35:21 +0000573if __name__ == '__main__':
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000574 print('Running XML-RPC server on port 8000')
Fredrik Lundhb329b712001-09-17 17:35:21 +0000575 server = SimpleXMLRPCServer(("localhost", 8000))
576 server.register_function(pow)
577 server.register_function(lambda x,y: x+y, 'add')
578 server.serve_forever()