server.py 36.5 KB
Newer Older
1
r"""XML-RPC Servers.
2 3 4

This module can be used to create simple XML-RPC servers
by creating a server and either installing functions, a
5
class instance, or by extending the SimpleXMLRPCServer
6 7
class.

8 9 10
It can also be used to handle XML-RPC requests in a CGI
environment using CGIXMLRPCRequestHandler.

11 12 13 14 15 16
The Doc* classes can be used to create XML-RPC servers that
serve pydoc-style documentation in response to HTTP
GET requests. This documentation is dynamically generated
based on the functions and methods registered with the
server.

17 18 19 20 21 22 23 24 25 26 27 28 29
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):
30 31 32
        # make all of the sys functions available through sys.func_name
        import sys
        self.sys = sys
33 34
    def _listMethods(self):
        # implement this method so that system.listMethods
35
        # knows to advertise the sys methods
36
        return list_public_methods(self) + \
37
                ['sys.' + method for method in list_public_methods(self.sys)]
38 39
    def pow(self, x, y): return pow(x, y)
    def add(self, x, y) : return x + y
Tim Peters's avatar
Tim Peters committed
40

41
server = SimpleXMLRPCServer(("localhost", 8000))
42
server.register_introspection_functions()
43 44 45 46 47 48
server.register_instance(MyFuncs())
server.serve_forever()

3. Install an instance with custom dispatch method:

class Math:
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    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 ""
64 65
    def _dispatch(self, method, params):
        if method == 'pow':
66
            return pow(*params)
67 68 69
        elif method == 'add':
            return params[0] + params[1]
        else:
70
            raise ValueError('bad method')
71

72
server = SimpleXMLRPCServer(("localhost", 8000))
73
server.register_introspection_functions()
74 75 76
server.register_instance(Math())
server.serve_forever()

77
4. Subclass SimpleXMLRPCServer:
78

79
class MathServer(SimpleXMLRPCServer):
80 81 82 83 84 85 86 87 88
    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:
89
            return func(*params)
90 91 92 93

    def export_add(self, x, y):
        return x + y

94
server = MathServer(("localhost", 8000))
95
server.serve_forever()
96 97 98 99 100 101

5. CGI script:

server = CGIXMLRPCRequestHandler()
server.register_function(pow)
server.handle_request()
102 103 104 105 106
"""

# Written by Brian Quinlan (brian@sweetapp.com).
# Based on code written by Fredrik Lundh.

107
from xmlrpc.client import Fault, dumps, loads, gzip_encode, gzip_decode
108
from http.server import BaseHTTPRequestHandler
109
from functools import partial
110
import http.server
111
import socketserver
112
import sys
113
import os
114 115 116
import re
import pydoc
import inspect
117
import traceback
118 119 120 121
try:
    import fcntl
except ImportError:
    fcntl = None
122

123
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
124
    """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
125

126 127
    Resolves a dotted attribute name to an object.  Raises
    an AttributeError if any attribute in the chain starts with a '_'.
128 129 130

    If the optional allow_dotted_names argument is false, dots are not
    supported and this function operates similar to getattr(obj, attr).
131 132
    """

133 134 135 136 137 138
    if allow_dotted_names:
        attrs = attr.split('.')
    else:
        attrs = [attr]

    for i in attrs:
139 140 141 142 143 144 145
        if i.startswith('_'):
            raise AttributeError(
                'attempt to access private attribute "%s"' % i
                )
        else:
            obj = getattr(obj,i)
    return obj
146

147 148 149 150 151 152
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
153
                    callable(getattr(obj, member))]
154 155 156 157 158

class SimpleXMLRPCDispatcher:
    """Mix-in class that dispatches XML-RPC requests.

    This class is used to register XML-RPC method handlers
159 160 161
    and then to dispatch them. This class doesn't need to be
    instanced directly when used by SimpleXMLRPCServer but it
    can be instanced when used by the MultiPathXMLRPCServer
162
    """
Tim Peters's avatar
Tim Peters committed
163

164 165
    def __init__(self, allow_none=False, encoding=None,
                 use_builtin_types=False):
166 167
        self.funcs = {}
        self.instance = None
168
        self.allow_none = allow_none
169
        self.encoding = encoding or 'utf-8'
170
        self.use_builtin_types = use_builtin_types
171

172
    def register_instance(self, instance, allow_dotted_names=False):
173
        """Registers an instance to respond to XML-RPC requests.
174

175 176 177 178
        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
179
        its parameters as a tuple
180 181 182 183 184 185 186 187
        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.

188
        If a registered function matches an XML-RPC request, then it
189
        will be called instead of the registered instance.
190 191 192 193 194 195 196 197 198 199 200 201 202

        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.

203 204
        """

205
        self.instance = instance
206
        self.allow_dotted_names = allow_dotted_names
207

208
    def register_function(self, function=None, name=None):
209 210 211 212 213
        """Registers a function to respond to XML-RPC requests.

        The optional name argument can be used to set a Unicode name
        for the function.
        """
214 215 216
        # decorator factory
        if function is None:
            return partial(self.register_function, name=name)
217 218 219 220 221

        if name is None:
            name = function.__name__
        self.funcs[name] = function

222 223
        return function

224 225 226 227 228 229
    def register_introspection_functions(self):
        """Registers the XML-RPC introspection methods in the system
        namespace.

        see http://xmlrpc.usefulinc.com/doc/reserved.html
        """
Tim Peters's avatar
Tim Peters committed
230

231 232 233 234 235 236 237 238 239
        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"""
Tim Peters's avatar
Tim Peters committed
240

241
        self.funcs.update({'system.multicall' : self.system_multicall})
Tim Peters's avatar
Tim Peters committed
242

243
    def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
244
        """Dispatches an XML-RPC method from marshalled (XML) data.
Tim Peters's avatar
Tim Peters committed
245

246 247 248
        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
Tim Peters's avatar
Tim Peters committed
249
        function can be provided as an argument (see comment in
250
        SimpleXMLRPCRequestHandler.do_POST) but overriding the
251
        existing method through subclassing is the preferred means
252 253
        of changing method dispatch behavior.
        """
Tim Peters's avatar
Tim Peters committed
254

255
        try:
256
            params, method = loads(data, use_builtin_types=self.use_builtin_types)
257 258

            # generate response
259 260
            if dispatch_method is not None:
                response = dispatch_method(method, params)
Tim Peters's avatar
Tim Peters committed
261
            else:
262
                response = self._dispatch(method, params)
263 264
            # wrap response in a singleton tuple
            response = (response,)
265 266
            response = dumps(response, methodresponse=1,
                             allow_none=self.allow_none, encoding=self.encoding)
267
        except Fault as fault:
268 269
            response = dumps(fault, allow_none=self.allow_none,
                             encoding=self.encoding)
270
        except:
271
            # report exception back to server
272
            exc_type, exc_value, exc_tb = sys.exc_info()
273 274 275 276 277 278 279 280
            try:
                response = dumps(
                    Fault(1, "%s:%s" % (exc_type, exc_value)),
                    encoding=self.encoding, allow_none=self.allow_none,
                    )
            finally:
                # Break reference cycle
                exc_type = exc_value = exc_tb = None
281

282
        return response.encode(self.encoding, 'xmlcharrefreplace')
283 284 285 286 287

    def system_listMethods(self):
        """system.listMethods() => ['add', 'subtract', 'multiple']

        Returns a list of the methods supported by the server."""
Tim Peters's avatar
Tim Peters committed
288

289
        methods = set(self.funcs.keys())
290 291 292 293
        if self.instance is not None:
            # Instance can implement _listMethod to return a list of
            # methods
            if hasattr(self.instance, '_listMethods'):
294
                methods |= set(self.instance._listMethods())
295 296 297 298
            # 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'):
299 300
                methods |= set(list_public_methods(self.instance))
        return sorted(methods)
Tim Peters's avatar
Tim Peters committed
301

302 303 304
    def system_methodSignature(self, method_name):
        """system.methodSignature('add') => [double, int, int]

305
        Returns a list describing the signature of the method. In the
306 307 308 309 310 311
        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
Tim Peters's avatar
Tim Peters committed
312

313 314 315 316 317 318
        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."""
Tim Peters's avatar
Tim Peters committed
319

320
        method = None
321
        if method_name in self.funcs:
322 323 324 325 326 327 328 329 330 331 332
            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,
333 334
                                method_name,
                                self.allow_dotted_names
335 336 337 338 339 340 341 342
                                )
                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 ""
343
        else:
Neal Norwitz's avatar
Neal Norwitz committed
344
            return pydoc.getdoc(method)
345

346 347 348 349 350 351
    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.
352

Tim Peters's avatar
Tim Peters committed
353
        See http://www.xmlrpc.com/discuss/msgReader$1208
354
        """
Tim Peters's avatar
Tim Peters committed
355

356 357 358 359 360 361 362 363 364
        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)])
365
            except Fault as fault:
366 367 368 369 370
                results.append(
                    {'faultCode' : fault.faultCode,
                     'faultString' : fault.faultString}
                    )
            except:
371
                exc_type, exc_value, exc_tb = sys.exc_info()
372 373 374 375 376 377 378 379
                try:
                    results.append(
                        {'faultCode' : 1,
                         'faultString' : "%s:%s" % (exc_type, exc_value)}
                        )
                finally:
                    # Break reference cycle
                    exc_type = exc_value = exc_tb = None
380
        return results
Tim Peters's avatar
Tim Peters committed
381

382 383 384 385 386 387 388 389 390 391
    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
392
        its parameters as a tuple
393 394 395 396 397 398 399
        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
400
        not be called.
401 402 403
        """

        try:
404
            # call the matching registered function
405
            func = self.funcs[method]
406
        except KeyError:
407
            pass
408
        else:
409 410
            if func is not None:
                return func(*params)
411
            raise Exception('method "%s" is not supported' % method)
Tim Peters's avatar
Tim Peters committed
412

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
        if self.instance is not None:
            if hasattr(self.instance, '_dispatch'):
                # call the `_dispatch` method on the instance
                return self.instance._dispatch(method, params)

            # call the instance's method directly
            try:
                func = resolve_dotted_attribute(
                    self.instance,
                    method,
                    self.allow_dotted_names
                )
            except AttributeError:
                pass
            else:
                if func is not None:
                    return func(*params)

        raise Exception('method "%s" is not supported' % method)

433
class SimpleXMLRPCRequestHandler(BaseHTTPRequestHandler):
434
    """Simple XML-RPC request handler class.
435

436 437 438
    Handles all HTTP POST requests and attempts to decode them as
    XML-RPC requests.
    """
439

440 441 442 443
    # Class attribute listing the accessible path components;
    # paths not on this list will result in a 404 error.
    rpc_paths = ('/', '/RPC2')

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
    #if not None, encode responses larger than this, if possible
    encode_threshold = 1400 #a common MTU

    #Override form StreamRequestHandler: full buffering of output
    #and no Nagle.
    wbufsize = -1
    disable_nagle_algorithm = True

    # a re to match a gzip Accept-Encoding
    aepattern = re.compile(r"""
                            \s* ([^\s;]+) \s*            #content-coding
                            (;\s* q \s*=\s* ([0-9\.]+))? #q
                            """, re.VERBOSE | re.IGNORECASE)

    def accept_encodings(self):
        r = {}
        ae = self.headers.get("Accept-Encoding", "")
        for e in ae.split(","):
            match = self.aepattern.match(e)
            if match:
                v = match.group(3)
                v = float(v) if v else 1.0
                r[match.group(1)] = v
        return r

469 470 471 472 473 474 475
    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

476 477
    def do_POST(self):
        """Handles the HTTP POST request.
478

479 480 481
        Attempts to interpret all HTTP POST requests as XML-RPC calls,
        which are forwarded to the server's _dispatch method for handling.
        """
Tim Peters's avatar
Tim Peters committed
482

483 484 485 486 487
        # Check that the path is legal
        if not self.is_rpc_path_valid():
            self.report_404()
            return

488
        try:
Tim Peters's avatar
Tim Peters committed
489 490
            # Get arguments by reading body of request.
            # We read this in chunks to avoid straining
491 492 493 494 495 496 497
            # 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)
498 499 500 501
                chunk = self.rfile.read(chunk_size)
                if not chunk:
                    break
                L.append(chunk)
502
                size_remaining -= len(L[-1])
503
            data = b''.join(L)
504

505 506 507 508
            data = self.decode_request_content(data)
            if data is None:
                return #response has been sent

509 510 511 512 513 514
            # 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(
515
                    data, getattr(self, '_dispatch', None), self.path
516
                )
517
        except Exception as e: # This should only happen if the module is buggy
518 519
            # internal error, report as HTTP server error
            self.send_response(500)
520 521 522 523 524

            # Send information about the exception if requested
            if hasattr(self.server, '_send_traceback_header') and \
                    self.server._send_traceback_header:
                self.send_header("X-exception", str(e))
525 526 527
                trace = traceback.format_exc()
                trace = str(trace.encode('ASCII', 'backslashreplace'), 'ASCII')
                self.send_header("X-traceback", trace)
528

529
            self.send_header("Content-length", "0")
530
            self.end_headers()
531
        else:
532 533
            self.send_response(200)
            self.send_header("Content-type", "text/xml")
534 535 536 537
            if self.encode_threshold is not None:
                if len(response) > self.encode_threshold:
                    q = self.accept_encodings().get("gzip", 0)
                    if q:
538 539 540 541 542
                        try:
                            response = gzip_encode(response)
                            self.send_header("Content-Encoding", "gzip")
                        except NotImplementedError:
                            pass
543 544 545
            self.send_header("Content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)
546

547 548 549 550 551 552 553 554
    def decode_request_content(self, data):
        #support gzip encoding of request
        encoding = self.headers.get("content-encoding", "identity").lower()
        if encoding == "identity":
            return data
        if encoding == "gzip":
            try:
                return gzip_decode(data)
555 556
            except NotImplementedError:
                self.send_response(501, "encoding %r not supported" % encoding)
557 558 559 560 561 562
            except ValueError:
                self.send_response(400, "error decoding gzip content")
        else:
            self.send_response(501, "encoding %r not supported" % encoding)
        self.send_header("Content-length", "0")
        self.end_headers()
Tim Peters's avatar
Tim Peters committed
563

564 565 566
    def report_404 (self):
            # Report a 404 error
        self.send_response(404)
567
        response = b'No such page'
568 569 570 571 572
        self.send_header("Content-type", "text/plain")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)

573 574
    def log_request(self, code='-', size='-'):
        """Selectively log an accepted request."""
575

576
        if self.server.logRequests:
577
            BaseHTTPRequestHandler.log_request(self, code, size)
578

579
class SimpleXMLRPCServer(socketserver.TCPServer,
580
                         SimpleXMLRPCDispatcher):
581 582 583
    """Simple XML-RPC server.

    Simple XML-RPC server that allows functions and a single instance
584 585
    to be installed to handle requests. The default implementation
    attempts to dispatch XML-RPC calls to the functions or instance
586
    installed in the server. Override the _dispatch method inherited
587
    from SimpleXMLRPCDispatcher to change this behavior.
588 589
    """

590 591
    allow_reuse_address = True

592 593 594 595 596 597
    # Warning: this is for debugging purposes only! Never set this to True in
    # production code, as will be sending out sensitive information (exception
    # and stack trace details) when exceptions are raised inside
    # SimpleXMLRPCRequestHandler.do_POST
    _send_traceback_header = False

598
    def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
599 600
                 logRequests=True, allow_none=False, encoding=None,
                 bind_and_activate=True, use_builtin_types=False):
601
        self.logRequests = logRequests
Tim Peters's avatar
Tim Peters committed
602

603
        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types)
604
        socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
Tim Peters's avatar
Tim Peters committed
605

606

607 608 609 610 611 612 613 614 615
class MultiPathXMLRPCServer(SimpleXMLRPCServer):
    """Multipath XML-RPC Server
    This specialization of SimpleXMLRPCServer allows the user to create
    multiple Dispatcher instances and assign them to different
    HTTP request paths.  This makes it possible to run two or more
    'virtual XML-RPC servers' at the same port.
    Make sure that the requestHandler accepts the paths in question.
    """
    def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
616 617
                 logRequests=True, allow_none=False, encoding=None,
                 bind_and_activate=True, use_builtin_types=False):
618 619

        SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, allow_none,
620
                                    encoding, bind_and_activate, use_builtin_types)
621 622
        self.dispatchers = {}
        self.allow_none = allow_none
623
        self.encoding = encoding or 'utf-8'
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640

    def add_dispatcher(self, path, dispatcher):
        self.dispatchers[path] = dispatcher
        return dispatcher

    def get_dispatcher(self, path):
        return self.dispatchers[path]

    def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
        try:
            response = self.dispatchers[path]._marshaled_dispatch(
               data, dispatch_method, path)
        except:
            # report low level exception back to server
            # (each dispatcher should have handled their own
            # exceptions)
            exc_type, exc_value = sys.exc_info()[:2]
641 642 643 644 645 646 647 648
            try:
                response = dumps(
                    Fault(1, "%s:%s" % (exc_type, exc_value)),
                    encoding=self.encoding, allow_none=self.allow_none)
                response = response.encode(self.encoding, 'xmlcharrefreplace')
            finally:
                # Break reference cycle
                exc_type = exc_value = None
649 650
        return response

651 652
class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
    """Simple handler for XML-RPC data passed through CGI."""
Tim Peters's avatar
Tim Peters committed
653

654 655
    def __init__(self, allow_none=False, encoding=None, use_builtin_types=False):
        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types)
656 657 658

    def handle_xmlrpc(self, request_text):
        """Handle a single XML-RPC request"""
Tim Peters's avatar
Tim Peters committed
659

660
        response = self._marshaled_dispatch(request_text)
Tim Peters's avatar
Tim Peters committed
661

662 663 664
        print('Content-Type: text/xml')
        print('Content-Length: %d' % len(response))
        print()
665 666 667
        sys.stdout.flush()
        sys.stdout.buffer.write(response)
        sys.stdout.buffer.flush()
668 669 670 671 672 673

    def handle_get(self):
        """Handle a single HTTP GET request.

        Default implementation indicates an error because
        XML-RPC uses the POST method.
674 675
        """

676
        code = 400
677
        message, explain = BaseHTTPRequestHandler.responses[code]
Tim Peters's avatar
Tim Peters committed
678

679
        response = http.server.DEFAULT_ERROR_MESSAGE % \
680
            {
Tim Peters's avatar
Tim Peters committed
681 682
             'code' : code,
             'message' : message,
683 684
             'explain' : explain
            }
685
        response = response.encode('utf-8')
686
        print('Status: %d %s' % (code, message))
687
        print('Content-Type: %s' % http.server.DEFAULT_ERROR_CONTENT_TYPE)
688 689
        print('Content-Length: %d' % len(response))
        print()
690 691 692
        sys.stdout.flush()
        sys.stdout.buffer.write(response)
        sys.stdout.buffer.flush()
Tim Peters's avatar
Tim Peters committed
693

694
    def handle_request(self, request_text=None):
695
        """Handle a single XML-RPC request passed through a CGI post method.
Tim Peters's avatar
Tim Peters committed
696

697 698 699
        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.
700
        """
Tim Peters's avatar
Tim Peters committed
701

702 703 704 705 706
        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
707 708
            try:
                length = int(os.environ.get('CONTENT_LENGTH', None))
709
            except (ValueError, TypeError):
710
                length = -1
711
            if request_text is None:
712
                request_text = sys.stdin.read(length)
713

714
            self.handle_xmlrpc(request_text)
Tim Peters's avatar
Tim Peters committed
715

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774

# -----------------------------------------------------------------------------
# Self documenting XML-RPC Server.

class ServerHTMLDoc(pydoc.HTMLDoc):
    """Class used to generate pydoc HTML document for a server"""

    def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
        """Mark up some plain text, given a context of symbols to look for.
        Each context dictionary maps object names to anchor names."""
        escape = escape or self.escape
        results = []
        here = 0

        # XXX Note that this regular expression does not allow for the
        # hyperlinking of arbitrary strings being used as method
        # names. Only methods with names consisting of word characters
        # and '.'s are hyperlinked.
        pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
                                r'RFC[- ]?(\d+)|'
                                r'PEP[- ]?(\d+)|'
                                r'(self\.)?((?:\w|\.)+))\b')
        while 1:
            match = pattern.search(text, here)
            if not match: break
            start, end = match.span()
            results.append(escape(text[here:start]))

            all, scheme, rfc, pep, selfdot, name = match.groups()
            if scheme:
                url = escape(all).replace('"', '"')
                results.append('<a href="%s">%s</a>' % (url, url))
            elif rfc:
                url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
                results.append('<a href="%s">%s</a>' % (url, escape(all)))
            elif pep:
                url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
                results.append('<a href="%s">%s</a>' % (url, escape(all)))
            elif text[end:end+1] == '(':
                results.append(self.namelink(name, methods, funcs, classes))
            elif selfdot:
                results.append('self.<strong>%s</strong>' % name)
            else:
                results.append(self.namelink(name, classes))
            here = end
        results.append(escape(text[here:]))
        return ''.join(results)

    def docroutine(self, object, name, mod=None,
                   funcs={}, classes={}, methods={}, cl=None):
        """Produce HTML documentation for a function or method object."""

        anchor = (cl and cl.__name__ or '') + '-' + name
        note = ''

        title = '<a name="%s"><strong>%s</strong></a>' % (
            self.escape(anchor), self.escape(name))

        if inspect.ismethod(object):
775
            args = inspect.getfullargspec(object)
776 777 778
            # exclude the argument bound to the instance, it will be
            # confusing to the non-Python user
            argspec = inspect.formatargspec (
779 780 781 782 783
                    args.args[1:],
                    args.varargs,
                    args.varkw,
                    args.defaults,
                    annotations=args.annotations,
784 785 786
                    formatvalue=self.formatvalue
                )
        elif inspect.isfunction(object):
787
            args = inspect.getfullargspec(object)
788
            argspec = inspect.formatargspec(
789 790 791
                args.args, args.varargs, args.varkw, args.defaults,
                annotations=args.annotations,
                formatvalue=self.formatvalue)
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
        else:
            argspec = '(...)'

        if isinstance(object, tuple):
            argspec = object[0] or argspec
            docstring = object[1] or ""
        else:
            docstring = pydoc.getdoc(object)

        decl = title + argspec + (note and self.grey(
               '<font face="helvetica, arial">%s</font>' % note))

        doc = self.markup(
            docstring, self.preformat, funcs, classes, methods)
        doc = doc and '<dd><tt>%s</tt></dd>' % doc
        return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)

    def docserver(self, server_name, package_documentation, methods):
        """Produce HTML documentation for an XML-RPC server."""

        fdict = {}
        for key, value in methods.items():
            fdict[key] = '#-' + key
            fdict[value] = fdict[key]

        server_name = self.escape(server_name)
        head = '<big><big><strong>%s</strong></big></big>' % server_name
        result = self.heading(head, '#ffffff', '#7799ee')

        doc = self.markup(package_documentation, self.preformat, fdict)
        doc = doc and '<tt>%s</tt>' % doc
        result = result + '<p>%s</p>\n' % doc

        contents = []
        method_items = sorted(methods.items())
        for key, value in method_items:
            contents.append(self.docroutine(value, key, funcs=fdict))
        result = result + self.bigsection(
            'Methods', '#ffffff', '#eeaa77', ''.join(contents))

        return result

class XMLRPCDocGenerator:
    """Generates documentation for an XML-RPC server.

    This class is designed as mix-in and should not
    be constructed directly.
    """

    def __init__(self):
        # setup variables used for HTML documentation
        self.server_name = 'XML-RPC Server Documentation'
        self.server_documentation = \
            "This server exports the following methods through the XML-RPC "\
            "protocol."
        self.server_title = 'XML-RPC Server Documentation'

    def set_server_title(self, server_title):
        """Set the HTML title of the generated server documentation"""

        self.server_title = server_title

    def set_server_name(self, server_name):
        """Set the name of the generated HTML server documentation"""

        self.server_name = server_name

    def set_server_documentation(self, server_documentation):
        """Set the documentation string for the entire server."""

        self.server_documentation = server_documentation

    def generate_html_documentation(self):
        """generate_html_documentation() => html documentation for the server

        Generates HTML documentation for the server using introspection for
        installed functions and instances that do not implement the
        _dispatch method. Alternatively, instances can choose to implement
        the _get_method_argstring(method_name) method to provide the
        argument string used in the documentation and the
        _methodHelp(method_name) method to provide the help text used
        in the documentation."""

        methods = {}

        for method_name in self.system_listMethods():
            if method_name in self.funcs:
                method = self.funcs[method_name]
            elif self.instance is not None:
                method_info = [None, None] # argspec, documentation
                if hasattr(self.instance, '_get_method_argstring'):
                    method_info[0] = self.instance._get_method_argstring(method_name)
                if hasattr(self.instance, '_methodHelp'):
                    method_info[1] = self.instance._methodHelp(method_name)

                method_info = tuple(method_info)
                if method_info != (None, None):
                    method = method_info
                elif not hasattr(self.instance, '_dispatch'):
                    try:
                        method = resolve_dotted_attribute(
                                    self.instance,
                                    method_name
                                    )
                    except AttributeError:
                        method = method_info
                else:
                    method = method_info
            else:
                assert 0, "Could not find method in self.functions and no "\
                          "instance installed"

            methods[method_name] = method

        documenter = ServerHTMLDoc()
        documentation = documenter.docserver(
                                self.server_name,
                                self.server_documentation,
                                methods
                            )

        return documenter.page(self.server_title, documentation)

class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
    """XML-RPC and documentation request handler class.

    Handles all HTTP POST requests and attempts to decode them as
    XML-RPC requests.

    Handles all HTTP GET requests and interprets them as requests
    for documentation.
    """

    def do_GET(self):
        """Handles the HTTP GET request.

        Interpret all HTTP GET requests as requests for server
        documentation.
        """
        # Check that the path is legal
        if not self.is_rpc_path_valid():
            self.report_404()
            return

936
        response = self.server.generate_html_documentation().encode('utf-8')
937 938 939 940
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
941
        self.wfile.write(response)
942 943 944 945 946 947 948 949 950 951

class DocXMLRPCServer(  SimpleXMLRPCServer,
                        XMLRPCDocGenerator):
    """XML-RPC and HTML documentation server.

    Adds the ability to serve server documentation to the capabilities
    of SimpleXMLRPCServer.
    """

    def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler,
952
                 logRequests=True, allow_none=False, encoding=None,
953
                 bind_and_activate=True, use_builtin_types=False):
954
        SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests,
955 956
                                    allow_none, encoding, bind_and_activate,
                                    use_builtin_types)
957 958 959 960 961 962 963 964 965 966 967 968 969 970
        XMLRPCDocGenerator.__init__(self)

class DocCGIXMLRPCRequestHandler(   CGIXMLRPCRequestHandler,
                                    XMLRPCDocGenerator):
    """Handler for XML-RPC data and documentation requests passed through
    CGI"""

    def handle_get(self):
        """Handles the HTTP GET request.

        Interpret all HTTP GET requests as requests for server
        documentation.
        """

971
        response = self.generate_html_documentation().encode('utf-8')
972 973 974 975

        print('Content-Type: text/html')
        print('Content-Length: %d' % len(response))
        print()
976 977 978
        sys.stdout.flush()
        sys.stdout.buffer.write(response)
        sys.stdout.buffer.flush()
979 980 981 982 983 984

    def __init__(self):
        CGIXMLRPCRequestHandler.__init__(self)
        XMLRPCDocGenerator.__init__(self)


985
if __name__ == '__main__':
986 987 988 989 990 991 992 993 994 995 996
    import datetime

    class ExampleService:
        def getData(self):
            return '42'

        class currentTime:
            @staticmethod
            def getCurrentTime():
                return datetime.datetime.now()

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    with SimpleXMLRPCServer(("localhost", 8000)) as server:
        server.register_function(pow)
        server.register_function(lambda x,y: x+y, 'add')
        server.register_instance(ExampleService(), allow_dotted_names=True)
        server.register_multicall_functions()
        print('Serving XML-RPC on localhost port 8000')
        print('It is advisable to run this example server within a secure, closed network.')
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            print("\nKeyboard interrupt received, exiting.")
            sys.exit(0)