Example #1
0
def onConnect():
    if not options['noshell']:
        conn.openChannel(SSHSession())
    if options.localForwards:
        for localPort, hostport in options.localForwards:
            reactor.listenTCP(localPort,
                        forwarding.SSHListenForwardingFactory(conn,
                            hostport,
                            SSHListenClientForwardingChannel))
    if options.remoteForwards:
        for remotePort, hostport in options.remoteForwards:
            log.msg('asking for remote forwarding for %s:%s' %
                    (remotePort, hostport))
            data = forwarding.packGlobal_tcpip_forward(
                ('0.0.0.0', remotePort))
            d = conn.sendGlobalRequest('tcpip-forward', data)
            conn.remoteForwards[remotePort] = hostport
    if options['fork']:
        if os.fork():
            os._exit(0)
        os.setsid()
        for i in range(3):
            try:
                os.close(i)
            except OSError, e:
                import errno
                if e.errno != errno.EBADF:
                    raise
	def start(self):
		self.zeroconf.publish()
		try:
			self.atconn = reactor.listenTCP(AIRTUNES_PORT, self.atsite, interface="::")
		except Exception:
			print "[SIFTeam OpenAirPlay] cannot bind airtunes server on ipv6 interface"
			self.atconn = None
			
		if self.atconn is None:
			try:
				self.atconn = reactor.listenTCP(AIRTUNES_PORT, self.atsite)
			except Exception:
				self.atconn = None
				self.apconn = None
				print "[SIFTeam OpenAirPlay] cannot start airtunes server"
				return
			
		try:
			self.apconn = reactor.listenTCP(AIRPLAY_PORT, self.apsite, interface="::")
		except Exception:
			print "[SIFTeam OpenAirPlay] cannot bind airplay server on ipv6 interface"
			self.apconn = None
			
		if self.apconn is None:
			try:
				self.apconn = reactor.listenTCP(AIRPLAY_PORT, self.apsite)
			except Exception:
				self.atconn.stopListening()
				self.atconn = None
				self.apconn = None
				print "[SIFTeam OpenAirPlay] cannot start airplay server"
				return
			
		print "[SIFTeam OpenAirPlay] server started"
Example #3
0
def run(port, hostname, interface, verbosity):
    if verbosity == 0: # -q
        level = logging.CRITICAL
    elif verbosity == 1: # default
        level = logging.WARNING
    elif verbosity == 2: # -v
        level = logging.INFO
    else: # -v -v
        level = logging.DEBUG
    logging.basicConfig(level=level)

    if hostname:
        if not hostname.startswith('http://'):
            hostname = 'http://%s' % (hostname,)
        sep = hostname.find('/')
        if sep != -1:
            hostname = hostname[:sep]
        if port != 80 and not ':' in hostname:
            hostname = "http://%s:%d/" % (hostname, port)
        else:
            hostname = "http://%s/" % hostname
        logging.info('Hostname set to %s' % hostname)

    pong = PongGame()

    reactor.listenTCP(port, HttpFactory(hostname, pong), interface=interface)
    reactor.run()
Example #4
0
	def __init__(self, password = None, port = 9000):
		'''
		Creates and Agent instance and attemps to connect
		to the AgentMaster.  If connection works the Client Hello message
		is sent.
		
		@type	password: string
		@param	password: Password to use
		'''
		
		from twisted.internet import reactor
		agent = AgentXmlRpc()
		
		agent._password = password
		agent._monitors = []
		agent._publishers = {}
		agent._id = None
		
		print "] Peach Agent\n"
		
		if agent._password != None:
			print "\n //-> Listening on [%s] with password [%s]\n" % (port, agent._password)
		else:
			print "\n //-> Listening on [%s] with no password\n" % (port)
		
		reactor.listenTCP(port, server.Site(agent))
		reactor.run()
Example #5
0
 def __init__(self, lm, port=12346, n=0):
     """n indicates the n-gram size, if set to 0 (which is default), the server will expect to only receive whole sentence, if set to a particular value, it will only expect n-grams of that value"""
     if n == 0:
         reactor.listenTCP(port, LMSentenceFactory(lm))
     else:
         reactor.listenTCP(port, LMNGramFactory(lm))
     reactor.run()
Example #6
0
    def run(self):
        self.factory = HTTPFactory(
            self.channel_layer,
            self.action_logger,
            timeout=self.http_timeout,
            websocket_timeout=self.websocket_timeout,
            ping_interval=self.ping_interval,
            ws_protocols=self.ws_protocols,
            root_path=self.root_path,
        )
        # Redirect the Twisted log to nowhere
        globalLogBeginner.beginLoggingTo([lambda _: None], redirectStandardIO=False, discardBuffer=True)
        # Listen on a socket
        if self.unix_socket:
            reactor.listenUNIX(self.unix_socket, self.factory)
        elif self.file_descriptor:
            # socket returns the same socket if supplied with a fileno
            sock = socket.socket(fileno=self.file_descriptor)
            reactor.adoptStreamPort(self.file_descriptor, sock.family, self.factory)
        else:
            reactor.listenTCP(self.port, self.factory, interface=self.host)

        if "twisted" in self.channel_layer.extensions:
            logging.info("Using native Twisted mode on channel layer")
            reactor.callLater(0, self.backend_reader_twisted)
        else:
            logging.info("Using busy-loop synchronous mode on channel layer")
            reactor.callLater(0, self.backend_reader_sync)
        reactor.callLater(2, self.timeout_checker)
        reactor.run(installSignalHandlers=self.signal_handlers)
Example #7
0
def main():
	factory = protocol.ServerFactory()      # 实例化一个ServerFactory对象
	factory.protocol = Echo     # 重写protocol

	# reactor(反应堆)就是twisted的事件驱动,是twisted的核心.
	reactor.listenTCP(1234, factory)  # 将factory回调函数注册到reactor中,reactor监听指定端口,根据状态来触发factory中不同的方法
	reactor.run()   # 启动一个TCP服务器, 监听1234端口,reactor则开始监听。
Example #8
0
    def _testServerStartStop(self, ignored, f, p1):
        self.assertEquals((f.started, f.stopped), (1,0))
        # listen on two more ports
        p2 = reactor.listenTCP(0, f, interface='127.0.0.1')
        self.n2 = p2.getHost().port
        self.ports.append(p2)
        p3 = reactor.listenTCP(0, f, interface='127.0.0.1')
        self.n3 = p3.getHost().port
        self.ports.append(p3)
        d = loopUntil(lambda :(p2.connected == 1 and p3.connected == 1))
        
        def cleanup(x):
            self.assertEquals((f.started, f.stopped), (1, 0))
            # close two ports
            d1 = defer.maybeDeferred(p1.stopListening)
            d2 = defer.maybeDeferred(p2.stopListening)
            return defer.gatherResults([d1, d2])
        
        def assert1(ignored):
            self.assertEquals((f.started, f.stopped), (1, 0))
            return p3.stopListening()

        def assert2(ignored):
            self.assertEquals((f.started, f.stopped), (1, 1))
            return self.cleanPorts(*self.ports)

        d.addCallback(cleanup)
        d.addCallback(assert1)
        d.addCallback(assert2)
        return d
Example #9
0
 def init_api(self):
     log.msg('Starting HTTP on %s...' % self.interface)
     root = resource.Resource()
     root.putChild("send", APISendResource(self))
     site = server.Site(root, logPath='/dev/null')
     host, port = self.interface.split(':')
     reactor.listenTCP(int(port), site, interface=host)
def main():
    global cbUrls, tsunamiUrl
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option(
        "-t",
        "--tsunami",
        dest="tsunami",
        type="string",
        default="http://127.0.0.1:9000",
        help="tsunami announce url. default: http://127.0.0.1:9000"
    )
    parser.add_option(
        "-p",
        "--port",
        dest="port",
        type="int",
        default=5000,
        help="port the RestQ demonstration resource should bind to. default: 5000"
    )
    options = parser.parse_args()[0]
    cbUrls = {
        'connect':'http://localhost:%s/connect'%options.port,
        'disconnect':'http://localhost:%s/disconnect'%options.port,
        'subscribe':'http://localhost:%s/subscribe'%options.port,
        'unsubscribe':'http://localhost:%s/unsubscribe'%options.port,
        'send':'http://localhost:%s/send'%options.port
    }
    tsunamiUrl = options.tsunami
    site = server.Site(RestQDummyResource())
    print 'running on %s'%options.port
    reactor.listenTCP(options.port, site)
    reactor.run()
Example #11
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--port')
  parser.add_argument('--store')
  parser.add_argument('--retrieve')
  parser.add_argument('--connect', default=None)

  args = parser.parse_args()
  port = int(args.port)

  service = ChordService()

  if (args.connect):
    dst = args.connect.split(':')
    service.AddToRoutingTable(IPv4Address('TCP', dst[0], int(dst[1])))

  if (args.store):
    key, value = args.store.split(':')
    service.StoreValue(key, value)
    
  if (args.retrieve):
    def EchoValue(value):
      print('Retrieved value: {}.'.format(value))
    d = service.GetValue(args.retrieve)
    d.addCallback(EchoValue)

  f = pb.PBServerFactory(service)
  reactor.listenTCP(port, f)
    
  reactor.run()
 def createForwardServer(self, session):
   from twisted.internet import reactor
   server_factory = forwardServerFactory(session, self)
   rndm = self.randomPort()
   reactor.listenTCP(rndm, server_factory)
   print 'listening at:',rndm
   return rndm
Example #13
0
def run(create_publisher, host='', port=80):
    """Runs a Twisted HTTP server server that publishes a Quixote
    application."""
    publisher = create_publisher()
    factory = QuixoteFactory(publisher)
    reactor.listenTCP(port, factory, interface=host)
    reactor.run()
Example #14
0
    def init_tests(self):
        """ Initialize testing infrastructure - sockets, resource limits, etc. """
        # Init Twisted factory.
        self.server_factory = network.TestServerFactory(controller = self)
        #self.client_factory = TestClientFactory(controller = self)

        ports = sorted(self.test_ports)
        log.notice("Binding to test ports: %s", ", ".join(map(str, ports)))
        # Sort to try privileged ports first, since sets have no
        # guaranteed ordering.
        for port in ports:
            reactor.listenTCP(port, self.server_factory)

        # Set RLIMIT_NOFILE to its hard limit; we want to be able to
        # use as many file descriptors as the system will allow.
        # NOTE: Your soft/hard limits are inherited from the root user!
        # The root user does NOT always have unlimited file descriptors.
        # Take this into account when editing /etc/security/limits.conf.
        (soft, hard) = resource.getrlimit(resource.RLIMIT_NOFILE)
        log.verbose1("RLIMIT_NOFILE: soft = %d, hard = %d", soft, hard) 
        if soft < hard:
            log.debug("Increasing RLIMIT_NOFILE soft limit to %d.", hard)
            resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard))                

        log.debug("Initializing test threads.")
        # TODO: Configure me!
        scheduler_class = getattr(scheduler, config.scheduler)
        self.scheduler = scheduler_class(controller = self,
                                         max_pending_factor = config.max_pending_factor,
                                         export_interval = config.export_interval)
        T = threading.Thread
        self.schedule_thread = T(target = Controller.test_schedule_thread,
                                 name = "Scheduler", args = (self,))
        self.watchdog_thread = T(target = Controller.watchdog,
                                 name = "Watchdog", args = (self,))
Example #15
0
def main():
    # command line processing
    process_commandline()

    call_list_server = None
    # run the call list providing web server in listening mode
    if CONFIG["LISTEN"]:
        call_list_server = CallListServer()
        site = http_server.Site(call_list_server)
        try:
            reactor.listenTCP(CONFIG["HTTP_PORT"], site, interface=CONFIG["HTTP_HOST"])
        except:
            # port could not be bound
            # (already in use, permission denied, ...)
            call_list_server = None
        else:
            dprint("running call list web server on 'http://{HTTP_HOST}:{HTTP_PORT}'".format(**CONFIG))

    # configure notifications
    enable_notifcations(
        not CONFIG["DISABLE_NOTIFICATIONS"],
        # 'All recent calls...' link only when the call list webserver
        # is running
        call_list_server,
    )

    # start the client
    reactor.connectTCP(
        CONFIG["NCID_HOST"], CONFIG["NCID_PORT"], NCIDClientFactory(reactor, CONFIG["LISTEN"], call_list_server)
    )

    # run the event dispatcher
    reactor.run()

    dprint("done.")
Example #16
0
 def __init__(self):
     # create a Command Queue, Client Manager, and Default Data Context
     self.commandQueue=CommandQueue()
     self.clientManager=ClientManager()
     self.dataContexts={'default':DataContext('default')}
     # create a TCP socket listener (called a factory by twisted)
     self.listener=GlabServerFactory()
     self.listener.parent=self
     # associate the CommandProtocol as a response method on that socket
     self.listener.protocol=CommandProtocol
     # tell the twisted reactor what port to listen on, and which factory to use for response protocols
     global port        
     reactor.listenTCP(port, self.listener)
     def hello(): print 'Listening on port', port
     reactor.callWhenRunning(hello)
     # associate the Command Queue and ClienManager with the socket listener
     self.listener.associateCommandQueue(self.commandQueue)
     self.listener.associateClientManager(self.clientManager)
     # create a periodic command queue execution
     self.queueCommand=task.LoopingCall(self.commandQueue.popexecute)
     self.queueCommand.start(0.03)
     self.initdisplay()
     #self.refreshdisplay=task.LoopingCall(self.display.refresh)
     #self.refreshdisplay.start(0.5)
     # run the main response loop through twisted framework
     reactor.run()
Example #17
0
    def _listen_http(self, listener_config):
        port = listener_config["port"]
        bind_address = listener_config.get("bind_address", "")
        site_tag = listener_config.get("tag", port)
        resources = {}
        for res in listener_config["resources"]:
            for name in res["names"]:
                if name == "metrics":
                    resources[METRICS_PREFIX] = MetricsResource(self)
                elif name == "federation":
                    resources.update({
                        FEDERATION_PREFIX: TransportLayerServer(self),
                    })

        root_resource = create_resource_tree(resources, Resource())
        reactor.listenTCP(
            port,
            SynapseSite(
                "synapse.access.http.%s" % (site_tag,),
                site_tag,
                listener_config,
                root_resource,
            ),
            interface=bind_address
        )
        logger.info("Synapse federation reader now listening on port %d", port)
def main(args):
    parent = map(Proxy, args.parent_url)
    aux_urls = args.aux_urls or ['http://*****:*****@127.0.0.1:8342/']
    auxs = [Proxy(url) for url in aux_urls]
    if args.merkle_size is None:
        for i in range(8):
            if (1<<i) > len(aux_urls):
                args.merkle_size = i
                logger.info('merkle size = %d', i)
                break

    if len(aux_urls) > args.merkle_size:
        raise ValueError('the merkle size must be at least as large as the number of aux chains')

    if args.merkle_size > 1 and not have_merkletree:
        raise ValueError('Missing merkletree module. Only a single subchain will work.')

    if args.pidfile:
        pidfile = open(args.pidfile, 'w')
        pidfile.write(str(os.getpid()))
        pidfile.close()

    listener = Listener(parent, auxs, args.merkle_size, args.rewrite_target)
    listener.update_aux_process()
    reactor.listenTCP(args.worker_port, server.Site(listener))
Example #19
0
def main():
        try:
                opts, args = getopt.getopt(sys.argv[1:], "hp:ndv", ["help", "port=", "no-server", "debug", "version"])
        except getopt.GetoptError:
                print_help()
        
        server = True
        for o, a in opts:
                if o in ("-h", "--help"):
                        print_help()
                if o in ("-d", "--debug"):
                        g_display.window.set_title('Session Exchange: Debug Mode')
                        g_data.debug_mode = True
                if o in ("-p", "--port"):
                        g_data.port = int(a)
                if o in ("-n", "--no-server"):
                        server = False
                if o in ("-v", "--version"):
                        print VERSION
                        sys.exit(2)
        
        if (server):
                try:
                        reactor.listenTCP(g_data.port, ExchangeServerFactory())
                except twisted.internet.error.CannotListenError:
                        print "Can not listen on a port number under 1024 unless run as root"
                        sys.exit(2)

        reactor.run()

        g_data.close()
Example #20
0
 def run(self):
     self.factory = get_factory(WebSocketServerFactory)("ws://0.0.0.0:%i" % self.port, debug=False)
     self.factory.protocol = get_protocol(WebSocketServerProtocol)
     reactor.listenTCP(self.port, self.factory)
     reactor.callInThread(self.backend_reader)
     reactor.callLater(1, self.keepalive_sender)
     reactor.run()
Example #21
0
 def __init__(self, config, port=None):
     super(IdentityServer, self).__init__(config)
     self.plugin_mapping = config["plugin_mapping"]
     self.setupMySQL(config)
     self.setupIdentityQueue(config)
     self.cassandra_cf_identity = config["cassandra_cf_identity"]
     self.cassandra_cf_connections = config["cassandra_cf_connections"]
     self.cassandra_cf_recommendations = config["cassandra_cf_recommendations"]
     self.cassandra_cf_reverse_recommendations = config["cassandra_cf_reverse_recommendations"]
     self.cassandra_client = CassandraClusterPool(
         config["cassandra_servers"],
         keyspace=config["cassandra_keyspace"],
         pool_size=len(config["cassandra_servers"]) * 2)
     self.cassandra_client.startService()
     resource = Resource()
     self.function_resource = Resource()
     resource.putChild("function", self.function_resource)
     if port is None:
         port = config["identity_server_port"]
     self.site_port = reactor.listenTCP(port, server.Site(resource))
     self.expose(self.updateConnections)
     self.expose(self.updateAllConnections)
     self.expose(self.updateAllIdentities)
     self.expose(self.getRecommendations)
     self.expose(self.getReverseRecommendations)
     self.expose(self.updateIdentity)
     # setup manhole
     manhole_namespace = {
         'service': self,
         'globals': globals(),
     }
     reactor.listenTCP(config["manhole_identity_port"], self.getManholeFactory(manhole_namespace, admin=config["manhole_password"]))
Example #22
0
    def _setupDistribServer(self, child):
        """
        Set up a resource on a distrib site using L{ResourcePublisher}.

        @param child: The resource to publish using distrib.

        @return: A tuple consisting of the host and port on which to contact
            the created site.
        """
        distribRoot = resource.Resource()
        distribRoot.putChild("child", child)
        distribSite = server.Site(distribRoot)
        self.f1 = distribFactory = PBServerFactory(
            distrib.ResourcePublisher(distribSite))
        distribPort = reactor.listenTCP(
            0, distribFactory, interface="127.0.0.1")
        self.addCleanup(distribPort.stopListening)
        addr = distribPort.getHost()

        self.sub = mainRoot = distrib.ResourceSubscription(
            addr.host, addr.port)
        mainSite = server.Site(mainRoot)
        mainPort = reactor.listenTCP(0, mainSite, interface="127.0.0.1")
        self.addCleanup(mainPort.stopListening)
        mainAddr = mainPort.getHost()

        return mainPort, mainAddr
Example #23
0
def do_listening():
	print "Listening for sensors..."
	reactor.listenTCP(SENSORPORT, SensorFactory())
	try:
		reactor.run(installSignalHandlers=0)
	except ReactorAlreadyRunning, e:
		pass
Example #24
0
def init(args):
    # hook events
    if args["--kill"]:
        s_events.gotRequest += kill
    if args["--auth"]:
        s_events.gotRequest += auth
        
    if args["--inject"]:
        c_events.gotResponseTree += inject
    if args["--beef"]:
        c_events.gotResponseTree += beef
    if args["--cats"]:
        c_events.gotResponseTree += cats
        
    if args["--upsidedown"]:
       c_events.gotResponseImage += upsidedown
       
    # start servers
    if args["--cats"] or args["--inject"]:
        datafolder = os.path.join(os.path.dirname(__file__), "data")
        reactor.listenTCP(FILEPORT, fileserver.Site( \
                fileserver.Data(datafolder)))
        log.info("starting file server on %s:%s" %(IP, FILEPORT))
    
    if args["--beef"]:
        Popen(["gnome-terminal", "-e", "./startbeef"])
        log.info("starting beef server on %s" %BEEFPORT)
Example #25
0
 def startup_routine(self):
     indexContent = False
     yes = set(['', 'Y', 'y', 'Yes', 'yes', 'YES'])
     no = set(['N', 'n', 'No', 'no', 'NO'])
     index_on_startup = False
     print("Type 'help' for help.")
     while True:
         print(">> ", end="")
         user_input = str(raw_input())
         if user_input == 'help': # Print available commands to user.
             print()
             print("         <command>   -       <description>")
             print("         help        -       Help.")
             print("         reset       -       Reset index database.")
             print("         init        -       Index all articles from content service on startup.")
             print("         start       -       Start service.")
             print("         exit        -       Quit.")
             print()
         elif user_input == 'reset': # Clearing tables in the index database.
             print("This will delete any existing data and reset the database.")
             print("Are you sure you want to continue? [Y/n] ", end="")
             while True:
                 user_input = str(raw_input())
                 if user_input in yes:
                     self.index_database.make_tables("wordfreq", {"articleid" : "VARCHAR", "word" : "VARCHAR", "frequency" : "INTEGER"}, "(articleid, word)")
                     print("Reset.")
                     break
                 else:
                     print("Abort.")
                     break
         elif user_input == 'init': # Toggle on/off indexing on startup.
             while True:
                 print("Do you want to index all the articles on startup? [Y/n] ", end="") 
                 user_input = str(raw_input())
                 if user_input in yes:
                     index_on_startup = True
                     print("Indexing will begin on start.")
                     break
                 elif user_input in no:
                     print("Indexing will not begin on start.")
                     index_on_startup = False
                     break
                 else:
                     print("Abort.")
                     break
         elif user_input == 'start': # Start indexing service.
             print("Starting index service. Use Ctrl + c to quit.")
             if index_on_startup:
                 host = self.get_service_ip(config.content_module_name)
                 self.index_all_articles(host)
             reactor.listenTCP(config.server_port, server.Site(self))
             reactor.run()
             break
         elif user_input == 'exit': # End program.
             break
         elif user_input == '': # Yes is default on return.
             continue
         else:
             print(user_input + ": command not found")
             continue
Example #26
0
def run(**settings):
    """Start the application.

    Parameters:

    host: Interface to listen on. [default: 0.0.0.0]

    port: TCP port to listen on. [default: 8888]

    log: The log file to use, the default is sys.stdout.

    base_handler: The class or factory for request handlers. The default
                  is cyclone.web.RequestHandler.

    more_handlers: A regular list of tuples containing regex -> handler

    All other parameters are passed directly to the `cyclone.web.Application`
    constructor.
    """

    port = settings.get("port", 8888)
    interface = settings.get("host", "0.0.0.0")
    log.startLogging(settings.pop("log", sys.stdout))
    reactor.listenTCP(port, create_app(**settings), interface=interface)
    reactor.run(installSignalHandlers = False)
Example #27
0
def main(keys_path, username_get=None, gid=None, port=2022):
    settings.username_get = username_get
    settings.gid = gid
    key_path = keys_path + '/id_rsa'

    if not os.path.exists(key_path):
        subprocess.check_call(['ssh-keygen', '-f', key_path,
                               '-t', 'rsa', '-N', ''])

    with open(key_path) as privateBlobFile:
        privateBlob = privateBlobFile.read()
        privateKey = Key.fromString(data=privateBlob)

    with open(key_path + '.pub') as publicBlobFile:
        publicBlob = publicBlobFile.read()
        publicKey = Key.fromString(data=publicBlob)

    factory = SSHFactory()
    factory.privateKeys = {'ssh-rsa': privateKey}
    factory.publicKeys = {'ssh-rsa': publicKey}
    factory.portal = Portal(KeyRealm())
    factory.portal.registerChecker(KeyChecker())

    reactor.listenTCP(port, factory)
    reactor.run()
Example #28
0
def splash_server(portnum, slots, network_manager, get_splash_proxy_factory=None,
                  js_profiles_path=None, disable_proxy=False, proxy_portnum=None):
    from twisted.internet import reactor
    from twisted.web.server import Site
    from splash.resources import Root
    from splash.pool import RenderPool
    from twisted.python import log

    slots = defaults.SLOTS if slots is None else slots
    log.msg("slots=%s" % slots)

    pool = RenderPool(
        slots=slots,
        network_manager=network_manager,
        get_splash_proxy_factory=get_splash_proxy_factory,
        js_profiles_path=js_profiles_path
    )

    # HTTP API
    root = Root(pool)
    factory = Site(root)
    reactor.listenTCP(portnum, factory)

    # HTTP Proxy
    if disable_proxy is False:
        from splash.proxy_server import SplashProxyFactory
        splash_proxy_factory = SplashProxyFactory(pool)
        proxy_portnum = defaults.PROXY_PORT if proxy_portnum is None else proxy_portnum
        reactor.listenTCP(proxy_portnum, splash_proxy_factory)
Example #29
0
    def __init__(self, save_dir=".", 
                       listen_port=6881, 
                       enable_DHT=False,
                       remote_debugging=False):
        """
        @param remote_degugging enables telnet login via port 9999 with a
            username and password of 'admin'
        """
        log.startLogging(sys.stdout) # Start logging to stdout
        self.save_dir = save_dir
        self.listen_port = listen_port
        self.enable_DHT = enable_DHT
        self.tasks = {}
        self.btServer = BTServerFactories(self.listen_port)
        reactor.listenTCP(self.listen_port, self.btServer)
        if enable_DHT:
            log.msg("Turning DHT on.")
            self.dht = DHTProtocol()
            reactor.listenUDP(self.listen_port, self.dht)

        if remote_debugging:
            log.msg("Turning remote debugging on. You may login via telnet " +\
                "on port 9999 username & password are 'admin'")
            import twisted.manhole.telnet
            dbg = twisted.manhole.telnet.ShellFactory()
            dbg.username = "******"
            dbg.password = "******"
            dbg.namespace['app'] = self 
            reactor.listenTCP(9999, dbg)
def GetworkProxy_main(cb):
    log.info("Stratum proxy version %s Connecting to Pool..." % version.VERSION)
        
    # Connect to Stratum pool
    f = SocketTransportClientFactory(settings.HOSTNAME, settings.LISTEN_SOCKET_TRANSPORT,
                debug=False, proxy=None, event_handler=client_service.ClientMiningService)
    
    job_registry = jobs.JobRegistry(f, cmd='', no_midstate=settings.GW_DISABLE_MIDSTATE, real_target=settings.GW_SEND_REAL_TARGET)
    client_service.ClientMiningService.job_registry = job_registry
    client_service.ClientMiningService.reset_timeout()
    
    workers = worker_registry.WorkerRegistry(f)
    f.on_connect.addCallback(on_connect, workers, job_registry)
    f.on_disconnect.addCallback(on_disconnect, workers, job_registry)
    
    # Cleanup properly on shutdown
    reactor.addSystemEventTrigger('before', 'shutdown', on_shutdown, f)

    # Block until proxy connects to the pool
    yield f.on_connect
    
    # Setup getwork listener
    gw_site = Site(getwork_listener.Root(job_registry, workers,
		stratum_host=settings.HOSTNAME, stratum_port=settings.LISTEN_SOCKET_TRANSPORT,
		custom_lp=False, custom_stratum=False,
		custom_user=False, custom_password=False
		))
    gw_site.noisy = False
    reactor.listenTCP(settings.GW_PORT, gw_site, interface='0.0.0.0')
    
    log.info("Getwork Proxy is online, Port: %d" % (settings.GW_PORT))
Example #31
0
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################

from twisted.internet.defer import inlineCallbacks, returnValue
from klein import Klein
from autobahn.twisted.wamp import Application

app = Klein()
wampapp = Application()


@app.route('/square/submit', methods=['POST'])
@inlineCallbacks
def square_submit(request):
    x = int(request.args.get('x', [0])[0])
    res = yield wampapp.session.call(u'com.example.square', x)
    returnValue("{} squared is {}".format(x, res))


if __name__ == "__main__":
    import sys
    from twisted.python import log
    from twisted.web.server import Site
    from twisted.internet import reactor
    log.startLogging(sys.stdout)

    reactor.listenTCP(8080, Site(app.resource()))
    wampapp.run(u"ws://127.0.0.1:9000", u"realm1", standalone=False)
Example #32
0
def main():
    reactor.disconnectAll()
    failover = False
    if settings.POOL_FAILOVER_ENABLE:
        failover = settings.failover_pool
        settings.failover_pool = not settings.failover_pool

    pool_host = settings.POOL_HOST
    pool_port = settings.POOL_PORT
    if failover and settings.POOL_FAILOVER_ENABLE:
        pool_host = settings.POOL_HOST_FAILOVER
        pool_port = settings.POOL_PORT_FAILOVER

    log.warning("Monero Stratum proxy version: %s" % version.VERSION)
    log.warning("Trying to connect to Stratum pool at %s:%d" %
                (pool_host, pool_port))

    # Connect to Stratum pool, main monitoring connection
    f = SocketTransportClientFactory(
        pool_host,
        pool_port,
        debug=settings.DEBUG,
        proxy=None,
        event_handler=client_service.ClientMiningService)

    job_registry = jobs.JobRegistry(f)
    client_service.ClientMiningService.job_registry = job_registry
    client_service.ClientMiningService.reset_timeout()

    f.on_connect.addCallback(on_connect)
    f.on_disconnect.addCallback(on_disconnect)
    # Cleanup properly on shutdown
    reactor.addSystemEventTrigger('before', 'shutdown', on_shutdown, f)

    # Block until proxy connect to the pool
    try:
        yield f.on_connect
    except TransportException:
        log.warning(
            "First pool server must be online first time to start failover")
        return

    # Setup stratum listener
    stratum_listener.StratumProxyService._set_upstream_factory(f)
    stratum_listener.StratumProxyService._set_custom_user(
        settings.CUSTOM_USER, settings.CUSTOM_PASSWORD,
        settings.ENABLE_WORKER_ID, settings.WORKER_ID_FROM_IP)
    reactor.listenTCP(settings.STRATUM_PORT,
                      SocketTransportFactory(
                          debug=settings.DEBUG,
                          event_handler=ServiceEventHandler),
                      interface=settings.STRATUM_HOST)

    # Setup multicast responder
    reactor.listenMulticast(3333,
                            multicast_responder.MulticastResponder(
                                (pool_host, pool_port), settings.STRATUM_PORT),
                            listenMultiple=True)

    log.warning(
        "-----------------------------------------------------------------------"
    )
    if settings.STRATUM_HOST == '0.0.0.0':
        log.warning("PROXY IS LISTENING ON ALL IPs ON PORT %d (stratum)" %
                    settings.STRATUM_PORT)
    else:
        log.warning("LISTENING FOR MINERS ON stratum+tcp://%s:%d (stratum)" % \
                 (settings.STRATUM_HOST, settings.STRATUM_PORT))
    log.warning(
        "-----------------------------------------------------------------------"
    )
Example #33
0
#coding:utf8

from twisted.internet import reactor

from syncplay.server import SyncFactory

reactor.listenTCP(8999, SyncFactory())
reactor.run()
Example #34
0
"""
Chat server
"""
from twisted.internet.protocol import Factory
from twisted.internet import reactor

from protocol import Chat


class ChatFactory(Factory):
    """
    build chat protocol.
    """

    def __init__(self):
        """
        factory initialization.
        """
        self.users = {}

    def buildProtocol(self, addr):
        """
        call Chat
        """
        return Chat(self.users)


reactor.listenTCP(8123, ChatFactory())
reactor.run()
Example #35
0
                            print("badsignature")

                        newtrans = transaction(
                            sender=payloaded["sender"],
                            senderwallet=wllt,
                            receiver=payloaded["receiver"],
                            prevblockhash=transaction.objects.all().last(
                            ).blockhash,
                            blockhash=payloaded["blockhash"],
                            amount=Decimal(payloaded["amount"]),
                            nonce=payloaded["nonce"],
                            first_timestamp=payloaded["timestamp"],
                            P2PKH=payloaded["P2PKH"],
                            verification=True).save()

                else:
                    print("other message")
                BroadcastServerFactory.broadcast(payloaded)

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


if __name__ == '__main__':
    print("start")
    ServerFactory = BroadcastServerFactory
    factory = ServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = BroadcastServerProtocol
    reactor.listenTCP(9000, factory)
    reactor.run()
Example #36
0
        plugin_module = 'plugins.' + service_config.get(service, 'plugin')
        plugin = importlib.import_module(plugin_module)
        service_object = None

        if args.d is False:
            if int(low_port) < 1024:
                if display_low_port_message:
                    print 'Your service configuration suggests that you want to run on at least one low port!'
                    print 'To enable port redirection run the following ipt-kit (https://github.com/foospidy/ipt-kit) commands as root:'
                    print ''
                    display_low_port_message = False

        try:
            if protocol.lower() == 'tcp':
                # run tcp service
                service_object = reactor.listenTCP(int(port), plugin.pluginFactory(service))
            else:
                # run udp service
                service_object = reactor.listenUDP(int(port), plugin.pluginMain(service, get_ip_address(), port))

            if service_object:
                # stop services from listening immediately if not starting in daemon mode.
                if args.d is False:
                    service_object.stopListening()

                # save service objects to array, to be used by HoneyPy Console
                services[0].append(service)
                services[1].append(service_object)

        except Exception as e:
            print str(e) + '\n'
Example #37
0
 
            msg = ""
            if command == "iam":
                self.name = content
                self.curr_clients[self.name] = self
                msg = self.name + " has joined"
                self.message(msg)
 
            elif command == "msg":
                msg = self.name + ": " + content
                print msg
                self.message(msg)
            else:
                if command in self.curr_clients:
                    self.curr_clients[command].message(self.name +": "+ content)
            
            #for c in self.factory.clients:
            #    if self.currentCleint == c:
            #        print c
            #        c.message(msg)
                
    def message(self, message):
        self.transport.write(message + '\n')
 
factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
factory.protocol.curr_clients = {}
reactor.listenTCP(80, factory)
print "Iphone Chat server started"
reactor.run()
Example #38
0
 def setUp(self):
     xmlrpc = Test()
     addIntrospection(xmlrpc)
     self.p = reactor.listenTCP(0, server.Site(xmlrpc),interface="127.0.0.1")
     self.port = self.p.getHost().port
     self.factories = []
Example #39
0
 def setUp(self):
     self.p = reactor.listenTCP(
         0, server.Site(Test(allowNone=True)), interface="127.0.0.1")
     self.port = self.p.getHost().port
Example #40
0
 def setUp(self):
     self.resource = static.File(__file__)
     self.resource.isLeaf = True
     self.port = reactor.listenTCP(0, server.Site(self.resource),
                                                  interface='127.0.0.1')
Example #41
0
        log.msg("Received response from proxied service: " + repr(response))
        return defer.succeed(response)


if __name__ == '__main__':
    """
    Demonstration LDAP proxy; listens on localhost:10389; passes all requests
    to localhost:8080 and logs responses..
    """
    from ldaptor.protocols.ldap.ldapclient import LDAPClient
    from twisted.internet import protocol, reactor
    from functools import partial
    import sys

    log.startLogging(sys.stderr)
    factory = protocol.ServerFactory()
    proxiedEndpointStr = 'tcp:host=localhost:port=8080'
    use_tls = False
    clientConnector = partial(ldapconnector.connectToLDAPEndpoint, reactor,
                              proxiedEndpointStr, LDAPClient)

    def buildProtocol():
        proto = ExampleProxy()
        proto.clientConnector = clientConnector
        proto.use_tls = use_tls
        return proto

    factory.protocol = buildProtocol
    reactor.listenTCP(10389, factory)
    reactor.run()
Example #42
0
 def setUp(self):
     self.p = reactor.listenTCP(0, server.Site(TestAuthHeader()),
                                interface="127.0.0.1")
     self.port = self.p.getHost().port
     self.factories = []
Example #43
0
from twisted.spread import pb
from twisted.internet import reactor


class Two(pb.Referenceable):
    def remote_print(self, arg):
        print("two.print was given", arg)


class One(pb.Root):
    def __init__(self, two):
        # pb.Root.__init__(self)   # pb.Root doesn't implement __init__
        self.two = two

    def remote_getTwo(self):
        print("One.getTwo(), returning my two called", self.two)
        return self.two

    def remote_checkTwo(self, newtwo):
        print("One.checkTwo(): comparing my two", self.two)
        print("One.checkTwo(): against your two", newtwo)
        if self.two == newtwo:
            print("One.checkTwo(): our twos are the same")


two = Two()
root_obj = One(two)
reactor.listenTCP(8800, pb.PBServerFactory(root_obj))
reactor.run()
Example #44
0
 def start(self):
     site = server.Site(self)
     reactor.listenTCP(7000, site)
     return reactor.run()
Example #45
0
 def pluginReactor(self, strippingFactory):
     reactor.listenTCP(3141, strippingFactory)
Example #46
0
from twisted.internet import protocol, reactor
from time import ctime
PORT = 2345


class TSServProtocol(protocol.Protocol):
    def connectionMade(self):
        clnt = self.clnt = self.transport.getPeer().host
        print('...connected from:', clnt)

    def dataReceived(self, data):
        self.transport.write(ctime().encode())


factory = protocol.Factory()
factory.protocol = TSServProtocol
print('waiting for connection...')
reactor.listenTCP(PORT, factory)
reactor.run()
Example #47
0
    """Authentication/authorization backend using the 'login' PAM service"""

    credentialInterfaces = IUsernamePassword,
    implements(ICredentialsChecker)

    def requestAvatarId(self, credentials):
        if pam.authenticate(credentials.username, credentials.password):
            return defer.succeed(credentials.username)
        return defer.fail(UnauthorizedLogin("invalid password"))


class UnixSSHdFactory(factory.SSHFactory):
    publicKeys = {'ssh-rsa': keys.Key.fromString(data=publicKey)}
    privateKeys = {'ssh-rsa': keys.Key.fromString(data=privateKey)}
    services = {
        'ssh-userauth': userauth.SSHUserAuthServer,
        'ssh-connection': connection.SSHConnection
    }


# Components have already been registered in twisted.conch.unix

portal = portal.Portal(UnixSSHRealm())
portal.registerChecker(PamPasswordDatabase())  # Supports PAM
portal.registerChecker(SSHPublicKeyDatabase())  # Supports PKI
UnixSSHdFactory.portal = portal

if __name__ == '__main__':
    reactor.listenTCP(5022, UnixSSHdFactory())
    reactor.run()
Example #48
0
        if self.authenticate(credentials[0], credentials[1]):
            print "Permission granted"

            command = 'su %s -c "%s"' % ("david", command)
            print "Running: %s" % command

            process = subprocess.Popen(command,
                                       shell=True,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT)
            out, nothing = process.communicate()

            print out

            #return the result
            self.transport.write(out)
        else:
            print "Permission denied"
            self.transport.write("Permission denied")


class ImpersonateFactory(Factory):
    def __init__(self, venv=None):
        self.key = "cL7eNdb3yJCkw1zlvizrZuUdbplTmsFD"

    def buildProtocol(self, addr):
        return Impersonate(self)


reactor.listenTCP(8123, ImpersonateFactory(sys.argv[1]))
reactor.run()
Example #49
0
 def start(self):
     self._listener = reactor.listenTCP(GeneralConfig.http_port, self._site)
Example #50
0
    def send(self, message):
        self.remote.callRemote("print", message)


class Group(pb.Viewable):
    def __init__(self, groupname, allowMattress):
        self.name = groupname
        self.allowMattress = allowMattress
        self.users = []

    def addUser(self, user):
        self.users.append(user)

    def view_send(self, from_user, message):
        if not self.allowMattress and "mattress" in message:
            raise ValueError, "Don't say that word"
        for user in self.users:
            user.send("<%s> says: %s" % (from_user.name, message))


realm = ChatRealm()
realm.server = ChatServer()
checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
checker.addUser("alice", "1234")
checker.addUser("bob", "secret")
checker.addUser("carol", "fido")
p = portal.Portal(realm, [checker])

reactor.listenTCP(8800, pb.PBServerFactory(p))
reactor.run()
Example #51
0
    if f3:
        f3.on_connect.addCallback(on_connect)
        f3.on_disconnect.addCallback(on_disconnect)
        reactor.addSystemEventTrigger('before', 'shutdown', on_shutdown, f3)


    # Block until proxy connect to the pool
    try:
        yield f.on_connect
    except TransportException:
        log.warning("First pool server must be online first time during start")
        return


    conn = reactor.listenTCP(settings.PORT, Site(getwork_listener.Root(job_registry, settings.ENABLE_WORKER_ID)), interface=settings.HOST)

    try:
        conn.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # Enable keepalive packets
        conn.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 60) # Seconds before sending keepalive probes
        conn.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 1) # Interval in seconds between keepalive probes
        conn.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 5) # Failed keepalive probles before declaring other end dead
    except:
        pass # Some socket features are not available on all platforms (you can guess which one)

    log.warning("-----------------------------------------------------------------------")
    if settings.HOST == '0.0.0.0':
        log.warning("PROXY IS LISTENING ON ALL IPs ON PORT %d" % settings.PORT)
    else:
        log.warning("LISTENING FOR MINERS ON http://%s:%d" % (settings.HOST, settings.PORT))
    log.warning("-----------------------------------------------------------------------")
        ilsc.init_database()

appBackend.init_schedulers()
scheduler.add_job(appBackend.cleanup_everything, 'cron', id=f"leon_der_profi", hour=appConfig.app['cleancron'], minute=0)
scheduler.start()

if appConfig.app['cleanonstart']:
    appBackend.checkout_all()
    appBackend.cleanup_everything()

#appBackend.inject_random_userdata()#just for testing
try:
    if appConfig.http['usessl']:
        priv = appConfig.http['serverpriv']
        cacert = appConfig.http['servercacert']
        certdata = ssl.DefaultOpenSSLContextFactory(priv, cacert)
        reactor.listenSSL(appConfig.http['port'], Site(WSGIResource(reactor, reactor.getThreadPool(), flaskApp)),certdata)
        reactor.listenSSL(appConfig.websocket['port'], appBackend.get_websocket_site(),certdata)
    else:
        reactor.listenTCP(appConfig.http['port'], Site(WSGIResource(reactor, reactor.getThreadPool(), flaskApp)))
        reactor.listenTCP(appConfig.websocket['port'], appBackend.get_websocket_site())
except Exception as e:
    logging.warning(str(e))
    print(e)
    
if __name__ == "__main__":
    try:
        reactor.run()
    except Exception as e:
        logging.warning(str(e))
        print(e)
Example #53
0
        close = zdefs.Close ()
        close.closeReason = zdefs.CloseReason.get_num_from_name (
            'responseToPeer')
        self.send_PDU ('close', close)
        self.transport.loseConnection ()
        
if __name__ == '__main__':
    if 0:
        from PyZ3950 import z3950
        print rpn_q_to_amazon (
            ('type_1', z3950.mk_simple_query ('Among the gently mad')))
        print rpn_q_to_amazon (('type_1', z3950.mk_compound_query ()))
    else:
        amazon.setLicense (amazon.getLicense ())
        factory = protocol.Factory ()
        factory.protocol = Z3950Server
        reactor.listenTCP (2100, factory)
        reactor.run ()

    










Example #54
0
        log.startLogging(sys.stdout)

    ##
    # create a Twisted Web resource for our WebSocket server
    ##
    wsFactory = WebSocketServerFactory(u"ws://127.0.0.1:8080",
                                       debug=debug,
                                       debugCodePaths=debug)

    wsFactory.protocol = EchoServerProtocol
    wsResource = WebSocketResource(wsFactory)

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

    ##
    # create a root resource serving everything via WSGI/Flask, but
    # the path "/ws" served by our WebSocket stuff
    ##
    rootResource = WSGIRootResource(wsgiResource, {'ws': wsResource})

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

    reactor.listenTCP(8080, site)
    reactor.run()
Example #55
0
def esc_markup(msg):
    return (msg.replace('&', '&amp;').replace('[', '&bl;').replace(']', '&br'))


class Chat(protocol.Protocol):
    def connectionMade(self):
        self.color = colors.pop()
        colors.insert(0, self.color)

    def dataReceived(self, data):
        transports.add(self.transport)

        if ':' not in data:
            return

        user, msg = data.split(':', 1)

        for t in transports:
            if t is not self.transport:
                t.write('[b][color={}]{}:[/color][/b]{}'.format(
                    self.color, user, esc_markup(msg)))


class ChatFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Chat()


reactor.listenTCP(9096, ChatFactory())
reactor.run()
Example #56
0
                        print 'Connecting to %s:%s' % (dest_addr, dest_port)
                        reactor.connectTCP(dest_addr, dest_port,
                                           RemoteFactory(self.session))
                        self.buf = self.buf[self.data_len:]
                        self.data_len = 0
                        self.stage = 2
                    else:
                        self.session.recv_seqcache.put(
                            self.data_seq, self.buf[:self.data_len])
                        #print 'red a seq '+ str(self.data_seq) + ' ' + str(len(self.buf[:self.data_len]))
                        self.buf = self.buf[self.data_len:]
                        self.data_len = 0
                        self.session.send_to_remote()
                else:
                    break

    def sendData(self, data):
        self.transport.write(data)


class ServerFactory(ServerFactory):
    def __init__(self):
        self.dct_session = {}

    def buildProtocol(self, addr):
        return Server(self.dct_session)


reactor.listenTCP(config.SERVER_PORT, ServerFactory())
reactor.run()
Example #57
0
def seleccionarPuertoParaCrear(ventana, letra):
    global volverAlMenuUnirseRED
    pygame.init()
    pygame.display.set_caption('Ta-Te-Ti de Carlitos')
    ventana = pygame.display.set_mode((800, 600))
    pygame.key.set_repeat(150, 50)

    fuenteParaMenu = pygame.font.Font('bibliottt/AtoZ.ttf', 40)
    opcionMenu = [
        Opcion('Menu', (650, 540), 'menu', funcionParaSalirAlMenuCrearRED,
               fuenteParaMenu, ventana)
    ]

    fuenteInput = pygame.font.Font(None, 40)
    inputTexto = pygame.Rect(209, 300, 250, 40)

    color = pygame.Color(250, 0, 0)

    cantidadMaximaDigitos = int(5)
    texto = 'Ej: 25000 o 8484'

    IPSERVENT = get_lan_ip()
    puertoEscuchado = None

    volverAlMenuUnirseRED = False

    while not volverAlMenuUnirseRED:
        if len(texto) is 0:
            texto = 'Ej: 25000 o 8484'

        evento = pygame.event.get()
        #print len(texto)
        for e in evento:

            if e.type == pygame.QUIT:
                try:
                    reactor.stop()
                except:
                    pass
                os._exit(0)

            if e.type == pygame.KEYDOWN:
                if texto is 'Ej: 25000 o 8484':
                    texto = ''

                if e.key == pygame.K_RETURN:
                    try:
                        puertoEscuchado = reactor.listenTCP(
                            int(texto), Fabrica())
                        banderaDePuerto = True
                    except Exception as e:
                        banderaDePuerto = False
                        print e

                    if banderaDePuerto:
                        volverAlMenuUnirseRED = SERVENTATETI(ventana, letra)
                        texto = ''
                elif e.key == pygame.K_BACKSPACE:
                    texto = texto[:-1]
                else:
                    if len(texto) < cantidadMaximaDigitos and\
                     e.unicode in '0 1 2 3 4 5 6 7 8 9 . :'.split():
                        texto += e.unicode

        try:
            puertoEscuchado.stopListening()
        except:
            pass

        ventana.fill(colorGris)

        fuenteParaUnirse = pygame.font.Font('bibliottt/AtoZ.ttf', 24)
        textoUnirseAUnaPartidaUNO = 'escriba el puerto en el que'
        textoUnirseAUnaPartidaFFUNO = fuenteParaUnirse.render(
            textoUnirseAUnaPartidaUNO, True, colorRojo)
        ventana.blit(textoUnirseAUnaPartidaFFUNO, (209, 200))
        textoUnirseAUnaPartidaDOS = 'quiere crear su servidor de tateti'
        textoUnirseAUnaPartidaFFDOS = fuenteParaUnirse.render(
            textoUnirseAUnaPartidaDOS, True, colorRojo)
        ventana.blit(textoUnirseAUnaPartidaFFDOS, (209, 230))
        fuenteParaUnirseDOS = pygame.font.Font(None, 24)
        textoUnirseAUnaPartidaTRES = '(1024<puerto<65535, si el puerto esta siendo utilizado intente con otro)'
        textoUnirseAUnaPartidaTRES = fuenteParaUnirseDOS.render(
            textoUnirseAUnaPartidaTRES, True, colorRojo)
        ventana.blit(textoUnirseAUnaPartidaTRES, (209, 260))

        fuenteParaTextoIp = pygame.font.Font(None, 24)
        textoSobreIP = 'Tu ip local es: ' + str(IPSERVENT)
        textoSobreIP = fuenteParaTextoIp.render(textoSobreIP, True, colorRojo)
        ventana.blit(textoSobreIP, (209, 400))

        # me quedé acá
        if texto is 'Ej: 25000 o 8484':
            superficieTexto = fuenteInput.render(texto, True, colorPlaceholder)
        else:
            superficieTexto = fuenteInput.render(texto, True, color)

        widthMaxTexto = int(250)
        inputTexto.w = widthMaxTexto

        ventana.blit(superficieTexto, (inputTexto.x + 4, inputTexto.y + 8))
        pygame.draw.rect(ventana, color, inputTexto, 3)

        for o in opcionMenu:
            if o.rect.collidepoint(pygame.mouse.get_pos()):
                o.hover = True
                if pygame.mouse.get_pressed()[0]:
                    o.funcion(ventana)
                    volverAlMenuUnirseRED = True
            else:
                o.hover = False

            o.imprimir()

        pygame.display.flip()

    return True
Example #58
0
        """

        self.clients = []  # создаем пустой список клиентов
        self.messages = []
        print("*" * 10, "Server started - [OK]",
              "*" * 10)  # уведомление в консоль сервера

    def startFactory(self):
        """Запуск прослушивания клиентов (уведомление в консоль)"""

        print("[ * ] Start listening ...")  # уведомление в консоль сервера

    def notify_all_users(self, message: str):
        """
        Отправка сообщения всем клиентам чата
        :param message: Текст сообщения
        """

        data = message.encode()  # закодируем текст в двоичное представление
        # отправим всем подключенным клиентам
        for user in self.clients:
            user.sendLine(data)


if __name__ == '__main__':
    # параметры прослушивания
    reactor.listenTCP(7410, Server())

    # запускаем реактор
    reactor.run()
		clientFactory = class_(self.method, rest, self.clientproto, headers, s, self)
		# if self.uri == 'http://music.163.com/eapi/song/like':
		# 	print rest, headers, s
		# if self.uri == 'http://music.163.com/eapi/v1/playlist/manipulate/tracks':
		# 	print rest, headers, s
		return host, port, clientFactory

	def process(self):
		if self.uri == 'music.163.com:443':
			print('DEBUG: Abort on request: ' + self.uri)
			self.channel._respondToBadRequestAndDisconnect()
			return
		host, port, clientFactory = self.process_prepare()
		if self.uri == 'http://music.163.com/eapi/song/enhance/player/url':
			print('request intercepted: ' + self.uri)
			#mainland_proxy.set_to_default()
			mainland_proxy.status = -1
			self.reactor.connectTCP(mainland_proxy.ip, mainland_proxy.port, clientFactory)
			return
		self.reactor.connectTCP(host, port, clientFactory)

class NeteaseMusicProxy(proxy.Proxy):
	requestFactory = NeteaseMusicProxyRequest

class NeteaseMusicProxyFactory(http.HTTPFactory):
	protocol = NeteaseMusicProxy

mainland_proxy = MainlandProxy()
reactor.listenTCP(32794, NeteaseMusicProxyFactory())
reactor.run()

class MyRequestHandler(http.Request):
    pages = {
        '/': '<h1>Home</h1>Home page',
        '/test': '<h1>Test</h1>Test page',
        }

    def process(self):
        if self.pages.has_key(self.path):
            self.write(self.pages[self.path])
        else:
            self.setResponseCode(http.NOT_FOUND)
            self.write(
                "<h1>Not Found</h1>Sorry, no such page.")
        self.finish()


class MyHttp(http.HTTPChannel):
    requestFactory = MyRequestHandler


class MyHttpFactory(http.HTTPFactory):
    protocol = MyHttp


if __name__ == "__main__":
    from twisted.internet import reactor
    reactor.listenTCP(8000, MyHttpFactory())
    reactor.run()