示例#1
0
文件: server.py 项目: doadin/deluge
    def __init__(self, options=None, daemon=True):
        """
        Setup the DelugeWeb server.

        Args:
            options (argparse.Namespace): The web server options.
            daemon (bool): If True run web server as a separate daemon process (starts a twisted
                reactor). If False shares the process and twisted reactor from WebUI plugin or tests.

        """
        component.Component.__init__(self, 'DelugeWeb', depend=['Web'])
        self.config = configmanager.ConfigManager(
            'web.conf', defaults=CONFIG_DEFAULTS, file_version=2
        )
        self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2)
        self.config.register_set_function('language', self._on_language_changed)
        self.socket = None
        self.top_level = TopLevel()

        self.interface = self.config['interface']
        self.port = self.config['port']
        self.https = self.config['https']
        self.pkey = self.config['pkey']
        self.cert = self.config['cert']
        self.base = self.config['base']

        if options:
            self.interface = (
                options.interface if options.interface is not None else self.interface
            )
            self.port = options.port if options.port else self.port
            self.base = options.base if options.base else self.base
            if options.ssl:
                self.https = True
            elif options.no_ssl:
                self.https = False

        if self.base != '/':
            # Strip away slashes and serve on the base path as well as root path
            self.top_level.putChild(self.base.strip('/'), self.top_level)

        setup_translation()

        # Remove twisted version number from 'server' http-header for security reasons
        server.version = 'TwistedWeb'
        self.site = server.Site(self.top_level)
        self.web_api = WebApi()
        self.web_utils = WebUtils()

        self.auth = Auth(self.config)
        self.daemon = daemon
        # Initialize the plugins
        self.plugins = PluginManager()
示例#2
0
    def __init__(self):
        super(DelugeWeb, self).__init__("DelugeWeb")
        self.config = configmanager.ConfigManager("web.conf", CONFIG_DEFAULTS)

        # Check to see if a configuration from the web interface prior to 1.2
        # exists and convert it over.
        if os.path.exists(configmanager.get_config_dir("webui06.conf")):
            old_config = configmanager.ConfigManager("webui06.conf")
            if old_config.config:
                # we have an old config file here to handle so we should move
                # all the values across to the new config file, and then remove
                # it.
                for key in OLD_CONFIG_KEYS:
                    if key in old_config:
                        self.config[key] = old_config[key]

                # We need to base64 encode the passwords since json can't handle
                # them otherwise.
                from base64 import encodestring
                self.config["old_pwd_md5"] = encodestring(
                    old_config["pwd_md5"])
                self.config["old_pwd_salt"] = encodestring(
                    old_config["pwd_salt"])

                # Save our config and if it saved successfully then rename the
                # old configuration file.
                if self.config.save():
                    config_dir = os.path.dirname(old_config.config_file)
                    backup_path = os.path.join(config_dir, 'web.conf.old')
                    os.rename(old_config.config_file, backup_path)
                    del old_config

        self.socket = None
        self.top_level = TopLevel()
        self.site = server.Site(self.top_level)
        self.interface = self.config["interface"]
        self.port = self.config["port"]
        self.https = self.config["https"]
        self.pkey = self.config["pkey"]
        self.cert = self.config["cert"]
        self.base = self.config["base"]
        self.web_api = WebApi()
        self.auth = Auth()

        # Initalize the plugins
        self.plugins = PluginManager()
示例#3
0
    def __init__(self, options=None, daemon=True):
        """
        Setup the DelugeWeb server.

        Args:
            options (argparse.Namespace): The web server options.
            daemon (bool): If True run web server as a seperate daemon process (starts a twisted
                reactor). If False shares the process and twisted reactor from WebUI plugin or tests.

        """
        component.Component.__init__(self, 'DelugeWeb', depend=['Web'])
        self.config = configmanager.ConfigManager('web.conf', defaults=CONFIG_DEFAULTS, file_version=2)
        self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2)
        self.config.register_set_function('language', self._on_language_changed)
        self.socket = None
        self.top_level = TopLevel()

        self.interface = self.config['interface']
        self.port = self.config['port']
        self.https = self.config['https']
        self.pkey = self.config['pkey']
        self.cert = self.config['cert']
        self.base = self.config['base']

        if options:
            self.interface = options.interface if options.interface is not None else self.interface
            self.port = options.port if options.port else self.port
            self.base = options.base if options.base else self.base
            if options.ssl:
                self.https = True
            elif options.no_ssl:
                self.https = False

        if self.base != '/':
            # Strip away slashes and serve on the base path as well as root path
            self.top_level.putChild(self.base.strip('/'), self.top_level)

        setup_translations(setup_gettext=True, setup_pygtk=False)

        self.site = server.Site(self.top_level)
        self.web_api = WebApi()
        self.web_utils = WebUtils()

        self.auth = Auth(self.config)
        self.daemon = daemon
        # Initalize the plugins
        self.plugins = PluginManager()
示例#4
0
文件: server.py 项目: laanwj/deluge
    def __init__(self):
        super(DelugeWeb, self).__init__("DelugeWeb")
        self.config = configmanager.ConfigManager("web.conf", CONFIG_DEFAULTS)

        # Check to see if a configuration from the web interface prior to 1.2
        # exists and convert it over.
        if os.path.exists(configmanager.get_config_dir("webui06.conf")):
            old_config = configmanager.ConfigManager("webui06.conf")
            if old_config.config:
                # we have an old config file here to handle so we should move
                # all the values across to the new config file, and then remove
                # it.
                for key in OLD_CONFIG_KEYS:
                    if key in old_config:
                        self.config[key] = old_config[key]

                # We need to base64 encode the passwords since json can't handle
                # them otherwise.
                from base64 import encodestring
                self.config["old_pwd_md5"] = encodestring(old_config["pwd_md5"])
                self.config["old_pwd_salt"] = encodestring(old_config["pwd_salt"])

                # Save our config and if it saved successfully then rename the
                # old configuration file.
                if self.config.save():
                    config_dir = os.path.dirname(old_config.config_file)
                    backup_path = os.path.join(config_dir, 'web.conf.old')
                    os.rename(old_config.config_file, backup_path)
                    del old_config

        self.socket = None
        self.top_level = RootLevel()
        self.site = server.Site(self.top_level)
        self.port = self.config["port"]
        self.interface = self.config["interface"] or "0.0.0.0"
        self.https = self.config["https"]
        self.pkey = self.config["pkey"]
        self.cert = self.config["cert"]
        self.base = self.config["base"]
        self.web_api = WebApi()
        self.auth = Auth()

        # Initalize the plugins
        self.plugins = PluginManager()
示例#5
0
class DelugeWeb(component.Component):
    def __init__(self):
        super(DelugeWeb, self).__init__("DelugeWeb")
        self.config = configmanager.ConfigManager("web.conf", CONFIG_DEFAULTS)

        # Check to see if a configuration from the web interface prior to 1.2
        # exists and convert it over.
        if os.path.exists(configmanager.get_config_dir("webui06.conf")):
            old_config = configmanager.ConfigManager("webui06.conf")
            if old_config.config:
                # we have an old config file here to handle so we should move
                # all the values across to the new config file, and then remove
                # it.
                for key in OLD_CONFIG_KEYS:
                    if key in old_config:
                        self.config[key] = old_config[key]

                # We need to base64 encode the passwords since json can't handle
                # them otherwise.
                from base64 import encodestring
                self.config["old_pwd_md5"] = encodestring(
                    old_config["pwd_md5"])
                self.config["old_pwd_salt"] = encodestring(
                    old_config["pwd_salt"])

                # Save our config and if it saved successfully then rename the
                # old configuration file.
                if self.config.save():
                    config_dir = os.path.dirname(old_config.config_file)
                    backup_path = os.path.join(config_dir, 'web.conf.old')
                    os.rename(old_config.config_file, backup_path)
                    del old_config

        self.socket = None
        self.top_level = TopLevel()
        self.site = server.Site(self.top_level)
        self.port = self.config["port"]
        self.https = self.config["https"]
        self.pkey = self.config["pkey"]
        self.cert = self.config["cert"]
        self.base = self.config["base"]
        self.web_api = WebApi()
        self.auth = Auth()

        # Initalize the plugins
        self.plugins = PluginManager()

    def install_signal_handlers(self):
        # Since twisted assigns itself all the signals may as well make
        # use of it.
        reactor.addSystemEventTrigger("after", "shutdown", self.shutdown)

        # Twisted doesn't handle windows specific signals so we still
        # need to attach to those to handle the close correctly.
        if common.windows_check():
            from win32api import SetConsoleCtrlHandler
            from win32con import CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT

            def win_handler(ctrl_type):
                log.debug("ctrl type: %s", ctrl_type)
                if ctrl_type == CTRL_CLOSE_EVENT or \
                   ctrl_type == CTRL_SHUTDOWN_EVENT:
                    self.shutdown()
                    return 1

            SetConsoleCtrlHandler(win_handler)

    def start(self, start_reactor=True):
        log.info("%s %s.", _("Starting server in PID"), os.getpid())
        if self.https:
            self.start_ssl()
        else:
            self.start_normal()

        component.get("JSON").enable()

        if start_reactor:
            reactor.run()

    def start_normal(self):
        self.socket = reactor.listenTCP(self.port, self.site)
        log.info("serving on %s:%s view at http://127.0.0.1:%s", "0.0.0.0",
                 self.port, self.port)

    def start_ssl(self):
        check_ssl_keys()
        self.socket = reactor.listenSSL(self.port, self.site,
                                        ServerContextFactory())
        log.info("serving on %s:%s view at https://127.0.0.1:%s", "0.0.0.0",
                 self.port, self.port)

    def stop(self):
        log.info("Shutting down webserver")
        component.get("JSON").disable()

        self.plugins.disable_plugins()
        log.debug("Saving configuration file")
        self.config.save()

        if self.socket:
            d = self.socket.stopListening()
            self.socket = None
        else:
            d = defer.Deferred()
            d.callback(False)
        return d

    def shutdown(self, *args):
        self.stop()
        try:
            reactor.stop()
        except error.ReactorNotRunning:
            log.debug("Reactor not running")
示例#6
0
class DelugeWeb(component.Component):

    def __init__(self):
        super(DelugeWeb, self).__init__("DelugeWeb")
        self.config = configmanager.ConfigManager("web.conf", CONFIG_DEFAULTS)

        # Check to see if a configuration from the web interface prior to 1.2
        # exists and convert it over.
        if os.path.exists(configmanager.get_config_dir("webui06.conf")):
            old_config = configmanager.ConfigManager("webui06.conf")
            if old_config.config:
                # we have an old config file here to handle so we should move
                # all the values across to the new config file, and then remove
                # it.
                for key in OLD_CONFIG_KEYS:
                    if key in old_config:
                        self.config[key] = old_config[key]

                # We need to base64 encode the passwords since json can't handle
                # them otherwise.
                from base64 import encodestring
                self.config["old_pwd_md5"] = encodestring(old_config["pwd_md5"])
                self.config["old_pwd_salt"] = encodestring(old_config["pwd_salt"])

                # Save our config and if it saved successfully then rename the
                # old configuration file.
                if self.config.save():
                    config_dir = os.path.dirname(old_config.config_file)
                    backup_path = os.path.join(config_dir, 'web.conf.old')
                    os.rename(old_config.config_file, backup_path)
                    del old_config

        self.socket = None
        self.top_level = TopLevel()
        self.site = server.Site(self.top_level)
        self.port = self.config["port"]
        self.https = self.config["https"]
        self.pkey = self.config["pkey"]
        self.cert = self.config["cert"]
        self.base = self.config["base"]
        self.web_api = WebApi()
        self.auth = Auth()

        # Initalize the plugins
        self.plugins = PluginManager()

    def install_signal_handlers(self):
        # Since twisted assigns itself all the signals may as well make
        # use of it.
        reactor.addSystemEventTrigger("after", "shutdown", self.shutdown)

        # Twisted doesn't handle windows specific signals so we still
        # need to attach to those to handle the close correctly.
        if common.windows_check():
            from win32api import SetConsoleCtrlHandler
            from win32con import CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT
            def win_handler(ctrl_type):
                log.debug("ctrl type: %s", ctrl_type)
                if ctrl_type == CTRL_CLOSE_EVENT or \
                   ctrl_type == CTRL_SHUTDOWN_EVENT:
                    self.shutdown()
                    return 1
            SetConsoleCtrlHandler(win_handler)

    def start(self, start_reactor=True):
        log.info("%s %s.", _("Starting server in PID"), os.getpid())
        if self.https:
            self.start_ssl()
        else:
            self.start_normal()

        component.get("JSON").enable()

        if start_reactor:
            reactor.run()

    def start_normal(self):
        self.socket = reactor.listenTCP(self.port, self.site)
        log.info("serving on %s:%s view at http://127.0.0.1:%s", "0.0.0.0",
            self.port, self.port)

    def start_ssl(self):
        check_ssl_keys()
        self.socket = reactor.listenSSL(self.port, self.site, ServerContextFactory())
        log.info("serving on %s:%s view at https://127.0.0.1:%s", "0.0.0.0",
            self.port, self.port)

    def stop(self):
        log.info("Shutting down webserver")
        component.get("JSON").disable()

        self.plugins.disable_plugins()
        log.debug("Saving configuration file")
        self.config.save()

        if self.socket:
            d = self.socket.stopListening()
            self.socket = None
        else:
            d = defer.Deferred()
            d.callback(False)
        return d

    def shutdown(self, *args):
        self.stop()
        try:
            reactor.stop()
        except error.ReactorNotRunning:
            log.debug("Reactor not running")
示例#7
0
class DelugeWeb(component.Component):

    def __init__(self, options=None, daemon=True):
        """
        Setup the DelugeWeb server.

        Args:
            options (argparse.Namespace): The web server options.
            daemon (bool): If True run web server as a seperate daemon process (starts a twisted
                reactor). If False shares the process and twisted reactor from WebUI plugin or tests.

        """
        component.Component.__init__(self, 'DelugeWeb', depend=['Web'])
        self.config = configmanager.ConfigManager('web.conf', defaults=CONFIG_DEFAULTS, file_version=2)
        self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2)
        self.config.register_set_function('language', self._on_language_changed)
        self.socket = None
        self.top_level = TopLevel()

        self.interface = self.config['interface']
        self.port = self.config['port']
        self.https = self.config['https']
        self.pkey = self.config['pkey']
        self.cert = self.config['cert']
        self.base = self.config['base']

        if options:
            self.interface = options.interface if options.interface is not None else self.interface
            self.port = options.port if options.port else self.port
            self.base = options.base if options.base else self.base
            if options.ssl:
                self.https = True
            elif options.no_ssl:
                self.https = False

        if self.base != '/':
            # Strip away slashes and serve on the base path as well as root path
            self.top_level.putChild(self.base.strip('/'), self.top_level)

        setup_translations(setup_gettext=True, setup_pygtk=False)

        self.site = server.Site(self.top_level)
        self.web_api = WebApi()
        self.web_utils = WebUtils()

        self.auth = Auth(self.config)
        self.daemon = daemon
        # Initalize the plugins
        self.plugins = PluginManager()

    def _on_language_changed(self, key, value):
        log.debug('Setting UI language %s', value)
        set_language(value)

    def install_signal_handlers(self):
        # Since twisted assigns itself all the signals may as well make
        # use of it.
        reactor.addSystemEventTrigger('after', 'shutdown', self.shutdown)

        # Twisted doesn't handle windows specific signals so we still
        # need to attach to those to handle the close correctly.
        if common.windows_check():
            from win32api import SetConsoleCtrlHandler
            from win32con import CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT

            def win_handler(ctrl_type):
                log.debug('ctrl type: %s', ctrl_type)
                if ctrl_type == CTRL_CLOSE_EVENT or \
                   ctrl_type == CTRL_SHUTDOWN_EVENT:
                    self.shutdown()
                    return 1
            SetConsoleCtrlHandler(win_handler)

    def start(self):
        """
        Start the DelugeWeb server
        """
        if self.socket:
            log.warn('DelugeWeb is already running and cannot be started')
            return

        log.info('Starting webui server at PID %s', os.getpid())
        if self.https:
            self.start_ssl()
        else:
            self.start_normal()

        component.get('Web').enable()

        if self.daemon:
            reactor.run()

    def start_normal(self):
        self.socket = reactor.listenTCP(self.port, self.site, interface=self.interface)
        ip = self.socket.getHost().host
        ip = '[%s]' % ip if is_ipv6(ip) else ip
        log.info('Serving at http://%s:%s%s', ip, self.port, self.base)

    def start_ssl(self):
        check_ssl_keys()
        log.debug('Enabling SSL with PKey: %s, Cert: %s', self.pkey, self.cert)

        with open(configmanager.get_config_dir(self.cert)) as cert:
            certificate = Certificate.loadPEM(cert.read()).original
        with open(configmanager.get_config_dir(self.pkey)) as pkey:
            private_key = KeyPair.load(pkey.read(), FILETYPE_PEM).original
        options = CertificateOptions(privateKey=private_key, certificate=certificate, method=SSL.SSLv23_METHOD)
        ctx = options.getContext()
        ctx.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3)
        ctx.use_certificate_chain_file(configmanager.get_config_dir(self.cert))

        self.socket = reactor.listenSSL(self.port, self.site, options, interface=self.interface)
        ip = self.socket.getHost().host
        ip = '[%s]' % ip if is_ipv6(ip) else ip
        log.info('Serving at https://%s:%s%s', ip, self.port, self.base)

    def stop(self):
        log.info('Shutting down webserver')
        try:
            component.get('Web').disable()
        except KeyError:
            pass

        self.plugins.disable_plugins()
        log.debug('Saving configuration file')
        self.config.save()

        if self.socket:
            d = self.socket.stopListening()
            self.socket = None
        else:
            d = defer.Deferred()
            d.callback(False)
        return d

    def shutdown(self, *args):
        self.stop()
        if self.daemon and reactor.running:
            reactor.stop()

    def _migrate_config_1_to_2(self, config):
        config['language'] = CONFIG_DEFAULTS['language']
        return config
示例#8
0
文件: server.py 项目: doadin/deluge
class DelugeWeb(component.Component):
    def __init__(self, options=None, daemon=True):
        """
        Setup the DelugeWeb server.

        Args:
            options (argparse.Namespace): The web server options.
            daemon (bool): If True run web server as a separate daemon process (starts a twisted
                reactor). If False shares the process and twisted reactor from WebUI plugin or tests.

        """
        component.Component.__init__(self, 'DelugeWeb', depend=['Web'])
        self.config = configmanager.ConfigManager(
            'web.conf', defaults=CONFIG_DEFAULTS, file_version=2
        )
        self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2)
        self.config.register_set_function('language', self._on_language_changed)
        self.socket = None
        self.top_level = TopLevel()

        self.interface = self.config['interface']
        self.port = self.config['port']
        self.https = self.config['https']
        self.pkey = self.config['pkey']
        self.cert = self.config['cert']
        self.base = self.config['base']

        if options:
            self.interface = (
                options.interface if options.interface is not None else self.interface
            )
            self.port = options.port if options.port else self.port
            self.base = options.base if options.base else self.base
            if options.ssl:
                self.https = True
            elif options.no_ssl:
                self.https = False

        if self.base != '/':
            # Strip away slashes and serve on the base path as well as root path
            self.top_level.putChild(self.base.strip('/'), self.top_level)

        setup_translation()

        # Remove twisted version number from 'server' http-header for security reasons
        server.version = 'TwistedWeb'
        self.site = server.Site(self.top_level)
        self.web_api = WebApi()
        self.web_utils = WebUtils()

        self.auth = Auth(self.config)
        self.daemon = daemon
        # Initialize the plugins
        self.plugins = PluginManager()

    def _on_language_changed(self, key, value):
        log.debug('Setting UI language %s', value)
        set_language(value)

    def install_signal_handlers(self):
        # Since twisted assigns itself all the signals may as well make
        # use of it.
        reactor.addSystemEventTrigger('after', 'shutdown', self.shutdown)

        # Twisted doesn't handle windows specific signals so we still
        # need to attach to those to handle the close correctly.
        if common.windows_check():
            from win32api import SetConsoleCtrlHandler
            from win32con import CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT

            def win_handler(ctrl_type):
                log.debug('ctrl type: %s', ctrl_type)
                if ctrl_type == CTRL_CLOSE_EVENT or ctrl_type == CTRL_SHUTDOWN_EVENT:
                    self.shutdown()
                    return 1

            SetConsoleCtrlHandler(win_handler)

    def start(self):
        """
        Start the DelugeWeb server
        """
        if self.socket:
            log.warning('DelugeWeb is already running and cannot be started')
            return

        log.info('Starting webui server at PID %s', os.getpid())
        if self.https:
            self.start_ssl()
        else:
            self.start_normal()

        component.get('Web').enable()

        if self.daemon:
            reactor.run()

    def start_normal(self):
        self.socket = reactor.listenTCP(self.port, self.site, interface=self.interface)
        ip = self.socket.getHost().host
        ip = '[%s]' % ip if is_ipv6(ip) else ip
        log.info('Serving at http://%s:%s%s', ip, self.port, self.base)

    def start_ssl(self):
        check_ssl_keys()
        log.debug('Enabling SSL with PKey: %s, Cert: %s', self.pkey, self.cert)

        cert = configmanager.get_config_dir(self.cert)
        pkey = configmanager.get_config_dir(self.pkey)

        self.socket = reactor.listenSSL(
            self.port,
            self.site,
            get_context_factory(cert, pkey),
            interface=self.interface,
        )
        ip = self.socket.getHost().host
        ip = '[%s]' % ip if is_ipv6(ip) else ip
        log.info('Serving at https://%s:%s%s', ip, self.port, self.base)

    def stop(self):
        log.info('Shutting down webserver')
        try:
            component.get('Web').disable()
        except KeyError:
            pass

        self.plugins.disable_plugins()
        log.debug('Saving configuration file')
        self.config.save()

        if self.socket:
            d = self.socket.stopListening()
            self.socket = None
        else:
            d = defer.Deferred()
            d.callback(False)
        return d

    def shutdown(self, *args):
        self.stop()
        if self.daemon and reactor.running:
            reactor.stop()

    def _migrate_config_1_to_2(self, config):
        config['language'] = CONFIG_DEFAULTS['language']
        return config