blob: 5fad0af4a344bbdbdbd5e445712d7c44923341bd [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):
24 # make all of the string functions available through
25 # string.func_name
26 import string
27 self.string = string
Martin v. Löwisd69663d2003-01-15 11:37:23 +000028 def _listMethods(self):
29 # implement this method so that system.listMethods
30 # knows to advertise the strings methods
31 return list_public_methods(self) + \
32 ['string.' + method for method in list_public_methods(self.string)]
Fredrik Lundhb329b712001-09-17 17:35:21 +000033 def pow(self, x, y): return pow(x, y)
34 def add(self, x, y) : return x + y
Tim Peters2c60f7a2003-01-29 03:49:43 +000035
Fredrik Lundhb329b712001-09-17 17:35:21 +000036server = SimpleXMLRPCServer(("localhost", 8000))
Martin v. Löwisd69663d2003-01-15 11:37:23 +000037server.register_introspection_functions()
Fredrik Lundhb329b712001-09-17 17:35:21 +000038server.register_instance(MyFuncs())
39server.serve_forever()
40
413. Install an instance with custom dispatch method:
42
43class Math:
Martin v. Löwisd69663d2003-01-15 11:37:23 +000044 def _listMethods(self):
45 # this method must be present for system.listMethods
46 # to work
47 return ['add', 'pow']
48 def _methodHelp(self, method):
49 # this method must be present for system.methodHelp
50 # to work
51 if method == 'add':
52 return "add(2,3) => 5"
53 elif method == 'pow':
54 return "pow(x, y[, z]) => number"
55 else:
56 # By convention, return empty
57 # string if no help is available
58 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +000059 def _dispatch(self, method, params):
60 if method == 'pow':
Martin v. Löwisd69663d2003-01-15 11:37:23 +000061 return pow(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +000062 elif method == 'add':
63 return params[0] + params[1]
64 else:
65 raise 'bad method'
Martin v. Löwisd69663d2003-01-15 11:37:23 +000066
Fredrik Lundhb329b712001-09-17 17:35:21 +000067server = SimpleXMLRPCServer(("localhost", 8000))
Martin v. Löwisd69663d2003-01-15 11:37:23 +000068server.register_introspection_functions()
Fredrik Lundhb329b712001-09-17 17:35:21 +000069server.register_instance(Math())
70server.serve_forever()
71
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000724. Subclass SimpleXMLRPCServer:
Fredrik Lundhb329b712001-09-17 17:35:21 +000073
Martin v. Löwisd69663d2003-01-15 11:37:23 +000074class MathServer(SimpleXMLRPCServer):
Fredrik Lundhb329b712001-09-17 17:35:21 +000075 def _dispatch(self, method, params):
76 try:
77 # We are forcing the 'export_' prefix on methods that are
78 # callable through XML-RPC to prevent potential security
79 # problems
80 func = getattr(self, 'export_' + method)
81 except AttributeError:
82 raise Exception('method "%s" is not supported' % method)
83 else:
Martin v. Löwisd69663d2003-01-15 11:37:23 +000084 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +000085
86 def export_add(self, x, y):
87 return x + y
88
Martin v. Löwisd69663d2003-01-15 11:37:23 +000089server = MathServer(("localhost", 8000))
Fredrik Lundhb329b712001-09-17 17:35:21 +000090server.serve_forever()
Martin v. Löwisd69663d2003-01-15 11:37:23 +000091
925. CGI script:
93
94server = CGIXMLRPCRequestHandler()
95server.register_function(pow)
96server.handle_request()
Fredrik Lundhb329b712001-09-17 17:35:21 +000097"""
98
99# Written by Brian Quinlan (brian@sweetapp.com).
100# Based on code written by Fredrik Lundh.
101
102import xmlrpclib
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000103from xmlrpclib import Fault
Georg Brandle152a772008-05-24 18:31:28 +0000104import SocketServer
Fredrik Lundhb329b712001-09-17 17:35:21 +0000105import BaseHTTPServer
106import sys
Anthony Baxtere29002c2006-04-12 12:07:31 +0000107import os
Facundo Batista7f686fc2007-08-17 19:16:44 +0000108import traceback
Anthony Baxtere29002c2006-04-12 12:07:31 +0000109try:
110 import fcntl
111except ImportError:
112 fcntl = None
Fredrik Lundhb329b712001-09-17 17:35:21 +0000113
Guido van Rossumd0641422005-02-03 15:01:24 +0000114def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000115 """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
Fredrik Lundhb329b712001-09-17 17:35:21 +0000116
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000117 Resolves a dotted attribute name to an object. Raises
118 an AttributeError if any attribute in the chain starts with a '_'.
Guido van Rossumd0641422005-02-03 15:01:24 +0000119
120 If the optional allow_dotted_names argument is false, dots are not
121 supported and this function operates similar to getattr(obj, attr).
Fredrik Lundhb329b712001-09-17 17:35:21 +0000122 """
123
Guido van Rossumd0641422005-02-03 15:01:24 +0000124 if allow_dotted_names:
125 attrs = attr.split('.')
126 else:
127 attrs = [attr]
128
129 for i in attrs:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000130 if i.startswith('_'):
131 raise AttributeError(
132 'attempt to access private attribute "%s"' % i
133 )
134 else:
135 obj = getattr(obj,i)
136 return obj
Fredrik Lundhb329b712001-09-17 17:35:21 +0000137
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000138def list_public_methods(obj):
139 """Returns a list of attribute strings, found in the specified
140 object, which represent callable attributes"""
141
142 return [member for member in dir(obj)
143 if not member.startswith('_') and
144 callable(getattr(obj, member))]
145
146def remove_duplicates(lst):
147 """remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
148
149 Returns a copy of a list without duplicates. Every list
150 item must be hashable and the order of the items in the
151 resulting list is not defined.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000152 """
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000153 u = {}
154 for x in lst:
155 u[x] = 1
156
157 return u.keys()
158
159class SimpleXMLRPCDispatcher:
160 """Mix-in class that dispatches XML-RPC requests.
161
162 This class is used to register XML-RPC method handlers
163 and then to dispatch them. There should never be any
164 reason to instantiate this class directly.
165 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000166
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000167 def __init__(self, allow_none, encoding):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000168 self.funcs = {}
169 self.instance = None
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000170 self.allow_none = allow_none
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000171 self.encoding = encoding
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000172
Guido van Rossumd0641422005-02-03 15:01:24 +0000173 def register_instance(self, instance, allow_dotted_names=False):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000174 """Registers an instance to respond to XML-RPC requests.
175
176 Only one instance can be installed at a time.
177
178 If the registered instance has a _dispatch method then that
179 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000180 its parameters as a tuple
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000181 e.g. instance._dispatch('add',(2,3))
182
183 If the registered instance does not have a _dispatch method
184 then the instance will be searched to find a matching method
185 and, if found, will be called. Methods beginning with an '_'
186 are considered private and will not be called by
187 SimpleXMLRPCServer.
188
189 If a registered function matches a XML-RPC request, then it
190 will be called instead of the registered instance.
Guido van Rossumd0641422005-02-03 15:01:24 +0000191
192 If the optional allow_dotted_names argument is true and the
193 instance does not have a _dispatch method, method names
194 containing dots are supported and resolved, as long as none of
195 the name segments start with an '_'.
196
197 *** SECURITY WARNING: ***
198
199 Enabling the allow_dotted_names options allows intruders
200 to access your module's global variables and may allow
201 intruders to execute arbitrary code on your machine. Only
202 use this option on a secure, closed network.
203
Fredrik Lundhb329b712001-09-17 17:35:21 +0000204 """
205
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000206 self.instance = instance
Guido van Rossumd0641422005-02-03 15:01:24 +0000207 self.allow_dotted_names = allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000208
209 def register_function(self, function, name = None):
210 """Registers a function to respond to XML-RPC requests.
211
212 The optional name argument can be used to set a Unicode name
213 for the function.
214 """
215
216 if name is None:
217 name = function.__name__
218 self.funcs[name] = function
219
220 def register_introspection_functions(self):
221 """Registers the XML-RPC introspection methods in the system
222 namespace.
223
224 see http://xmlrpc.usefulinc.com/doc/reserved.html
225 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000226
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000227 self.funcs.update({'system.listMethods' : self.system_listMethods,
228 'system.methodSignature' : self.system_methodSignature,
229 'system.methodHelp' : self.system_methodHelp})
230
231 def register_multicall_functions(self):
232 """Registers the XML-RPC multicall method in the system
233 namespace.
234
235 see http://www.xmlrpc.com/discuss/msgReader$1208"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000236
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000237 self.funcs.update({'system.multicall' : self.system_multicall})
Tim Peters2c60f7a2003-01-29 03:49:43 +0000238
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000239 def _marshaled_dispatch(self, data, dispatch_method = None):
240 """Dispatches an XML-RPC method from marshalled (XML) data.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000241
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000242 XML-RPC methods are dispatched from the marshalled (XML) data
243 using the _dispatch method and the result is returned as
244 marshalled data. For backwards compatibility, a dispatch
Tim Peters2c60f7a2003-01-29 03:49:43 +0000245 function can be provided as an argument (see comment in
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000246 SimpleXMLRPCRequestHandler.do_POST) but overriding the
247 existing method through subclassing is the prefered means
248 of changing method dispatch behavior.
249 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000250
Fredrik Lundhb329b712001-09-17 17:35:21 +0000251 try:
Georg Brandlb9120e72006-06-01 12:30:46 +0000252 params, method = xmlrpclib.loads(data)
253
254 # generate response
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000255 if dispatch_method is not None:
256 response = dispatch_method(method, params)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000257 else:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000258 response = self._dispatch(method, params)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000259 # wrap response in a singleton tuple
260 response = (response,)
Tim Peters536cf992005-12-25 23:18:31 +0000261 response = xmlrpclib.dumps(response, methodresponse=1,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000262 allow_none=self.allow_none, encoding=self.encoding)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000263 except Fault, fault:
Tim Peters536cf992005-12-25 23:18:31 +0000264 response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000265 encoding=self.encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000266 except:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000267 # report exception back to server
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000268 exc_type, exc_value, exc_tb = sys.exc_info()
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000269 response = xmlrpclib.dumps(
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000270 xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)),
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000271 encoding=self.encoding, allow_none=self.allow_none,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000272 )
273
274 return response
275
276 def system_listMethods(self):
277 """system.listMethods() => ['add', 'subtract', 'multiple']
278
279 Returns a list of the methods supported by the server."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000280
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000281 methods = self.funcs.keys()
282 if self.instance is not None:
283 # Instance can implement _listMethod to return a list of
284 # methods
285 if hasattr(self.instance, '_listMethods'):
286 methods = remove_duplicates(
287 methods + self.instance._listMethods()
288 )
289 # if the instance has a _dispatch method then we
290 # don't have enough information to provide a list
291 # of methods
292 elif not hasattr(self.instance, '_dispatch'):
293 methods = remove_duplicates(
294 methods + list_public_methods(self.instance)
295 )
296 methods.sort()
297 return methods
Tim Peters2c60f7a2003-01-29 03:49:43 +0000298
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000299 def system_methodSignature(self, method_name):
300 """system.methodSignature('add') => [double, int, int]
301
Brett Cannonb9b5f162004-10-03 23:21:44 +0000302 Returns a list describing the signature of the method. In the
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000303 above example, the add method takes two integers as arguments
304 and returns a double result.
305
306 This server does NOT support system.methodSignature."""
307
308 # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
Tim Peters2c60f7a2003-01-29 03:49:43 +0000309
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000310 return 'signatures not supported'
311
312 def system_methodHelp(self, method_name):
313 """system.methodHelp('add') => "Adds two integers together"
314
315 Returns a string containing documentation for the specified method."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000316
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000317 method = None
318 if self.funcs.has_key(method_name):
319 method = self.funcs[method_name]
320 elif self.instance is not None:
321 # Instance can implement _methodHelp to return help for a method
322 if hasattr(self.instance, '_methodHelp'):
323 return self.instance._methodHelp(method_name)
324 # if the instance has a _dispatch method then we
325 # don't have enough information to provide help
326 elif not hasattr(self.instance, '_dispatch'):
327 try:
328 method = resolve_dotted_attribute(
329 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000330 method_name,
331 self.allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000332 )
333 except AttributeError:
334 pass
335
336 # Note that we aren't checking that the method actually
337 # be a callable object of some kind
338 if method is None:
339 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +0000340 else:
Neal Norwitz732911f2003-06-29 04:16:28 +0000341 import pydoc
Neal Norwitz3f401f02003-06-29 04:19:37 +0000342 return pydoc.getdoc(method)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000343
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000344 def system_multicall(self, call_list):
345 """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
346[[4], ...]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000347
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000348 Allows the caller to package multiple XML-RPC calls into a single
349 request.
350
Tim Peters2c60f7a2003-01-29 03:49:43 +0000351 See http://www.xmlrpc.com/discuss/msgReader$1208
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000352 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000353
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000354 results = []
355 for call in call_list:
356 method_name = call['methodName']
357 params = call['params']
358
359 try:
360 # XXX A marshalling error in any response will fail the entire
361 # multicall. If someone cares they should fix this.
362 results.append([self._dispatch(method_name, params)])
363 except Fault, fault:
364 results.append(
365 {'faultCode' : fault.faultCode,
366 'faultString' : fault.faultString}
367 )
368 except:
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000369 exc_type, exc_value, exc_tb = sys.exc_info()
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000370 results.append(
371 {'faultCode' : 1,
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000372 'faultString' : "%s:%s" % (exc_type, exc_value)}
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000373 )
374 return results
Tim Peters2c60f7a2003-01-29 03:49:43 +0000375
Fredrik Lundhb329b712001-09-17 17:35:21 +0000376 def _dispatch(self, method, params):
377 """Dispatches the XML-RPC method.
378
379 XML-RPC calls are forwarded to a registered function that
380 matches the called XML-RPC method name. If no such function
381 exists then the call is forwarded to the registered instance,
382 if available.
383
384 If the registered instance has a _dispatch method then that
385 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000386 its parameters as a tuple
Fredrik Lundhb329b712001-09-17 17:35:21 +0000387 e.g. instance._dispatch('add',(2,3))
388
389 If the registered instance does not have a _dispatch method
390 then the instance will be searched to find a matching method
391 and, if found, will be called.
392
393 Methods beginning with an '_' are considered private and will
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000394 not be called.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000395 """
396
Fredrik Lundhb329b712001-09-17 17:35:21 +0000397 func = None
398 try:
399 # check to see if a matching function has been registered
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000400 func = self.funcs[method]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000401 except KeyError:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000402 if self.instance is not None:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000403 # check for a _dispatch method
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000404 if hasattr(self.instance, '_dispatch'):
405 return self.instance._dispatch(method, params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000406 else:
407 # call instance method directly
408 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000409 func = resolve_dotted_attribute(
410 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000411 method,
412 self.allow_dotted_names
Fredrik Lundhb329b712001-09-17 17:35:21 +0000413 )
414 except AttributeError:
415 pass
416
417 if func is not None:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000418 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000419 else:
420 raise Exception('method "%s" is not supported' % method)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000421
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000422class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
423 """Simple XML-RPC request handler class.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000424
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000425 Handles all HTTP POST requests and attempts to decode them as
426 XML-RPC requests.
427 """
428
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000429 # Class attribute listing the accessible path components;
430 # paths not on this list will result in a 404 error.
431 rpc_paths = ('/', '/RPC2')
432
433 def is_rpc_path_valid(self):
434 if self.rpc_paths:
435 return self.path in self.rpc_paths
436 else:
437 # If .rpc_paths is empty, just assume all paths are legal
438 return True
439
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000440 def do_POST(self):
441 """Handles the HTTP POST request.
442
443 Attempts to interpret all HTTP POST requests as XML-RPC calls,
444 which are forwarded to the server's _dispatch method for handling.
445 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000446
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000447 # Check that the path is legal
448 if not self.is_rpc_path_valid():
449 self.report_404()
450 return
Tim Peters5535da02006-06-01 13:41:46 +0000451
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000452 try:
Tim Peters536cf992005-12-25 23:18:31 +0000453 # Get arguments by reading body of request.
454 # We read this in chunks to avoid straining
Andrew M. Kuchlinge63fde72005-12-04 15:36:57 +0000455 # socket.read(); around the 10 or 15Mb mark, some platforms
456 # begin to have problems (bug #792570).
457 max_chunk_size = 10*1024*1024
458 size_remaining = int(self.headers["content-length"])
459 L = []
460 while size_remaining:
461 chunk_size = min(size_remaining, max_chunk_size)
462 L.append(self.rfile.read(chunk_size))
463 size_remaining -= len(L[-1])
464 data = ''.join(L)
465
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000466 # In previous versions of SimpleXMLRPCServer, _dispatch
467 # could be overridden in this class, instead of in
468 # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
469 # check to see if a subclass implements _dispatch and dispatch
470 # using that method if present.
471 response = self.server._marshaled_dispatch(
472 data, getattr(self, '_dispatch', None)
473 )
Facundo Batista7f686fc2007-08-17 19:16:44 +0000474 except Exception, e: # This should only happen if the module is buggy
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000475 # internal error, report as HTTP server error
476 self.send_response(500)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000477
478 # Send information about the exception if requested
479 if hasattr(self.server, '_send_traceback_header') and \
480 self.server._send_traceback_header:
481 self.send_header("X-exception", str(e))
482 self.send_header("X-traceback", traceback.format_exc())
483
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000484 self.end_headers()
485 else:
486 # got a valid XML RPC response
487 self.send_response(200)
488 self.send_header("Content-type", "text/xml")
489 self.send_header("Content-length", str(len(response)))
490 self.end_headers()
491 self.wfile.write(response)
492
493 # shut down the connection
494 self.wfile.flush()
495 self.connection.shutdown(1)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000496
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000497 def report_404 (self):
498 # Report a 404 error
Tim Peters5535da02006-06-01 13:41:46 +0000499 self.send_response(404)
500 response = 'No such page'
501 self.send_header("Content-type", "text/plain")
502 self.send_header("Content-length", str(len(response)))
503 self.end_headers()
504 self.wfile.write(response)
505 # shut down the connection
506 self.wfile.flush()
507 self.connection.shutdown(1)
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000508
Fredrik Lundhb329b712001-09-17 17:35:21 +0000509 def log_request(self, code='-', size='-'):
510 """Selectively log an accepted request."""
511
512 if self.server.logRequests:
513 BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
514
Georg Brandle152a772008-05-24 18:31:28 +0000515class SimpleXMLRPCServer(SocketServer.TCPServer,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000516 SimpleXMLRPCDispatcher):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000517 """Simple XML-RPC server.
518
519 Simple XML-RPC server that allows functions and a single instance
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000520 to be installed to handle requests. The default implementation
521 attempts to dispatch XML-RPC calls to the functions or instance
522 installed in the server. Override the _dispatch method inhereted
523 from SimpleXMLRPCDispatcher to change this behavior.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000524 """
525
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000526 allow_reuse_address = True
527
Facundo Batista7f686fc2007-08-17 19:16:44 +0000528 # Warning: this is for debugging purposes only! Never set this to True in
529 # production code, as will be sending out sensitive information (exception
530 # and stack trace details) when exceptions are raised inside
531 # SimpleXMLRPCRequestHandler.do_POST
532 _send_traceback_header = False
533
Fredrik Lundhb329b712001-09-17 17:35:21 +0000534 def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
Collin Winterae041062007-03-10 14:41:48 +0000535 logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000536 self.logRequests = logRequests
Tim Peters2c60f7a2003-01-29 03:49:43 +0000537
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000538 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Georg Brandle152a772008-05-24 18:31:28 +0000539 SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000540
Tim Peters536cf992005-12-25 23:18:31 +0000541 # [Bug #1222790] If possible, set close-on-exec flag; if a
542 # method spawns a subprocess, the subprocess shouldn't have
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000543 # the listening socket open.
Anthony Baxtere29002c2006-04-12 12:07:31 +0000544 if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000545 flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
546 flags |= fcntl.FD_CLOEXEC
547 fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
548
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000549class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
550 """Simple handler for XML-RPC data passed through CGI."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000551
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000552 def __init__(self, allow_none=False, encoding=None):
553 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000554
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000555 def handle_xmlrpc(self, request_text):
556 """Handle a single XML-RPC request"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000557
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000558 response = self._marshaled_dispatch(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000559
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000560 print 'Content-Type: text/xml'
561 print 'Content-Length: %d' % len(response)
562 print
Martin v. Löwis9c5ea502003-05-01 05:05:09 +0000563 sys.stdout.write(response)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000564
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000565 def handle_get(self):
566 """Handle a single HTTP GET request.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000567
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000568 Default implementation indicates an error because
569 XML-RPC uses the POST method.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000570 """
571
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000572 code = 400
573 message, explain = \
574 BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
Tim Peters2c60f7a2003-01-29 03:49:43 +0000575
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000576 response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
577 {
Tim Peters2c60f7a2003-01-29 03:49:43 +0000578 'code' : code,
579 'message' : message,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000580 'explain' : explain
581 }
582 print 'Status: %d %s' % (code, message)
583 print 'Content-Type: text/html'
584 print 'Content-Length: %d' % len(response)
585 print
Neal Norwitz732911f2003-06-29 04:16:28 +0000586 sys.stdout.write(response)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000587
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000588 def handle_request(self, request_text = None):
589 """Handle a single XML-RPC request passed through a CGI post method.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000590
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000591 If no XML data is given then it is read from stdin. The resulting
592 XML-RPC response is printed to stdout along with the correct HTTP
593 headers.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000594 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000595
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000596 if request_text is None and \
597 os.environ.get('REQUEST_METHOD', None) == 'GET':
598 self.handle_get()
599 else:
600 # POST data is normally available through stdin
601 if request_text is None:
Tim Peters2c60f7a2003-01-29 03:49:43 +0000602 request_text = sys.stdin.read()
Fredrik Lundhb329b712001-09-17 17:35:21 +0000603
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000604 self.handle_xmlrpc(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000605
Fredrik Lundhb329b712001-09-17 17:35:21 +0000606if __name__ == '__main__':
Andrew M. Kuchlingb0a1e6b2006-04-21 12:57:35 +0000607 print 'Running XML-RPC server on port 8000'
Fredrik Lundhb329b712001-09-17 17:35:21 +0000608 server = SimpleXMLRPCServer(("localhost", 8000))
609 server.register_function(pow)
610 server.register_function(lambda x,y: x+y, 'add')
611 server.serve_forever()