merge in bad ways, so I'll have to merge that extra-carefully (probably manually.) Merged revisions 46495-46605 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r46495 | tim.peters | 2006-05-28 03:52:38 +0200 (Sun, 28 May 2006) | 2 lines Added missing svn:eol-style property to text files. ........ r46497 | tim.peters | 2006-05-28 12:41:29 +0200 (Sun, 28 May 2006) | 3 lines PyErr_Display(), PyErr_WriteUnraisable(): Coverity found a cut-and-paste bug in both: `className` was referenced before being checked for NULL. ........ r46499 | fredrik.lundh | 2006-05-28 14:06:46 +0200 (Sun, 28 May 2006) | 5 lines needforspeed: added Py_MEMCPY macro (currently tuned for Visual C only), and use it for string copy operations. this gives a 20% speedup on some string benchmarks. ........ r46501 | michael.hudson | 2006-05-28 17:51:40 +0200 (Sun, 28 May 2006) | 26 lines Quality control, meet exceptions.c. Fix a number of problems with the need for speed code: One is doing this sort of thing: Py_DECREF(self->field); self->field = newval; Py_INCREF(self->field); without being very sure that self->field doesn't start with a value that has a __del__, because that almost certainly can lead to segfaults. As self->args is constrained to be an exact tuple we may as well exploit this fact consistently. This leads to quite a lot of simplification (and, hey, probably better performance). Add some error checking in places lacking it. Fix some rather strange indentation in the Unicode code. Delete some trailing whitespace. More to come, I haven't fixed all the reference leaks yet... ........ r46502 | george.yoshida | 2006-05-28 18:39:09 +0200 (Sun, 28 May 2006) | 3 lines Patch #1080727: add "encoding" parameter to doctest.DocFileSuite Contributed by Bjorn Tillenius. ........ r46503 | martin.v.loewis | 2006-05-28 18:57:38 +0200 (Sun, 28 May 2006) | 4 lines Rest of patch #1490384: Commit icon source, remove claim that Erik von Blokland is the author of the installer picture. ........ r46504 | michael.hudson | 2006-05-28 19:40:29 +0200 (Sun, 28 May 2006) | 16 lines Quality control, meet exceptions.c, round two. Make some functions that should have been static static. Fix a bunch of refleaks by fixing the definition of MiddlingExtendsException. Remove all the __new__ implementations apart from BaseException_new. Rewrite most code that needs it to cope with NULL fields (such code could get excercised anyway, the __new__-removal just makes it more likely). This involved editing the code for WindowsError, which I can't test. This fixes all the refleaks in at least the start of a regrtest -R :: run. ........ r46505 | marc-andre.lemburg | 2006-05-28 19:46:58 +0200 (Sun, 28 May 2006) | 10 lines Initial version of systimes - a module to provide platform dependent performance measurements. The module is currently just a proof-of-concept implementation, but will integrated into pybench once it is stable enough. License: pybench license. Author: Marc-Andre Lemburg. ........ r46507 | armin.rigo | 2006-05-28 21:13:17 +0200 (Sun, 28 May 2006) | 15 lines ("Forward-port" of r46506) Remove various dependencies on dictionary order in the standard library tests, and one (clearly an oversight, potentially critical) in the standard library itself - base64.py. Remaining open issues: * test_extcall is an output test, messy to make robust * tarfile.py has a potential bug here, but I'm not familiar enough with this code. Filed in as SF bug #1496501. * urllib2.HTTPPasswordMgr() returns a random result if there is more than one matching root path. I'm asking python-dev for clarification... ........ r46508 | georg.brandl | 2006-05-28 22:11:45 +0200 (Sun, 28 May 2006) | 4 lines The empty string is a valid import path. (fixes #1496539) ........ r46509 | georg.brandl | 2006-05-28 22:23:12 +0200 (Sun, 28 May 2006) | 3 lines Patch #1496206: urllib2 PasswordMgr ./. default ports ........ r46510 | georg.brandl | 2006-05-28 22:57:09 +0200 (Sun, 28 May 2006) | 3 lines Fix refleaks in UnicodeError get and set methods. ........ r46511 | michael.hudson | 2006-05-28 23:19:03 +0200 (Sun, 28 May 2006) | 3 lines use the UnicodeError traversal and clearing functions in UnicodeError subclasses. ........ r46512 | thomas.wouters | 2006-05-28 23:32:12 +0200 (Sun, 28 May 2006) | 4 lines Make last patch valid C89 so Windows compilers can deal with it. ........ r46513 | georg.brandl | 2006-05-28 23:42:54 +0200 (Sun, 28 May 2006) | 3 lines Fix ref-antileak in _struct.c which eventually lead to deallocating None. ........ r46514 | georg.brandl | 2006-05-28 23:57:35 +0200 (Sun, 28 May 2006) | 4 lines Correct None refcount issue in Mac modules. (Are they still used?) ........ r46515 | armin.rigo | 2006-05-29 00:07:08 +0200 (Mon, 29 May 2006) | 3 lines A clearer error message when passing -R to regrtest.py with release builds of Python. ........ r46516 | georg.brandl | 2006-05-29 00:14:04 +0200 (Mon, 29 May 2006) | 3 lines Fix C function calling conventions in _sre module. ........ r46517 | georg.brandl | 2006-05-29 00:34:51 +0200 (Mon, 29 May 2006) | 3 lines Convert audioop over to METH_VARARGS. ........ r46518 | georg.brandl | 2006-05-29 00:38:57 +0200 (Mon, 29 May 2006) | 3 lines METH_NOARGS functions do get called with two args. ........ r46519 | georg.brandl | 2006-05-29 11:46:51 +0200 (Mon, 29 May 2006) | 4 lines Fix refleak in socketmodule. Replace bogus Py_BuildValue calls. Fix refleak in exceptions. ........ r46520 | nick.coghlan | 2006-05-29 14:43:05 +0200 (Mon, 29 May 2006) | 7 lines Apply modified version of Collin Winter's patch #1478788 Renames functional extension module to _functools and adds a Python functools module so that utility functions like update_wrapper can be added easily. ........ r46522 | georg.brandl | 2006-05-29 15:53:16 +0200 (Mon, 29 May 2006) | 3 lines Convert fmmodule to METH_VARARGS. ........ r46523 | georg.brandl | 2006-05-29 16:13:21 +0200 (Mon, 29 May 2006) | 3 lines Fix #1494605. ........ r46524 | georg.brandl | 2006-05-29 16:28:05 +0200 (Mon, 29 May 2006) | 3 lines Handle PyMem_Malloc failure in pystrtod.c. Closes #1494671. ........ r46525 | georg.brandl | 2006-05-29 16:33:55 +0200 (Mon, 29 May 2006) | 3 lines Fix compiler warning. ........ r46526 | georg.brandl | 2006-05-29 16:39:00 +0200 (Mon, 29 May 2006) | 3 lines Fix #1494787 (pyclbr counts whitespace as superclass name) ........ r46527 | bob.ippolito | 2006-05-29 17:47:29 +0200 (Mon, 29 May 2006) | 1 line simplify the struct code a bit (no functional changes) ........ r46528 | armin.rigo | 2006-05-29 19:59:47 +0200 (Mon, 29 May 2006) | 2 lines Silence a warning. ........ r46529 | georg.brandl | 2006-05-29 21:39:45 +0200 (Mon, 29 May 2006) | 3 lines Correct some value converting strangenesses. ........ r46530 | nick.coghlan | 2006-05-29 22:27:44 +0200 (Mon, 29 May 2006) | 1 line When adding a module like functools, it helps to let SVN know about the file. ........ r46531 | georg.brandl | 2006-05-29 22:52:54 +0200 (Mon, 29 May 2006) | 4 lines Patches #1497027 and #972322: try HTTP digest auth first, and watch out for handler name collisions. ........ r46532 | georg.brandl | 2006-05-29 22:57:01 +0200 (Mon, 29 May 2006) | 3 lines Add News entry for last commit. ........ r46533 | georg.brandl | 2006-05-29 23:04:52 +0200 (Mon, 29 May 2006) | 4 lines Make use of METH_O and METH_NOARGS where possible. Use Py_UnpackTuple instead of PyArg_ParseTuple where possible. ........ r46534 | georg.brandl | 2006-05-29 23:58:42 +0200 (Mon, 29 May 2006) | 3 lines Convert more modules to METH_VARARGS. ........ r46535 | georg.brandl | 2006-05-30 00:00:30 +0200 (Tue, 30 May 2006) | 3 lines Whoops. ........ r46536 | fredrik.lundh | 2006-05-30 00:42:07 +0200 (Tue, 30 May 2006) | 4 lines fixed "abc".count("", 100) == -96 error (hopefully, nobody's relying on the current behaviour ;-) ........ r46537 | bob.ippolito | 2006-05-30 00:55:48 +0200 (Tue, 30 May 2006) | 1 line struct: modulo math plus warning on all endian-explicit formats for compatibility with older struct usage (ugly) ........ r46539 | bob.ippolito | 2006-05-30 02:26:01 +0200 (Tue, 30 May 2006) | 1 line Add a length check to aifc to ensure it doesn't write a bogus file ........ r46540 | tim.peters | 2006-05-30 04:25:25 +0200 (Tue, 30 May 2006) | 10 lines deprecated_err(): Stop bizarre warning messages when the tests are run in the order: test_genexps (or any other doctest-based test) test_struct test_doctest The `warnings` module needs an advertised way to save/restore its internal filter list. ........ r46541 | tim.peters | 2006-05-30 04:26:46 +0200 (Tue, 30 May 2006) | 2 lines Whitespace normalization. ........ r46542 | tim.peters | 2006-05-30 04:30:30 +0200 (Tue, 30 May 2006) | 2 lines Set a binary svn:mime-type property on this UTF-8 encoded file. ........ r46543 | neal.norwitz | 2006-05-30 05:18:50 +0200 (Tue, 30 May 2006) | 1 line Simplify further by using AddStringConstant ........ r46544 | tim.peters | 2006-05-30 06:16:25 +0200 (Tue, 30 May 2006) | 6 lines Convert relevant dict internals to Py_ssize_t. I don't have a box with nearly enough RAM, or an OS, that could get close to tickling this, though (requires a dict w/ at least 2**31 entries). ........ r46545 | neal.norwitz | 2006-05-30 06:19:21 +0200 (Tue, 30 May 2006) | 1 line Remove stray | in comment ........ r46546 | neal.norwitz | 2006-05-30 06:25:05 +0200 (Tue, 30 May 2006) | 1 line Use Py_SAFE_DOWNCAST for safety. Fix format strings. Remove 2 more stray | in comment ........ r46547 | neal.norwitz | 2006-05-30 06:43:23 +0200 (Tue, 30 May 2006) | 1 line No DOWNCAST is required since sizeof(Py_ssize_t) >= sizeof(int) and Py_ReprEntr returns an int ........ r46548 | tim.peters | 2006-05-30 07:04:59 +0200 (Tue, 30 May 2006) | 3 lines dict_print(): Explicitly narrow the return value from a (possibly) wider variable. ........ r46549 | tim.peters | 2006-05-30 07:23:59 +0200 (Tue, 30 May 2006) | 5 lines dict_print(): So that Neal & I don't spend the rest of our lives taking turns rewriting code that works ;-), get rid of casting illusions by declaring a new variable with the obvious type. ........ r46550 | georg.brandl | 2006-05-30 09:04:55 +0200 (Tue, 30 May 2006) | 3 lines Restore exception pickle support. #1497319. ........ r46551 | georg.brandl | 2006-05-30 09:13:29 +0200 (Tue, 30 May 2006) | 3 lines Add a test case for exception pickling. args is never NULL. ........ r46552 | neal.norwitz | 2006-05-30 09:21:10 +0200 (Tue, 30 May 2006) | 1 line Don't fail if the (sub)pkgname already exist. ........ r46553 | georg.brandl | 2006-05-30 09:34:45 +0200 (Tue, 30 May 2006) | 3 lines Disallow keyword args for exceptions. ........ r46554 | neal.norwitz | 2006-05-30 09:36:54 +0200 (Tue, 30 May 2006) | 5 lines I'm impatient. I think this will fix a few more problems with the buildbots. I'm not sure this is the best approach, but I can't think of anything better. If this creates problems, feel free to revert, but I think it's safe and should make things a little better. ........ r46555 | georg.brandl | 2006-05-30 10:17:00 +0200 (Tue, 30 May 2006) | 4 lines Do the check for no keyword arguments in __init__ so that subclasses of Exception can be supplied keyword args ........ r46556 | georg.brandl | 2006-05-30 10:47:19 +0200 (Tue, 30 May 2006) | 3 lines Convert test_exceptions to unittest. ........ r46557 | andrew.kuchling | 2006-05-30 14:52:01 +0200 (Tue, 30 May 2006) | 1 line Add SoC name, and reorganize this section a bit ........ r46559 | tim.peters | 2006-05-30 17:53:34 +0200 (Tue, 30 May 2006) | 11 lines PyLong_FromString(): Continued fraction analysis (explained in a new comment) suggests there are almost certainly large input integers in all non-binary input bases for which one Python digit too few is initally allocated to hold the final result. Instead of assert-failing when that happens, allocate more space. Alas, I estimate it would take a few days to find a specific such case, so this isn't backed up by a new test (not to mention that such a case may take hours to run, since conversion time is quadratic in the number of digits, and preliminary attempts suggested that the smallest such inputs contain at least a million digits). ........ r46560 | fredrik.lundh | 2006-05-30 19:11:48 +0200 (Tue, 30 May 2006) | 3 lines changed find/rfind to return -1 for matches outside the source string ........ r46561 | bob.ippolito | 2006-05-30 19:37:54 +0200 (Tue, 30 May 2006) | 1 line Change wrapping terminology to overflow masking ........ r46562 | fredrik.lundh | 2006-05-30 19:39:58 +0200 (Tue, 30 May 2006) | 3 lines changed count to return 0 for slices outside the source string ........ r46568 | tim.peters | 2006-05-31 01:28:02 +0200 (Wed, 31 May 2006) | 2 lines Whitespace normalization. ........ r46569 | brett.cannon | 2006-05-31 04:19:54 +0200 (Wed, 31 May 2006) | 5 lines Clarify wording on default values for strptime(); defaults are used when better values cannot be inferred. Closes bug #1496315. ........ r46572 | neal.norwitz | 2006-05-31 09:43:27 +0200 (Wed, 31 May 2006) | 1 line Calculate smallest properly (it was off by one) and use proper ssize_t types for Win64 ........ r46573 | neal.norwitz | 2006-05-31 10:01:08 +0200 (Wed, 31 May 2006) | 1 line Revert last checkin, it is better to do make distclean ........ r46574 | neal.norwitz | 2006-05-31 11:02:44 +0200 (Wed, 31 May 2006) | 3 lines On 64-bit platforms running test_struct after test_tarfile would fail since the deprecation warning wouldn't be raised. ........ r46575 | thomas.heller | 2006-05-31 13:37:58 +0200 (Wed, 31 May 2006) | 3 lines PyTuple_Pack is not available in Python 2.3, but ctypes must stay compatible with that. ........ r46576 | andrew.kuchling | 2006-05-31 15:18:56 +0200 (Wed, 31 May 2006) | 1 line 'functional' module was renamed to 'functools' ........ r46577 | kristjan.jonsson | 2006-05-31 15:35:41 +0200 (Wed, 31 May 2006) | 1 line Fixup the PCBuild8 project directory. exceptions.c have moved to Objects, and the functionalmodule.c has been replaced with _functoolsmodule.c. Other minor changes to .vcproj files and .sln to fix compilation ........ r46578 | andrew.kuchling | 2006-05-31 16:08:48 +0200 (Wed, 31 May 2006) | 15 lines [Bug #1473048] SimpleXMLRPCServer and DocXMLRPCServer don't look at the path of the HTTP request at all; you can POST or GET from / or /RPC2 or /blahblahblah with the same results. Security scanners that look for /cgi-bin/phf will therefore report lots of vulnerabilities. Fix: add a .rpc_paths attribute to the SimpleXMLRPCServer class, and report a 404 error if the path isn't on the allowed list. Possibly-controversial aspect of this change: the default makes only '/' and '/RPC2' legal. Maybe this will break people's applications (though I doubt it). We could just set the default to an empty tuple, which would exactly match the current behaviour. ........ r46579 | andrew.kuchling | 2006-05-31 16:12:47 +0200 (Wed, 31 May 2006) | 1 line Mention SimpleXMLRPCServer change ........ r46580 | tim.peters | 2006-05-31 16:28:07 +0200 (Wed, 31 May 2006) | 2 lines Trimmed trailing whitespace. ........ r46581 | tim.peters | 2006-05-31 17:33:22 +0200 (Wed, 31 May 2006) | 4 lines _range_error(): Speed and simplify (there's no real need for loops here). Assert that size_t is actually big enough, and that f->size is at least one. Wrap a long line. ........ r46582 | tim.peters | 2006-05-31 17:34:37 +0200 (Wed, 31 May 2006) | 2 lines Repaired error in new comment. ........ r46584 | neal.norwitz | 2006-06-01 07:32:49 +0200 (Thu, 01 Jun 2006) | 4 lines Remove ; at end of macro. There was a compiler recently that warned about extra semi-colons. It may have been the HP C compiler. This file will trigger a bunch of those warnings now. ........ r46585 | georg.brandl | 2006-06-01 08:39:19 +0200 (Thu, 01 Jun 2006) | 3 lines Correctly unpickle 2.4 exceptions via __setstate__ (patch #1498571) ........ r46586 | georg.brandl | 2006-06-01 10:27:32 +0200 (Thu, 01 Jun 2006) | 3 lines Correctly allocate complex types with tp_alloc. (bug #1498638) ........ r46587 | georg.brandl | 2006-06-01 14:30:46 +0200 (Thu, 01 Jun 2006) | 2 lines Correctly dispatch Faults in loads (patch #1498627) ........ r46588 | georg.brandl | 2006-06-01 15:00:49 +0200 (Thu, 01 Jun 2006) | 3 lines Some code style tweaks, and remove apply. ........ r46589 | armin.rigo | 2006-06-01 15:19:12 +0200 (Thu, 01 Jun 2006) | 5 lines [ 1497053 ] Let dicts propagate the exceptions in user __eq__(). [ 1456209 ] dictresize() vulnerability ( <- backport candidate ). ........ r46590 | tim.peters | 2006-06-01 15:41:46 +0200 (Thu, 01 Jun 2006) | 2 lines Whitespace normalization. ........ r46591 | tim.peters | 2006-06-01 15:49:23 +0200 (Thu, 01 Jun 2006) | 2 lines Record bugs 1275608 and 1456209 as being fixed. ........ r46592 | tim.peters | 2006-06-01 15:56:26 +0200 (Thu, 01 Jun 2006) | 5 lines Re-enable a new empty-string test added during the NFS sprint, but disabled then because str and unicode strings gave different results. The implementations were repaired later during the sprint, but the new test remained disabled. ........ r46594 | tim.peters | 2006-06-01 17:50:44 +0200 (Thu, 01 Jun 2006) | 7 lines Armin committed his patch while I was reviewing it (I'm sure he didn't know this), so merged in some changes I made during review. Nothing material apart from changing a new `mask` local from int to Py_ssize_t. Mostly this is repairing comments that were made incorrect, and adding new comments. Also a few minor code rewrites for clarity or helpful succinctness. ........ r46599 | neal.norwitz | 2006-06-02 06:45:53 +0200 (Fri, 02 Jun 2006) | 1 line Convert docstrings to comments so regrtest -v prints method names ........ r46600 | neal.norwitz | 2006-06-02 06:50:49 +0200 (Fri, 02 Jun 2006) | 2 lines Fix memory leak found by valgrind. ........ r46601 | neal.norwitz | 2006-06-02 06:54:52 +0200 (Fri, 02 Jun 2006) | 1 line More memory leaks from valgrind ........ r46602 | neal.norwitz | 2006-06-02 08:23:00 +0200 (Fri, 02 Jun 2006) | 11 lines Patch #1357836: Prevent an invalid memory read from test_coding in case the done flag is set. In that case, the loop isn't entered. I wonder if rather than setting the done flag in the cases before the loop, if they should just exit early. This code looks like it should be refactored. Backport candidate (also the early break above if decoding_fgets fails) ........ r46603 | martin.blais | 2006-06-02 15:03:43 +0200 (Fri, 02 Jun 2006) | 1 line Fixed struct test to not use unittest. ........ r46605 | tim.peters | 2006-06-03 01:22:51 +0200 (Sat, 03 Jun 2006) | 10 lines pprint functions used to sort a dict (by key) if and only if the output required more than one line. "Small" dicts got displayed in seemingly random order (the hash-induced order produced by dict.__repr__). None of this was documented. Now pprint functions always sort dicts by key, and the docs promise it. This was proposed and agreed to during the PyCon 2006 core sprint -- I just didn't have time for it before now. ........
596 lines
20 KiB
Python
596 lines
20 KiB
Python
"""Simple XML-RPC Server.
|
|
|
|
This module can be used to create simple XML-RPC servers
|
|
by creating a server and either installing functions, a
|
|
class instance, or by extending the SimpleXMLRPCServer
|
|
class.
|
|
|
|
It can also be used to handle XML-RPC requests in a CGI
|
|
environment using CGIXMLRPCRequestHandler.
|
|
|
|
A list of possible usage patterns follows:
|
|
|
|
1. Install functions:
|
|
|
|
server = SimpleXMLRPCServer(("localhost", 8000))
|
|
server.register_function(pow)
|
|
server.register_function(lambda x,y: x+y, 'add')
|
|
server.serve_forever()
|
|
|
|
2. Install an instance:
|
|
|
|
class MyFuncs:
|
|
def __init__(self):
|
|
# make all of the string functions available through
|
|
# string.func_name
|
|
import string
|
|
self.string = string
|
|
def _listMethods(self):
|
|
# implement this method so that system.listMethods
|
|
# knows to advertise the strings methods
|
|
return list_public_methods(self) + \
|
|
['string.' + method for method in list_public_methods(self.string)]
|
|
def pow(self, x, y): return pow(x, y)
|
|
def add(self, x, y) : return x + y
|
|
|
|
server = SimpleXMLRPCServer(("localhost", 8000))
|
|
server.register_introspection_functions()
|
|
server.register_instance(MyFuncs())
|
|
server.serve_forever()
|
|
|
|
3. Install an instance with custom dispatch method:
|
|
|
|
class Math:
|
|
def _listMethods(self):
|
|
# this method must be present for system.listMethods
|
|
# to work
|
|
return ['add', 'pow']
|
|
def _methodHelp(self, method):
|
|
# this method must be present for system.methodHelp
|
|
# to work
|
|
if method == 'add':
|
|
return "add(2,3) => 5"
|
|
elif method == 'pow':
|
|
return "pow(x, y[, z]) => number"
|
|
else:
|
|
# By convention, return empty
|
|
# string if no help is available
|
|
return ""
|
|
def _dispatch(self, method, params):
|
|
if method == 'pow':
|
|
return pow(*params)
|
|
elif method == 'add':
|
|
return params[0] + params[1]
|
|
else:
|
|
raise 'bad method'
|
|
|
|
server = SimpleXMLRPCServer(("localhost", 8000))
|
|
server.register_introspection_functions()
|
|
server.register_instance(Math())
|
|
server.serve_forever()
|
|
|
|
4. Subclass SimpleXMLRPCServer:
|
|
|
|
class MathServer(SimpleXMLRPCServer):
|
|
def _dispatch(self, method, params):
|
|
try:
|
|
# We are forcing the 'export_' prefix on methods that are
|
|
# callable through XML-RPC to prevent potential security
|
|
# problems
|
|
func = getattr(self, 'export_' + method)
|
|
except AttributeError:
|
|
raise Exception('method "%s" is not supported' % method)
|
|
else:
|
|
return func(*params)
|
|
|
|
def export_add(self, x, y):
|
|
return x + y
|
|
|
|
server = MathServer(("localhost", 8000))
|
|
server.serve_forever()
|
|
|
|
5. CGI script:
|
|
|
|
server = CGIXMLRPCRequestHandler()
|
|
server.register_function(pow)
|
|
server.handle_request()
|
|
"""
|
|
|
|
# Written by Brian Quinlan (brian@sweetapp.com).
|
|
# Based on code written by Fredrik Lundh.
|
|
|
|
import xmlrpclib
|
|
from xmlrpclib import Fault
|
|
import SocketServer
|
|
import BaseHTTPServer
|
|
import sys
|
|
import os
|
|
try:
|
|
import fcntl
|
|
except ImportError:
|
|
fcntl = None
|
|
|
|
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
|
|
"""resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
|
|
|
|
Resolves a dotted attribute name to an object. Raises
|
|
an AttributeError if any attribute in the chain starts with a '_'.
|
|
|
|
If the optional allow_dotted_names argument is false, dots are not
|
|
supported and this function operates similar to getattr(obj, attr).
|
|
"""
|
|
|
|
if allow_dotted_names:
|
|
attrs = attr.split('.')
|
|
else:
|
|
attrs = [attr]
|
|
|
|
for i in attrs:
|
|
if i.startswith('_'):
|
|
raise AttributeError(
|
|
'attempt to access private attribute "%s"' % i
|
|
)
|
|
else:
|
|
obj = getattr(obj,i)
|
|
return obj
|
|
|
|
def list_public_methods(obj):
|
|
"""Returns a list of attribute strings, found in the specified
|
|
object, which represent callable attributes"""
|
|
|
|
return [member for member in dir(obj)
|
|
if not member.startswith('_') and
|
|
callable(getattr(obj, member))]
|
|
|
|
def remove_duplicates(lst):
|
|
"""remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
|
|
|
|
Returns a copy of a list without duplicates. Every list
|
|
item must be hashable and the order of the items in the
|
|
resulting list is not defined.
|
|
"""
|
|
u = {}
|
|
for x in lst:
|
|
u[x] = 1
|
|
|
|
return u.keys()
|
|
|
|
class SimpleXMLRPCDispatcher:
|
|
"""Mix-in class that dispatches XML-RPC requests.
|
|
|
|
This class is used to register XML-RPC method handlers
|
|
and then to dispatch them. There should never be any
|
|
reason to instantiate this class directly.
|
|
"""
|
|
|
|
def __init__(self, allow_none, encoding):
|
|
self.funcs = {}
|
|
self.instance = None
|
|
self.allow_none = allow_none
|
|
self.encoding = encoding
|
|
|
|
def register_instance(self, instance, allow_dotted_names=False):
|
|
"""Registers an instance to respond to XML-RPC requests.
|
|
|
|
Only one instance can be installed at a time.
|
|
|
|
If the registered instance has a _dispatch method then that
|
|
method will be called with the name of the XML-RPC method and
|
|
its parameters as a tuple
|
|
e.g. instance._dispatch('add',(2,3))
|
|
|
|
If the registered instance does not have a _dispatch method
|
|
then the instance will be searched to find a matching method
|
|
and, if found, will be called. Methods beginning with an '_'
|
|
are considered private and will not be called by
|
|
SimpleXMLRPCServer.
|
|
|
|
If a registered function matches a XML-RPC request, then it
|
|
will be called instead of the registered instance.
|
|
|
|
If the optional allow_dotted_names argument is true and the
|
|
instance does not have a _dispatch method, method names
|
|
containing dots are supported and resolved, as long as none of
|
|
the name segments start with an '_'.
|
|
|
|
*** SECURITY WARNING: ***
|
|
|
|
Enabling the allow_dotted_names options allows intruders
|
|
to access your module's global variables and may allow
|
|
intruders to execute arbitrary code on your machine. Only
|
|
use this option on a secure, closed network.
|
|
|
|
"""
|
|
|
|
self.instance = instance
|
|
self.allow_dotted_names = allow_dotted_names
|
|
|
|
def register_function(self, function, name = None):
|
|
"""Registers a function to respond to XML-RPC requests.
|
|
|
|
The optional name argument can be used to set a Unicode name
|
|
for the function.
|
|
"""
|
|
|
|
if name is None:
|
|
name = function.__name__
|
|
self.funcs[name] = function
|
|
|
|
def register_introspection_functions(self):
|
|
"""Registers the XML-RPC introspection methods in the system
|
|
namespace.
|
|
|
|
see http://xmlrpc.usefulinc.com/doc/reserved.html
|
|
"""
|
|
|
|
self.funcs.update({'system.listMethods' : self.system_listMethods,
|
|
'system.methodSignature' : self.system_methodSignature,
|
|
'system.methodHelp' : self.system_methodHelp})
|
|
|
|
def register_multicall_functions(self):
|
|
"""Registers the XML-RPC multicall method in the system
|
|
namespace.
|
|
|
|
see http://www.xmlrpc.com/discuss/msgReader$1208"""
|
|
|
|
self.funcs.update({'system.multicall' : self.system_multicall})
|
|
|
|
def _marshaled_dispatch(self, data, dispatch_method = None):
|
|
"""Dispatches an XML-RPC method from marshalled (XML) data.
|
|
|
|
XML-RPC methods are dispatched from the marshalled (XML) data
|
|
using the _dispatch method and the result is returned as
|
|
marshalled data. For backwards compatibility, a dispatch
|
|
function can be provided as an argument (see comment in
|
|
SimpleXMLRPCRequestHandler.do_POST) but overriding the
|
|
existing method through subclassing is the prefered means
|
|
of changing method dispatch behavior.
|
|
"""
|
|
|
|
try:
|
|
params, method = xmlrpclib.loads(data)
|
|
|
|
# generate response
|
|
if dispatch_method is not None:
|
|
response = dispatch_method(method, params)
|
|
else:
|
|
response = self._dispatch(method, params)
|
|
# wrap response in a singleton tuple
|
|
response = (response,)
|
|
response = xmlrpclib.dumps(response, methodresponse=1,
|
|
allow_none=self.allow_none, encoding=self.encoding)
|
|
except Fault, fault:
|
|
response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
|
|
encoding=self.encoding)
|
|
except:
|
|
# report exception back to server
|
|
response = xmlrpclib.dumps(
|
|
xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2]),
|
|
encoding=self.encoding, allow_none=self.allow_none,
|
|
)
|
|
|
|
return response
|
|
|
|
def system_listMethods(self):
|
|
"""system.listMethods() => ['add', 'subtract', 'multiple']
|
|
|
|
Returns a list of the methods supported by the server."""
|
|
|
|
methods = self.funcs.keys()
|
|
if self.instance is not None:
|
|
# Instance can implement _listMethod to return a list of
|
|
# methods
|
|
if hasattr(self.instance, '_listMethods'):
|
|
methods = remove_duplicates(
|
|
methods + self.instance._listMethods()
|
|
)
|
|
# if the instance has a _dispatch method then we
|
|
# don't have enough information to provide a list
|
|
# of methods
|
|
elif not hasattr(self.instance, '_dispatch'):
|
|
methods = remove_duplicates(
|
|
methods + list_public_methods(self.instance)
|
|
)
|
|
methods.sort()
|
|
return methods
|
|
|
|
def system_methodSignature(self, method_name):
|
|
"""system.methodSignature('add') => [double, int, int]
|
|
|
|
Returns a list describing the signature of the method. In the
|
|
above example, the add method takes two integers as arguments
|
|
and returns a double result.
|
|
|
|
This server does NOT support system.methodSignature."""
|
|
|
|
# See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
|
|
|
|
return 'signatures not supported'
|
|
|
|
def system_methodHelp(self, method_name):
|
|
"""system.methodHelp('add') => "Adds two integers together"
|
|
|
|
Returns a string containing documentation for the specified method."""
|
|
|
|
method = None
|
|
if self.funcs.has_key(method_name):
|
|
method = self.funcs[method_name]
|
|
elif self.instance is not None:
|
|
# Instance can implement _methodHelp to return help for a method
|
|
if hasattr(self.instance, '_methodHelp'):
|
|
return self.instance._methodHelp(method_name)
|
|
# if the instance has a _dispatch method then we
|
|
# don't have enough information to provide help
|
|
elif not hasattr(self.instance, '_dispatch'):
|
|
try:
|
|
method = resolve_dotted_attribute(
|
|
self.instance,
|
|
method_name,
|
|
self.allow_dotted_names
|
|
)
|
|
except AttributeError:
|
|
pass
|
|
|
|
# Note that we aren't checking that the method actually
|
|
# be a callable object of some kind
|
|
if method is None:
|
|
return ""
|
|
else:
|
|
import pydoc
|
|
return pydoc.getdoc(method)
|
|
|
|
def system_multicall(self, call_list):
|
|
"""system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
|
|
[[4], ...]
|
|
|
|
Allows the caller to package multiple XML-RPC calls into a single
|
|
request.
|
|
|
|
See http://www.xmlrpc.com/discuss/msgReader$1208
|
|
"""
|
|
|
|
results = []
|
|
for call in call_list:
|
|
method_name = call['methodName']
|
|
params = call['params']
|
|
|
|
try:
|
|
# XXX A marshalling error in any response will fail the entire
|
|
# multicall. If someone cares they should fix this.
|
|
results.append([self._dispatch(method_name, params)])
|
|
except Fault, fault:
|
|
results.append(
|
|
{'faultCode' : fault.faultCode,
|
|
'faultString' : fault.faultString}
|
|
)
|
|
except:
|
|
results.append(
|
|
{'faultCode' : 1,
|
|
'faultString' : "%s:%s" % sys.exc_info()[:2]}
|
|
)
|
|
return results
|
|
|
|
def _dispatch(self, method, params):
|
|
"""Dispatches the XML-RPC method.
|
|
|
|
XML-RPC calls are forwarded to a registered function that
|
|
matches the called XML-RPC method name. If no such function
|
|
exists then the call is forwarded to the registered instance,
|
|
if available.
|
|
|
|
If the registered instance has a _dispatch method then that
|
|
method will be called with the name of the XML-RPC method and
|
|
its parameters as a tuple
|
|
e.g. instance._dispatch('add',(2,3))
|
|
|
|
If the registered instance does not have a _dispatch method
|
|
then the instance will be searched to find a matching method
|
|
and, if found, will be called.
|
|
|
|
Methods beginning with an '_' are considered private and will
|
|
not be called.
|
|
"""
|
|
|
|
func = None
|
|
try:
|
|
# check to see if a matching function has been registered
|
|
func = self.funcs[method]
|
|
except KeyError:
|
|
if self.instance is not None:
|
|
# check for a _dispatch method
|
|
if hasattr(self.instance, '_dispatch'):
|
|
return self.instance._dispatch(method, params)
|
|
else:
|
|
# call instance method directly
|
|
try:
|
|
func = resolve_dotted_attribute(
|
|
self.instance,
|
|
method,
|
|
self.allow_dotted_names
|
|
)
|
|
except AttributeError:
|
|
pass
|
|
|
|
if func is not None:
|
|
return func(*params)
|
|
else:
|
|
raise Exception('method "%s" is not supported' % method)
|
|
|
|
class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
|
|
"""Simple XML-RPC request handler class.
|
|
|
|
Handles all HTTP POST requests and attempts to decode them as
|
|
XML-RPC requests.
|
|
"""
|
|
|
|
# Class attribute listing the accessible path components;
|
|
# paths not on this list will result in a 404 error.
|
|
rpc_paths = ('/', '/RPC2')
|
|
|
|
def is_rpc_path_valid(self):
|
|
if self.rpc_paths:
|
|
return self.path in self.rpc_paths
|
|
else:
|
|
# If .rpc_paths is empty, just assume all paths are legal
|
|
return True
|
|
|
|
def do_POST(self):
|
|
"""Handles the HTTP POST request.
|
|
|
|
Attempts to interpret all HTTP POST requests as XML-RPC calls,
|
|
which are forwarded to the server's _dispatch method for handling.
|
|
"""
|
|
|
|
# Check that the path is legal
|
|
if not self.is_rpc_path_valid():
|
|
self.report_404()
|
|
return
|
|
|
|
try:
|
|
# Get arguments by reading body of request.
|
|
# We read this in chunks to avoid straining
|
|
# socket.read(); around the 10 or 15Mb mark, some platforms
|
|
# begin to have problems (bug #792570).
|
|
max_chunk_size = 10*1024*1024
|
|
size_remaining = int(self.headers["content-length"])
|
|
L = []
|
|
while size_remaining:
|
|
chunk_size = min(size_remaining, max_chunk_size)
|
|
L.append(self.rfile.read(chunk_size))
|
|
size_remaining -= len(L[-1])
|
|
data = ''.join(L)
|
|
|
|
# In previous versions of SimpleXMLRPCServer, _dispatch
|
|
# could be overridden in this class, instead of in
|
|
# SimpleXMLRPCDispatcher. To maintain backwards compatibility,
|
|
# check to see if a subclass implements _dispatch and dispatch
|
|
# using that method if present.
|
|
response = self.server._marshaled_dispatch(
|
|
data, getattr(self, '_dispatch', None)
|
|
)
|
|
except: # This should only happen if the module is buggy
|
|
# internal error, report as HTTP server error
|
|
self.send_response(500)
|
|
self.end_headers()
|
|
else:
|
|
# got a valid XML RPC response
|
|
self.send_response(200)
|
|
self.send_header("Content-type", "text/xml")
|
|
self.send_header("Content-length", str(len(response)))
|
|
self.end_headers()
|
|
self.wfile.write(response)
|
|
|
|
# shut down the connection
|
|
self.wfile.flush()
|
|
self.connection.shutdown(1)
|
|
|
|
def report_404 (self):
|
|
# Report a 404 error
|
|
self.send_response(404)
|
|
response = 'No such page'
|
|
self.send_header("Content-type", "text/plain")
|
|
self.send_header("Content-length", str(len(response)))
|
|
self.end_headers()
|
|
self.wfile.write(response)
|
|
# shut down the connection
|
|
self.wfile.flush()
|
|
self.connection.shutdown(1)
|
|
|
|
def log_request(self, code='-', size='-'):
|
|
"""Selectively log an accepted request."""
|
|
|
|
if self.server.logRequests:
|
|
BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
|
|
|
|
class SimpleXMLRPCServer(SocketServer.TCPServer,
|
|
SimpleXMLRPCDispatcher):
|
|
"""Simple XML-RPC server.
|
|
|
|
Simple XML-RPC server that allows functions and a single instance
|
|
to be installed to handle requests. The default implementation
|
|
attempts to dispatch XML-RPC calls to the functions or instance
|
|
installed in the server. Override the _dispatch method inhereted
|
|
from SimpleXMLRPCDispatcher to change this behavior.
|
|
"""
|
|
|
|
allow_reuse_address = True
|
|
|
|
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
|
|
logRequests=True, allow_none=False, encoding=None):
|
|
self.logRequests = logRequests
|
|
|
|
SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
|
|
SocketServer.TCPServer.__init__(self, addr, requestHandler)
|
|
|
|
# [Bug #1222790] If possible, set close-on-exec flag; if a
|
|
# method spawns a subprocess, the subprocess shouldn't have
|
|
# the listening socket open.
|
|
if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
|
|
flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
|
|
flags |= fcntl.FD_CLOEXEC
|
|
fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
|
|
|
|
class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
|
|
"""Simple handler for XML-RPC data passed through CGI."""
|
|
|
|
def __init__(self, allow_none=False, encoding=None):
|
|
SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
|
|
|
|
def handle_xmlrpc(self, request_text):
|
|
"""Handle a single XML-RPC request"""
|
|
|
|
response = self._marshaled_dispatch(request_text)
|
|
|
|
print 'Content-Type: text/xml'
|
|
print 'Content-Length: %d' % len(response)
|
|
print
|
|
sys.stdout.write(response)
|
|
|
|
def handle_get(self):
|
|
"""Handle a single HTTP GET request.
|
|
|
|
Default implementation indicates an error because
|
|
XML-RPC uses the POST method.
|
|
"""
|
|
|
|
code = 400
|
|
message, explain = \
|
|
BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
|
|
|
|
response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
|
|
{
|
|
'code' : code,
|
|
'message' : message,
|
|
'explain' : explain
|
|
}
|
|
print 'Status: %d %s' % (code, message)
|
|
print 'Content-Type: text/html'
|
|
print 'Content-Length: %d' % len(response)
|
|
print
|
|
sys.stdout.write(response)
|
|
|
|
def handle_request(self, request_text = None):
|
|
"""Handle a single XML-RPC request passed through a CGI post method.
|
|
|
|
If no XML data is given then it is read from stdin. The resulting
|
|
XML-RPC response is printed to stdout along with the correct HTTP
|
|
headers.
|
|
"""
|
|
|
|
if request_text is None and \
|
|
os.environ.get('REQUEST_METHOD', None) == 'GET':
|
|
self.handle_get()
|
|
else:
|
|
# POST data is normally available through stdin
|
|
if request_text is None:
|
|
request_text = sys.stdin.read()
|
|
|
|
self.handle_xmlrpc(request_text)
|
|
|
|
if __name__ == '__main__':
|
|
print 'Running XML-RPC server on port 8000'
|
|
server = SimpleXMLRPCServer(("localhost", 8000))
|
|
server.register_function(pow)
|
|
server.register_function(lambda x,y: x+y, 'add')
|
|
server.serve_forever()
|