def __init__(self, url):
   WebSocketServerFactory.__init__(self, url)
   self.clients = []
   self.tickGap = 5
   self.tickSetup()
   
   listenWS(self)
Exemplo n.º 2
0
    def bind(self):
        """
        Start listening on the port specified
        """
        factory = WebSocketServerFactory(debug=False)
        factory.noisy = False
        factory.server = self
        factory.protocol = MdcloudWebsocketServerProtocol

        web_resource = File(resource_filename(__name__, 'static/build/client'))

        rootResource = WSGIRootResource(web_resource, {'ws': WebSocketResource(factory)})

        if not self.no_ssl and self.settings and self.settings.ssl.enabled:
            print '*' * 60
            print 'Running in secure mode'
            print 'Ssl key:         %s' % self.settings.ssl.key
            print 'Ssl certificate: %s' % self.settings.ssl.cert
            print '*' * 60

            listen_ssl(self.port, Site(rootResource), interface=self.settings.websocket_ip)

        else:

            print '*' * 60
            print 'Running on 0.0.0.0 without SSL'
            print '*' * 60
            reactor.listenTCP(self.port, Site(rootResource), interface='0.0.0.0')
Exemplo n.º 3
0
class WebSocketListenerService(service.Service):

   name = "WebSocketListenerService"

   logger = Logger()

   def __init__(self, server_uri, router_uri, debug=False):
      self.s_uri = server_uri
      self.s_address = urlparse(server_uri).hostname
      self.s_port = urlparse(server_uri).port

      self.r_uri = router_uri
      self.r_address = urlparse(router_uri).hostname
      self.r_port = urlparse(router_uri).port

      self.debug = debug

      self.s_factory = WebSocketServerFactory(server_uri)
      proto = WSServer
      proto.service = self
      self.s_factory.protocol = proto
      self.s_factory.setProtocolOptions(maxConnections=10)

   def startService(self):
      self.s_listener = reactor.listenTCP(self.s_port, self.s_factory, interface=self.s_address)
      self.logger.info("service started")

   def stopService(self):
      self.s_listener.stopListening()
      self.s_factory.stopFactory()
      self.logger.info("service stopped")
Exemplo n.º 4
0
 def __init__(self, url, mserver, kserver, debug=False, debugCodePaths=False):
     WebSocketServerFactory.__init__(self, url, debug=debug, debugCodePaths=debugCodePaths)
     self.mserver = mserver
     self.kserver = kserver
     self.db = mserver.db
     self.outstanding = {}
     self.clients = []
Exemplo n.º 5
0
def main(reactor):
    log.startLogging(sys.stdout)
    factory = WebSocketServerFactory()
    factory.protocol = OpenFaceServerProtocol
    ctx_factory = DefaultOpenSSLContextFactory(tls_key, tls_crt)
    reactor.listenSSL(args.port, factory, ctx_factory)
    return defer.Deferred()
Exemplo n.º 6
0
    def startService(self):

        factory = WebSocketServerFactory(u"ws://127.0.0.1:%d" % self.port, debug=self.debug)
        factory.protocol = DispatcherProtocol
        factory.protocol.core = self._core

        # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources
        factory.startFactory()

        resource = WebSocketResource(factory)

        # we server static files under "/" ..
        webdir = os.path.abspath(pkg_resources.resource_filename("leap.bitmask_core", "web"))
        root = File(webdir)

        # and our WebSocket server under "/ws"
        root.putChild(u"bitmask", resource)

        # both under one Twisted Web Site
        site = Site(root)

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site)
Exemplo n.º 7
0
    def __init__(self, config, templates):
        """
        :param config: Crossbar transport configuration.
        :type config: dict
        """
        options = config.get("options", {})

        server = "Crossbar/{}".format(crossbar.__version__)
        externalPort = options.get("external_port", None)

        WebSocketServerFactory.__init__(
            self,
            url=config.get("url", None),
            server=server,
            externalPort=externalPort,
            debug=config.get("debug", False),
        )

        # transport configuration
        self._config = config

        # Jinja2 templates for 404 etc
        self._templates = templates

        # set WebSocket options
        set_websocket_options(self, options)
Exemplo n.º 8
0
 def __init__(self, url, debug = False, debugCodePaths = False):
    WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths)
    self.clients = []
    self.oldGifs = []
    self.lastBroadcast = json.dumps({"url":"http://alexwglenn.com/brady/gifs/Alex.gif"});
    self.time = time.time()
    reactor.callLater(gifLoopTime, self.broadcastRandom, ())
Exemplo n.º 9
0
 def __init__(self, url, debug = False, debugCodePaths = False):
   WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths)
   self.clients = []
   self.tickcount = 0
   self.tick()
   self.time = "0"
   self.status = "-1"
Exemplo n.º 10
0
   def __init__(self, config, templates):
      """
      Ctor.

      :param factory: WAMP session factory.
      :type factory: An instance of ..
      :param config: Crossbar transport configuration.
      :type config: dict 
      """
      options = config.get('options', {})

      server = "Crossbar/{}".format(crossbar.__version__)
      externalPort = options.get('external_port', None)


      WebSocketServerFactory.__init__(self,
                                      url = config.get('url', None),
                                      server = server,
                                      externalPort = externalPort,
                                      debug = config.get('debug', False))

      ## transport configuration
      self._config = config

      ## Jinja2 templates for 404 etc
      self._templates = templates

      ## set WebSocket options
      set_websocket_options(self, options)
Exemplo n.º 11
0
def RPCEndpoint(method, debug = False):
    "why the debug param? because "
    f = WebSocketServerFactory(debug = debug, debugCodePaths = debug )
    f.setSessionParameters(externalPort = 8080) #bug in autobahn
    f.protocol = lambda: RPCProtocol(method)
    
    return WebSocketResource(f)
Exemplo n.º 12
0
 def __init__(self, url, debug = False, debugCodePaths = False):
    WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths)
    self.clients = []
    self.nao = Nao()
    self.tickcount = 0
    #self.tick()
    self.measure()
Exemplo n.º 13
0
    def start(self, launchBrowser=True, useBackgroundThread=False,
              selectedTab="capture"):
        # Initialize the websocket, and gets its port
        factory = WebSocketServerFactory()
        factory.protocol = makeSanityWebSocketClass(self.localTargets, {}, {})
        log.startLogging(sys.stdout)
        twistedData = reactor.listenTCP(0, factory)
        websocketPort = twistedData.socket.getsockname()[1]

        # Start the server that hosts the html / CSS / javascript
        server = SocketServer.TCPServer(("", 0),
                                        makeRunnerRequestHandler(websocketPort,
                                                                 selectedTab))
        serverThread = threading.Thread(target=server.serve_forever)
        serverThread.daemon = True
        serverThread.start()

        serverPort = server.socket.getsockname()[1]
        url = "http://localhost:%d/" % serverPort
        print "Navigate to %s" % url

        if launchBrowser:
            webbrowser.open(url)

        # Begin listening on the websocket
        if useBackgroundThread:
            t = threading.Thread(target=reactor.run, kwargs={"installSignalHandlers": 0})
            t.daemon = True
            t.start()
        else:
            reactor.run()
Exemplo n.º 14
0
def debugWS():
    factory = WebSocketServerFactory(u"ws://"+HOST+":"+str(WS_PORT_NUMBER))
    factory.protocol = MyServerProtocol
    # factory.setProtocolOptions(maxConnections=2)

    reactor.listenTCP(WS_PORT_NUMBER, factory)
    reactor.run()
    def __init__(self, url, debug=False, debugCodePaths=False, externalPort=None):
        WebSocketServerFactory.__init__(self, url, debug=debug,
                                        debugCodePaths=debugCodePaths,
                                        externalPort=externalPort)

        reactor.callLater(5, self.gc_conns)
        reactor.callLater(60, self.gc_users)
Exemplo n.º 16
0
def _init(queue_in, queue_out):
    """Initialize the module."""
    global INPUT, OUTPUT, FACTORY, UDP_THREAD

    LOGGER.info("Initializing...")
    INPUT = queue_in
    OUTPUT = queue_out

    FACTORY = WebSocketServerFactory()
    FACTORY.protocol = Server

    reactor.listenTCP(19113, FACTORY)

    LOGGER.info("Listening for remote instances of Samantha on the network.")
    remote_address = _wait_for_server_ip()
    if remote_address == (None, None):
        LOGGER.info("I'm alone on the network.")
    else:
        LOGGER.info("Remote instance found at %s:%s",
                    remote_address[0], remote_address[1])

    UDP_THREAD = UDPThread(name="udp_thread")
    UDP_THREAD.daemon = True

    LOGGER.info("Initialisation complete.")
    return True
Exemplo n.º 17
0
 def __init__(self, url, gameList, updateLobby, wampdispatch, gamechannel, debug = False, debugCodePaths = False):
     WebSocketServerFactory.__init__(self, url, debug = debug, \
                                     debugCodePaths = debugCodePaths)
     self.gameList = gameList
     self.wampdispatch = wampdispatch
     self.gamechannel = gamechannel
     self.updateLobby = updateLobby
Exemplo n.º 18
0
def create_server(app, port):
    ##
    # create a Twisted Web resource for our WebSocket server
    ##
    ws_factory = WebSocketServerFactory(u"ws://127.0.0.1:5000",
                                        debug=app.debug,
                                        debugCodePaths=app.debug)
    ws_factory.protocol = NotificationService
    ws_resource = WebSocketResource(ws_factory)

    ##
    # create a Twisted Web WSGI resource for our Flask server
    ##
    wsgi_resource = WSGIResource(reactor, reactor.getThreadPool(), app)

    ##
    # create a root resource serving everything via WSGI/Flask, but
    # the path "/ws" served by our WebSocket stuff
    ##
    root_resource = WSGIRootResource(wsgi_resource, {'notification-service': ws_resource})

    ##
    # create a Twisted Web Site and run everything
    ##
    site = Site(root_resource)

    reactor.listenTCP(port, site)
    reactor.run()
Exemplo n.º 19
0
    def __init__(self, mease, host, port, debug):
        self.host = host
        self.port = port

        self.address = 'ws://{host}:{port}'.format(host=host, port=self.port)
        WebSocketServerFactory.__init__(self, self.address, debug=debug)

        self.storage = {}
        self.clients_list = set()

        self.mease = mease

        # Connect to subscriber
        logger.debug("Connecting to backend ({backend_name})...".format(
            backend_name=self.mease.backend.name))

        self.mease.subscriber.connect()
        self.mease.subscriber.factory = self

        # Log registered callbacks
        logger.debug("Registered callback functions :")

        logger.debug(
            "Openers : [%s]" % self.mease._get_registry_names('openers'))
        logger.debug(
            "Closers : [%s]" % self.mease._get_registry_names('closers'))
        logger.debug(
            "Receivers : [%s]" % self.mease._get_registry_names('receivers'))
        logger.debug(
            "Senders : [%s]" % self.mease._get_registry_names('senders'))
Exemplo n.º 20
0
def makeWebsocketProxyResource(
        proxy_url, 
        proxied_ws_endpoint_str, 
        proxied_url, 
        request,
        origin=None, 
        reactor=None, 
        verbose=False):
    proxy_url = _strip_query(proxy_url)
    headers = dict((k, ' '.join(v)) for k, v in request.requestHeaders.getAllRawHeaders()
                if k in ['Cookie'])
    factory = WebSocketServerFactory(
        proxy_url,
        debug=False,
        debugCodePaths=False)
    factory.protocol = lambda : WSProxyProtocol(
        proxied_ws_endpoint_str, 
        proxied_url, 
        origin=origin,
        headers=headers,
        verbose=verbose,
        reactor=reactor,
    ) 
    resource = WebSocketResource(factory)
    return resource
Exemplo n.º 21
0
def runtime(server, port):
    import sys

    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory("ws://" + server + ":" + str(port), debug=False)
    factory.protocol = NoFloUiProtocol
    factory.runtime = WebSocketRuntime()

    debug["factory"] = factory
    debug["runtime"] = factory.runtime
    debug["networks"] = factory.runtime.network.networks
    debug["graphs"] = factory.runtime.graph.graphs

    # Required for Chromium ~33 and newer
    def accept(offers):
        for offer in offers:
            if isinstance(offer, PerMessageDeflateOffer):
                return PerMessageDeflateOfferAccept(offer)

    factory.setProtocolOptions(perMessageCompressionAccept=accept)

    reactor.listenTCP(port, factory)

    if not reactor.running:
        reactor.run()
Exemplo n.º 22
0
	def __init__(self, url, debug = True):
		WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debug)
		self.clients = []
	
		self.tc = 0

		self.tick()
   def __init__(self, url, debug = False, debugCodePaths = False):
      WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths)
      self.clients = []
      self.tickcount = 0
      self.tempstatus=None
      self.sprinkler_status=spinklercontrol()
	  
      reactor.callLater(5, self.tick)
Exemplo n.º 24
0
    def __init__(self, *args, **kwargs):
        WebSocketServerFactory.__init__(
            self, *args, **kwargs
        )  # can't use super(); twisted and autobahn do not derive their classes from `object`
        self._listeners = []

        PubSubBroker._brokers[PubSubBroker._unused_broker_id] = self  # debug only!
        PubSubBroker._unused_broker_id += 1
Exemplo n.º 25
0
 def __init__(self, socket_url, debug=False, debugCodePaths=False):
     WebSocketServerFactory.__init__(
         self,
         socket_url,
         debug=debug,
         debugCodePaths=debugCodePaths
     )
     self.subscribers = []
Exemplo n.º 26
0
 def __init__(self, url, debug=False, debugCodePaths=False):
     WebSocketServerFactory.__init__(self, url, debug=debug, debugCodePaths=debugCodePaths)
     self.clients = []
     self.tickcount = 0
     self.data = [self.datagen.next()]
     self.lastbroadcast = 0
     self.tick()
     self.acquiredata()
Exemplo n.º 27
0
Arquivo: server.py Projeto: sndbox/tsp
def run():
    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory('ws://localhost:9002', debug=False)
    factory.protocol = TspServerProtocol

    reactor.listenTCP(9002, factory)
    reactor.run()
Exemplo n.º 28
0
 def __init__(self, url, mserver, kserver, only_ip="127.0.0.1", debug=False, debugCodePaths=False):
     WebSocketServerFactory.__init__(self, url, debug=debug, debugCodePaths=debugCodePaths)
     self.mserver = mserver
     self.kserver = kserver
     self.db = mserver.db
     self.outstanding_listings = {}
     self.outstanding_vendors = {}
     self.clients = []
     self.only_ip = only_ip
Exemplo n.º 29
0
    def __init__(self, url):
        WebSocketServerFactory.__init__(self, url)
        self.clients = []

        # Bind zmq sockets
        bridge.bind()

        # thread the bridges
        bridge.startThreads()
Exemplo n.º 30
0
    def __init__(self,debug, port):
#         self.task = task_queue
#         self.notein = notein_queue
        self.debug = debug
        self.clients = []
        self.lastmsg = ""
        WebSocketServerFactory.__init__(self, "ws://localhost:"+str(port), 
                                        debug = debug, 
                                        debugCodePaths = debug)
Exemplo n.º 31
0
    def listen(self, listen_ws_url, tls_info=None):
        if listen_ws_url.startswith("wss") and not tls_info:
            return "must specify tls_info to listen with TLS"

        if tls_info:
            logging.info("listening with TLS %s" % tls_info)
            contextFactory = ssl.DefaultOpenSSLContextFactory(
                tls_info['key_file'],
                tls_info['cert_file'],
                sslmethod=tls_info['sslmethod'])

            if tls_info['cert_chain_file']:
                ctx = contextFactory.getContext()
                ctx.use_certificate_chain_file(tls_info['cert_chain_file'])

            factory = WebSocketServerFactory(listen_ws_url)
            factory.protocol = IncomingSocket
            factory.setProtocolOptions(openHandshakeTimeout=30,
                                       autoPingInterval=30,
                                       autoPingTimeout=5)
            factory.ms_protocol_layer = self
            factory.ms_shared_seed = None
            self.listener = listenWS(factory, contextFactory)
        else:
            logging.info("listening without TLS")
            port = int(listen_ws_url.split(":")[-1])
            factory = WebSocketServerFactory(listen_ws_url)
            factory.protocol = IncomingSocket
            factory.ms_protocol_layer = self
            factory.ms_shared_seed = None
            self.listener = reactor.listenTCP(port, factory)
        return None
Exemplo n.º 32
0
 def __init__(self):
     self.clients = []
     WebSocketServerFactory.__init__(self)
Exemplo n.º 33
0
 def __init__(self, url):
     WebSocketServerFactory.__init__(self, url)
     self.clients = []
     self.tickcount = 0
     self.tick()
Exemplo n.º 34
0
    def __init__(self,
                 manager,
                 port,
                 secure=False,
                 key_path=None,
                 crt_path=None,
                 unix_socket_path=None):
        self.manager = manager
        from twisted.internet import reactor, ssl

        from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol

        class MyServerProtocol(WebSocketServerProtocol):
            def __init__(self):
                WebSocketServerProtocol.__init__(self)
                self.widget_id = ""

            def onConnect(self, request):
                pass

            def onOpen(self):
                log.info("WebSocket connection open")

            def onMessage(self, payload, isBinary):
                if isBinary:
                    log.info(f"Binary message received: {len(payload)} bytes")
                else:
                    with DBManager.create_session_scope() as db_session:
                        try:
                            message = json.loads(payload)
                        except:
                            self.sendClose()
                            return
                        switcher = {
                            "auth": self._auth,
                            "next_song": self._next_song,
                            "ready": self._ready
                        }
                        if ("event" in message and "data" in message
                                and message["event"] in switcher
                                and switcher[message["event"]](
                                    db_session, message["data"])):
                            pass
                        else:
                            self.sendClose()

            def onClose(self, wasClean, code, reason):
                log.info(
                    f"WebSocket {self.widget_id} connection closed: {reason}")
                try:
                    WebSocketServer.clients.remove(self)
                except:
                    pass

            def _auth(self, db_session, data):
                if "salt" not in data:
                    return False
                ws = WebSocket._by_salt(db_session, data["salt"])
                if not ws:
                    return False
                self.widget_id = ws.widget_id
                WebSocketServer.clients.append(self)
                return True

            def _next_song(self, db_session, data):
                if "salt" not in data:
                    return False
                if not WebSocket._by_salt(db_session, data["salt"]):
                    return False
                manager.bot.songrequest_manager.load_song()
                return True

            def _ready(self, db_session, data):
                if "salt" not in data:
                    return False
                if not WebSocket._by_salt(db_session, data["salt"]):
                    return False
                manager.bot.songrequest_manager.ready()
                return True

        factory = WebSocketServerFactory()
        factory.setProtocolOptions(autoPingInterval=15, autoPingTimeout=5)
        factory.protocol = MyServerProtocol

        def reactor_run(reactor,
                        factory,
                        port,
                        context_factory=None,
                        unix_socket_path=None):
            if unix_socket_path:
                sock_file = Path(unix_socket_path)
                if sock_file.exists():
                    sock_file.unlink()
                reactor.listenUNIX(unix_socket_path, factory)
            else:
                if context_factory:
                    log.info("wss secure")
                    reactor.listenSSL(port, factory, context_factory)
                else:
                    log.info("ws unsecure")
                    reactor.listenTCP(port, factory)

        if secure:
            context_factory = ssl.DefaultOpenSSLContextFactory(
                key_path, crt_path)
        else:
            context_factory = None

        reactor_thread = threading.Thread(target=reactor_run,
                                          args=(reactor, factory, port,
                                                context_factory,
                                                unix_socket_path),
                                          name="WebSocketThread")
        reactor_thread.daemon = True
        reactor_thread.start()
Exemplo n.º 35
0
class RadiusServer(object):
    def __init__(self, config, db_engine=None, daemon=False):
        self.config = config
        self.db_engine = db_engine
        self.daemon = daemon
        self.tasks = {}
        self.init_config()
        self.init_timezone()
        self.init_db_engine()
        self.init_protocol()
        self.init_task()

    def _check_ssl_config(self):
        self.use_ssl = False
        self.privatekey = None
        self.certificate = None
        if self.config.has_option('DEFAULT', 'ssl') and self.config.getboolean(
                'DEFAULT', 'ssl'):
            self.privatekey = self.config.get('DEFAULT', 'privatekey')
            self.certificate = self.config.get('DEFAULT', 'certificate')
            if os.path.exists(self.privatekey) and os.path.exists(
                    self.certificate):
                self.use_ssl = True

    def init_config(self):
        self.logfile = self.config.get('radiusd', 'logfile')
        self.standalone = self.config.has_option('DEFAULT','standalone') and \
            self.config.getboolean('DEFAULT','standalone') or False
        self.secret = self.config.get('DEFAULT', 'secret')
        self.timezone = self.config.has_option(
            'DEFAULT', 'tz') and self.config.get('DEFAULT', 'tz') or "CST-8"
        self.debug = self.config.getboolean('DEFAULT', 'debug')
        self.authport = self.config.getint('radiusd', 'authport')
        self.acctport = self.config.getint('radiusd', 'acctport')
        self.adminport = self.config.getint('radiusd', 'adminport')
        self.radiusd_host = self.config.has_option('radiusd','host') \
            and self.config.get('radiusd','host') or  '0.0.0.0'
        #parse dictfile
        self.dictfile = os.path.join(
            os.path.split(__file__)[0], 'dicts/dictionary')
        if self.config.has_option('radiusd', 'dictfile'):
            if os.path.exists(self.config.get('radiusd', 'dictfile')):
                self.dictfile = self.config.get('radiusd', 'dictfile')

        # update aescipher
        utils.aescipher.setup(self.secret)
        self.encrypt = utils.aescipher.encrypt
        self.decrypt = utils.aescipher.decrypt
        #parse ssl
        self._check_ssl_config()

    def init_timezone(self):
        try:
            os.environ["TZ"] = self.timezone
            time.tzset()
        except:
            pass

    def init_db_engine(self):
        if not self.db_engine:
            self.db_engine = get_engine(self.config)
        self.store = Store(self.config, self.db_engine)

    def reload_coa_clients(self):
        for bas in self.store.list_bas():

            if bas['ip_addr'] in self.coa_clients:
                self.coa_clients[bas['ip_addr']].close()

            self.coa_clients[bas['ip_addr']] = CoAClient(bas,
                                                         dictionary.Dictionary(
                                                             self.dictfile),
                                                         debug=self.debug)

    def init_protocol(self):
        # rundata
        self.trace = utils.UserTrace()
        self.runstat = utils.RunStat()
        self.midware = middleware.Middleware()
        # init coa clients
        self.coa_clients = {}
        for bas in self.store.list_bas():
            self.coa_clients[bas['ip_addr']] = CoAClient(bas,
                                                         dictionary.Dictionary(
                                                             self.dictfile),
                                                         debug=self.debug)
        self.auth_protocol = RADIUSAccess(self)
        self.acct_protocol = RADIUSAccounting(self)

        ws_url = "ws://%s:%s" % (self.radiusd_host, self.adminport)
        if self.use_ssl:
            ws_url = "wss://%s:%s" % (self.radiusd_host, self.adminport)

        self.admin_factory = WebSocketServerFactory(ws_url, debug=False)
        self.admin_factory.protocol = AdminServerProtocol
        self.admin_factory.setProtocolOptions(allowHixie76=True)
        self.admin_factory.protocol.radiusd = self

    def _check_online_over(self):
        reactor.callInThread(self.store.check_online_over)

    def init_task(self):
        _task = task.LoopingCall(self.auth_protocol.process_delay)
        _task.start(2.7)
        _online_task = task.LoopingCall(self._check_online_over)
        _online_task.start(3600 * 4)
        _msg_stat_task = task.LoopingCall(self.runstat.run_stat)
        _msg_stat_task.start(60)
        self.tasks['process_delay'] = _task
        self.tasks['check_online_over'] = _online_task

    def run_normal(self):
        if self.debug:
            log.startLogging(sys.stdout)
        else:
            log.startLogging(DailyLogFile.fromFullPath(self.logfile))
        log.msg('server listen %s' % self.radiusd_host)
        reactor.listenUDP(self.authport,
                          self.auth_protocol,
                          interface=self.radiusd_host)
        reactor.listenUDP(self.acctport,
                          self.acct_protocol,
                          interface=self.radiusd_host)
        if self.use_ssl:
            log.msg('WS SSL Enable!')
            from twisted.internet import ssl
            sslContext = ssl.DefaultOpenSSLContextFactory(
                self.privatekey, self.certificate)
            reactor.listenSSL(self.adminport,
                              self.admin_factory,
                              contextFactory=sslContext,
                              interface=self.radiusd_host)
        else:
            reactor.listenTCP(self.adminport,
                              self.admin_factory,
                              interface=self.radiusd_host)
        if not self.standalone:
            reactor.run()

    def get_coa_client(self, nasaddr):
        cli = self.coa_clients.get(nasaddr)
        if not cli:
            bas = self.store.get_bas(nasaddr)
            if bas:
                cli = CoAClient(bas,
                                dictionary.Dictionary(self.dictfile),
                                debug=self.debug)
                self.coa_clients[nasaddr] = cli
        return cli

    def get_service(self):
        from twisted.application import service, internet
        top_service = service.MultiService()

        internet.UDPServer(
            self.authport, self.auth_protocol,
            interface=self.radiusd_host).setServiceParent(top_service)

        internet.UDPServer(
            self.acctport, self.acct_protocol,
            interface=self.radiusd_host).setServiceParent(top_service)

        if self.use_ssl:
            log.msg('WS SSL Enable!')
            from twisted.internet import ssl
            sslContext = ssl.DefaultOpenSSLContextFactory(
                self.privatekey, self.certificate)
            internet.SSLServer(
                self.adminport,
                self.admin_factory,
                contextFactory=sslContext,
                interface=self.radiusd_host).setServiceParent(top_service)
        else:
            log.msg('WS SSL Disable!')
            internet.TCPServer(
                self.adminport,
                self.admin_factory,
                interface=self.radiusd_host).setServiceParent(top_service)
        return top_service
Exemplo n.º 36
0
}

switch_modes = {
    "on": False,
    "off": True
}


class HWRouter(WebSocketServerProtocol):
    def onConnect(self, request):
        print("Client connected")

    def onMessage(self, payload, isBinary):
        message = payload.decode('utf8').split(":")
        action, device = message[0], message[1]

        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(hw_pin_layout[message[1]], GPIO.OUT)
        GPIO.output(hw_pin_layout[message[1]], switch_modes[action])

    def onClose(self, wasClean, code, reason):
        print("Connection closed")


factory = WebSocketServerFactory("ws://localhost:5000", debug=False)
factory.protocol = HWRouter

reactor.listenTCP(5000, factory)
reactor.run()
Exemplo n.º 37
0
 def __init__(self, url):
     WebSocketServerFactory.__init__(self, url)
     # this dict has a key for each channel
     # values are list of clients.
     self.workspace_clients = defaultdict(list)
     self.tick()
Exemplo n.º 38
0
        print("WebSocket connection request: {}".format(request))

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)


if __name__ == '__main__':

    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False

    factory = WebSocketServerFactory("ws://127.0.0.1:8080",
                                     debug=debug,
                                     debugCodePaths=debug)

    factory.protocol = EchoServerProtocol
    factory.setProtocolOptions(
        allowHixie76=True)  # needed if Hixie76 is to be supported

    resource = WebSocketResource(factory)

    # we server static files under "/" ..
    root = File(".")

    # and our WebSocket server under "/ws"
    root.putChild("ws", resource)

    # both under one Twisted Web Site
Exemplo n.º 39
0
 def __init__(self, url, ruleEnvironment):
     WebSocketServerFactory.__init__(self, url)
     self.ruleEnvironment = ruleEnvironment
Exemplo n.º 40
0
                grabber_1.addCallback(dictionary_com__handler)
                grabber_1.addErrback(dictionary_com__fail)

            # This code runs unconditionally upon message. May trigger grabber 1.
            # GET webpage, and involke callback upon reciept of data
            grabber_2 = client.getPage(
                'http://www.collinsdictionary.com/dictionary/english/' +
                payload)
            grabber_2.addCallback(collinsdictionary_com__handler)
            grabber_2.addErrback(collinsdictionary_com__fail)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))


if __name__ == '__main__':

    import sys

    from twisted.python import log
    from twisted.internet import reactor

    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol
    # factory.setProtocolOptions(maxConnections=2)

    reactor.listenTCP(9000, factory)
    reactor.run()
Exemplo n.º 41
0
class Server(object):
    _DEFAULT_PORT = 9000
    _DEFAULT_KEYS_PATH = "../resources/keys"

    class Notifier(QtCore.QObject):
        different_user_requested = QtCore.Signal(str, int)

    def __init__(
        self,
        keys_path,
        encrypt,
        host,
        user_id,
        host_aliases,
        port=None,
        uses_intermediate_certificate_chain=False,
    ):
        """
        Constructor.

        :param keys_path: Path to the keys. If the path is relative, it will be relative to the
            current working directory. Mandatory
        :param encrypt: If True, the communication with clients will be encrypted.
        :param host: Url of the host we're expecting requests from.
        :param user_id: Id of the user we're expecting requests from.
        :param host_aliases: List of aliases available for the current host.
        :param port: Port to listen for websocket requests from.
        :param low_level_debug: If True, wss traffic will be written to the console.
        """
        self._port = port or self._DEFAULT_PORT
        self._keys_path = keys_path or self._DEFAULT_KEYS_PATH
        self._host = host
        self._user_id = user_id
        self._host_aliases = host_aliases
        self._uses_intermediate_certificate_chain = uses_intermediate_certificate_chain

        # If encryption is required, compute a server id and retrieve the secret associated to it.
        if encrypt:
            # urandom is considered cryptographically secure as it calls the OS's CSRNG, so we can
            # use that to generate our own server id.
            self._ws_server_id = six.ensure_str(
                base64.urlsafe_b64encode(os.urandom(16)))
        else:
            self._ws_server_id = None

        self.notifier = self.Notifier()

        if not os.path.exists(keys_path):
            raise MissingCertificateError(keys_path)

        twisted = get_logger("twisted")

        logger.debug("Browser integration using certificates at %s",
                     self._keys_path)
        logger.debug("Encryption: %s", encrypt)

        # This will take the Twisted logging and forward it to Python's logging.
        self._observer = log.PythonLoggingObserver(twisted.name)
        self._observer.start()

    def get_logger(self):
        """
        :returns: The python logger root for the framework.
        """
        return logger

    def _raise_if_missing_certificate(self, certificate_path):
        """
        Raises an exception is a certificate file is missing.

        :param certificate_path: Path to the certificate file.

        :raises Exception: Thrown if the certificate file is missing.
        """
        if not os.path.exists(certificate_path):
            raise MissingCertificateError("Missing certificate file: %s" %
                                          certificate_path)

    def _start_server(self):
        """
        Start shotgun web server, listening to websocket connections.

        :param debug: Boolean Show debug output. Will also Start local web server to test client pages.
        """
        cert_crt_path, cert_key_path = certificates.get_certificate_file_names(
            self._keys_path)

        self._raise_if_missing_certificate(cert_key_path)
        self._raise_if_missing_certificate(cert_crt_path)

        if self._uses_intermediate_certificate_chain:
            ctx_factory = ChainedOpenSSLContextFactory
        else:
            ctx_factory = ssl.DefaultOpenSSLContextFactory

        self.context_factory = ctx_factory(cert_key_path, cert_crt_path)

        # FIXME: Seems like the debugging flags are gone from the initializer at the moment.
        # We should try to restore these.
        self.factory = WebSocketServerFactory("wss://localhost:%d" %
                                              self._port)

        self.factory.protocol = ServerProtocol
        self.factory.host = self._host
        self.factory.host_aliases = self._host_aliases
        self.factory.user_id = self._user_id
        self.factory.notifier = self.notifier
        self.factory.ws_server_id = self._ws_server_id
        self.factory.setProtocolOptions(echoCloseCodeReason=True)
        try:
            self.listener = listenWS(self.factory, self.context_factory)
        except error.CannotListenError as e:
            raise PortBusyError(str(e))

    def _start_reactor(self):
        """
        Starts the reactor in a Python thread.
        """
        def start():
            reactor.run(installSignalHandlers=0)

        self._reactor_thread = threading.Thread(target=start)
        self._reactor_thread.start()

    def start(self):
        """
        Start shotgun web server, listening to websocket connections.
        """
        self._start_server()
        self._start_reactor()

    def is_running(self):
        """
        :returns: True if the server is up and running, False otherwise.
        """
        return self._reactor_thread.isAlive()

    def tear_down(self):
        """
        Tears down Twisted.
        """
        reactor.callFromThread(reactor.stop)
        self._reactor_thread.join()
Exemplo n.º 42
0
    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

        # echo back message verbatim
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))


if __name__ == '__main__':

    import sys

    from twisted.python import log
    from twisted.internet import reactor

    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory("ws://localhost:9000", debug=False)
    factory.protocol = MyServerProtocol
    # factory.setProtocolOptions(maxConnections=2)

    reactor.listenTCP(9000, factory)
    reactor.run()
Exemplo n.º 43
0

if __name__ == '__main__':

    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False

    wsPort = 9000

    # Our WebSocket server
    ##
    factory = WebSocketServerFactory(u"ws://127.0.0.1:%d" % wsPort,
                                     debug=debug,
                                     debugCodePaths=debug)

    factory.protocol = EchoServerProtocol
    listenWS(factory)

    # We need to start a "Flash Policy Server" on TCP/843
    # which Adobe Flash player will contact to check if
    # it is allowed to connect to the WebSocket port.
    ##
    flashPolicyFactory = FlashPolicyFactory()
    reactor.listenTCP(843, flashPolicyFactory)

    # Static Web server
    ##
    webdir = File("./web")
Exemplo n.º 44
0
	def __init__(self, url):
		WebSocketServerFactory.__init__(self, url)
		self.client = None
Exemplo n.º 45
0
        else:
            yield sleep(1)
            returnValue(x * x)

    @inlineCallbacks
    def onMessage(self, payload, isBinary):
        if not isBinary:
            x = json.loads(payload.decode('utf8'))
            try:
                res = yield self.slowsquare(x)
            except Exception as e:
                self.sendClose(1000, "Exception raised: {0}".format(e))
            else:
                self.sendMessage(json.dumps(res).encode('utf8'))


if __name__ == '__main__':

    import sys

    from twisted.python import log
    from twisted.internet import reactor

    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = SlowSquareServerProtocol

    reactor.listenTCP(9000, factory)
    reactor.run()
from twisted.python import log
from twisted.web.server import Site
from twisted.web.static import File

from autobahn.twisted.websocket import WebSocketServerFactory, \
    WebSocketServerProtocol, \
    listenWS

from autobahn.twisted.resource import WebSocketResource


if __name__ == '__main__':

    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory("ws://localhost:9000", debug=False, debugCodePaths=True)
    factory.protocol = WebSocketServerProtocol

    factory.setProtocolOptions(autoPingInterval=1, autoPingTimeout=3, autoPingSize=20)

    listenWS(factory)

    resource = WebSocketResource(factory)

    root = File(".")
    root.putChild("ws", resource)
    site = Site(root)

    reactor.listenTCP(8080, site)

    reactor.run()
Exemplo n.º 47
0
def create_log_streaming_resource():
    factory = WebSocketServerFactory()
    factory.protocol = TokenAuthenticatedWebSocketServerProtocol
    return WebSocketResource(factory)
Exemplo n.º 48
0
 def __init__(self, master):
     WebSocketServerFactory.__init__(self)
     self.master = master
Exemplo n.º 49
0
 def __init__(self, uri, debug=False, assets='./'):
     WebSocketServerFactory.__init__(self, uri, debug=debug)
     self._peers = WeakKeyDictionary()
     self.assets = assets
Exemplo n.º 50
0
    def onConnect(self, request):
        print("WebSocket connection request by {}".format(request.peer))

    def onOpen(self):
        print("WebSocket extensions in use: {}".format(self.websocket_extensions_in_use))

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)


if __name__ == '__main__':

    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory("ws://127.0.0.1:9000")
    factory.protocol = EchoServerProtocol

    # Enable WebSocket extension "permessage-deflate".

    # Function to accept offers from the client ..
    def accept(offers):
        for offer in offers:
            if isinstance(offer, PerMessageDeflateOffer):
                return PerMessageDeflateOfferAccept(offer)

    factory.setProtocolOptions(perMessageCompressionAccept=accept)

    # run server
    listenWS(factory)
Exemplo n.º 51
0
                            (epoch_time, int(data_parsed[2])))
                    sensor2.commit()

            if data_parsed[0] == "USERDATA":
                if data_parsed[1] in webClients:
                    webClients[data_parsed[1]].sendMessage(data_parsed[2] +
                                                           "-" +
                                                           data_parsed[3])

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))


if __name__ == '__main__':

    import sys

    from twisted.python import log
    from twisted.internet import reactor

    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory(u"ws://sp.ebiw.com:9000")
    factory.protocol = MyServerProtocol

    reactor.listenTCP(9000, factory)
    reactor.run()

sensor1.close()
sensor2.close()
Exemplo n.º 52
0
from autobahn.twisted.resource import WebSocketResource


class EchoServerProtocol(WebSocketServerProtocol):
    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)


if __name__ == '__main__':

    log.startLogging(sys.stdout)

    contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key',
                                                      'keys/server.crt')

    factory = WebSocketServerFactory(u"wss://127.0.0.1:8080")
    factory.protocol = EchoServerProtocol

    resource = WebSocketResource(factory)

    # we server static files under "/" ..
    root = File(".")

    # and our WebSocket server under "/ws" (note that Twisted uses
    # bytes for URIs)
    root.putChild(b"ws", resource)

    # both under one Twisted Web Site
    site = Site(root)

    reactor.listenSSL(8080, site, contextFactory)
Exemplo n.º 53
0
                        action="store_true",
                        help="Enable debug output.")

    parser.add_argument(
        "--endpoint",
        default="tcp:8080",
        help=
        'WebSocket server Twisted endpoint descriptor, e.g. "tcp:127.0.0.1:8080" or "unix:/tmp/mywebsocket".'
    )

    parser.add_argument(
        "--url",
        default=u"ws://localhost:8080/ws",
        help=
        'WebSocket URL (must suit the endpoint), e.g. ws://localhost:8080/ws.')

    args = parser.parse_args()

    if args.debug:
        txaio.start_logging(level='debug')
    else:
        txaio.start_logging(level='info')

    factory = WebSocketServerFactory(args.url, reactor=reactor)
    factory.protocol = MyServerProtocol

    server = serverFromString(reactor, args.endpoint)
    server.listen(factory)

    reactor.run()
Exemplo n.º 54
0
 def __init__(self, chute, *args, **kwargs):
     WebSocketServerFactory.__init__(self, *args, **kwargs)
     self.chute = chute
Exemplo n.º 55
0
def connection_main(sysargs=None, use_files=True):
    """Main entry point to setup a connection node, aka the autopush script"""
    args, parser = _parse_connection(sysargs, use_files)
    log_format = "text" if args.human_logs else "json"
    log_level = args.log_level or ("debug" if args.debug else "info")
    sentry_dsn = bool(os.environ.get("SENTRY_DSN"))
    PushLogger.setup_logging(
        "Autopush",
        log_level=log_level,
        log_format=log_format,
        log_output=args.log_output,
        sentry_dsn=sentry_dsn,
        firehose_delivery_stream=args.firehose_stream_name)
    settings = make_settings(
        args,
        port=args.port,
        endpoint_scheme=args.endpoint_scheme,
        endpoint_hostname=args.endpoint_hostname,
        endpoint_port=args.endpoint_port,
        router_scheme="https" if args.router_ssl_key else "http",
        router_hostname=args.router_hostname,
        router_port=args.router_port,
        env=args.env,
        hello_timeout=args.hello_timeout,
    )

    r = RouterHandler
    r.ap_settings = settings
    n = NotificationHandler
    n.ap_settings = settings

    # Internal HTTP notification router
    site = cyclone.web.Application([
        (r"/push/([^\/]+)", r),
        (r"/notif/([^\/]+)(/([^\/]+))?", n),
    ],
                                   default_host=settings.router_hostname,
                                   debug=args.debug,
                                   log_function=skip_request_logging)
    mount_health_handlers(site, settings)

    # Public websocket server
    proto = "wss" if args.ssl_key else "ws"
    factory = WebSocketServerFactory(
        "%s://%s:%s/" % (proto, args.hostname, args.port), )
    factory.protocol = PushServerProtocol
    factory.protocol.ap_settings = settings
    factory.setProtocolOptions(
        webStatus=False,
        openHandshakeTimeout=5,
        autoPingInterval=args.auto_ping_interval,
        autoPingTimeout=args.auto_ping_timeout,
        maxConnections=args.max_connections,
        closeHandshakeTimeout=args.close_handshake_timeout,
    )
    settings.factory = factory

    settings.metrics.start()

    # Wrap the WebSocket server in a default resource that exposes the
    # `/status` handler, and delegates to the WebSocket resource for all
    # other requests.
    resource = DefaultResource(WebSocketResource(factory))
    resource.putChild("status", StatusResource())
    siteFactory = Site(resource)

    # Start the WebSocket listener.
    if args.ssl_key:
        contextFactory = AutopushSSLContextFactory(args.ssl_key, args.ssl_cert)
        if args.ssl_dh_param:
            contextFactory.getContext().load_tmp_dh(args.ssl_dh_param)

        reactor.listenSSL(args.port, siteFactory, contextFactory)
    else:
        reactor.listenTCP(args.port, siteFactory)

    # Start the internal routing listener.
    if args.router_ssl_key:
        contextFactory = AutopushSSLContextFactory(args.router_ssl_key,
                                                   args.router_ssl_cert)
        if args.ssl_dh_param:
            contextFactory.getContext().load_tmp_dh(args.ssl_dh_param)
        reactor.listenSSL(args.router_port, site, contextFactory)
    else:
        reactor.listenTCP(args.router_port, site)

    reactor.suggestThreadPoolSize(50)

    l = task.LoopingCall(periodic_reporter, settings)
    l.start(1.0)

    # Start the table rotation checker/updater
    l = task.LoopingCall(settings.update_rotating_tables)
    l.start(60)
    reactor.run()
Exemplo n.º 56
0
                        "w": w,
                        "h": h,
                        "ex": ex,
                        "ey": ey,
                        "ew": ew,
                        "eh": eh
                    }
                    allEyes.append(eyeDict)
                    #cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

            eyesDto = json.dumps(allEyes)
            self.sendMessage(eyesDto)

        #self.sendMessage("got it!", isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))


if __name__ == '__main__':

    import sys

    from twisted.python import log
    from twisted.internet import reactor

    log.startLogging(sys.stdout)
    factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = GooglySocketProtocol
    reactor.listenTCP(9000, factory)
    reactor.run()
Exemplo n.º 57
0
            ):  #Multiple Image displaying algorithms can be added below
            #Replace your own code here. Below is a simple example

            img = cv2.imread('res/facetest.jpg')

            #The code below sends the image to the Image viewer. DO NOT DELETE
            #the image is passed to the encoder as img, you can pass any other image matrix
            encode_param = [1, 90]
            res, image = cv2.imencode('.jpg', img, encode_param)
            sample = base64.b64encode(image)
            self.sendMessage(sample, isBinary)

        #if (message == '2'): #add extra algorithm like this

    def onClose(self, wasClean, code,
                reason):  #Message displayed when there is an error
        print format(reason)


#Start Websocket Server
if __name__ == '__main__':
    import sys
    from twisted.internet import reactor

    factory = WebSocketServerFactory(
        "ws://localhost:5555")  #Set debug false to save on processing time
    factory.protocol = MyServerProtocol

    reactor.listenTCP(5555, factory)
    reactor.run()
Exemplo n.º 58
0

if __name__ == '__main__':

    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False

    # SSL server context: load server key and certificate
    # We use this for both WS and Web!
    #
    contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key',
                                                      'keys/server.crt')

    factory = WebSocketServerFactory(u"wss://127.0.0.1:9000",
                                     debug=debug,
                                     debugCodePaths=debug)

    factory.protocol = EchoServerProtocol
    listenWS(factory, contextFactory)

    webdir = File(".")
    webdir.contentTypes['.crt'] = 'application/x-x509-ca-cert'
    web = Site(webdir)
    # reactor.listenSSL(8080, web, contextFactory)
    reactor.listenTCP(8080, web)

    reactor.run()
Exemplo n.º 59
0
 def __init__(self, update, *args, **kwargs):
     WebSocketServerFactory.__init__(self, *args, **kwargs)
     self.update = update
Exemplo n.º 60
0
 def __init__(self, url, bridge):
     WebSocketServerFactory.__init__(self, url)
     self.frame = None
     self.connections = {}
     self.bridge = bridge
     self.rec = Recognition()