def serve_wss(self): """Start a web socket server over SSL, used by the web UI to get notifications about updates.""" import os from .events import SystemEvent from autobahn.websocket import WebSocketServerProtocol, WebSocketServerFactory from twisted.internet import reactor from twisted.internet.error import BindError # Start a web socket server if the web UI is enabled if not self._config['web-ui-enabled']: return if not self._config['wss-enabled']: return if not os.path.isfile(self._config['ssl-cert']): self._startup_event.log_critical("Unable to activate SSL: File does not exist: %s" % self._config['ssl-cert']) return from twisted.internet import ssl try: # Create a WebSocketClientHandler instance WebSocketClientHandler = WebSocketClientHandlerFactory(self._config, self._ws_clients, self._event_store, self._server_status) uri = u"ws://%s:%s" % (self._config['wss-host'], self._config['wss-port']) factory = WebSocketServerFactory(uri) factory.protocol = WebSocketClientHandler # factory.setProtocolOptions(maxConnections=2) # note to self: if using putChild, the child must be bytes... if self._config['ssl-key'] and self._config['ssl-cert']: contextFactory = ssl.DefaultOpenSSLContextFactory(privateKeyFileName=self._config['ssl-key'], certificateFileName=self._config['ssl-cert']) else: contextFactory = ssl.DefaultOpenSSLContextFactory(privateKeyFileName=self._config['ssl-cert'], certificateFileName=self._config['ssl-cert']) self._ws_server_port = reactor.listenSSL(self._config['wss-port'], factory, contextFactory) self._server_status['wss-uri'] = "wss://%s:%s" % (self._config['wss-host'], self._config['wss-port']) self._startup_event.log_info(u"Escutando conexões em %s" % self._server_status['wss-uri']) self._startup_event.ws_address = self._config['wss-host'] self._startup_event.ws_port = self._config['wss-port'] self._startup_event.set_ws_started(True) # Serve forever (until reactor.stop()) reactor.run(installSignalHandlers=False) except BindError as e: self._startup_event.log_critical("Unable to start web socket server: %s" % e) except ImportError: self._startup_event.log_error("Unable to start web socket server due to missing dependency.") event = SystemEvent() self._event_store.register_action(event) event.log_info('WSS server did quit')
def main(): logging.setLoggerClass(ColoredLogger) logger = logging.getLogger('SERVER - MAIN') cacert = "cacert.pem" privkey = "privkey.pem" # Check if certifice exists cacert_file = Path(cacert) privkey_file = Path(privkey) if not cacert_file.is_file() or not privkey_file.is_file(): create_self_signed_cert(cacert, privkey) server_port = 8080 ssl_context = ssl.DefaultOpenSSLContextFactory( privkey, cacert, ) site = server.Site(ServerHandler()) endpoint = endpoints.SSL4ServerEndpoint(reactor, server_port, ssl_context) endpoint.listen(site) logger.info('Server start listening on {0}'.format(server_port)) reactor.run()
def run(self): log("SERVER UP") # 接受Web控制指令 Thread(target=socket_method().run, daemon=True).start() # 处理远程任务,包括任务的状态和提交结果 Thread(target=remote_event_loop, daemon=True).start() sslContext = ssl.DefaultOpenSSLContextFactory( 'CA/key.pem', # 私钥 'CA/cert.pem', # 公钥 ) # 处理文件异步上传 UploadQueue().start() # 服务启动时,初始化所有用户状态---未登录 close_all_conn() # 监听服务 reactor.listenSSL(kPort, self.protocol_factory, sslContext) reactor.callWhenRunning(self.check_remote_task) # reactor.listenTCP(kPort, self.protocol_factory) reactor.run()
def main(): server_port = 8080 ssl_context = ssl.DefaultOpenSSLContextFactory( 'privkey.pem', 'cacert.pem', ) site = server.Site(ClientHandler()) endpoint = endpoints.SSL4ServerEndpoint(reactor, server_port, ssl_context) endpoint.listen(site) logger.info('Server start listening on {0}'.format(server_port)) reactor.run()
def start_reactor(callback_fn: object, use_keyring, secret_manager: sslcert.SecretManager, port: int = 9096) -> None: """ Opens an echo socket server. :param secret_manager: An initialised SecretManager :param use_keyring: Whether to load certificate and key from keyring or files. :param callback_fn: Function to call when message was received :param port: Port to use """ logger.info("Starting server") factory = MyServerFactory(data_callback_fn=callback_fn, secret_manager=secret_manager) if use_keyring: key = keyring.get_password("snoty", "key") certificate = keyring.get_password("snoty", "cert") reactor.listenSSL(port, factory, CtxFactory(key, certificate)) else: reactor.listenSSL(port, factory, ssl.DefaultOpenSSLContextFactory( 'key.pem', 'cert.pem')) reactor.run(installSignalHandlers=False) print("stopped")
def startTwisted(self): from twisted.python import log log.startLogging(open("wssserver.log", "w")) self.print_debug("startTwisted() started") ws = "ws" ResourceProtocol.server = self sslcontext = None if self.ssl: self.print_debug("using wss... and ssl") sslcontext = ssl.DefaultOpenSSLContextFactory(self.sslkey, self.sslcert) ws = "wss" factory = WebSocketServerFactory(u"{}://127.0.0.1:{}".format(ws, self.port)) factory.protocol = ResourceProtocol listenWS(factory, sslcontext) reactor.run()
# Start update loop update_stats = task.LoopingCall(build_stats) update_stats.start(FREQUENCY) # Start a timout loop if CLIENT_TIMEOUT > 0: timeout = task.LoopingCall(timeout_clients) timeout.start(10) # Connect to HBlink reactor.connectTCP(HBLINK_IP, HBLINK_PORT, reportClientFactory()) # Create websocket server to push content to clients dashboard_server = dashboardFactory('wss://*:9488') dashboard_server.protocol = dashboard sslContext = ssl.DefaultOpenSSLContextFactory('/etc/letsencrypt/live/dmr02.bzsax.de/privkey.pem','/etc/letsencrypt/live/dmr02.bzsax.de/fullchain.pem') reactor.listenSSL(9488, dashboard_server, sslContext) # Create static web server to push initial index.html website = Site(web_server()) reactor.listenSSL(WEB_SERVER_PORT, website, sslContext) # Redirect with twisted to SSL port HTTPnoSSL = Resource() no_SSL_URL = "https://dmr02.bzsax.de:8488" HTTPnoSSL.putChild(b'', Redirect(bytes(no_SSL_URL, 'utf-8'))) reactor.listenTCP(8088, Site(HTTPnoSSL)) reactor.run()
def serve_wss(self): """Start a web socket server over SSL, used by the web UI to get notifications about updates.""" import os from .events import SystemEvent # Start a web socket server if the web UI is enabled if not self._config['web-ui-enabled']: return if not self._config['wss-enabled']: return if not os.path.isfile(self._config['ssl-cert']): self._startup_event.log_critical( "Unable to activate SSL: File does not exist: %s" % self._config['ssl-cert']) return try: import os from autobahn.asyncio.websocket import WebSocketServerProtocol, WebSocketServerFactory from twisted.internet.protocol import ClientFactory from twisted.internet import reactor, ssl from twisted.internet.error import BindError import trollius as asyncio class PatchedWebSocketServerFactory(ClientFactory, WebSocketServerFactory): pass # Create a WebSocketClientHandler instance WebSocketClientHandler = WebSocketClientHandlerFactory( self._config, self._ws_clients, self._event_store, self._server_status) uri = u"ws://%s:%s" % (self._config['wss-host'], self._config['wss-port']) loop = asyncio.new_event_loop() factory = PatchedWebSocketServerFactory(uri, loop=loop) factory.protocol = WebSocketClientHandler # factory.setProtocolOptions(maxConnections=2) # note to self: if using putChild, the child must be bytes... if self._config['ssl-key'] and self._config['ssl-cert']: contextFactory = ssl.DefaultOpenSSLContextFactory( privateKeyFileName=self._config['ssl-key'], certificateFileName=self._config['ssl-cert']) else: contextFactory = ssl.DefaultOpenSSLContextFactory( privateKeyFileName=self._config['ssl-cert'], certificateFileName=self._config['ssl-cert']) self._ws_server_port = reactor.listenSSL(self._config['wss-port'], factory, contextFactory) # self._ws_server_port = reactor.listenTCP(self._config['wss-port'], factory) self._server_status['wss-uri'] = "wss://%s:%s" % ( self._config['wss-host'], self._config['wss-port']) self._startup_event.log_info("Listening for connections on %s" % self._server_status['wss-uri']) self._startup_event.ws_address = self._config['wss-host'] self._startup_event.ws_port = self._config['wss-port'] self._startup_event.set_ws_started(True) # Serve forever (until reactor.stop()) reactor.run(installSignalHandlers=False) # this needs to be a part of an try-execpt block # except BindError as e: # self._startup_event.log_critical("Unable to start web socket server: %s" % e) except ImportError as e: raise (e) self._startup_event.log_error( "Unable to start web socket server due to missing dependency.") event = SystemEvent() self._event_store.register_action(event) event.log_info('WSS server did quit')