예제 #1
0
def run(app,
        root_prefix="",
        hostname="0.0.0.0",
        http_port=None,
        https_port=None,
        https_cert_path=None,
        https_certkey_path=None):
    root_prefix = root_prefix or ""
    dispatcher = wsgi.PathInfoDispatcher({root_prefix: app})
    global _http_server
    global _https_server
    http_thread = None
    https_thread = None
    if http_port:
        _http_server = wsgi.Server((hostname, http_port), dispatcher)
        http_thread = threading.Thread(target=_http_server.start)
    if https_port:
        _https_server = wsgi.Server((hostname, https_port), dispatcher)
        _https_server.ssl_adapter = BuiltinSSLAdapter(https_cert_path,
                                                      https_certkey_path)
        https_thread = threading.Thread(target=_https_server.start)
    if http_thread is not None:
        http_thread.start()
    if https_thread is not None:
        https_thread.start()
예제 #2
0
    def run_webapp(self):
        from main.wsgi import application

        class Root():
            pass

        cherrypy.config.update({'environment': 'production'})
        static_app = cherrypy.tree.mount(Root(),
                                         '/',
                                         config={
                                             '/': {
                                                 'tools.staticdir.on':
                                                 True,
                                                 'tools.staticdir.dir':
                                                 join(settings.ROOT_DIR,
                                                      'public')
                                             }
                                         })

        addr = ('0.0.0.0', settings.HTTP_PLATFORM_PORT)
        dispatcher = wsgi.PathInfoDispatcher({
            '/': application,
            '/static': static_app,
        })
        server = wsgi.Server(addr, dispatcher)
        self.logger.info('Starting webapp: {}'.format(server._bind_addr))
        server.safe_start()
예제 #3
0
파일: __main__.py 프로젝트: Oxygem/MiniWiki
def start_miniwiki(
    import_filename,
    export_filename,
    initdb,
    host,
    port,
    config_filename,
):
    config = load_config(config_filename)
    app = make_app(config)

    if initdb:
        with app.app_context():
            db.create_all()
        click.echo('Database initialized!')
        return

    if import_filename:
        with app.app_context():
            return import_pages(import_filename)

    if export_filename:
        with app.app_context():
            return export_pages(export_filename)

    if config['debug']:
        app.run(host=host, port=port)
    else:
        server = wsgi.Server((host, port), app)
        server.start()
예제 #4
0
 def activate(self):
     Component.activate(self)
     # Late import to speed up application startup.
     from cheroot import wsgi
     self.wsgi_server = wsgi.Server(\
         ("0.0.0.0", self.port), self.wsgi_app, server_name="localhost",
         numthreads=1, timeout=5)
예제 #5
0
def main() -> None:
    args = parse_arguments()
    if args.print_version:
        print('{}, version {}'.format(os.path.basename(sys.argv[0]),
                                      __version__))
        sys.exit(0)
    elif args.print_default_config:
        Config.write_default_config(sys.stdout)
        sys.exit(0)
    config.read_config(args.config_filename)
    app = setup_app()
    if config.debug:
        if config.server_prefix != '/':
            app = DispatcherMiddleware(
                Flask('debugging_frontend'),
                {config.server_prefix: app})  # type: ignore
        run_simple(config.socket_host,
                   config.socket_port,
                   app,
                   use_debugger=True,
                   use_reloader=True)  # type: ignore
    else:
        wsgi_server = wsgi.Server(
            (config.socket_host, config.socket_port),
            wsgi.PathInfoDispatcher({config.server_prefix: app}))
        wsgi_server.safe_start()
예제 #6
0
    def run(self, handler):
        server = wsgi.Server((self.host, self.port), handler)

        try:
            server.start()
        finally:
            server.stop()
예제 #7
0
    def run(self, handler):
        from cheroot import wsgi
        from cheroot.ssl.builtin import BuiltinSSLAdapter
        import ssl

        self.server = wsgi.Server((self.host, self.port), handler)

        cert_file = self.options.get('cert_file', None)
        key_file = self.options.get('key_file', None)
        enable_ssl = self.options.get('enable_ssl', False)

        p_cert_file = Path(cert_file)
        p_key_file = Path(key_file)

        if p_cert_file.exists() and p_key_file.exists() and enable_ssl:
            self.server.ssl_adapter = BuiltinSSLAdapter(
                str(p_cert_file.absolute()), str(p_key_file.absolute()))

            # By default, the server will allow negotiations with extremely old protocols
            # that are susceptible to attacks, so we only allow TLSv1.2
            self.server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1
            self.server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1_1
        else:
            dlna_server: SimpleDLNAServer = self.options.get('dlna_server')
            dlna_server.is_ssl_enabled = False

        self.server.prepare()

        # 必须在self.server被赋值后触发初始化完成时间
        # 这里在开启循环前触发,保证服务器已经启动
        init_event: threading.Event = self.options.get('init_event', None)
        if init_event is not None:
            init_event.set()

        self.server.serve()
예제 #8
0
파일: agent.py 프로젝트: Limmen/kagent-chef
 def run(self, handler):
     server = wsgi.Server((self.host, self.port), handler)
     server.ssl_adapter = BuiltinSSLAdapter(kconfig.certificate_file, kconfig.key_file)
     try:
         server.start()
     finally:
         server.stop()
예제 #9
0
def main():

    cheroot_server_options = {
        'wsgi_app': wsgi_app,
        'bind_addr': ('0.0.0.0', 8082),

        # numthreads (int): number of threads for WSGI thread pool
        'numthreads': 10,

        # server_name (str): web server name to be advertised via Server HTTP header
        # 'server_name': None,
        # max (int): maximum number of worker threads
        # 'max': -1,
        # request_queue_size (int): the 'backlog' arg to socket.listen(); max queued conn
        # 'request_queue_size': 5,
        # timeout (int): the timeout in seconds for accepted connections
        # 'timeout': 10,
        # shutdown_timeout (int): the total time (sec), 2 wait 4 worker threads 2 cleanly exit
        # 'shutdown_timeout': 5,
        # accepted_queue_size (int): maximum number of active requests in queue
        # 'accepted_queue_size': -1,
        # accepted_queue_timeout (int): timeout for putting request into queue
        # 'accepted_queue_timeout': 10,
    }

    server = wsgi.Server(**cheroot_server_options)
    try:
        server.start()
    finally:
        server.stop()
예제 #10
0
    def run(self):
        """ Starts listening server"""

        logging.info (" [+] Starting Macro_Pack WebDAV server...")
        logging.info ("   [-] Files in \"" + self.WRoot + r"\" folder are accessible using url http://<hostname>:%s  or \\<hostname>@%s\DavWWWRoot" % (self.listenPort, self.listenPort))
        logging.info ("   [-] Listening on port %s (ctrl-c to exit)...", self.listenPort)

        # Prepare WsgiDAV config
        config = {
            'middleware_stack' : {
                WsgiDavDirBrowser,  #Enabling dir_browser middleware
            },
            'host': 'localhost',
            'dir_browser': {'davmount': False,
                'enable': True, #Enabling directory browsing on dir_browser
                'ms_mount': False,
                'ms_sharepoint_plugin': True,
                'ms_sharepoint_urls': False,
                'response_trailer': ''},
            'port': self.listenPort,    # Specifying listening port
            'provider_mapping': {'/': self.WRoot}   #Specifying root folder
        }

        app = WsgiDAVApp(config)

        server_args = {
            "bind_addr": (config["host"], config["port"]),
        "wsgi_app": app,
        }
        server = wsgi.Server(**server_args)
        try:
            server.start()
        except:
            logging.info("  [!] Ctrl + C detected, closing WebDAV sever")
            server.stop()
예제 #11
0
    def run(self, handler):
        try:
            # First try to use the new version
            from cheroot.ssl.pyopenssl import pyOpenSSLAdapter
            from cheroot import wsgi
            server = wsgi.Server((self.host, self.port),
                                 handler,
                                 request_queue_size=32)
        except:
            from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter
            from cherrypy import wsgiserver
            server = wsgiserver.CherryPyWSGIServer((self.host, self.port),
                                                   handler,
                                                   request_queue_size=32)

        self.srv = server

        # If cert variable is has a valid path, SSL will be used
        # You can set it to None to disable SSL
        server.ssl_adapter = pyOpenSSLAdapter(Config.REST_SSL_CERTFILE,
                                              Config.REST_SSL_KEYFILE,
                                              Config.REST_SSL_CA_CERTS)
        try:
            server.start()
        finally:
            server.stop()
예제 #12
0
    def run_webapp(self):
        from main.wsgi import application

        class Root:
            pass

        cherrypy.config.update({"environment": "production"})
        static_app = cherrypy.tree.mount(
            Root(),
            "/",
            config={
                "/": {
                    "tools.staticdir.on": True,
                    "tools.staticdir.dir": join(settings.ROOT_DIR, "public"),
                }
            },
        )

        addr = ("0.0.0.0", settings.HTTP_PLATFORM_PORT)
        dispatcher = wsgi.PathInfoDispatcher({
            "/": application,
            "/static": static_app
        })
        server = wsgi.Server(addr, dispatcher)
        self.logger.info("Starting webapp: {}".format(server._bind_addr))
        server.safe_start()
예제 #13
0
def WSGIServer(server_address, wsgi_app):
    """Creates CherryPy WSGI server listening at `server_address` to serve `wsgi_app`.
    This function can be overwritten to customize the webserver or use a different webserver.
    """
    from cheroot import wsgi
    server = wsgi.Server(server_address, wsgi_app, server_name='localhost')
    server.nodelay = not sys.platform.startswith('java')
    return server
예제 #14
0
 def run(self):
     cx_Logging.Info("Running the web server")
     try:
         self.server = wsgi.Server((address, port),
                                   StaticFilesHandler(WSGIHandler()))
         self.server.start()
     except Exception as e:
         cx_Logging.ERROR("Exception: %s" % e)
예제 #15
0
 def run(self, handler):
     server = wsgi.Server((self.host, self.port), handler)
     certificate, key = get_x509_material()
     server.ssl_adapter = BuiltinSSLAdapter(certificate, key)
     try:
         server.start()
     finally:
         server.stop()
def runserver():
    app = WsgiDAVApp(DEFAULT_CONFIG)

    server_args = {
        "bind_addr": (DEFAULT_CONFIG["host"], DEFAULT_CONFIG["port"]),
        "wsgi_app": app,
        }
    server = wsgi.Server(**server_args)
    return server.start()
예제 #17
0
파일: cli.py 프로젝트: ychaim/fava
def main(
    filenames, port, host, prefix, incognito, debug, profile, profile_dir
):
    """Start Fava for FILENAMES on http://<host>:<port>.

    If the `BEANCOUNT_FILE` environment variable is set, Fava will use the
    files (space-delimited) specified there in addition to FILENAMES.

    Note you can also specify command-line options via environment variables.
    For example, `--host=0.0.0.0` is equivalent to setting the environment
    variable `FAVA_HOST=0.0.0.0`.
    """

    if profile:  # pragma: no cover
        debug = True

    env_filename = os.environ.get("BEANCOUNT_FILE")
    if env_filename:
        filenames = filenames + tuple(env_filename.split())

    if not filenames:
        raise click.UsageError("No file specified")

    app.config["BEANCOUNT_FILES"] = filenames
    app.config["INCOGNITO"] = incognito

    if prefix:
        app.wsgi_app = DispatcherMiddleware(
            simple_wsgi, {prefix: app.wsgi_app}
        )

    if not debug:
        server = wsgi.Server((host, port), app)
        print("Running Fava on http://{}:{}".format(host, port))
        server.safe_start()
    else:
        if profile:
            from werkzeug.contrib.profiler import ProfilerMiddleware

            app.config["PROFILE"] = True
            app.wsgi_app = ProfilerMiddleware(
                app.wsgi_app,
                restrictions=(30,),
                profile_dir=profile_dir if profile_dir else None,
            )

        app.jinja_env.auto_reload = True
        try:
            app.run(host, port, debug)
        except OSError as error:
            if error.errno == errno.EADDRINUSE:
                raise click.UsageError(
                    "Can not start webserver because the port is already in "
                    "use. Please choose another port with the '-p' option."
                )
            raise
예제 #18
0
def create_wsgi_server(**conf):
    """Create test server."""
    ssl_adapter = BuiltinSSLAdapter(
        certificate=conf.pop('certificate'),
        private_key=conf.pop('private_key'),
        certificate_chain=conf.pop('certificate_chain'))
    ssl_adapter.context.verify_mode = conf.pop('verify_mode', ssl.CERT_NONE)
    server = wsgi.Server(**conf)
    server.ssl_adapter = ssl_adapter
    return server
예제 #19
0
    def run(self, handler):
        from cheroot.ssl.builtin import BuiltinSSLAdapter
        from cheroot import wsgi
        server = wsgi.Server((self.host, self.port), handler)
        self.srv = server

        server.ssl_adapter = BuiltinSSLAdapter(self._ssl_certfile,
                                               self._ssl_keyfile)
        try:
            server.start()
        finally:
            server.stop()
예제 #20
0
파일: davsrv.py 프로젝트: alirionx/filegw
def start_davsrv(config=False):
    if config == False:
        config = commonConf

    app = WsgiDAVApp(config)

    server_args = {
        "bind_addr": (config["host"], config["port"]),
        "wsgi_app": app,
    }
    server = wsgi.Server(**server_args)
    server.start()
예제 #21
0
파일: http.py 프로젝트: chrlag/testplan
    def setup(self):
        """
        Generate the flask App and prepare the HTTP server.

        :return: server host and port tuple
        :rtype: ``Tuple[str, int]``
        """
        app, _ = generate_interactive_api(self.cfg.ihandler)
        self._server = wsgi.Server((self.cfg.host, self.cfg.port), app)
        self._server.prepare()

        return self._server.bind_addr
예제 #22
0
    def run(self):
        """ Starts listening server"""

        logging.info(" [+] Starting Macro_Pack WebDAV server...")
        logging.info(
            "   [-] Files in \"" + self.WRoot +
            r"\" folder are accessible using url http://{ip}:{port}  or \\{ip}@{port}\DavWWWRoot"
            .format(ip=getHostIp(), port=self.listenPort))
        logging.info("   [-] Listening on port %s (ctrl-c to exit)...",
                     self.listenPort)

        # Prepare WsgiDAV config
        config = {
            'middleware_stack': {
                WsgiDavDirBrowser,  #Enabling dir_browser middleware
            },
            'verbose': 3,
            'add_header_MS_Author_Via': True,
            'unquote_path_info': False,
            're_encode_path_info': None,
            'host': '0.0.0.0',
            'dir_browser': {
                'davmount': False,
                'enable': True,  #Enabling directory browsing on dir_browser
                'ms_mount': False,
                'show_user': True,
                'ms_sharepoint_plugin': True,
                'ms_sharepoint_urls': False,
                'response_trailer': False
            },
            'port': self.listenPort,  # Specifying listening port
            'provider_mapping': {
                '/': self.WRoot
            }  #Specifying root folder
        }

        app = WsgiDAVApp(config)

        server_args = {
            "bind_addr": (config["host"], config["port"]),
            "wsgi_app": app,
        }
        server = wsgi.Server(**server_args)

        try:
            log = logging.getLogger('wsgidav')
            log.raiseExceptions = False  # hack to avoid false exceptions
            log.propagate = True
            log.setLevel(logging.INFO)
            server.start()
        except KeyboardInterrupt:
            logging.info("  [!] Ctrl + C detected, closing WebDAV sever")
            server.stop()
예제 #23
0
 def run(self):
     """Start up the server."""
     subprocess.run(["flask", "db", "upgrade"], check=True)
     # pylint: disable=import-outside-toplevel
     import coverage
     coverage.process_startup()
     # pylint: disable=import-outside-toplevel
     from animeu.app import app
     self.app = app
     self.app.config["SERVER_NAME"] = f"{self.host}:{self.port}"
     self.server = wsgi.Server((self.host, self.port), self.app, max=1)
     self.server.start()
예제 #24
0
 def run(self, handler):
     server = wsgi.Server((self.host, self.port), handler)
     certificate, key = get_x509_material()
     ssl_adapter = BuiltinSSLAdapter(certificate, key)
     ssl_adapter.context.options |= ssl.OP_NO_SSLv2
     ssl_adapter.context.options |= ssl.OP_NO_SSLv3
     ssl_adapter.context.options |= ssl.OP_NO_TLSv1
     ssl_adapter.context.options |= ssl.OP_NO_TLSv1_1
     server.ssl_adapter = ssl_adapter
     try:
         server.start()
     finally:
         server.stop()
예제 #25
0
    def run(self, handler):
        server = wsgi.Server((self.host, self.port), handler)
        server.ssl_adapter = BuiltinSSLAdapter('cacert.pem', 'privkey.pem')

        # By default, the server will allow negotiations with extremely old protocols
        # that are susceptible to attacks, so we only allow TLSv1.2
        server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1
        server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1_1

        try:
            server.start()
        finally:
            server.stop()
예제 #26
0
    def handle(self, **options):
        from cheroot import wsgi

        # Determine the port number
        port = options["port"]

        # Determine the number of threads
        threads = options["threads"]
        if threads < 1:
            raise Exception("Invalid number of threads: %s" % threads)

        # Determine the IP-address to listen on:
        # - either as command line argument
        # - either 0.0.0.0 by default, which means all active IPv4 interfaces
        address = options["address"] or "0.0.0.0"

        # Validate the address and port number
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((address, port))
            s.close()
        except socket.error as e:
            raise Exception(
                "Invalid address '%s' and/or port '%s': %s" % (address, port, e)
            )

        # Print a header message
        hostname = socket.getfqdn()
        print("Starting frePPLe %s web server\n" % VERSION)
        print(
            "To access the server, point your browser to either of the following URLS:"
        )
        if address == "0.0.0.0":
            print("    http://%s:%s/" % (hostname, port))
            for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
                print("    http://%s:%s/" % (ip, port))
        else:
            print("    http://%s:%s/" % (address, port))
        print("Quit the server with CTRL-C.\n")

        # Run the WSGI server
        server = wsgi.Server(
            (address, port), StaticFilesHandler(WSGIHandler()), numthreads=threads
        )
        # Want SSL support? Just set these attributes apparently, but I haven't tested or verified this
        #  server.ssl_certificate = <filename>
        #  server.ssl_private_key = <filename>
        try:
            server.start()
        except KeyboardInterrupt:
            server.stop()
예제 #27
0
파일: box.py 프로젝트: sb864/theonionbox
            def run(self, handler):  # pragma: no cover
                from cheroot import wsgi
                from cheroot.ssl import builtin
                self.options['bind_addr'] = (self.host, self.port)
                self.options['wsgi_app'] = handler
                certfile = self.options.pop('certfile', None)
                keyfile = self.options.pop('keyfile', None)
                chainfile = self.options.pop('chainfile', None)
                self.server = wsgi.Server(**self.options)
                if certfile and keyfile:
                    self.server.ssl_adapter = builtin.BuiltinSSLAdapter(
                        certfile, keyfile, chainfile)

                self.server.start()
예제 #28
0
    def run(self, handler):
        try:
            # First try to use the new version
            from cheroot import wsgi
            server = wsgi.Server((self.host, self.port), handler, request_queue_size=32)
        except:
            from cherrypy import wsgiserver
            server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler, request_queue_size=32)

        self.srv = server
        try:
            server.start()
        finally:
            server.stop()
예제 #29
0
파일: cli.py 프로젝트: stephas/fava
def main(filenames, port, host, prefix, incognito, debug, profile,
         profile_dir):
    """Start Fava for FILENAMES on http://<host>:<port>.

    If the `BEANCOUNT_FILE` environment variable is set, Fava will use the
    files (space-delimited) specified there in addition to FILENAMES.
    """

    if profile:  # pragma: no cover
        debug = True

    env_filename = os.environ.get('BEANCOUNT_FILE')
    if env_filename:
        filenames = filenames + tuple(env_filename.split())

    if not filenames:
        raise click.UsageError('No file specified')

    # TODO: do we actually support multiple filenames, when cli has nargs=-1?
    app.config['BEANCOUNT_FILES'] = filenames
    app.config['INCOGNITO'] = incognito

    if prefix:
        app.wsgi_app = DispatcherMiddleware(simple_wsgi,
                                            {prefix: app.wsgi_app})

    if not debug:
        server = wsgi.Server((host, port), app)
        print('Running Fava on http://{}:{}'.format(host, port))
        server.safe_start()
    else:
        if profile:
            from werkzeug.contrib.profiler import ProfilerMiddleware
            app.config['PROFILE'] = True
            app.wsgi_app = ProfilerMiddleware(
                app.wsgi_app,
                restrictions=(30, ),
                profile_dir=profile_dir if profile_dir else None)

        app.jinja_env.auto_reload = True
        try:
            app.run(host, port, debug)
        except OSError as error:
            if error.errno == errno.EADDRINUSE:
                raise click.UsageError(
                    "Can not start webserver because the port is already in "
                    "use. Please choose another port with the '-p' option.")
            else:  # pragma: no cover
                raise
예제 #30
0
파일: server.py 프로젝트: kerchen/cryptex
    def run(self, handler):
        server = wsgi.Server((self.host, self.port), handler)
        server.ssl_adapter = BuiltinSSLAdapter('./certs/device.crt',
                                               './certs/device.key')

        # By default, the server will allow negotiations with extremely old
        # protocols that are susceptible to attacks, so only allow TLSv1.2
        server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1
        server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1_1

        try:
            server.start()
        finally:
            log.info("Stopping web server.")
            server.stop()