blob: 53ad9c5d220185b9b4710e07b29f143c799cc56f [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
Fredrik Lundhb329b712001-09-17 17:35:21 +0000104import SocketServer
105import BaseHTTPServer
106import sys
Anthony Baxtere29002c2006-04-12 12:07:31 +0000107import os
108try:
109 import fcntl
110except ImportError:
111 fcntl = None
Fredrik Lundhb329b712001-09-17 17:35:21 +0000112
Guido van Rossumd0641422005-02-03 15:01:24 +0000113def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000114 """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
Fredrik Lundhb329b712001-09-17 17:35:21 +0000115
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000116 Resolves a dotted attribute name to an object. Raises
117 an AttributeError if any attribute in the chain starts with a '_'.
Guido van Rossumd0641422005-02-03 15:01:24 +0000118
119 If the optional allow_dotted_names argument is false, dots are not
120 supported and this function operates similar to getattr(obj, attr).
Fredrik Lundhb329b712001-09-17 17:35:21 +0000121 """
122
Guido van Rossumd0641422005-02-03 15:01:24 +0000123 if allow_dotted_names:
124 attrs = attr.split('.')
125 else:
126 attrs = [attr]
127
128 for i in attrs:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000129 if i.startswith('_'):
130 raise AttributeError(
131 'attempt to access private attribute "%s"' % i
132 )
133 else:
134 obj = getattr(obj,i)
135 return obj
Fredrik Lundhb329b712001-09-17 17:35:21 +0000136
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000137def list_public_methods(obj):
138 """Returns a list of attribute strings, found in the specified
139 object, which represent callable attributes"""
140
141 return [member for member in dir(obj)
142 if not member.startswith('_') and
143 callable(getattr(obj, member))]
144
145def remove_duplicates(lst):
146 """remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
147
148 Returns a copy of a list without duplicates. Every list
149 item must be hashable and the order of the items in the
150 resulting list is not defined.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000151 """
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000152 u = {}
153 for x in lst:
154 u[x] = 1
155
156 return u.keys()
157
158class SimpleXMLRPCDispatcher:
159 """Mix-in class that dispatches XML-RPC requests.
160
161 This class is used to register XML-RPC method handlers
162 and then to dispatch them. There should never be any
163 reason to instantiate this class directly.
164 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000165
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000166 def __init__(self, allow_none, encoding):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000167 self.funcs = {}
168 self.instance = None
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000169 self.allow_none = allow_none
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000170 self.encoding = encoding
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000171
Guido van Rossumd0641422005-02-03 15:01:24 +0000172 def register_instance(self, instance, allow_dotted_names=False):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000173 """Registers an instance to respond to XML-RPC requests.
174
175 Only one instance can be installed at a time.
176
177 If the registered instance has a _dispatch method then that
178 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000179 its parameters as a tuple
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000180 e.g. instance._dispatch('add',(2,3))
181
182 If the registered instance does not have a _dispatch method
183 then the instance will be searched to find a matching method
184 and, if found, will be called. Methods beginning with an '_'
185 are considered private and will not be called by
186 SimpleXMLRPCServer.
187
188 If a registered function matches a XML-RPC request, then it
189 will be called instead of the registered instance.
Guido van Rossumd0641422005-02-03 15:01:24 +0000190
191 If the optional allow_dotted_names argument is true and the
192 instance does not have a _dispatch method, method names
193 containing dots are supported and resolved, as long as none of
194 the name segments start with an '_'.
195
196 *** SECURITY WARNING: ***
197
198 Enabling the allow_dotted_names options allows intruders
199 to access your module's global variables and may allow
200 intruders to execute arbitrary code on your machine. Only
201 use this option on a secure, closed network.
202
Fredrik Lundhb329b712001-09-17 17:35:21 +0000203 """
204
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000205 self.instance = instance
Guido van Rossumd0641422005-02-03 15:01:24 +0000206 self.allow_dotted_names = allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000207
208 def register_function(self, function, name = None):
209 """Registers a function to respond to XML-RPC requests.
210
211 The optional name argument can be used to set a Unicode name
212 for the function.
213 """
214
215 if name is None:
216 name = function.__name__
217 self.funcs[name] = function
218
219 def register_introspection_functions(self):
220 """Registers the XML-RPC introspection methods in the system
221 namespace.
222
223 see http://xmlrpc.usefulinc.com/doc/reserved.html
224 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000225
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000226 self.funcs.update({'system.listMethods' : self.system_listMethods,
227 'system.methodSignature' : self.system_methodSignature,
228 'system.methodHelp' : self.system_methodHelp})
229
230 def register_multicall_functions(self):
231 """Registers the XML-RPC multicall method in the system
232 namespace.
233
234 see http://www.xmlrpc.com/discuss/msgReader$1208"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000235
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000236 self.funcs.update({'system.multicall' : self.system_multicall})
Tim Peters2c60f7a2003-01-29 03:49:43 +0000237
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000238 def _marshaled_dispatch(self, data, dispatch_method = None):
239 """Dispatches an XML-RPC method from marshalled (XML) data.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000240
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000241 XML-RPC methods are dispatched from the marshalled (XML) data
242 using the _dispatch method and the result is returned as
243 marshalled data. For backwards compatibility, a dispatch
Tim Peters2c60f7a2003-01-29 03:49:43 +0000244 function can be provided as an argument (see comment in
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000245 SimpleXMLRPCRequestHandler.do_POST) but overriding the
246 existing method through subclassing is the prefered means
247 of changing method dispatch behavior.
248 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000249
Fredrik Lundhb329b712001-09-17 17:35:21 +0000250 try:
Georg Brandlb9120e72006-06-01 12:30:46 +0000251 params, method = xmlrpclib.loads(data)
252
253 # generate response
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000254 if dispatch_method is not None:
255 response = dispatch_method(method, params)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000256 else:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000257 response = self._dispatch(method, params)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000258 # wrap response in a singleton tuple
259 response = (response,)
Tim Peters536cf992005-12-25 23:18:31 +0000260 response = xmlrpclib.dumps(response, methodresponse=1,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000261 allow_none=self.allow_none, encoding=self.encoding)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000262 except Fault, fault:
Tim Peters536cf992005-12-25 23:18:31 +0000263 response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000264 encoding=self.encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000265 except:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000266 # report exception back to server
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000267 exc_type, exc_value, exc_tb = sys.exc_info()
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000268 response = xmlrpclib.dumps(
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000269 xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)),
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000270 encoding=self.encoding, allow_none=self.allow_none,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000271 )
272
273 return response
274
275 def system_listMethods(self):
276 """system.listMethods() => ['add', 'subtract', 'multiple']
277
278 Returns a list of the methods supported by the server."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000279
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000280 methods = self.funcs.keys()
281 if self.instance is not None:
282 # Instance can implement _listMethod to return a list of
283 # methods
284 if hasattr(self.instance, '_listMethods'):
285 methods = remove_duplicates(
286 methods + self.instance._listMethods()
287 )
288 # if the instance has a _dispatch method then we
289 # don't have enough information to provide a list
290 # of methods
291 elif not hasattr(self.instance, '_dispatch'):
292 methods = remove_duplicates(
293 methods + list_public_methods(self.instance)
294 )
295 methods.sort()
296 return methods
Tim Peters2c60f7a2003-01-29 03:49:43 +0000297
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000298 def system_methodSignature(self, method_name):
299 """system.methodSignature('add') => [double, int, int]
300
Brett Cannonb9b5f162004-10-03 23:21:44 +0000301 Returns a list describing the signature of the method. In the
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000302 above example, the add method takes two integers as arguments
303 and returns a double result.
304
305 This server does NOT support system.methodSignature."""
306
307 # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
Tim Peters2c60f7a2003-01-29 03:49:43 +0000308
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000309 return 'signatures not supported'
310
311 def system_methodHelp(self, method_name):
312 """system.methodHelp('add') => "Adds two integers together"
313
314 Returns a string containing documentation for the specified method."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000315
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000316 method = None
317 if self.funcs.has_key(method_name):
318 method = self.funcs[method_name]
319 elif self.instance is not None:
320 # Instance can implement _methodHelp to return help for a method
321 if hasattr(self.instance, '_methodHelp'):
322 return self.instance._methodHelp(method_name)
323 # if the instance has a _dispatch method then we
324 # don't have enough information to provide help
325 elif not hasattr(self.instance, '_dispatch'):
326 try:
327 method = resolve_dotted_attribute(
328 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000329 method_name,
330 self.allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000331 )
332 except AttributeError:
333 pass
334
335 # Note that we aren't checking that the method actually
336 # be a callable object of some kind
337 if method is None:
338 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +0000339 else:
Neal Norwitz732911f2003-06-29 04:16:28 +0000340 import pydoc
Neal Norwitz3f401f02003-06-29 04:19:37 +0000341 return pydoc.getdoc(method)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000342
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000343 def system_multicall(self, call_list):
344 """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
345[[4], ...]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000346
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000347 Allows the caller to package multiple XML-RPC calls into a single
348 request.
349
Tim Peters2c60f7a2003-01-29 03:49:43 +0000350 See http://www.xmlrpc.com/discuss/msgReader$1208
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000351 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000352
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000353 results = []
354 for call in call_list:
355 method_name = call['methodName']
356 params = call['params']
357
358 try:
359 # XXX A marshalling error in any response will fail the entire
360 # multicall. If someone cares they should fix this.
361 results.append([self._dispatch(method_name, params)])
362 except Fault, fault:
363 results.append(
364 {'faultCode' : fault.faultCode,
365 'faultString' : fault.faultString}
366 )
367 except:
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000368 exc_type, exc_value, exc_tb = sys.exc_info()
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000369 results.append(
370 {'faultCode' : 1,
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000371 'faultString' : "%s:%s" % (exc_type, exc_value)}
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000372 )
373 return results
Tim Peters2c60f7a2003-01-29 03:49:43 +0000374
Fredrik Lundhb329b712001-09-17 17:35:21 +0000375 def _dispatch(self, method, params):
376 """Dispatches the XML-RPC method.
377
378 XML-RPC calls are forwarded to a registered function that
379 matches the called XML-RPC method name. If no such function
380 exists then the call is forwarded to the registered instance,
381 if available.
382
383 If the registered instance has a _dispatch method then that
384 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000385 its parameters as a tuple
Fredrik Lundhb329b712001-09-17 17:35:21 +0000386 e.g. instance._dispatch('add',(2,3))
387
388 If the registered instance does not have a _dispatch method
389 then the instance will be searched to find a matching method
390 and, if found, will be called.
391
392 Methods beginning with an '_' are considered private and will
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000393 not be called.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000394 """
395
Fredrik Lundhb329b712001-09-17 17:35:21 +0000396 func = None
397 try:
398 # check to see if a matching function has been registered
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000399 func = self.funcs[method]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000400 except KeyError:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000401 if self.instance is not None:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000402 # check for a _dispatch method
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000403 if hasattr(self.instance, '_dispatch'):
404 return self.instance._dispatch(method, params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000405 else:
406 # call instance method directly
407 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000408 func = resolve_dotted_attribute(
409 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000410 method,
411 self.allow_dotted_names
Fredrik Lundhb329b712001-09-17 17:35:21 +0000412 )
413 except AttributeError:
414 pass
415
416 if func is not None:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000417 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000418 else:
419 raise Exception('method "%s" is not supported' % method)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000420
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000421class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
422 """Simple XML-RPC request handler class.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000423
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000424 Handles all HTTP POST requests and attempts to decode them as
425 XML-RPC requests.
426 """
427
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000428 # Class attribute listing the accessible path components;
429 # paths not on this list will result in a 404 error.
430 rpc_paths = ('/', '/RPC2')
431
432 def is_rpc_path_valid(self):
433 if self.rpc_paths:
434 return self.path in self.rpc_paths
435 else:
436 # If .rpc_paths is empty, just assume all paths are legal
437 return True
438
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000439 def do_POST(self):
440 """Handles the HTTP POST request.
441
442 Attempts to interpret all HTTP POST requests as XML-RPC calls,
443 which are forwarded to the server's _dispatch method for handling.
444 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000445
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000446 # Check that the path is legal
447 if not self.is_rpc_path_valid():
448 self.report_404()
449 return
Tim Peters5535da02006-06-01 13:41:46 +0000450
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000451 try:
Tim Peters536cf992005-12-25 23:18:31 +0000452 # Get arguments by reading body of request.
453 # We read this in chunks to avoid straining
Andrew M. Kuchlinge63fde72005-12-04 15:36:57 +0000454 # socket.read(); around the 10 or 15Mb mark, some platforms
455 # begin to have problems (bug #792570).
456 max_chunk_size = 10*1024*1024
457 size_remaining = int(self.headers["content-length"])
458 L = []
459 while size_remaining:
460 chunk_size = min(size_remaining, max_chunk_size)
461 L.append(self.rfile.read(chunk_size))
462 size_remaining -= len(L[-1])
463 data = ''.join(L)
464
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000465 # In previous versions of SimpleXMLRPCServer, _dispatch
466 # could be overridden in this class, instead of in
467 # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
468 # check to see if a subclass implements _dispatch and dispatch
469 # using that method if present.
470 response = self.server._marshaled_dispatch(
471 data, getattr(self, '_dispatch', None)
472 )
473 except: # This should only happen if the module is buggy
474 # internal error, report as HTTP server error
475 self.send_response(500)
476 self.end_headers()
477 else:
478 # got a valid XML RPC response
479 self.send_response(200)
480 self.send_header("Content-type", "text/xml")
481 self.send_header("Content-length", str(len(response)))
482 self.end_headers()
483 self.wfile.write(response)
484
485 # shut down the connection
486 self.wfile.flush()
487 self.connection.shutdown(1)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000488
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000489 def report_404 (self):
490 # Report a 404 error
Tim Peters5535da02006-06-01 13:41:46 +0000491 self.send_response(404)
492 response = 'No such page'
493 self.send_header("Content-type", "text/plain")
494 self.send_header("Content-length", str(len(response)))
495 self.end_headers()
496 self.wfile.write(response)
497 # shut down the connection
498 self.wfile.flush()
499 self.connection.shutdown(1)
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000500
Fredrik Lundhb329b712001-09-17 17:35:21 +0000501 def log_request(self, code='-', size='-'):
502 """Selectively log an accepted request."""
503
504 if self.server.logRequests:
505 BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
506
Tim Peters2c60f7a2003-01-29 03:49:43 +0000507class SimpleXMLRPCServer(SocketServer.TCPServer,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000508 SimpleXMLRPCDispatcher):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000509 """Simple XML-RPC server.
510
511 Simple XML-RPC server that allows functions and a single instance
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000512 to be installed to handle requests. The default implementation
513 attempts to dispatch XML-RPC calls to the functions or instance
514 installed in the server. Override the _dispatch method inhereted
515 from SimpleXMLRPCDispatcher to change this behavior.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000516 """
517
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000518 allow_reuse_address = True
519
Fredrik Lundhb329b712001-09-17 17:35:21 +0000520 def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000521 logRequests=True, allow_none=False, encoding=None):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000522 self.logRequests = logRequests
Tim Peters2c60f7a2003-01-29 03:49:43 +0000523
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000524 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000525 SocketServer.TCPServer.__init__(self, addr, requestHandler)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000526
Tim Peters536cf992005-12-25 23:18:31 +0000527 # [Bug #1222790] If possible, set close-on-exec flag; if a
528 # method spawns a subprocess, the subprocess shouldn't have
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000529 # the listening socket open.
Anthony Baxtere29002c2006-04-12 12:07:31 +0000530 if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000531 flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
532 flags |= fcntl.FD_CLOEXEC
533 fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
534
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000535class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
536 """Simple handler for XML-RPC data passed through CGI."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000537
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000538 def __init__(self, allow_none=False, encoding=None):
539 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000540
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000541 def handle_xmlrpc(self, request_text):
542 """Handle a single XML-RPC request"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000543
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000544 response = self._marshaled_dispatch(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000545
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000546 print 'Content-Type: text/xml'
547 print 'Content-Length: %d' % len(response)
548 print
Martin v. Löwis9c5ea502003-05-01 05:05:09 +0000549 sys.stdout.write(response)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000550
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000551 def handle_get(self):
552 """Handle a single HTTP GET request.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000553
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000554 Default implementation indicates an error because
555 XML-RPC uses the POST method.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000556 """
557
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000558 code = 400
559 message, explain = \
560 BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
Tim Peters2c60f7a2003-01-29 03:49:43 +0000561
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000562 response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
563 {
Tim Peters2c60f7a2003-01-29 03:49:43 +0000564 'code' : code,
565 'message' : message,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000566 'explain' : explain
567 }
568 print 'Status: %d %s' % (code, message)
569 print 'Content-Type: text/html'
570 print 'Content-Length: %d' % len(response)
571 print
Neal Norwitz732911f2003-06-29 04:16:28 +0000572 sys.stdout.write(response)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000573
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000574 def handle_request(self, request_text = None):
575 """Handle a single XML-RPC request passed through a CGI post method.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000576
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000577 If no XML data is given then it is read from stdin. The resulting
578 XML-RPC response is printed to stdout along with the correct HTTP
579 headers.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000580 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000581
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000582 if request_text is None and \
583 os.environ.get('REQUEST_METHOD', None) == 'GET':
584 self.handle_get()
585 else:
586 # POST data is normally available through stdin
587 if request_text is None:
Tim Peters2c60f7a2003-01-29 03:49:43 +0000588 request_text = sys.stdin.read()
Fredrik Lundhb329b712001-09-17 17:35:21 +0000589
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000590 self.handle_xmlrpc(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000591
Fredrik Lundhb329b712001-09-17 17:35:21 +0000592if __name__ == '__main__':
Andrew M. Kuchlingb0a1e6b2006-04-21 12:57:35 +0000593 print 'Running XML-RPC server on port 8000'
Fredrik Lundhb329b712001-09-17 17:35:21 +0000594 server = SimpleXMLRPCServer(("localhost", 8000))
595 server.register_function(pow)
596 server.register_function(lambda x,y: x+y, 'add')
597 server.serve_forever()