Beispiel #1
0
 def __init__(self, no_introspection=False):
     if sys.version_info[:2] < (2, 5):
         SimpleXMLRPCDispatcher.__init__(self)
     else:
         SimpleXMLRPCDispatcher.__init__(self, False, 'utf-8')
     if not no_introspection:
         self.register_introspection_functions()
Beispiel #2
0
    def post(self, request):
        dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None)
        dispatcher.register_function(partial(self.ping, request), 'pingback:ping')

        response = HttpResponse(mimetype="application/xml")
        response.write(dispatcher._marshaled_dispatch(request.raw_post_data))
        return response
Beispiel #3
0
 def __init__(self):
     #: Python 2.5 requires some arguments like `allow_none`
     #: and the encoding. Python 2.4 and 2.3 doesn't.
     if sys.version_info[:2] < (2, 5):
         SimpleXMLRPCDispatcher.__init__(self)
     else:
         SimpleXMLRPCDispatcher.__init__(self, True, 'utf-8')
Beispiel #4
0
 def __init__(self, path):
     path = to_unicode(path)
     SimpleXMLRPCDispatcher.__init__(self, True, 'utf-8')
     self.register_introspection_functions()
     self.register_multicall_functions()
     self.instance = self.instance_class(path)
     self.path = path
Beispiel #5
0
    def __init__(self, requestHandler, logRequests=True, allow_none=False,
                 encoding=None):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none=allow_none,
                                        encoding=encoding)
        ConnectedTCPServer.__init__(self, requestHandler)
Beispiel #6
0
 def __init__(self, allow_none=False, encoding=None):
     try:
         SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
     except TypeError:
         # see http://bugs.debian.org/470645
         # python2.4 and before only took one argument
         SimpleXMLRPCDispatcher.__init__(self)
Beispiel #7
0
    def __init__(self, registerInstance, server_address, keyFile=DEFAULTKEYFILE,
            certFile=DEFAULTCERTFILE, caFile = DEFAULTCAFILE, logRequests=True):
        """Secure Documenting XML-RPC server.
        It it very similar to DocXMLRPCServer but it uses HTTPS for transporting XML data.
        """
        SimpleXMLRPCServer.__init__(self, server_address, SecureXMLRPCRequestHandler, logRequests)
        self.logRequests = logRequests

        self.register_introspection_functions()

        # init stuff, handle different versions:
        try:
            SimpleXMLRPCDispatcher.__init__(self)
        except TypeError:
            # An exception is raised in Python 2.5 as the prototype of the __init__
            # method has changed and now has 3 arguments (self, allow_none, encoding)
            SimpleXMLRPCDispatcher.__init__(self, False, None)
        SocketServer.BaseServer.__init__(self, server_address, SecureXMLRPCRequestHandler)
        self.register_instance(registerInstance) # for some reason, have to register instance down here!

        # SSL socket stuff
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file(keyFile)
        ctx.use_certificate_file(certFile)
        # verify
        ctx.load_verify_locations(caFile)
        ctx.set_verify(SSL.VERIFY_PEER|SSL.VERIFY_FAIL_IF_NO_PEER_CERT, self._verify)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
        self.server_bind()
        self.server_activate()

        # requests count and condition, to allow for keyboard quit via CTL-C
        self.requests = 0
        self.rCondition = Condition()
    def CreateApp(self, name):
        """
        Creates new app.
        
        @param name: Name of an app.
        @type name: C{str}
        
        @return: Instance id of an app.
        @rtype: C{int}
        """ 
        if not self.Apps:
            return 0
        if name not in self.Apps:
            return 0

        id= int(random.getrandbits(16))
        print self.Apps[name]
        if not self.instances:
            self.instances= {}
        self.instances[id]= (self.Apps[name](), name,)

        dispatcher= SimpleXMLRPCDispatcher()
        dispatcher.register_introspection_functions()
        dispatcher.register_instance(self.instances[id][0])
        self.server.add_dispatcher( "/"+str(id), dispatcher)

        return id
Beispiel #9
0
	def __init__(self,application, request, transforms=None):
		tornado.web.RequestHandler.__init__(self,application, request, transforms)

		SimpleXMLRPCDispatcher.__init__(self,True,None)

		self.register_multicall_functions()

		self.register_methods()
Beispiel #10
0
 def __init__(self, prefix):
     self.prefix = prefix
     try:
         # Python 2.4
         self.dispatcher = SimpleXMLRPCDispatcher()
     except TypeError:
         # Python 2.5
         self.dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None)
Beispiel #11
0
 def __init__(self, clientHost, clientPort):
     SimpleXMLRPCDispatcher.__init__(self)
     ThreadingTCPServer.__init__(self,
                                 (clientHost, clientPort),
                                 SimpleXMLRPCRequestHandler)
     self.logRequests = 1
     self.client = AdminControlInterface()
     self.register_introspection_functions()
     self.register_instance(self.client)
Beispiel #12
0
 def __init__(self, addr, requestHandler=RequestHandler):
     self.logRequests = 0
     if os.path.exists(addr):
         os.unlink(addr)
     dir = os.path.dirname(addr)
     if not(os.path.exists(dir)):
         os.makedirs(dir)
     SimpleXMLRPCDispatcher.__init__(self)
     UnixStreamServer.__init__(self, addr, requestHandler)
class Server(Thread):
    """
    XML-RPC server.
    """ 

    @LogCall()
    def __init__(self, requestHandler, host="localhost", port=8400):
        """
        Initializes server.
        
        @param requestHandler: Request handler for base class calls.
        @type requestHandler: C{AppsHandler}
        @param host: Host where to bind.
        @type host: C{str}
        @param port: Port where to bind.
        @type port: C{int}
        
        @return: Instance of self.
        @rtype: C{Server}
        """ 
        Thread.__init__(self)

        self.server = MultiPathXMLRPCServer((host, port), requestHandler=RHandler)
        self.requestHandler= requestHandler(self.server, False)
        self.dispatcher= SimpleXMLRPCDispatcher()
        self.dispatcher.register_introspection_functions()
        self.dispatcher.register_instance(self.requestHandler)
        self.server.add_dispatcher("/", self.dispatcher)

    @LogCall({"level": INFO})
    def run(self):
        """
        Runs server.
        
        @return: Nothing
        @rtype: C{None}
        """ 
        self.server.serve_forever()

    @LogCall({"level": INFO})
    def __del__(self):
        """
        Stops server.
        
        @return: Nothing
        @rtype: C{None}
        """ 
        self.server.shutdown()

    def GetRequestHandler(self):
        """
        Gets base request handler used with this server.
        
        @return: Request handler used with this server.
        @rtype: C{AppsHandler}
        """ 
        return self.requestHandler
Beispiel #14
0
    def __init__(self, requestHandler=IPXMLRPCRequestHandler,
                 logRequests=False, allow_none=False, encoding=None):
        SimpleXMLRPCDispatcher.__init__(self, allow_none=allow_none,
                                        encoding=encoding)

        self.requestHandler = requestHandler
        self.logRequests = logRequests

        # TODO provide proper limit for this queue
        self.queue = TaskQueue(sys.maxint)
Beispiel #15
0
    def __init__(self,
                 address,
                 requestHandler=SimpleXMLRPCRequestHandler,
                 allow_none=False,
                 encoding=None):

        self.logRequests = False

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        UnixStreamServer.__init__(self, address, requestHandler)
    def __init__(self, allow_none=True, encoding=None):
        if sys.version_info[:2] == (2, 4):
            # doesn't support extra args in python 2.4
            SimpleXMLRPCDispatcher.__init__(self)
        else:
            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)

        self.allow_none = allow_none
        self.encoding = encoding
        self.register_multicall_functions()
Beispiel #17
0
 def __init__(self):
     try:
         # older Pythons like 2.4.3 demand a single parameter
         # newest Python versions handle 1, 2 or 3 parameters
         # supplying defaults for the 2nd and 3rd
         SimpleXMLRPCDispatcher.__init__(self)
     except:
         # some mid-age Python versions demand 3 parameters without
         # offering default values for the 2nd and 3rd
         SimpleXMLRPCDispatcher.__init__(self, False, None)
Beispiel #18
0
    def __init__(self, addr, requestHandler=DroidPresRequestHandler, logRequests=False, allow_none=False, encoding=None, bind_and_activate=True):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        ThreadingTCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        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)
Beispiel #19
0
    def __init__(self, allow_none=True, encoding=None):
        if sys.version_info[:2] == (2, 4):
            # doesn't support extra args in python 2.4
            SimpleXMLRPCDispatcher.__init__(self)
        else:
            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)

        self.allow_none = allow_none
        self.encoding = encoding
        self.register_multicall_functions()
Beispiel #20
0
	def __init__(self, apis):
		SimpleXMLRPCDispatcher.__init__(self, True, 'utf-8')
		funcs = {}
		for api in apis:
			prefix = api.prefix
			for attr_name in dir(api):
				attr = getattr(api, attr_name)
				if callable(attr):
					funcs[prefix + attr_name] = attr
		self.funcs = funcs
		self.register_introspection_functions()
Beispiel #21
0
        def __init__(self, addr, requestHandler, 
                 logRequests, allow_none, encoding, bind_and_activate):
            self.logRequests = logRequests

            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
            ForkingTCPServer.__init__(self, addr, requestHandler, bind_and_activate)

            if fcntl is not None and hasattr(fcntl, 'FD_COLEXEC'):
                flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
                flags |= fcntl.FD_COLEXEC
                fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
Beispiel #22
0
    def __init__(self,
                 requestHandler,
                 logRequests=True,
                 allow_none=False,
                 encoding=None):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self,
                                        allow_none=allow_none,
                                        encoding=encoding)
        ConnectedTCPServer.__init__(self, requestHandler)
Beispiel #23
0
    def __init__(self, host, port):
        '''create a XML-RPC server

Takes two initial inputs:
    host  -- hostname of XML-RPC server host
    port  -- port number for server requests
        '''
        Server.__init__(self)
        SimpleXMLRPCDispatcher.__init__(self, allow_none=False, encoding=None)

        self._installSocket(host, port)
        self._activeProcesses = {}  #{ fd : pid }
Beispiel #24
0
def main_loop():
    setproctitle("webshelld")

    dispatcher = SimpleXMLRPCDispatcher()
    SOCKFILE = "/var/run/webshell.sock"
    if os.path.exists(SOCKFILE):
        os.unlink(SOCKFILE)
    server = SocketServer.UnixStreamServer(SOCKFILE, XMLRPCHandler)
    os.chmod(SOCKFILE, 0o700)
    dispatcher.register_instance(Multiplex("/usr/local/bin/bash", "xterm-color"))
    server.dispatcher = dispatcher
    server.serve_forever()
Beispiel #25
0
    def __init__(self, host, port):
        """create a XML-RPC server

Takes two initial inputs:
    host  -- hostname of XML-RPC server host
    port  -- port number for server requests
        """
        Server.__init__(self)
        SimpleXMLRPCDispatcher.__init__(self, allow_none=False, encoding=None)

        self._installSocket(host, port)
        self._activeProcesses = {}  # { fd : pid }
Beispiel #26
0
 def __init__(self, instance=None, methods=[]):
     """Create windmill xmlrpc dispatcher"""
     try:
         self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None)
     except TypeError:
         # python 2.4
         self.dispatcher = SimpleXMLRPCDispatcher()
     if instance is not None:
         self.dispatcher.register_instance(instance)
     for method in methods:
         self.dispatcher.register_function(method)
     self.dispatcher.register_introspection_functions()
Beispiel #27
0
 def __init__(self, instance=None, methods=[]):
     """Create windmill xmlrpc dispatcher"""
     try:
         self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True,
                                                  encoding=None)
     except TypeError:
         # python 2.4
         self.dispatcher = SimpleXMLRPCDispatcher()
     if instance is not None:
         self.dispatcher.register_instance(instance)
     for method in methods:
         self.dispatcher.register_function(method)
     self.dispatcher.register_introspection_functions()
Beispiel #28
0
def main_loop():
    setproctitle('webshelld')

    dispatcher = SimpleXMLRPCDispatcher()
    SOCKFILE = '/var/run/webshell.sock'
    if os.path.exists(SOCKFILE):
        os.unlink(SOCKFILE)
    server = SocketServer.UnixStreamServer(SOCKFILE, XMLRPCHandler)
    os.chmod(SOCKFILE, 0o700)
    dispatcher.register_instance(
        Multiplex("/usr/local/bin/bash", "xterm-color"))
    server.dispatcher = dispatcher
    server.serve_forever()
Beispiel #29
0
    def __init__(self,
                 requestHandler=IPXMLRPCRequestHandler,
                 logRequests=False,
                 allow_none=False,
                 encoding=None):
        SimpleXMLRPCDispatcher.__init__(self,
                                        allow_none=allow_none,
                                        encoding=encoding)

        self.requestHandler = requestHandler
        self.logRequests = logRequests

        # TODO provide proper limit for this queue
        self.queue = TaskQueue(sys.maxint)
    def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
                 logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        ThreadingTCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        # [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)
Beispiel #31
0
    def __init__(self):
        SimpleXMLRPCDispatcher.__init__(self, allow_none=False,
                                        encoding=None)
        XMLRPCDocGenerator.__init__(self)

        def _dumps(obj, *args, **kwargs):
            kwargs['allow_none'] = self.allow_none
            kwargs['encoding'] = self.encoding
            return xmlrpclib.dumps(obj, *args, **kwargs)

        self.dumps = _dumps

        # map of name => (auth, func)
        self.func_map = {}
Beispiel #32
0
    def __init__(self,
                 addr,
                 logger,
                 allow_none=False,
                 logRequests=1,
                 encoding='iso-8859-1'):
        class AuthenticatedRequestHandler(SimpleXMLRPCRequestHandler):
            def parse_request(myself):
                if SimpleXMLRPCRequestHandler.parse_request(myself):
                    header = myself.headers.get('Authorization')

                    if header == None:
                        username = None
                        password = None
                    else:
                        (basic, encoded) = \
                            header.split(' ', 2)

                        assert basic == 'Basic', 'Only basic authentication supported'

                        (username,
                         password) = base64.b64decode(encoded).split(':', 2)

                    if self.authenticate(username, password):
                        return True
                    else:
                        myself.send_response(401, 'Authentication failed')
                        myself.send_header('WWW-Authenticate',
                                           'Basic realm="XML-RPC"')
                        myself.end_headers()

                        myself.wfile.write('Authentication failed.')

                return False

        self.logRequests = logRequests

        if sys.version_info[:2] < (2, 5):
            SimpleXMLRPCDispatcher.__init__(self)
        else:
            SimpleXMLRPCDispatcher.__init__(self,
                                            allow_none=allow_none,
                                            encoding=encoding)

        ThreadingTCPServer.__init__(self, addr, AuthenticatedRequestHandler)

        self.required_username = None
        self.required_password = None

        self.logger = logger
Beispiel #33
0
 def __init__(self):
     SimpleXMLRPCDispatcher.__init__(self, True, 'utf-8')
     self.register_function(list_packages)
     self.register_function(package_releases)
     self.register_function(release_urls)
     self.register_function(release_urls, name='package_urls') # Deprecated
     self.register_function(release_data)
     self.register_function(release_data, name='package_data') # Deprecated
     self.register_function(search)
     self.register_function(updated_releases)
     self.register_function(changelog)
     self.register_function(post_cheesecake_for_release)
     self.register_introspection_functions()
     self.register_multicall_functions()
Beispiel #34
0
 def __init__(self):
     SimpleXMLRPCDispatcher.__init__(self, True, 'utf-8')
     self.register_function(list_packages)
     self.register_function(package_releases)
     self.register_function(release_urls)
     self.register_function(release_urls, name='package_urls')  # Deprecated
     self.register_function(release_data)
     self.register_function(release_data, name='package_data')  # Deprecated
     self.register_function(search)
     self.register_function(updated_releases)
     self.register_function(changelog)
     self.register_function(post_cheesecake_for_release)
     self.register_introspection_functions()
     self.register_multicall_functions()
Beispiel #35
0
def get_handler(methodlist):
    dispatcher = SimpleXMLRPCDispatcher(False, None)
    for method in web.group(methodlist, 2):
        dispatcher.register_function(method[1], method[0])
    class rpc:
        def GET(self):
            web.header('Content-Type', 'text/html')
            print get_doc(dispatcher)

        def POST(self):
            response = dispatcher._marshaled_dispatch(web.webapi.data())
            web.header('Content-Type', 'text/xml')
            web.header('Content-length', str(len(response)))
            print response
    return rpc
Beispiel #36
0
    def __init__(self, server_address, requestHandler, keyfile, certfile, logRequests=True, allow_none=False):
        """Secure XML-RPC server.

        It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data.
        """
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none=allow_none)
        SocketServer.BaseServer.__init__(self, server_address, requestHandler)
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file(keyfile)
        ctx.use_certificate_file(certfile)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
        self.server_bind()
        self.server_activate()
Beispiel #37
0
    def __init__(self, addr, KEYFILE, CERTFILE):
        SimpleXMLRPCDispatcher.__init__(self)

        VerifyingServer.__init__(self, addr)
        self.socket = ssl.wrap_socket(
            socket.socket(self.address_family, self.socket_type),
            server_side=True,
            keyfile=KEYFILE,
            certfile=CERTFILE,
            cert_reqs=ssl.CERT_NONE,
            ssl_version=ssl.PROTOCOL_SSLv23,
            )

        self.server_bind()
        self.server_activate()
Beispiel #38
0
 def register_function(self, function, name=None):
     """
     This will register the given function. There are two ways to use it.
     
     As a plain old method, with or without a name::
     
         handler.register_function(spam)
         handler.register_function(spam, 'spam')
     
     As a decorator, also with or without a name::
     
         @handler.register_function
         def spam():
             pass
         
         @handler.register_function('spam')
         def spam():
             pass
     
     It's shorter and easier to use :meth:`register`, however, as it does
     the exact same thing.
     
     :param function: The function to register. (In the named decorator
                      form, this is the function's name.)
     :param name: The name to use, except in the named decorator form.
                  If not given, the function's :obj:`__name__` attribute
                  will be used.
     """
     if isinstance(function, basestring):
         return lambda fn: self.register_function(fn, function)
     return Dispatcher.register_function(self, function, name)
Beispiel #39
0
 def __init__(self,
              endpoint_name=None,
              instance=None,
              introspection=True,
              multicall=False):
     if sys.version_info[:2] < (2, 5):
         Dispatcher.__init__(self)
     else:
         Dispatcher.__init__(self, True, 'utf-8')
     self.endpoint_name = endpoint_name
     if introspection:
         self.register_introspection_functions()
     if multicall:
         self.register_multicall_functions()
     if instance:
         self.register_instance(instance)
Beispiel #40
0
    def __init__(self, server_address, HandlerClass, logRequests=True):
        """Secure XML-RPC server.
           It it very similar to SimpleXMLRPCServer but it uses HTTPS for 
           transporting XML data.
        """
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self)
        SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file (KEYFILE)
        ctx.use_certificate_file(CERTFILE)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family,
                                                       self.socket_type))
        self.server_bind()
        self.server_activate()
Beispiel #41
0
 def __init__(self,instance=None,methods=[]):
     self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True,encoding=None)
     if instance is not None:
         self.dispatcher.register_instance(instance)
     for method in methods:
         self.dispatcher.register_function(method)
     self.dispatcher.register_introspection_functions()
	def _dispatch(self, *args, **kw):
		try:
			result = SimpleXMLRPCDispatcher._dispatch(self, *args, **kw)
		#	self.logger.debug("Result: %s" % (result, ))
			return result
		except:
			self.logger.exception("Error while processing request")
			raise
Beispiel #43
0
def handle_request(app, request):
    '''Wrap an invocation of the XML-RPC dispatcher.
    '''
    dispatcher = SimpleXMLRPCDispatcher()
    dispatcher.register_instance(Interface(app, request))

    # read in the XML-RPC request data, limiting to a sensible size
    if int(request.headers['Content-Length']) > 10 * 1024 * 1024:
        raise BadRequest('request data too large')
    xml_request = request.get_data(cache=False, as_text=True)

    # errors here are handled by _marshaled_dispatch
    response = dispatcher._marshaled_dispatch(xml_request)
    # legacy; remove non-printable ASCII control codes from the response
    response = re.sub('([\x00-\x08]|[\x0b-\x0c]|[\x0e-\x1f])+', '', response)

    return Response(response, mimetype="text/xml")
Beispiel #44
0
    def __init__(self):
        if sys.version_info[:3] >= (2,5,):
            SimpleXMLRPCDispatcher.__init__(self, allow_none=False,
                    encoding=None)
            def _dumps(obj, *args, **kwargs):
                kwargs['allow_none'] = self.allow_none
                kwargs['encoding'] = self.encoding
                return xmlrpclib.dumps(obj, *args, **kwargs)
        else:
            def _dumps(obj, *args, **kwargs):
                return xmlrpclib.dumps(obj, *args, **kwargs)
            SimpleXMLRPCDispatcher.__init__(self)

        self.dumps = _dumps

        # map of name => (auth, func)
        self.func_map = {}
Beispiel #45
0
 def register_instance(self, instance, allow_dotted_names=False):
     """
     This registers any kind of object. If the requested method hasn't been
     registered by :meth:`register_function`, it will be checked against
     the instance. You can only have one instance at a time, however.
     If :obj:`allow_dotted_names` is True, the name will be split on the
     dots and the object will be traveled down recursively. However, this
     is a **HUGE SECURITY LOOPHOLE**, as while private methods (starting
     with ``_``) will not be exposed, it's still possible that someone
     could get access to your globals and do very bad things. So don't
     do it unless you have a very good reason.
     :param instance: The instance to register.
     :param allow_dotted_names: Whether to resolve dots in method names.
                                You probably shouldn't.
     """
     # Yes, it's just a wrapper. I know. This way the docs are consistent.
     Dispatcher.register_instance(self, instance, allow_dotted_names)
Beispiel #46
0
    def __init__(self,
                 addr,
                 requestHandler=UnixStreamXMLRPCRequestHandler,
                 logRequests=True,
                 allow_none=False,
                 encoding=None,
                 bind_and_activate=True,
                 use_builtin_types=False):
        self.logRequests = logRequests

        try:
            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding,
                                            use_builtin_types)
        except TypeError:
            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)

        socketserver.UnixStreamServer.__init__(self, addr, requestHandler,
                                               bind_and_activate)
Beispiel #47
0
 def _dispatch(self, method, params):
     try:
         return SimpleXMLRPCDispatcher._dispatch(self, method, params)
     except Exception, e:
         message = "XML-RPC request caused exception:\n"
         message += "Method: %s\n" % (method)
         message += "Parameters: %s" % (str(params))
         self.logger.exception(message)
         raise
class WSGIXMLRPCApplication(object):
    """Application to handle requests to the XMLRPC service"""

    def __init__(self, instance=None, methods=[]):
        """Create windmill xmlrpc dispatcher"""
        self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True,
                                                 encoding=None)
        if instance is not None:
            self.dispatcher.register_instance(instance)
        for method in methods:
            self.dispatcher.register_function(method)
        self.dispatcher.register_introspection_functions()

    def handler(self, environ, start_response):
        """XMLRPC service for windmill browser core to communicate with"""
        if environ['REQUEST_METHOD'] == 'POST':
            return self.handle_POST(environ, start_response)
        else:
            start_response("400 Bad request", [('Content-Type', 'text/plain')])
            return ['']

    def handle_POST(self, environ, start_response):
        """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.

        Most code taken from SimpleXMLRPCServer with modifications for wsgi and
        my custom dispatcher.
        """
        try:
            # Get arguments by reading body of request.
            # We read this in chunks to avoid straining

            length = int(environ['CONTENT_LENGTH'])
            data = environ['wsgi.input'].read(length)

            # 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
            # using that method if present.
            response = self.dispatcher._marshaled_dispatch(
                    data, getattr(self.dispatcher, '_dispatch', None)
                )
            response += '\n'
        except:  # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            start_response("500 Server error", [('Content-Type',
                                                 'text/plain')])
            return []
        else:
            # got a valid XML RPC response
            start_response("200 OK", [('Content-Type', 'text/xml'),
                                      ('Content-Length', str(len(response)),)])
            return [response]

    def __call__(self, environ, start_response):
      return self.handler(environ, start_response)
Beispiel #49
0
    def system_listMethods(self):
        """
        Gets a list of the methods supported by the server.

        :returns: ['method name', ...]
        :rtype: list

        """

        return SimpleXMLRPCDispatcher.system_listMethods(self)
Beispiel #50
0
    def __init__(self,
                 addr,
                 requestHandler,
                 logRequests=True,
                 allow_none=False,
                 encoding=None,
                 bind_and_activate=True):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        HTTPServer.__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)
Beispiel #51
0
def handler(request, response, methods):
    response.session_id = None  # no sessions for xmlrpc
    dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None)
    for method in methods:
        dispatcher.register_function(method)
    dispatcher.register_introspection_functions()
    response.headers['Content-Type'] = 'text/xml'
    dispatch = getattr(dispatcher, '_dispatch', None)
    return dispatcher._marshaled_dispatch(request.body.read(), dispatch)
Beispiel #52
0
class WSGIXMLRPCApplication(object):
    """Application to handle requests to the XMLRPC service"""
    def __init__(self, instance=None, methods=()):
        """Create windmill xmlrpc dispatcher"""
        try:
            self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True,
                                                     encoding=None)
        except TypeError:
            # python 2.4
            self.dispatcher = SimpleXMLRPCDispatcher()

        if instance is not None:
            self.dispatcher.register_instance(instance)

        for method in methods:
            self.dispatcher.register_function(method)

        self.dispatcher.register_introspection_functions()

    @Request.application
    def handler(self, request):
        if request.method == 'POST':
            return self.handle_POST(request)
        else:
            return BadRequest()

    def handle_POST(self, request):
        """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.

        Most code taken from SimpleXMLRPCServer with modifications for wsgi and
        my custom dispatcher.
        """

        try:
            # Read the data from the request
            data = request.get_data()

            # 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
            # using that method if present.
            response = self.dispatcher._marshaled_dispatch(
                data, getattr(self.dispatcher, '_dispatch', None))
            response += '\n'
        except:  # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            return InternalServerError()
        else:
            # got a valid XML RPC response
            return Response(response, mimetype='text/xml')

    def __call__(self, environ, start_response):
        return self.handler(environ, start_response)
Beispiel #53
0
    def __init__(self, hostname='', port=5370, threadcount=1):

        # Satisfy base classes.
        # =====================
        addr = (hostname, port)
        SimpleXMLRPCDispatcher.__init__(self)
        SocketServer.TCPServer.__init__(self, addr, SimpleXMLRPCRequestHandler)

        # Set up signal handling.
        # =======================
        self.DIE = threading.Event()
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)

        # Set up threading.
        # =================
        self.SHUTDOWN = object()
        self.threads = {}
        self.queue = Queue.Queue()
        self.fill_thread_pool(threadcount)
Beispiel #54
0
    def system_methodHelp(self, method_name):
        """
        Gets documentation for the specified method.

        :type method_name: string

        :returns: 'help text'
        :rtype: string

        """

        return SimpleXMLRPCDispatcher.system_methodHelp(self, method_name)
Beispiel #55
0
 def _dispatch(self, method, params):
     """
     Custom _dispatch so we can log exceptions and the time taken to
     execute each method.
     """
     start = datetime.utcnow()
     try:
         result = SimpleXMLRPCDispatcher._dispatch(self, method, params)
     except:
         logger.exception('Error handling XML-RPC call %s', str(method))
         logger.debug('Time: %s %s %s', datetime.utcnow() - start, str(method), str(params)[0:50])
         raise
     logger.debug('Time: %s %s %s', datetime.utcnow() - start, str(method), str(params)[0:50])
     return result
Beispiel #56
0
 def __init__(self):
     SimpleXMLRPCDispatcher.__init__(self, True, 'utf-8')
     self.register_function(list_packages)
     self.register_function(package_releases)
     self.register_function(release_urls)
     self.register_function(release_urls, name='package_urls') # Deprecated
     self.register_function(release_data)
     self.register_function(release_data, name='package_data') # Deprecated
     self.register_function(search)
     self.register_function(browse)
     self.register_function(updated_releases)
     self.register_function(changelog)
     self.register_function(changelog_last_serial)
     self.register_function(changelog_since_serial)
     self.register_function(changed_packages)
     self.register_function(post_cheesecake_for_release)
     self.register_function(release_downloads)
     self.register_function(package_roles)
     self.register_function(user_packages)
     self.register_function(package_hosting_mode)
     self.register_function(top_packages)
     self.register_function(list_packages_with_serial)
     self.register_introspection_functions()
     self.register_multicall_functions()
Beispiel #57
0
    def __init__(self,
                 server_address,
                 keyfile,
                 certfile,
                 ssl_version=ssl.PROTOCOL_TLSv1,
                 requestHandler=SimpleXMLRPCRequestHandler,
                 logRequests=True,
                 allow_none=False,
                 encoding=None,
                 bind_and_activate=True):
        self.logRequests = logRequests

        self.keyfile = keyfile
        self.certfile = certfile
        self.ssl_version = ssl_version

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        TCPServer.__init__(self, server_address, requestHandler,
                           bind_and_activate)

        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)
Beispiel #58
0
 def _dispatch(self, method, auth, response_method, params):
     params = (self.auth, response_method, params)
     SimpleXMLRPCDispatcher._dispatch(self, method, params)
Beispiel #59
0
 def __init__(self):
     if sys.version[0:3] == '2.4':
         SimpleXMLRPCDispatcher.__init__(self)
     else:
         SimpleXMLRPCDispatcher.__init__(self, False, None)
     self.authMethod = None