def make_server(db_dir='/tmp/fake_mesh_dir', host='0.0.0.0', port=8829, ca_cert=default_ca_cert, server_cert=default_server_cert, server_key=default_server_key, debug=False, logging=False): app = FakeMeshApplication(db_dir) if debug: app = DebugMiddleware(app) elif logging: app = LoggingMiddleware(app, logger=LOGGER_NAME) httpd = Server((host, port), app) server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=ca_cert) server_context.load_cert_chain(server_cert, server_key) server_context.check_hostname = False server_context.verify_mode = ssl.CERT_REQUIRED ssl_adapter = BuiltinSSLAdapter(server_cert, server_key, ca_cert) ssl_adapter.context = server_context httpd.ssl_adapter = ssl_adapter return httpd
def e2e_test_context(): app = DomainDispatcherApplication(create_backend_app) aws_server = Server((FAKE_AWS_HOST, FAKE_AWS_PORT), app) aws_httpd = ThreadedHttpd(aws_server) aws_httpd.start() mesh_dir = TemporaryDirectory() forwarder_dir = TemporaryDirectory() app = FakeMeshApplication(mesh_dir.name, FAKE_MESH_SHARED_KEY.encode("utf-8"), FAKE_MESH_CLIENT_PASSWORD) mesh_server = Server((FAKE_MESH_HOST, FAKE_MESH_PORT), app) server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=CA_CERT_PATH) server_context.load_cert_chain(SERVER_CERT_PATH, SERVER_KEY_PATH) server_context.check_hostname = False server_context.verify_mode = ssl.CERT_REQUIRED ssl_adapter = BuiltinSSLAdapter(SERVER_CERT_PATH, SERVER_KEY_PATH, CA_CERT_PATH) ssl_adapter.context = server_context mesh_server.ssl_adapter = ssl_adapter mesh_httpd = ThreadedHttpd(mesh_server) mesh_httpd.start() yield E2ETestContext( fowarder_home=forwarder_dir.name, fake_aws_endpoint=f"http://{FAKE_AWS_HOST}:{FAKE_AWS_PORT}", ) mesh_httpd.stop() aws_httpd.stop() mesh_dir.cleanup() forwarder_dir.cleanup()
def main(ip: dict): app = mywebapp(urls, vars(webui)) app.notfound = notfound global se port = 8080 if 'p' in se: port = int(se['p']) if 'p' in ip: port = ip['p'] host = '127.0.0.1' if 's' in se: host = se['s'] if 's' in ip: host = ip['s'] sslc = None sslp = None sslcc = None if 'sslc' in se and 'sslp' in se: sslc = se['sslc'] sslp = se['sslp'] if 'sslcc' in se: sslcc = se['sslcc'] if 'sslc' in ip: sslc = ip['sslc'] sslp = ip['sslp'] if (sslcc is not None or 'sslc' in ip) and 'sslcc' in ip: sslcc = se['sslcc'] if sslc is not None and sslcc is not None: HTTPServer.ssl_adapter = BuiltinSSLAdapter(certificate=sslc, private_key=sslp, certificate_chain=sslcc) pa.https = True elif sslc is not None: HTTPServer.ssl_adapter = BuiltinSSLAdapter(certificate=sslc, private_key=sslp) pa.https = True if 'pas' in se: pa.pas = True re = pa.setpassword(se['pas']) if re == -1: print(lan['INVALPAS']) return -1 if 'pas' in ip: pa.pas = True re = pa.setpassword(ip['pas']) if re == -1: print(lan['INVALPAS']) return -1 app.add_processor(server_ver) app.run(host, port)
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()
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()
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()
def _build_fake_mesh(mesh_dir): app = FakeMeshApplication(mesh_dir, _utf_8(FAKE_MESH_SHARED_KEY), FAKE_MESH_CLIENT_PASSWORD) httpd = Server((FAKE_MESH_HOST, FAKE_MESH_PORT), app) server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=CA_CERT_PATH) server_context.load_cert_chain(SERVER_CERT_PATH, SERVER_KEY_PATH) server_context.check_hostname = False server_context.verify_mode = ssl.CERT_REQUIRED ssl_adapter = BuiltinSSLAdapter(SERVER_CERT_PATH, SERVER_KEY_PATH, CA_CERT_PATH) ssl_adapter.context = server_context httpd.ssl_adapter = ssl_adapter return ThreadedHttpd(httpd)
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 initiate(): log_main.info('Iniciando a API versão: {}'.format(app_version)) signal.signal(signal.SIGTERM, finalize) signal.signal(signal.SIGINT, finalize) global token, database, sms token = conf.get('Auth', 'Token', fallback='14acd1c3b2f50c1e7354668f7d0b4057') ttvToken = open( os.path.join(workdir, conf.get('Auth', 'TokenTTV', fallback=False)), 'r') sms = SMS(ttvToken.readline()) ttvToken.close() log_main.warning('Iniciando conexão com banco de dados ...') try: db = os.path.join(workdir, conf.get('Database', 'Database', fallback='data.db')) database = Database(db) except Exception as e: log_main.exception( 'Erro ao iniciar a conexão com o banco de dados: [{}]'.format(e)) _port = conf.getint('Flask', 'Port', fallback=8860) _host = conf.get('Flask', 'Host', fallback='0.0.0.0') _threads = conf.getint('Flask', 'Threads', fallback=100) _ssl_cert = os.path.join(workdir, 'SSL', conf.get('Flask', 'SSL_Cert', fallback='')) _ssl_key = os.path.join(workdir, 'SSL', conf.get('Flask', 'SSL_Key', fallback='')) try: _ssl_enabled = os.path.isfile(_ssl_cert) and os.path.isfile(_ssl_key) except Exception: _ssl_enabled = False if len(sys.argv) > 1: if sys.argv[1] in ('-v', '--version'): print('API') print('Versão: {}'.format(app_version)) sys.exit(0) elif sys.argv[1] in ('-d', '--debug'): app.run(host=_host, port=_port, threaded=True, debug=True) else: print('ERRO | Parâmetro desconhecido: {}'.format(sys.argv)) sys.exit(2) else: global server server = WSGIServer(bind_addr=(_host, _port), wsgi_app=app, numthreads=_threads) if _ssl_enabled: server.ssl_adapter = BuiltinSSLAdapter(_ssl_cert, _ssl_key) log_main.warning('Iniciando flask ...') server.start()
def _init_ssl(self): import flask_sslify flask_sslify.SSLify(_app, permanent=True) if not (os.path.exists(self._certfile_path) and os.path.exists(self._keyfile_path)): self._create_self_signed_cert() WSGIServer.ssl_adapter = BuiltinSSLAdapter( certificate=self._certfile_path, private_key=self._keyfile_path)
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
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()
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()
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()
def main(): """ _function_: `mast.datapower.web.main()` This is the main function which will spin up a server listening to the configured port and block until a SIGTERM or equivalent (Ctrl + C) is received at which point it will quit. Logs to: `gui.main.log` Parameters: This function does not accept any arguments. """ logger = make_logger("gui.main") logger.debug("Running as user {}".format(getpass.getuser())) logger.debug("Running in directory {}".format(os.getcwd())) cherrypy.tree.graft(app, '/') # Set the configuration of the web server cherrypy.config.update({ 'engine.autoreload.on': False, 'log.screen': False, 'server.socket_port': port, 'server.socket_host': host, 'server.max_request_body_size': max_file_upload_size }) if secure: logger.debug("Configuring TLS") cherrypy.server.ssl_module = 'builtin' WSGIServer.ssl_adapter = BuiltinSSLAdapter(cert, key, cacert) # Start the CherryPy WSGI web server try: engine = cherrypy.engine engine.signal_handler.subscribe() if hasattr(engine, "console_control_handler"): engine.console_control_handler.subscribe() print "MAST Web listening on https://{}:{}".format(host, port) cherrypy.engine.start() cherrypy.engine.block() except KeyboardInterrupt: cherrypy.engine.exit() except: logger.exception( "Sorry, an unhandled exception occurred while starting CherryPy")
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()
def _run_produc(self): bind_path = self.prefix.strip("/") + "/" bind_addr = (self.host, self.port) wsgi_app = wsgi.PathInfoDispatcher({bind_path: self.app}) server = wsgi.Server(bind_addr, wsgi_app) if self.use_ssl: server.ssl_adapter = BuiltinSSLAdapter(self.certfile, self.keyfile, self.certchain) #: hack cheroot to use our custom logger server.error_log = lambda *args, **kwgs: self.log.log( kwgs.get("level", logging.ERROR), args[0], exc_info=self.pyload.debug ) server.safe_start()
def main(): config = CONFIG_T.load_config() if not config: print("配置文件加载失败!") return CONFIG_T.init_logger() if config and "certs" in config and "key" in config[ "certs"] and "pem" in config["certs"]: HTTPServer.ssl_adapter = BuiltinSSLAdapter( certificate=config["certs"]["pem"], private_key=config["certs"]["key"]) urls = ("/", "Index", "/detail", "Detail", "/login", "Login", "/codediff", "Codediff", "/downfile", "Downfile", "/syncdetail", "Syncdetail", "/gopub", "Gopub") web.config.debug = False app = web.application(urls, globals()) session = WEB_T.get_session(app) app.run()
def SSLAdapter(root_ca, tmpdir_factory): """Given a testme CA, create SSL files and return a BuiltinSSLAdapter.""" server_cert = root_ca.issue_server_cert(u'localhost', u'127.0.0.1', u'::1') server_dir = tmpdir_factory.mktemp('server') server_cert_file = server_dir.join('server.cert') server_cert_file.write(server_cert.cert_chain_pems[0].bytes()) server_pkey_file = server_dir.join('server_pkey') server_pkey_file.write(server_cert.private_key_pem.bytes()) cert_chain_file = server_dir.join('ca.cert') cert_chain_file.write(root_ca.cert_pem.bytes()) ssl_adapter = BuiltinSSLAdapter( certificate=str(server_cert_file), private_key=str(server_pkey_file), certificate_chain=str(cert_chain_file), ) ssl_adapter.context.verify_mode = ssl.CERT_REQUIRED return ssl_adapter
def run(self, handler): self.server = wsgi.Server((self.host, self.port), handler) certfile = self.options.pop('certfile', None) keyfile = self.options.pop('keyfile', None) if certfile and keyfile: self.server.ssl_adapter = BuiltinSSLAdapter(certfile, keyfile) # 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 try: self.server.start() finally: if self.server: self.server.stop()
def run(self, handler): """ Runs a CherryPy Server using the SSL certificate. """ from cheroot.wsgi import Server as CherryPyWSGIServer from cheroot.ssl.builtin import BuiltinSSLAdapter server = CherryPyWSGIServer((self.host, self.port), handler) server.ssl_adapter = BuiltinSSLAdapter( certificate=get_ssl_certificate(), private_key=get_ssl_private_key(), certificate_chain=get_ssl_certificate_chain() if get_ssl_certificate_chain() != "" else None) try: server.start() except Exception as ex: LOG.error('Unable to start SSL server: %s' % ex) server.stop()
def run(self, handler): """ Runs a CherryPy Server using the SSL certificate. """ from cheroot import wsgi from cheroot.ssl.builtin import BuiltinSSLAdapter server = wsgi.Server((self.host, self.port), handler) server.ssl_adapter = BuiltinSSLAdapter( certificate="cert/remotesensors.crt", private_key="cert/remotesensors.key", certificate_chain="cert/rootCA.pem") try: server.start() except Exception as e: print('SERVER START ERROR:') print(str(e)) server.stop()
sign_alg = None digest_alg = None try: sign_alg = CONFIG.SIGN_ALG except AttributeError: pass try: digest_alg = CONFIG.DIGEST_ALG except AttributeError: pass ds.DefaultSignature(sign_alg, digest_alg) SRV = WSGIServer((HOST, PORT), application) _https = "" if CONFIG.HTTPS: https = "using HTTPS" # SRV.ssl_adapter = ssl_pyopenssl.pyOpenSSLAdapter( # config.SERVER_CERT, config.SERVER_KEY, config.CERT_CHAIN) SRV.ssl_adapter = BuiltinSSLAdapter(CONFIG.SERVER_CERT, CONFIG.SERVER_KEY, CONFIG.CERT_CHAIN) logger.info("Server starting") print("IDP listening on %s:%s%s" % (HOST, PORT, _https)) try: SRV.start() except KeyboardInterrupt: SRV.stop()
def ssl_adapter(certificate, private_key): _check_file_readable(certificate) _check_file_readable(private_key) return BuiltinSSLAdapter(certificate, private_key)
# -*- coding: utf-8 -*- # filename: main.py import web from handle import Handle from html import Html from cheroot.server import HTTPServer from cheroot.ssl.builtin import BuiltinSSLAdapter HTTPServer.ssl_adapter = BuiltinSSLAdapter(certificate='key/certificate.pem', private_key='key/key.pem') urls = ( '/wx', 'Handle', '/wechat/(.*)', 'Html', ) class MyApplication(web.application): def run(self, port=443, *middleware): func = self.wsgifunc(*middleware) return web.httpserver.runsimple(func, ('0.0.0.0', port)) if __name__ == "__main__": app = MyApplication(urls, globals()) app.run(port=443)
print(u"Creating plugins menu", e) pass tl = Thread(target=timing_loop) tl.daemon = True tl.start() if gv.use_gpio_pins: set_output() app.notfound = lambda: web.seeother(u"/") ########################### #### For HTTPS (SSL): #### if gv.sd["htp"] == 443: try: from cheroot.server import HTTPServer from cheroot.ssl.builtin import BuiltinSSLAdapter HTTPServer.ssl_adapter = BuiltinSSLAdapter( certificate='/usr/lib/ssl/certs/SIP.crt', private_key='/usr/lib/ssl/private/SIP.key' ) except IOError as e: gv.sd[u"htp"] = int(80) jsave(gv.sd, u"sd") print(u"SSL error", e) restart(2) app.run()
def start(): #NOTE: bots directory should always be on PYTHONPATH - otherwise it will not start. #***command line arguments************************** usage = ''' This is "%(name)s" version %(version)s, part of Bots open source edi translator (http://bots.sourceforge.net). The %(name)s is the web server for bots; the interface (bots-monitor) can be accessed in a browser, eg 'http://localhost:8080'. Usage: %(name)s -c<directory> Options: -c<directory> directory for configuration files (default: config). ''' % { 'name': os.path.basename(sys.argv[0]), 'version': botsglobal.version } configdir = 'config' for arg in sys.argv[1:]: if arg.startswith('-c'): configdir = arg[2:] if not configdir: print( 'Error: configuration directory indicated, but no directory name.' ) sys.exit(1) else: print(usage) sys.exit(0) #***end handling command line arguments************************** botsinit.generalinit( configdir) #find locating of bots, configfiles, init paths etc. process_name = 'webserver' botsglobal.logger = botsinit.initserverlogging( process_name ) #initialise file-logging for web-server. This logging only contains the logging from bots-webserver, not from cherrypy. #***init cherrypy as webserver********************************************* #global configuration for cherrypy cherrypy.config.update({ 'global': { 'log.screen': False, 'server.environment': botsglobal.ini.get('webserver', 'environment', 'production') } }) #cherrypy handling of static files conf = { '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'media', 'tools.staticdir.root': botsglobal.ini.get('directories', 'botspath') } } servestaticfiles = cherrypy.tree.mount( None, '/media', conf ) #None: no cherrypy application (as this only serves static files) #cherrypy handling of django servedjango = WSGIHandler( ) #was: servedjango = AdminMediaHandler(WSGIHandler()) - django does not need the AdminMediaHandler. #cherrypy uses a dispatcher in order to handle the serving of static files and django. dispatcher = WSGIPathInfoDispatcher({ '/': servedjango, str('/media'): servestaticfiles }) #UNICODEPROBLEM: needs to be binary botswebserver = WSGIServer( bind_addr=('0.0.0.0', botsglobal.ini.getint('webserver', 'port', 8080)), wsgi_app=dispatcher, server_name=botsglobal.ini.get('webserver', 'name', 'bots-webserver')) #botswebserver = wsgiserver.CherryPyWSGIServer(bind_addr=('0.0.0.0', botsglobal.ini.getint('webserver','port',8080)), wsgi_app=dispatcher, server_name=botsglobal.ini.get('webserver','name','bots-webserver')) botsglobal.logger.log(25, _('Bots %(process_name)s started.'), {'process_name': process_name}) botsglobal.logger.log( 25, _('Bots %(process_name)s configdir: "%(configdir)s".'), { 'process_name': process_name, 'configdir': botsglobal.ini.get('directories', 'config') }) botsglobal.logger.log( 25, _('Bots %(process_name)s serving at port: "%(port)s".'), { 'process_name': process_name, 'port': botsglobal.ini.getint('webserver', 'port', 8080) }) #handle ssl: cherrypy < 3.2 always uses pyOpenssl. cherrypy >= 3.2 uses python buildin ssl (python >= 2.6 has buildin support for ssl). ssl_certificate = botsglobal.ini.get('webserver', 'ssl_certificate', None) ssl_private_key = botsglobal.ini.get('webserver', 'ssl_private_key', None) if ssl_certificate and ssl_private_key: if StrictVersion(cherrypy.__version__) >= StrictVersion('3.2.0'): botswebserver.ssl_adapter = BuiltinSSLAdapter( ssl_certificate, ssl_private_key) else: #but: pyOpenssl should be there! botswebserver.ssl_certificate = ssl_certificate botswebserver.ssl_private_key = ssl_private_key botsglobal.logger.log(25, _('Bots %(process_name)s uses ssl (https).'), {'process_name': process_name}) else: botsglobal.logger.log( 25, _('Bots %(process_name)s uses plain http (no ssl).'), {'process_name': process_name}) #***start the cherrypy webserver.************************************************ try: botswebserver.start() except KeyboardInterrupt: botswebserver.stop()
def _run(self) -> None: # Server and end points app = Flask(__name__) def _with_state_lock( req: Request, callback: Callable[[Request], Response]) -> Response: if self.processing: return Response("Processing contribution. Retry later.", 503) self.state_lock.acquire() try: return callback(req) except Exception as ex: warning(f"error in request: {ex}") print(f"error in request: {ex}") return Response("error: {ex}", 400) finally: self.state_lock.release() @app.route('/contributors', methods=['GET']) def contributors() -> Response: # pylint: disable=unused-variable return _with_state_lock(request, self._contributors) @app.route('/state', methods=['GET']) def state() -> Response: # pylint: disable=unused-variable return _with_state_lock(request, self._state) @app.route('/challenge', methods=['GET']) def challenge() -> Response: # pylint: disable=unused-variable return _with_state_lock(request, self._challenge) @app.route('/contribute', methods=['POST']) def contribute() -> Response: # pylint: disable=unused-variable return _with_state_lock(request, self._contribute) def _tick() -> None: self.state_lock.acquire() try: self._update_state(time.time()) finally: self.state_lock.release() interval = Interval(60.0, _tick) try: if not exists(self.config.tls_certificate): raise Exception(f"no cert file {self.config.tls_certificate}") if not exists(self.config.tls_key): raise Exception(f"no key file {self.config.tls_key}") listen_addr = ('0.0.0.0', self.config.port) self.server = WSGIServer(listen_addr, PathInfoDispatcher({'/': app}), numthreads=1) self.server.ssl_adapter = BuiltinSSLAdapter( self.config.tls_certificate, self.config.tls_key) print(f"Listening on {listen_addr} ...") self.server.start() finally: interval.stop() self.server = None
def run(app_directory, listener_address=None, no_logs=False, running_describe=False): """ When an application is run, the following is performed: - Identify application root - Check for qwstart.py on - Startup script directory - Current working directory - Setup port number, if $PORT is not set, use a random port """ start_t = time() # Use for startup time calculation print("** Starting application %s using QuickWeb %s " % (info(app_directory), info(quickweb.version.version))) startup_cwd = os.getcwd() # Check if beeing run from gunicorn is_gunicorn = "gunicorn" in os.environ.get("SERVER_SOFTWARE", "") if is_gunicorn: sys.stderr.write( "Quickweb provides it's own HTTP server module.\n" "Running from another HTTP server is not supported at this time\n") sys.exit(1) # Identify the application root directory app_root_directory = app_directory or os.getcwd() startup.setup_app("app_name", app_root_directory, no_logs) if running_describe: return colored_elapsed_time = info("%0.2fms" % ((time() - start_t) * 1000.0)) print("=" * 10 + " Startup completed in " + colored_elapsed_time) # Determine the HTTP listener port listener_port = int(os.getenv("PORT", 8080)) if os.name == "posix": socket_host = "0.0.0.0" else: socket_host = "127.0.0.1" if listener_address is not None: socket_host = listener_address cherrypy.config.update({"server.socket_host": socket_host}) cherrypy.config.update({"server.socket_port": listener_port}) ssl_certificate = os.environ.get("SSL_CERTIFICATE") if ssl_certificate: ssl_adapter = BuiltinSSLAdapter( certificate=ssl_certificate, private_key=os.environ["SSL_PRIVATE_KEY"], certificate_chain=os.environ.get("SSL_CERTIFICATE_CHAIN"), ) verify_mode = ssl.CERT_NONE if os.getenv("SSL_VERIFY_CLIENT_CERT") == "required": verify_mode = ssl.CERT_REQUIRED if os.getenv("SSL_VERIFY_CLIENT_CERT") == "optional": verify_mode = ssl.CERT_OPTIONAL ssl_adapter.context.verify_mode = verify_mode HTTPServer.ssl_adapter = ssl_adapter # In some platforms signals are not available: if hasattr(cherrypy.engine, "signals"): cherrypy.engine.signals.subscribe() cherrypy.engine.subscribe("stop", lambda: os.chdir(startup_cwd)) if os.environ.get("DAEMON_MODE"): daemon = Daemonizer(cherrypy.engine, stdout='stdout.log', stderr='stderr.log') daemon.subscribe() PIDFile(cherrypy.engine, 'quickweb.pid').subscribe() cherrypy.engine.start() cherrypy.engine.block()
def cherrypy_server_runner(app, global_conf=None, host='127.0.0.1', port=None, ssl_pem=None, protocol_version=None, numthreads=None, server_name=None, max=None, request_queue_size=None, timeout=None): # pragma: no cover """ Entry point for CherryPy's WSGI server Serves the specified WSGI app via CherryPyWSGIServer. ``app`` The WSGI 'application callable'; multiple WSGI applications may be passed as (script_name, callable) pairs. ``host`` This is the ipaddress to bind to (or a hostname if your nameserver is properly configured). This defaults to 127.0.0.1, which is not a public interface. ``port`` The port to run on, defaults to 8080 for HTTP, or 4443 for HTTPS. This can be a string or an integer value. ``ssl_pem`` This an optional SSL certificate file (via OpenSSL) You can generate a self-signed test PEM certificate file as follows: $ openssl genrsa 1024 > host.key $ chmod 400 host.key $ openssl req -new -x509 -nodes -sha1 -days 365 \\ -key host.key > host.cert $ cat host.cert host.key > host.pem $ chmod 400 host.pem ``protocol_version`` The protocol used by the server, by default ``HTTP/1.1``. ``numthreads`` The number of worker threads to create. ``server_name`` The string to set for WSGI's SERVER_NAME environ entry. ``max`` The maximum number of queued requests. (defaults to -1 = no limit). ``request_queue_size`` The 'backlog' argument to socket.listen(); specifies the maximum number of queued connections. ``timeout`` The timeout in seconds for accepted connections. """ is_ssl = False if ssl_pem: port = port or 4443 is_ssl = True if not port: if ':' in host: host, port = host.split(':', 1) else: port = 8080 bind_addr = (host, int(port)) kwargs = {} for var_name in ('numthreads', 'max', 'request_queue_size', 'timeout'): var = locals()[var_name] if var is not None: kwargs[var_name] = int(var) try: from cheroot.wsgi import Server as WSGIServer except ImportError: from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer server = WSGIServer(bind_addr, app, server_name=server_name, **kwargs) if ssl_pem is not None: if PY2: server.ssl_certificate = server.ssl_private_key = ssl_pem else: # creates wsgiserver.ssl_builtin as side-effect try: from cheroot.server import get_ssl_adapter_class from cheroot.ssl.builtin import BuiltinSSLAdapter except ImportError: from cherrypy.wsgiserver import get_ssl_adapter_class from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter get_ssl_adapter_class() server.ssl_adapter = BuiltinSSLAdapter(ssl_pem, ssl_pem) if protocol_version: server.protocol = protocol_version try: protocol = is_ssl and 'https' or 'http' if host == '0.0.0.0': print('serving on 0.0.0.0:%s view at %s://127.0.0.1:%s' % (port, protocol, port)) else: print('serving on %s://%s:%s' % (protocol, host, port)) server.start() except (KeyboardInterrupt, SystemExit): server.stop() return server