blob: 5b5aced8eb94aa9cb5a0e1de7b2aeb0b0f015f56 [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
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000109import re
Anthony Baxtere29002c2006-04-12 12:07:31 +0000110try:
111 import fcntl
112except ImportError:
113 fcntl = None
Fredrik Lundhb329b712001-09-17 17:35:21 +0000114
Guido van Rossumd0641422005-02-03 15:01:24 +0000115def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000116 """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
Fredrik Lundhb329b712001-09-17 17:35:21 +0000117
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000118 Resolves a dotted attribute name to an object. Raises
119 an AttributeError if any attribute in the chain starts with a '_'.
Guido van Rossumd0641422005-02-03 15:01:24 +0000120
121 If the optional allow_dotted_names argument is false, dots are not
122 supported and this function operates similar to getattr(obj, attr).
Fredrik Lundhb329b712001-09-17 17:35:21 +0000123 """
124
Guido van Rossumd0641422005-02-03 15:01:24 +0000125 if allow_dotted_names:
126 attrs = attr.split('.')
127 else:
128 attrs = [attr]
129
130 for i in attrs:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000131 if i.startswith('_'):
132 raise AttributeError(
133 'attempt to access private attribute "%s"' % i
134 )
135 else:
136 obj = getattr(obj,i)
137 return obj
Fredrik Lundhb329b712001-09-17 17:35:21 +0000138
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000139def list_public_methods(obj):
140 """Returns a list of attribute strings, found in the specified
141 object, which represent callable attributes"""
142
143 return [member for member in dir(obj)
144 if not member.startswith('_') and
Brett Cannon0a0f6082008-08-03 22:57:23 +0000145 hasattr(getattr(obj, member), '__call__')]
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000146
147def remove_duplicates(lst):
148 """remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
149
150 Returns a copy of a list without duplicates. Every list
151 item must be hashable and the order of the items in the
152 resulting list is not defined.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000153 """
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000154 u = {}
155 for x in lst:
156 u[x] = 1
157
158 return u.keys()
159
160class SimpleXMLRPCDispatcher:
161 """Mix-in class that dispatches XML-RPC requests.
162
163 This class is used to register XML-RPC method handlers
164 and then to dispatch them. There should never be any
165 reason to instantiate this class directly.
166 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000167
Matthias Klosea5d58c82009-04-05 21:00:48 +0000168 def __init__(self, allow_none=False, encoding=None):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000169 self.funcs = {}
170 self.instance = None
Andrew M. Kuchling10a16de2005-12-04 16:34:40 +0000171 self.allow_none = allow_none
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000172 self.encoding = encoding
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000173
Guido van Rossumd0641422005-02-03 15:01:24 +0000174 def register_instance(self, instance, allow_dotted_names=False):
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000175 """Registers an instance to respond to XML-RPC requests.
176
177 Only one instance can be installed at a time.
178
179 If the registered instance has a _dispatch method then that
180 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000181 its parameters as a tuple
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000182 e.g. instance._dispatch('add',(2,3))
183
184 If the registered instance does not have a _dispatch method
185 then the instance will be searched to find a matching method
186 and, if found, will be called. Methods beginning with an '_'
187 are considered private and will not be called by
188 SimpleXMLRPCServer.
189
190 If a registered function matches a XML-RPC request, then it
191 will be called instead of the registered instance.
Guido van Rossumd0641422005-02-03 15:01:24 +0000192
193 If the optional allow_dotted_names argument is true and the
194 instance does not have a _dispatch method, method names
195 containing dots are supported and resolved, as long as none of
196 the name segments start with an '_'.
197
198 *** SECURITY WARNING: ***
199
200 Enabling the allow_dotted_names options allows intruders
201 to access your module's global variables and may allow
202 intruders to execute arbitrary code on your machine. Only
203 use this option on a secure, closed network.
204
Fredrik Lundhb329b712001-09-17 17:35:21 +0000205 """
206
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000207 self.instance = instance
Guido van Rossumd0641422005-02-03 15:01:24 +0000208 self.allow_dotted_names = allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000209
210 def register_function(self, function, name = None):
211 """Registers a function to respond to XML-RPC requests.
212
213 The optional name argument can be used to set a Unicode name
214 for the function.
215 """
216
217 if name is None:
218 name = function.__name__
219 self.funcs[name] = function
220
221 def register_introspection_functions(self):
222 """Registers the XML-RPC introspection methods in the system
223 namespace.
224
225 see http://xmlrpc.usefulinc.com/doc/reserved.html
226 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000227
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000228 self.funcs.update({'system.listMethods' : self.system_listMethods,
229 'system.methodSignature' : self.system_methodSignature,
230 'system.methodHelp' : self.system_methodHelp})
231
232 def register_multicall_functions(self):
233 """Registers the XML-RPC multicall method in the system
234 namespace.
235
236 see http://www.xmlrpc.com/discuss/msgReader$1208"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000237
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000238 self.funcs.update({'system.multicall' : self.system_multicall})
Tim Peters2c60f7a2003-01-29 03:49:43 +0000239
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000240 def _marshaled_dispatch(self, data, dispatch_method = None):
241 """Dispatches an XML-RPC method from marshalled (XML) data.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000242
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000243 XML-RPC methods are dispatched from the marshalled (XML) data
244 using the _dispatch method and the result is returned as
245 marshalled data. For backwards compatibility, a dispatch
Tim Peters2c60f7a2003-01-29 03:49:43 +0000246 function can be provided as an argument (see comment in
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000247 SimpleXMLRPCRequestHandler.do_POST) but overriding the
248 existing method through subclassing is the prefered means
249 of changing method dispatch behavior.
250 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000251
Fredrik Lundhb329b712001-09-17 17:35:21 +0000252 try:
Georg Brandlb9120e72006-06-01 12:30:46 +0000253 params, method = xmlrpclib.loads(data)
254
255 # generate response
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000256 if dispatch_method is not None:
257 response = dispatch_method(method, params)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000258 else:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000259 response = self._dispatch(method, params)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000260 # wrap response in a singleton tuple
261 response = (response,)
Tim Peters536cf992005-12-25 23:18:31 +0000262 response = xmlrpclib.dumps(response, methodresponse=1,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000263 allow_none=self.allow_none, encoding=self.encoding)
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000264 except Fault, fault:
Tim Peters536cf992005-12-25 23:18:31 +0000265 response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000266 encoding=self.encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000267 except:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000268 # report exception back to server
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000269 exc_type, exc_value, exc_tb = sys.exc_info()
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000270 response = xmlrpclib.dumps(
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000271 xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)),
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000272 encoding=self.encoding, allow_none=self.allow_none,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000273 )
274
275 return response
276
277 def system_listMethods(self):
278 """system.listMethods() => ['add', 'subtract', 'multiple']
279
280 Returns a list of the methods supported by the server."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000281
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000282 methods = self.funcs.keys()
283 if self.instance is not None:
284 # Instance can implement _listMethod to return a list of
285 # methods
286 if hasattr(self.instance, '_listMethods'):
287 methods = remove_duplicates(
288 methods + self.instance._listMethods()
289 )
290 # if the instance has a _dispatch method then we
291 # don't have enough information to provide a list
292 # of methods
293 elif not hasattr(self.instance, '_dispatch'):
294 methods = remove_duplicates(
295 methods + list_public_methods(self.instance)
296 )
297 methods.sort()
298 return methods
Tim Peters2c60f7a2003-01-29 03:49:43 +0000299
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000300 def system_methodSignature(self, method_name):
301 """system.methodSignature('add') => [double, int, int]
302
Brett Cannonb9b5f162004-10-03 23:21:44 +0000303 Returns a list describing the signature of the method. In the
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000304 above example, the add method takes two integers as arguments
305 and returns a double result.
306
307 This server does NOT support system.methodSignature."""
308
309 # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
Tim Peters2c60f7a2003-01-29 03:49:43 +0000310
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000311 return 'signatures not supported'
312
313 def system_methodHelp(self, method_name):
314 """system.methodHelp('add') => "Adds two integers together"
315
316 Returns a string containing documentation for the specified method."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000317
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000318 method = None
Brett Cannon0a0f6082008-08-03 22:57:23 +0000319 if method_name in self.funcs:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000320 method = self.funcs[method_name]
321 elif self.instance is not None:
322 # Instance can implement _methodHelp to return help for a method
323 if hasattr(self.instance, '_methodHelp'):
324 return self.instance._methodHelp(method_name)
325 # if the instance has a _dispatch method then we
326 # don't have enough information to provide help
327 elif not hasattr(self.instance, '_dispatch'):
328 try:
329 method = resolve_dotted_attribute(
330 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000331 method_name,
332 self.allow_dotted_names
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000333 )
334 except AttributeError:
335 pass
336
337 # Note that we aren't checking that the method actually
338 # be a callable object of some kind
339 if method is None:
340 return ""
Fredrik Lundhb329b712001-09-17 17:35:21 +0000341 else:
Neal Norwitz732911f2003-06-29 04:16:28 +0000342 import pydoc
Neal Norwitz3f401f02003-06-29 04:19:37 +0000343 return pydoc.getdoc(method)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000344
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000345 def system_multicall(self, call_list):
346 """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
347[[4], ...]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000348
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000349 Allows the caller to package multiple XML-RPC calls into a single
350 request.
351
Tim Peters2c60f7a2003-01-29 03:49:43 +0000352 See http://www.xmlrpc.com/discuss/msgReader$1208
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000353 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000354
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000355 results = []
356 for call in call_list:
357 method_name = call['methodName']
358 params = call['params']
359
360 try:
361 # XXX A marshalling error in any response will fail the entire
362 # multicall. If someone cares they should fix this.
363 results.append([self._dispatch(method_name, params)])
364 except Fault, fault:
365 results.append(
366 {'faultCode' : fault.faultCode,
367 'faultString' : fault.faultString}
368 )
369 except:
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000370 exc_type, exc_value, exc_tb = sys.exc_info()
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000371 results.append(
372 {'faultCode' : 1,
Andrew M. Kuchlinga5453c42006-09-05 13:15:41 +0000373 'faultString' : "%s:%s" % (exc_type, exc_value)}
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000374 )
375 return results
Tim Peters2c60f7a2003-01-29 03:49:43 +0000376
Fredrik Lundhb329b712001-09-17 17:35:21 +0000377 def _dispatch(self, method, params):
378 """Dispatches the XML-RPC method.
379
380 XML-RPC calls are forwarded to a registered function that
381 matches the called XML-RPC method name. If no such function
382 exists then the call is forwarded to the registered instance,
383 if available.
384
385 If the registered instance has a _dispatch method then that
386 method will be called with the name of the XML-RPC method and
Georg Brandl7eb4b7d2005-07-22 21:49:32 +0000387 its parameters as a tuple
Fredrik Lundhb329b712001-09-17 17:35:21 +0000388 e.g. instance._dispatch('add',(2,3))
389
390 If the registered instance does not have a _dispatch method
391 then the instance will be searched to find a matching method
392 and, if found, will be called.
393
394 Methods beginning with an '_' are considered private and will
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000395 not be called.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000396 """
397
Fredrik Lundhb329b712001-09-17 17:35:21 +0000398 func = None
399 try:
400 # check to see if a matching function has been registered
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000401 func = self.funcs[method]
Fredrik Lundhb329b712001-09-17 17:35:21 +0000402 except KeyError:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000403 if self.instance is not None:
Fredrik Lundhb329b712001-09-17 17:35:21 +0000404 # check for a _dispatch method
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000405 if hasattr(self.instance, '_dispatch'):
406 return self.instance._dispatch(method, params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000407 else:
408 # call instance method directly
409 try:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000410 func = resolve_dotted_attribute(
411 self.instance,
Guido van Rossumd0641422005-02-03 15:01:24 +0000412 method,
413 self.allow_dotted_names
Fredrik Lundhb329b712001-09-17 17:35:21 +0000414 )
415 except AttributeError:
416 pass
417
418 if func is not None:
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000419 return func(*params)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000420 else:
421 raise Exception('method "%s" is not supported' % method)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000422
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000423class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
424 """Simple XML-RPC request handler class.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000425
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000426 Handles all HTTP POST requests and attempts to decode them as
427 XML-RPC requests.
428 """
429
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000430 # Class attribute listing the accessible path components;
431 # paths not on this list will result in a 404 error.
432 rpc_paths = ('/', '/RPC2')
433
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000434 #if not None, encode responses larger than this, if possible
435 encode_threshold = 1400 #a common MTU
436
437 #Override form StreamRequestHandler: full buffering of output
438 #and no Nagle.
439 wbufsize = -1
440 disable_nagle_algorithm = True
441
442 # a re to match a gzip Accept-Encoding
443 aepattern = re.compile(r"""
444 \s* ([^\s;]+) \s* #content-coding
445 (;\s* q \s*=\s* ([0-9\.]+))? #q
446 """, re.VERBOSE | re.IGNORECASE)
447
448 def accept_encodings(self):
449 r = {}
450 ae = self.headers.get("Accept-Encoding", "")
451 for e in ae.split(","):
452 match = self.aepattern.match(e)
453 if match:
454 v = match.group(3)
455 v = float(v) if v else 1.0
456 r[match.group(1)] = v
457 return r
458
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000459 def is_rpc_path_valid(self):
460 if self.rpc_paths:
461 return self.path in self.rpc_paths
462 else:
463 # If .rpc_paths is empty, just assume all paths are legal
464 return True
465
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000466 def do_POST(self):
467 """Handles the HTTP POST request.
468
469 Attempts to interpret all HTTP POST requests as XML-RPC calls,
470 which are forwarded to the server's _dispatch method for handling.
471 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000472
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000473 # Check that the path is legal
474 if not self.is_rpc_path_valid():
475 self.report_404()
476 return
Tim Peters5535da02006-06-01 13:41:46 +0000477
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000478 try:
Tim Peters536cf992005-12-25 23:18:31 +0000479 # Get arguments by reading body of request.
480 # We read this in chunks to avoid straining
Andrew M. Kuchlinge63fde72005-12-04 15:36:57 +0000481 # socket.read(); around the 10 or 15Mb mark, some platforms
482 # begin to have problems (bug #792570).
483 max_chunk_size = 10*1024*1024
484 size_remaining = int(self.headers["content-length"])
485 L = []
486 while size_remaining:
487 chunk_size = min(size_remaining, max_chunk_size)
488 L.append(self.rfile.read(chunk_size))
489 size_remaining -= len(L[-1])
490 data = ''.join(L)
491
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000492 data = self.decode_request_content(data)
493 if data is None:
494 return #response has been sent
495
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000496 # In previous versions of SimpleXMLRPCServer, _dispatch
497 # could be overridden in this class, instead of in
498 # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
499 # check to see if a subclass implements _dispatch and dispatch
500 # using that method if present.
501 response = self.server._marshaled_dispatch(
502 data, getattr(self, '_dispatch', None)
503 )
Facundo Batista7f686fc2007-08-17 19:16:44 +0000504 except Exception, e: # This should only happen if the module is buggy
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000505 # internal error, report as HTTP server error
506 self.send_response(500)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000507
508 # Send information about the exception if requested
509 if hasattr(self.server, '_send_traceback_header') and \
510 self.server._send_traceback_header:
511 self.send_header("X-exception", str(e))
512 self.send_header("X-traceback", traceback.format_exc())
513
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000514 self.send_header("Content-length", "0")
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000515 self.end_headers()
516 else:
517 # got a valid XML RPC response
518 self.send_response(200)
519 self.send_header("Content-type", "text/xml")
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000520 if self.encode_threshold is not None:
521 if len(response) > self.encode_threshold:
522 q = self.accept_encodings().get("gzip", 0)
523 if q:
524 response = xmlrpclib.gzip_encode(response)
525 self.send_header("Content-Encoding", "gzip")
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000526 self.send_header("Content-length", str(len(response)))
527 self.end_headers()
528 self.wfile.write(response)
529
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000530 def decode_request_content(self, data):
531 #support gzip encoding of request
532 encoding = self.headers.get("content-encoding", "identity").lower()
533 if encoding == "identity":
534 return data
535 if encoding == "gzip":
536 try:
537 return xmlrpclib.gzip_decode(data)
538 except ValueError:
539 self.send_response(400, "error decoding gzip content")
540 else:
541 self.send_response(501, "encoding %r not supported" % encoding)
542 self.send_header("Content-length", "0")
543 self.end_headers()
Tim Peters2c60f7a2003-01-29 03:49:43 +0000544
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000545 def report_404 (self):
546 # Report a 404 error
Tim Peters5535da02006-06-01 13:41:46 +0000547 self.send_response(404)
548 response = 'No such page'
549 self.send_header("Content-type", "text/plain")
550 self.send_header("Content-length", str(len(response)))
551 self.end_headers()
552 self.wfile.write(response)
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000553
Fredrik Lundhb329b712001-09-17 17:35:21 +0000554 def log_request(self, code='-', size='-'):
555 """Selectively log an accepted request."""
556
557 if self.server.logRequests:
558 BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
559
Georg Brandle152a772008-05-24 18:31:28 +0000560class SimpleXMLRPCServer(SocketServer.TCPServer,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000561 SimpleXMLRPCDispatcher):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000562 """Simple XML-RPC server.
563
564 Simple XML-RPC server that allows functions and a single instance
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000565 to be installed to handle requests. The default implementation
566 attempts to dispatch XML-RPC calls to the functions or instance
567 installed in the server. Override the _dispatch method inhereted
568 from SimpleXMLRPCDispatcher to change this behavior.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000569 """
570
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000571 allow_reuse_address = True
572
Facundo Batista7f686fc2007-08-17 19:16:44 +0000573 # Warning: this is for debugging purposes only! Never set this to True in
574 # production code, as will be sending out sensitive information (exception
575 # and stack trace details) when exceptions are raised inside
576 # SimpleXMLRPCRequestHandler.do_POST
577 _send_traceback_header = False
578
Fredrik Lundhb329b712001-09-17 17:35:21 +0000579 def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
Collin Winterae041062007-03-10 14:41:48 +0000580 logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
Fredrik Lundhb329b712001-09-17 17:35:21 +0000581 self.logRequests = logRequests
Tim Peters2c60f7a2003-01-29 03:49:43 +0000582
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000583 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Georg Brandle152a772008-05-24 18:31:28 +0000584 SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000585
Tim Peters536cf992005-12-25 23:18:31 +0000586 # [Bug #1222790] If possible, set close-on-exec flag; if a
587 # method spawns a subprocess, the subprocess shouldn't have
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000588 # the listening socket open.
Anthony Baxtere29002c2006-04-12 12:07:31 +0000589 if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
Andrew M. Kuchling3a976052005-12-04 15:07:41 +0000590 flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
591 flags |= fcntl.FD_CLOEXEC
592 fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
593
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000594class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
595 """Simple handler for XML-RPC data passed through CGI."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000596
Andrew M. Kuchling427aedb2005-12-04 17:13:12 +0000597 def __init__(self, allow_none=False, encoding=None):
598 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000599
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000600 def handle_xmlrpc(self, request_text):
601 """Handle a single XML-RPC request"""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000602
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000603 response = self._marshaled_dispatch(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000604
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000605 print 'Content-Type: text/xml'
606 print 'Content-Length: %d' % len(response)
607 print
Martin v. Löwis9c5ea502003-05-01 05:05:09 +0000608 sys.stdout.write(response)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000609
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000610 def handle_get(self):
611 """Handle a single HTTP GET request.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000612
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000613 Default implementation indicates an error because
614 XML-RPC uses the POST method.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000615 """
616
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000617 code = 400
618 message, explain = \
619 BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
Tim Peters2c60f7a2003-01-29 03:49:43 +0000620
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000621 response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
622 {
Tim Peters2c60f7a2003-01-29 03:49:43 +0000623 'code' : code,
624 'message' : message,
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000625 'explain' : explain
626 }
627 print 'Status: %d %s' % (code, message)
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000628 print 'Content-Type: %s' % BaseHTTPServer.DEFAULT_ERROR_CONTENT_TYPE
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000629 print 'Content-Length: %d' % len(response)
630 print
Neal Norwitz732911f2003-06-29 04:16:28 +0000631 sys.stdout.write(response)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000632
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000633 def handle_request(self, request_text = None):
634 """Handle a single XML-RPC request passed through a CGI post method.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000635
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000636 If no XML data is given then it is read from stdin. The resulting
637 XML-RPC response is printed to stdout along with the correct HTTP
638 headers.
Fredrik Lundhb329b712001-09-17 17:35:21 +0000639 """
Tim Peters2c60f7a2003-01-29 03:49:43 +0000640
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000641 if request_text is None and \
642 os.environ.get('REQUEST_METHOD', None) == 'GET':
643 self.handle_get()
644 else:
645 # POST data is normally available through stdin
Georg Brandle92d4b62009-04-01 04:21:14 +0000646 try:
647 length = int(os.environ.get('CONTENT_LENGTH', None))
Georg Brandl61fce382009-04-01 15:23:43 +0000648 except (TypeError, ValueError):
Georg Brandle92d4b62009-04-01 04:21:14 +0000649 length = -1
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000650 if request_text is None:
Georg Brandle92d4b62009-04-01 04:21:14 +0000651 request_text = sys.stdin.read(length)
Fredrik Lundhb329b712001-09-17 17:35:21 +0000652
Martin v. Löwisd69663d2003-01-15 11:37:23 +0000653 self.handle_xmlrpc(request_text)
Tim Peters2c60f7a2003-01-29 03:49:43 +0000654
Fredrik Lundhb329b712001-09-17 17:35:21 +0000655if __name__ == '__main__':
Andrew M. Kuchlingb0a1e6b2006-04-21 12:57:35 +0000656 print 'Running XML-RPC server on port 8000'
Fredrik Lundhb329b712001-09-17 17:35:21 +0000657 server = SimpleXMLRPCServer(("localhost", 8000))
658 server.register_function(pow)
659 server.register_function(lambda x,y: x+y, 'add')
660 server.serve_forever()