Ejemplo n.º 1
0
    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)

        class VerifyingRequestHandler(SimpleXMLRPCRequestHandler):
            # this is the method we must override
            def parse_request(self):
                # first, call the original implementation which returns
                # True if all OK so far
                if SimpleXMLRPCRequestHandler.parse_request(self):
                    return True
                return False
        
        #    Override the normal socket methods with an SSL socket
        socketserver.BaseServer.__init__(self, addr, VerifyingRequestHandler)
        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,
            )
        if bind_and_activate:
            self.server_bind()
            self.server_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)
Ejemplo n.º 2
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 }
Ejemplo n.º 3
0
    def __init__(self, dispatch_method, encoding=None):
        """
        Sets up the servlet
        """
        SimpleXMLRPCDispatcher.__init__(self, allow_none=True,
                                        encoding=encoding)

        # Register the system.* functions
        self.register_introspection_functions()

        # Make a link to the dispatch method
        self._dispatch_method = dispatch_method
Ejemplo n.º 4
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 }
Ejemplo n.º 5
0
    def __init__(self, dispatch_method, encoding=None):
        """
        Sets up the servlet
        """
        SimpleXMLRPCDispatcher.__init__(self, allow_none=True,
                                        encoding=encoding)

        # Register the system.* functions
        self.register_introspection_functions()

        # Make a link to the dispatch method
        self._dispatch_method = dispatch_method
Ejemplo n.º 6
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()
Ejemplo n.º 7
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 xmlrpc_client.dumps(obj, *args, **kwargs)

        self.dumps = _dumps

        # map of name => (auth, func)
        self.func_map = {}
Ejemplo n.º 8
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()
Ejemplo n.º 9
0
    def __init__(self,
                 addr,
                 requestHandler=SimpleXMLRPCRequestHandler,
                 logRequests=True,
                 allow_none=False,
                 encoding=None,
                 bind_and_activate=True,
                 use_builtin_types=False):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding,
                                        use_builtin_types)
        socketserver.ThreadingTCPServer.__init__(self, addr, requestHandler,
                                                 bind_and_activate)
Ejemplo n.º 10
0
	def init_server(self,host,port):
		
		dprint("Starting N4D ...")
		self.core=n4d.server.core.Core.get_core(DEBUG)
		self.server_host=host
		self.server_port=port
		self.handler=N4dServer.N4dCallHandler
		self.handler.encode_threshold=None
		self.server=N4dServer.ThreadedXMLRPCServer((host,port),self.handler,DEBUG)
		#allow_none
		SimpleXMLRPCDispatcher.__init__(self.server,allow_none=True)
		
		self.wrap_ssl()
		self.server.register_instance(self.core)
Ejemplo n.º 11
0
 def __init__(self, instance=None, methods=None, **kwargs):
     """
     创建xmlrpc dispatcher
     """
     if methods is 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()
     self.logger = kwargs.get('logger', logging.getLogger(__name__))
Ejemplo n.º 12
0
 def __init__(self, instance=None, methods=None):
     """Create windmill xmlrpc dispatcher"""
     if methods is None:
         methods = []
     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()
Ejemplo n.º 13
0
 def _dispatch(self, method, params):
     logger.info("Recv XMLRPC call: path=%s, method=%s, params=%s", getattr(self, "_path", None), method, params)
     try:
         return SimpleXMLRPCDispatcher._dispatch(self, method, params)
     except:
         logger.exception("")
         raise
Ejemplo n.º 14
0
    def init_secondary_server(self, host, port, ssl_wrapped=False):

        self.secondary_server_host = host
        self.secondary_server_port = port
        self.secondary_handler = N4dServer.N4dCallHandler
        self.is_secondary_server_secured = ssl_wrapped
        self.handler.encode_threshold = None
        self.secondary_server = N4dServer.ThreadedXMLRPCServer(
            (host, port), self.secondary_handler, DEBUG)
        SimpleXMLRPCDispatcher.__init__(self.secondary_server, allow_none=True)

        if ssl_wrapped:
            self.secondary_server.socket = ssl.wrap_socket(
                self.secondary_server.socket, N4dServer.N4D_KEYFILE,
                N4dServer.N4D_CERTFILE)

        self.secondary_server.register_instance(self.core)
Ejemplo n.º 15
0
 def _dispatch(self, method, params):
     logger.info("Recv XMLRPC call: path=%s, method=%s, params=%s",
                 getattr(self, "_path", None), method, params)
     try:
         return SimpleXMLRPCDispatcher._dispatch(self, method, params)
     except:
         logger.exception("")
         raise
Ejemplo n.º 16
0
        def __init__(self,
                     addr,
                     ca_file,
                     cert_key_file,
                     requestHandler=XMLRPCRequestHandler,
                     logRequests=True,
                     allow_none=False,
                     encoding=None,
                     bind_and_activate=True,
                     crl_file_url=None):
            """Overriding __init__ method of the SimpleXMLRPCServer

            The method is a copy, except for the TCPServer __init__
            call, which is rewritten using TLS, and the certfile argument
            which is required for TLS
            """
            import socketserver

            self.logRequests = logRequests
            self.crl_file_url = crl_file_url
            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
            socketserver.BaseServer.__init__(self, addr, requestHandler)
            self.socket = ssl.wrap_socket(socket.socket(
                self.address_family, self.socket_type),
                                          server_side=True,
                                          certfile=cert_key_file,
                                          ca_certs=ca_file,
                                          cert_reqs=ssl.CERT_REQUIRED,
                                          ssl_version=PROTOCOL)
            if bind_and_activate:
                self.server_bind()
                self.server_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.
            try:
                import fcntl
            except ImportError:
                pass
            else:
                if hasattr(fcntl, 'FD_CLOEXEC'):
                    flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
                    flags |= fcntl.FD_CLOEXEC
                    fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
Ejemplo n.º 17
0
    def __init__(self, section=None, configfile=None):
        super(XmlRpcBot, self).__init__(section, configfile)
        self.cfg['authorized_users'] = None

        allow_none = False
        encoding = None
        # SimpleXMLRPCDispatcher is still an "old-style" class,
        # so super doesn't work right
        #
        # further ick, this is an 'internal' class so signature changed
        # between python2.4 and python2.5
        if sys.version_info[0] == 2 and sys.version_info[1] > 4:
            # python 2.5 version
            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        else:
            # python 2.3, 2.4 version
            SimpleXMLRPCDispatcher.__init__(self)
        self.authorized_users = None
Ejemplo n.º 18
0
    def __init__(self, section=None, configfile=None):
        super(XmlRpcBot, self).__init__(section, configfile)
        self.cfg['authorized_users'] = None

        allow_none = False
        encoding = None
        # SimpleXMLRPCDispatcher is still an "old-style" class,
        # so super doesn't work right
        #
        # further ick, this is an 'internal' class so signature changed
        # between python2.4 and python2.5
        if sys.version_info[0] == 2 and sys.version_info[1] > 4:
            # python 2.5 version
            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        else:
            # python 2.3, 2.4 version
            SimpleXMLRPCDispatcher.__init__(self)
        self.authorized_users = None
Ejemplo n.º 19
0
    def __init__(self, addr, certfile, keyfile=None,
                 requestHandler=SimpleXMLRPCRequestHandler,
                 logRequests=True, allow_none=False, encoding=None,
                 bind_and_activate=True, ssl_version=ssl.PROTOCOL_TLSv1):
        self.logRequests = logRequests

        # create an SSL context
        self.context = ssl.SSLContext(ssl_version)
        self.context.load_cert_chain(certfile=certfile, keyfile=keyfile)

        SimpleXMLRPCDispatcher.__init__(self, allow_none,
                                        encoding)
        # call TCPServer constructor
        socketserver.TCPServer.__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)
Ejemplo n.º 20
0
def handler(app, request):
    '''Wrap an invocation of the XML-RPC dispatcher.
    '''
    # unicode strings will be encoded in utf-8 by xmlrpclib
    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
    # RJ: disabled this as it's a giant, unreliable hack that doesn't work and
    # I can't even remember why it's in here to start with
    # response = re.sub('([\x00-\x08]|[\x0b-\x0c]|[\x0e-\x1f])+', '', response)

    return Response(response, mimetype="text/xml; charset=utf-8")
Ejemplo n.º 21
0
def handle_request(app, request):
    '''Wrap an invocation of the XML-RPC dispatcher.
    '''
    # unicode strings will be encoded in utf-8 by xmlrpclib
    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
    # RJ: disabled this as it's a giant, unreliable hack that doesn't work and
    # I can't even remember why it's in here to start with
    # response = re.sub('([\x00-\x08]|[\x0b-\x0c]|[\x0e-\x1f])+', '', response)

    return Response(response, mimetype="text/xml; charset=utf-8")
Ejemplo n.º 22
0
        def __init__(self, addr, ca_file, cert_key_file,
            requestHandler=XMLRPCRequestHandler, logRequests=True,
            allow_none=False, encoding=None, bind_and_activate=True, 
            crl_file_url=None):
            """Overriding __init__ method of the SimpleXMLRPCServer

            The method is a copy, except for the TCPServer __init__
            call, which is rewritten using TLS, and the certfile argument
            which is required for TLS
            """
            import socketserver

            self.logRequests = logRequests
            self.crl_file_url =  crl_file_url
            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
            socketserver.BaseServer.__init__(self, addr, requestHandler)
            self.socket = ssl.wrap_socket(
                socket.socket(self.address_family, self.socket_type),
                server_side=True,
                certfile=cert_key_file,
                ca_certs=ca_file,
                cert_reqs=ssl.CERT_REQUIRED,
                ssl_version=PROTOCOL)
            if bind_and_activate:
                self.server_bind()
                self.server_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.
            try:
                import fcntl
            except ImportError:
                pass
            else:
                if hasattr(fcntl, 'FD_CLOEXEC'):
                    flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
                    flags |= fcntl.FD_CLOEXEC
                    fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
Ejemplo n.º 23
0
class WSGIXMLRPCApplication(object):
    """
    基于WSGI的XMLRPC应用
    """
    def __init__(self, instance=None, methods=None, **kwargs):
        """
        创建xmlrpc dispatcher
        """
        if methods is 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()
        self.logger = kwargs.get('logger', logging.getLogger(__name__))

    def register_instance(self, instance):
        return self.dispatcher.register_instance(instance)

    def register_function(self, function, name=None):
        return self.dispatcher.register_function(function, name)

    def handler(self, environ, start_response):
        """
        处理HTTP访问
        """

        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):
        """
        处理HTTP POST请求
        """

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

            response = self.dispatcher._marshaled_dispatch(
                data, getattr(self.dispatcher, '_dispatch', None))
            response += b'\n'
        except Exception as e:
            self.logger.exception(e)
            start_response("500 Server error",
                           [('Content-Type', 'text/plain')])
            return []
        else:
            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)
Ejemplo n.º 24
0
 def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
     setattr(self, "_path", path)
     return SimpleXMLRPCDispatcher._marshaled_dispatch(
         self, data, dispatch_method, path)
Ejemplo n.º 25
0
    def __init__(self,
                 ip,
                 port,
                 keyFile=DEFAULTKEYFILE,
                 certFile=DEFAULTCERTFILE,
                 logRequests=True):
        self.logRequests = logRequests

        class VerifyingRequestHandler(SimpleXMLRPCRequestHandler):
            def setup(myself):
                myself.connection = myself.request
                myself.rfile = socket.socket.makefile(myself.request, "rb",
                                                      myself.rbufsize)
                myself.wfile = socket.socket.makefile(myself.request, "wb",
                                                      myself.wbufsize)

            def address_string(myself):
                "getting 'FQDN' from host seems to stall on some ip addresses, so... just (quickly!) return raw host address"
                host, port = myself.client_address
                #return socket.getfqdn(host)
                return host

            def do_POST(myself):
                """Handles the HTTPS POST request.
                It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
                """
                try:
                    # get arguments
                    data = myself.rfile.read(
                        int(myself.headers["content-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 dispatch
                    # using that method if present.
                    response = myself.server._marshaled_dispatch(
                        data, getattr(myself, '_dispatch', None))
                except Exception as info:  # This should only happen if the module is buggy
                    print("ERROR do_POST: ", info)
                    print("Traceback follows:", traceback.print_exc())

                    # internal error, report as HTTP server error
                    myself.send_response(500)
                    myself.end_headers()
                else:
                    # got a valid XML RPC response
                    myself.send_response(200)
                    myself.send_header("Content-type", "text/xml")
                    myself.send_header("Content-length", str(len(response)))
                    myself.end_headers()
                    myself.wfile.write(response)

                    # shut down the connection
                    myself.wfile.flush()
                    myself.connection.shutdown()  # Modified here!

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

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

                response = myself.server.generate_html_documentation()
                myself.send_response(200)
                myself.send_header("Content-type", "text/html")
                myself.send_header("Content-length", str(len(response)))
                myself.end_headers()
                myself.wfile.write(response)

                # shut down the connection
                myself.wfile.flush()
                myself.connection.shutdown()  # Modified here!

            def report_404(myself):
                # Report a 404 error
                myself.send_response(404)
                response = 'No such page'
                myself.send_header("Content-type", "text/plain")
                myself.send_header("Content-length", str(len(response)))
                myself.end_headers()
                myself.wfile.write(response)
                # shut down the connection
                myself.wfile.flush()
                myself.connection.shutdown()  # Modified here!

            def parse_request(myself):
                if SimpleXMLRPCRequestHandler.parse_request(myself):
                    basic, foo, encoded = myself.headers.get(
                        'Authorization').partition(' ')
                    username, foo, password = b64decode(encoded).decode(
                        'UTF-8').partition(':')
                    if username == 'admin':
                        return True
                    else:
                        myself.send_error(401, 'Authentication failed')
                        return False

        SimpleXMLRPCDispatcher.__init__(self, False, None)
        BaseServer.__init__(self, (ip, port), VerifyingRequestHandler)

        # SSL socket stuff
        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()

        self.funcs = {}
        self.register_introspection_functions()
        self.register_instance(Services())

        # requests count and condition, to allow for keyboard quit via CTL-C
        self.requests = 0
        self.rCondition = Condition()
Ejemplo n.º 26
0
        import dbfunctions as dbfn
        d = dbfn.TaskEntry(entry.pk)
        d_list = d.get_decoders_trained_in_block()
        for d in d_list:
            print(d.pk, d.name)
    print("Saved decoder to %s" % os.path.join(base, pklname))


def hide_task_entry(entry, dbname='default'):
    te = TaskEntry.objects.using(dbname).get(id=entry)
    te.visible = False
    te.save()


#############################################################################
##### Register functions for remote procedure call from other processes #####
#############################################################################
dispatcher = SimpleXMLRPCDispatcher(allow_none=True)
dispatcher.register_function(save_log, 'save_log')
dispatcher.register_function(save_calibration, 'save_cal')
dispatcher.register_function(save_data, 'save_data')
dispatcher.register_function(save_bmi, 'save_bmi')
dispatcher.register_function(hide_task_entry, 'hide_task_entry')


@csrf_exempt
def rpc_handler(request):
    response = HttpResponse(content_type="application/xml")
    response.write(dispatcher._marshaled_dispatch(request.body))
    return response
    def __init__(self,addr,useSSL=False,logRequests=False,
                 allow_none=False, encoding=None):
        """:param addr: the (server address,port)-tuple)
        :param logRequests: patched thru to the base class"""
        certfile=config().get("Network","personalSSLCertificate")
        keyfile=config().get("Network","privateSSLKey")
        self.useSSL=useSSL
        if self.useSSL and not path.exists(certfile):
            warning("No certficate file",certfile,
                    "exists. Therefor no SSL-connection for the FoamServer possible\n",
                    "To generate a private key:\n",
                    ("   openssl genrsa -out %s 2048" % keyfile),
                    "\nThen generate the cerificate that is valid for 3 years with \n",
                    ("   openssl req -new -x509 -key %s -out %s -days 1095" % (keyfile,certfile)))
            self.useSSL=False
        self.authOK=True

        if self.useSSL:
            try:
                import ssl
                if PY3:
                    import socketserver
                else:
                    import SocketServer as socketserver
                import socket
            except ImportError:
                warning("Problem with the imports. Dropping SSL-support")
                self.useSSL=False

        if self.useSSL:
            self.logRequests = logRequests

            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)

            class VerifyingRequestHandler(SimpleXMLRPCRequestHandler):
                '''
                Request Handler that verifies username and security token to
                XML RPC server in HTTP URL sent by client.
                '''
                # this is the method we must override
                def parse_request(self):
                    # first, call the original implementation which returns
                    # True if all OK so far

                    if SimpleXMLRPCRequestHandler.parse_request(self):
                        # next we authenticate
                        if self.authenticate(self.headers):
                            return True
                        else:
                            # if authentication fails, tell the client
                            self.send_error(401, 'Authentication failed')
                    return False

                def authenticate(self, headers):
                    from base64 import b64decode
                    #    Confirm that Authorization header is set to Basic
                    authHeader=headers.get('Authorization')
                    if authHeader is None:
                        return True
                    (basic, _, encoded) = authHeader.partition(' ')
                    assert basic == 'Basic', 'Only basic authentication supported'
                    #    Encoded portion of the header is a string
                    #    Need to convert to bytestring
                    encodedByteString = encoded.encode()
                    #    Decode Base64 byte String to a decoded Byte String
                    decodedBytes = b64decode(encodedByteString)
                    #    Convert from byte string to a regular String
                    decodedString = decodedBytes.decode()
                    #    Get the username and password from the string
                    (username, _, password) = decodedString.partition(':')
                    #    Check that username and password match internal global dictionary
                    self.server.authOK=auth.checkAuthentication(username,password)
                    return True
            #    Override the normal socket methods with an SSL socket
            socketserver.BaseServer.__init__(self, addr, VerifyingRequestHandler)
            try:
                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()
            except socket.error as e:
                warning("Socket error",e)
                raise e
        else:
            SimpleXMLRPCServer.__init__(self,addr,logRequests=logRequests)
Ejemplo n.º 28
0
if sys.version_info >= (3, 0):
    from urllib.parse import urljoin
else:
    from urlparse import urljoin

from bottle import static_file, redirect, request, HTTPError, Bottle, response
from pypiserver import __version__
from pypiserver.core import listdir, find_packages, store, get_prefixes, exists

if sys.version_info[0] > 2:
    from xmlrpc.server import SimpleXMLRPCDispatcher
else:
    from SimpleXMLRPCServer import SimpleXMLRPCDispatcher

dispatcher = SimpleXMLRPCDispatcher(True, 'utf-8')

packages = None


class configuration(object):
    def __init__(self):
        self.fallback_url = "http://pypi.python.org/simple"
        self.redirect_to_fallback = True
        self.htpasswdfile = None

config = configuration()


def validate_user(username, password):
    if config.htpasswdfile is not None:
Ejemplo n.º 29
0
    def __init__(self, addr, requestHandler = SimpleXMLRPCRequestHandler,
                 logRequests = True, allow_none = False, encoding = None, bind_and_activate = True):
        """Overriding __init__ method of the SimpleXMLRPCServer

        The method is an exact copy, except the TCPServer __init__
        call, which is rewritten using TLS
        """
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)

        """This is the modified part. Original code was:

            socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        which executed:

            def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
                BaseServer.__init__(self, server_address, RequestHandlerClass)
                self.socket = socket.socket(self.address_family,
                                            self.socket_type)
                if bind_and_activate:
                    self.server_bind()
                    self.server_activate()

        """
        class VerifyingRequestHandler(SimpleXMLRPCRequestHandler):
            '''
            Request Handler that verifies username and password passed to
            XML RPC server in HTTP URL sent by client.
            '''
            # this is the method we must override
            def parse_request(self):
                # first, call the original implementation which returns
                # True if all OK so far
                if SimpleXMLRPCRequestHandler.parse_request(self):
                    # next we authenticate
                    if self.authenticate(self.headers):
                        return True
                    else:
                        # if authentication fails, tell the client
                        self.send_error(401, 'Authentication failed')
                return False
           
            def authenticate(self, headers):
                from base64 import b64decode
                #    Confirm that Authorization header is set to Basic
                (basic, _, encoded) = headers.get('Authorization').partition(' ')
                assert basic == 'Basic', 'Only basic authentication supported'
               
                #    Encoded portion of the header is a string
                #    Need to convert to bytestring
                encodedByteString = encoded.encode()
                #    Decode Base64 byte String to a decoded Byte String
                decodedBytes = b64decode(encodedByteString)
                #    Convert from byte string to a regular String
                decodedString = decodedBytes.decode()
                #    Get the username and password from the string
                (username, _, password) = decodedString.partition(':')
                #    Check that username and password match internal global dictionary
                if dissomniagLive.getIdentity().authServer(username, password):
                    return True
                else:
                    return False
       
        #    Override the normal socket methods with an SSL socket
        socketserver.BaseServer.__init__(self, addr, VerifyingRequestHandler)
        self.socket = ssl.wrap_socket(
            socket.socket(self.address_family, self.socket_type),
            server_side = True,
            keyfile = dissomniagLive.config.sslPrivateKey,
            certfile = dissomniagLive.config.sslCertFile,
            cert_reqs = ssl.CERT_NONE,
            ssl_version = ssl.PROTOCOL_SSLv23,
            )
        if bind_and_activate:
            self.server_bind()
            self.server_activate()

        """End of modified part"""

        # [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)
Ejemplo n.º 30
0
 def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
     setattr(self, "_path", path)
     return SimpleXMLRPCDispatcher._marshaled_dispatch(self, data, dispatch_method, path)
Ejemplo n.º 31
0
    def __init__(self,
                 addr,
                 useSSL=False,
                 logRequests=False,
                 allow_none=False,
                 encoding=None):
        """:param addr: the (server address,port)-tuple)
        :param logRequests: patched thru to the base class"""
        certfile = config().get("Network", "personalSSLCertificate")
        keyfile = config().get("Network", "privateSSLKey")
        self.useSSL = useSSL
        if self.useSSL and not path.exists(certfile):
            warning(
                "No certficate file", certfile,
                "exists. Therefor no SSL-connection for the FoamServer possible\n",
                "To generate a private key:\n",
                ("   openssl genrsa -out %s 2048" % keyfile),
                "\nThen generate the cerificate that is valid for 3 years with \n",
                ("   openssl req -new -x509 -key %s -out %s -days 1095" %
                 (keyfile, certfile)))
            self.useSSL = False
        self.authOK = True

        if self.useSSL:
            try:
                import ssl
                if PY3:
                    import socketserver
                else:
                    import SocketServer as socketserver
                import socket
            except ImportError:
                warning("Problem with the imports. Dropping SSL-support")
                self.useSSL = False

        if self.useSSL:
            self.logRequests = logRequests

            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)

            class VerifyingRequestHandler(SimpleXMLRPCRequestHandler):
                '''
                Request Handler that verifies username and security token to
                XML RPC server in HTTP URL sent by client.
                '''

                # this is the method we must override
                def parse_request(self):
                    # first, call the original implementation which returns
                    # True if all OK so far

                    if SimpleXMLRPCRequestHandler.parse_request(self):
                        # next we authenticate
                        if self.authenticate(self.headers):
                            return True
                        else:
                            # if authentication fails, tell the client
                            self.send_error(401, 'Authentication failed')
                    return False

                def authenticate(self, headers):
                    from base64 import b64decode
                    #    Confirm that Authorization header is set to Basic
                    authHeader = headers.get('Authorization')
                    if authHeader is None:
                        return True
                    (basic, _, encoded) = authHeader.partition(' ')
                    assert basic == 'Basic', 'Only basic authentication supported'
                    #    Encoded portion of the header is a string
                    #    Need to convert to bytestring
                    encodedByteString = encoded.encode()
                    #    Decode Base64 byte String to a decoded Byte String
                    decodedBytes = b64decode(encodedByteString)
                    #    Convert from byte string to a regular String
                    decodedString = decodedBytes.decode()
                    #    Get the username and password from the string
                    (username, _, password) = decodedString.partition(':')
                    #    Check that username and password match internal global dictionary
                    self.server.authOK = auth.checkAuthentication(
                        username, password)
                    return True

            #    Override the normal socket methods with an SSL socket
            socketserver.BaseServer.__init__(self, addr,
                                             VerifyingRequestHandler)
            try:
                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()
            except socket.error as e:
                warning("Socket error", e)
                raise e
        else:
            SimpleXMLRPCServer.__init__(self, addr, logRequests=logRequests)
Ejemplo n.º 32
0
    def __init__(self,
                 addr,
                 requestHandler=SimpleXMLRPCRequestHandler,
                 logRequests=True,
                 allow_none=False,
                 encoding=None,
                 bind_and_activate=True):
        """Overriding __init__ method of the SimpleXMLRPCServer

        The method is an exact copy, except the TCPServer __init__
        call, which is rewritten using TLS
        """
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        """This is the modified part. Original code was:

            socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        which executed:

            def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
                BaseServer.__init__(self, server_address, RequestHandlerClass)
                self.socket = socket.socket(self.address_family,
                                            self.socket_type)
                if bind_and_activate:
                    self.server_bind()
                    self.server_activate()

        """
        class VerifyingRequestHandler(SimpleXMLRPCRequestHandler):
            '''
            Request Handler that verifies username and password passed to
            XML RPC server in HTTP URL sent by client.
            '''

            # this is the method we must override
            def parse_request(self):
                # first, call the original implementation which returns
                # True if all OK so far
                if SimpleXMLRPCRequestHandler.parse_request(self):
                    # next we authenticate
                    if self.authenticate(self.headers):
                        return True
                    else:
                        # if authentication fails, tell the client
                        self.send_error(401, 'Authentication failed')
                return False

            def authenticate(self, headers):
                from base64 import b64decode
                #    Confirm that Authorization header is set to Basic
                (basic, _,
                 encoded) = headers.get('Authorization').partition(' ')
                assert basic == 'Basic', 'Only basic authentication supported'

                #    Encoded portion of the header is a string
                #    Need to convert to bytestring
                encodedByteString = encoded.encode()
                #    Decode Base64 byte String to a decoded Byte String
                decodedBytes = b64decode(encodedByteString)
                #    Convert from byte string to a regular String
                decodedString = decodedBytes.decode()
                #    Get the username and password from the string
                (username, _, password) = decodedString.partition(':')
                #    Check that username and password match internal global dictionary
                if dissomniagLive.getIdentity().authServer(username, password):
                    return True
                else:
                    return False

        #    Override the normal socket methods with an SSL socket
        socketserver.BaseServer.__init__(self, addr, VerifyingRequestHandler)
        self.socket = ssl.wrap_socket(
            socket.socket(self.address_family, self.socket_type),
            server_side=True,
            keyfile=dissomniagLive.config.sslPrivateKey,
            certfile=dissomniagLive.config.sslCertFile,
            cert_reqs=ssl.CERT_NONE,
            ssl_version=ssl.PROTOCOL_SSLv23,
        )
        if bind_and_activate:
            self.server_bind()
            self.server_activate()
        """End of modified part"""

        # [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)
Ejemplo n.º 33
0
class WSGIXMLRPCApplication(object):
    """Application to handle requests to the XMLRPC service"""
    def __init__(self, instance=None, methods=None):
        """Create windmill xmlrpc dispatcher"""
        if methods is None:
            methods = []
        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()

    def register_instance(self, instance):
        return self.dispatcher.register_instance(instance)

    def register_function(self, function, name=None):
        return self.dispatcher.register_function(function, name)

    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
            # socket.read(); around the 10 or 15Mb mark, some platforms
            # begin to have problems (bug #792570).

            length = int(environ['CONTENT_LENGTH'])
            data = environ['wsgi.input'].read(length)
            print('-------wsgi----data')
            print(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 += b'\n'
        except Exception as e:  # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            print(e)
            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):
        print(environ)
        return self.handler(environ, start_response)
Ejemplo n.º 34
0
            self.s.shutdown(socket.SHUT_RDWR)
            self.s.close()
        except:
            pass
        self.s = None

    def spawn(self):
        t = threading.Thread(target=self.connect_thread)
        t.daemon = True
        t.start()
        t = threading.Thread(target=self.emit_thread)
        t.daemon = True
        t.start()


def test_stuff_add(a, b):
    return a + b


server = SimpleXMLRPCDispatcher(allow_none=True)
# register_module(idc)
server.register_function(wrap(test_stuff_add), 'test_stuff_add')
server.register_introspection_functions()

conn = ReverseConn('/tmp/talon_editor_socket')
conn.spawn()

# time.sleep(2)
# conn.emit("test", {'a':"lol hi", 'b':5})
# time.sleep(2)
    def __init__(self, ip, port, keyFile=DEFAULTKEYFILE, certFile=DEFAULTCERTFILE, logRequests=True):
        self.logRequests = logRequests
        class VerifyingRequestHandler(SimpleXMLRPCRequestHandler):

            def setup(myself):
                myself.connection = myself.request
                myself.rfile = socket.socket.makefile(myself.request, "rb", myself.rbufsize)
                myself.wfile = socket.socket.makefile(myself.request, "wb", myself.wbufsize)

            def address_string(myself):
                "getting 'FQDN' from host seems to stall on some ip addresses, so... just (quickly!) return raw host address"
                host, port = myself.client_address
                #return socket.getfqdn(host)
                return host

            def do_POST(myself):
                """Handles the HTTPS POST request.
                It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
                """
                try:
                    # get arguments
                    data = myself.rfile.read(int(myself.headers["content-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 dispatch
                    # using that method if present.
                    response = myself.server._marshaled_dispatch(data, getattr(myself, '_dispatch', None))
                except Exception as info: # This should only happen if the module is buggy
                    print ("ERROR do_POST: ", info)
                    print ("Traceback follows:", traceback.print_exc())

                    # internal error, report as HTTP server error
                    myself.send_response(500)
                    myself.end_headers()
                else:
                    # got a valid XML RPC response
                    myself.send_response(200)
                    myself.send_header("Content-type", "text/xml")
                    myself.send_header("Content-length", str(len(response)))
                    myself.end_headers()
                    myself.wfile.write(response)

                    # shut down the connection
                    myself.wfile.flush()
                    myself.connection.shutdown() # Modified here!

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

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

                response = myself.server.generate_html_documentation()
                myself.send_response(200)
                myself.send_header("Content-type", "text/html")
                myself.send_header("Content-length", str(len(response)))
                myself.end_headers()
                myself.wfile.write(response)

                # shut down the connection
                myself.wfile.flush()
                myself.connection.shutdown() # Modified here!

            def report_404(myself):
                # Report a 404 error
                myself.send_response(404)
                response = 'No such page'
                myself.send_header("Content-type", "text/plain")
                myself.send_header("Content-length", str(len(response)))
                myself.end_headers()
                myself.wfile.write(response)
                # shut down the connection
                myself.wfile.flush()
                myself.connection.shutdown() # Modified here!

            def parse_request(myself):
                if SimpleXMLRPCRequestHandler.parse_request(myself):
                    basic, foo, encoded = myself.headers.get('Authorization').partition(' ')
                    username, foo, password = b64decode(encoded).decode('UTF-8').partition(':')
                    if username == 'admin':
                        return True
                    else:
                        myself.send_error(401, 'Authentication failed')
                        return False
        SimpleXMLRPCDispatcher.__init__(self, False, None)
        BaseServer.__init__(self, (ip, port), VerifyingRequestHandler)

        # SSL socket stuff
        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()

        self.funcs = {}
        self.register_introspection_functions()
        self.register_instance(Services())

        # requests count and condition, to allow for keyboard quit via CTL-C
        self.requests = 0
        self.rCondition = Condition()
Ejemplo n.º 36
0
def metaweblog(request):
    request_log.info("目标请求:{0}".format(request.body))

    dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding="UTF-8")
    dispatcher.register_introspection_functions()
    dispatcher.register_function(Api().getUsersBlogs, 'blogger.getUsersBlogs')
    dispatcher.register_function(Api().getCategories, 'metaWeblog.getCategories')
    dispatcher.register_function(Api().getRecentPosts, 'metaWeblog.getRecentPosts')
    dispatcher.register_function(Api().getPost, 'metaWeblog.getPost')
    dispatcher.register_function(Api().newPost, 'metaWeblog.newPost')
    dispatcher.register_function(Api().newMediaObject, 'metaWeblog.newMediaObject')
    dispatcher.register_function(Api().editPost, 'metaWeblog.editPost')
    dispatcher.register_function(Api().deletePost, 'metaWeblog.deletePost')

    response = dispatcher._marshaled_dispatch(request.body)
    request_log.info("响应目标:{0}".format(response))
    return HttpResponse(response)

    # def wlwmanifest(req):
    #     return render_to_response('wlwmanifest.xml')
Ejemplo n.º 37
0
from flask import Blueprint, request, Response
from xmlrpc.server import SimpleXMLRPCDispatcher
from adif import parse as adif_parser

bp_extapi = Blueprint("bp_extapi", __name__)

handler = SimpleXMLRPCDispatcher(allow_none=True, encoding=None)
"""
Register the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature.
"""
handler.register_introspection_functions()
"""
<value>log.add_record</value>       log.add_record ADIF RECORD
<value>log.check_dup</value>        log.check_dup CALL, MODE(0), TIME_SPAN (0), FREQ_HZ(0), STATE(0), XCHG_IN(0)
<value>log.get_record</value>       log.get_record CALL
"""


def add_record(adif_record):
    print("Log.add_record")
    # FLDIGI send only a record, add fake end-of-header to not break parser
    parsed = adif_parser(b"<eoh>" + adif_record.encode("UTF-8"))
    if len(parsed) >= 1:
        parsed = parsed[0]
    """
    freq in MHz, time_off HHMMSS, qso_date YYYYMMDD, qso_date_off time_on same
    {'freq': '14.070997', 'mode': 'PSK31', 'time_off': '152417', 'qso_date': '20160824',
    'call': 'F4TEST', 'qso_date_off': '20160824', 'time_on': '1503'}
    """
    return "xxx"
Ejemplo n.º 38
0
def metaweblog(request):
    # request_log.info("目标请求:{0}".format(request.body))

    dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding="UTF-8")
    dispatcher.register_introspection_functions()
    dispatcher.register_function(Api().getUsersBlogs, 'blogger.getUsersBlogs')
    dispatcher.register_function(Api().getCategories,
                                 'metaWeblog.getCategories')
    dispatcher.register_function(Api().getRecentPosts,
                                 'metaWeblog.getRecentPosts')
    dispatcher.register_function(Api().getPost, 'metaWeblog.getPost')
    dispatcher.register_function(Api().newPost, 'metaWeblog.newPost')
    dispatcher.register_function(Api().newMediaObject,
                                 'metaWeblog.newMediaObject')
    dispatcher.register_function(Api().editPost, 'metaWeblog.editPost')
    dispatcher.register_function(Api().deletePost, 'metaWeblog.deletePost')

    response = dispatcher._marshaled_dispatch(request.body)
    # request_log.info("响应目标:{0}".format(response))
    return HttpResponse(response)