twisted.internet.reactor.listenUDP

Here are the examples of the python api twisted.internet.reactor.listenUDP taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

73 Examples 7

Page 1 Selected Page 2

Example 1

Project: mythbox Source File: test_udp.py
Function: test_start_stop
    def testStartStop(self):
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        port1 = reactor.listenUDP(0, server, interface="127.0.0.1")
        def cbStarted(ignored):
            self.assertEquals(server.started, 1)
            self.assertEquals(server.stopped, 0)
            return port1.stopListening()
        def cbStopped(ignored):
            self.assertEquals(server.stopped, 1)
        return d.addCallback(cbStarted).addCallback(cbStopped)

Example 2

Project: SubliminalCollaborator Source File: test_udp.py
Function: test_start_stop
    def test_startStop(self):
        """
        The L{DatagramProtocol}'s C{startProtocol} and C{stopProtocol}
        methods are called when its transports starts and stops listening,
        respectively.
        """
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        port1 = reactor.listenUDP(0, server, interface="127.0.0.1")
        def cbStarted(ignored):
            self.assertEqual(server.started, 1)
            self.assertEqual(server.stopped, 0)
            return port1.stopListening()
        def cbStopped(ignored):
            self.assertEqual(server.stopped, 1)
        return d.addCallback(cbStarted).addCallback(cbStopped)

Example 3

Project: khashmir Source File: airhook.py
def listenAirhookStream(port, factory):
    ah = Airhook()
    ah.connection = StreamConnection
    ah.factory = factory
    reactor.listenUDP(port, ah)
    return ah

Example 4

Project: CommunityCellularManager Source File: _openbts.py
Function: start
    def start(self):
        self.proxy = SipProxy(self.user, self.port, self.call_h, self.sms_h,
                              self.self_ip, self.other_ip)
        reactor.listenUDP(self.port, self.proxy, self.self_ip)
        if not OpenBTSFakePhone.reactorRunning:
            OpenBTSFakePhone.reactorRunning = True
            Thread(target=reactor.run, args=(False,)).start()

Example 5

Project: netflix-no-ipv6-dns-proxy Source File: server.py
def main():
    factory = server.DNSServerFactory(
        clients=[
            BlockNetflixAAAAResolver(),
            client.Resolver(
                servers=OPTIONS.get('upstream-dns', None),
                resolv=OPTIONS.get('resolv-conf', None)
            )
        ]
    )

    protocol = dns.DNSDatagramProtocol(controller=factory)

    reactor.listenUDP(OPTIONS['listen-port'], protocol, interface=OPTIONS['listen-address'])
    reactor.listenTCP(OPTIONS['listen-port'], factory, interface=OPTIONS['listen-address'])

    reactor.run()

Example 6

Project: scalyr-agent-2 Source File: udp.py
Function: openclientmode
    def openClientMode(self, iface=None):
        if iface is None:
            iface = ('', 0)
        try:
            self._lport = reactor.listenUDP(iface[1], self, iface[0])
        except Exception:
            raise error.CarrierError(sys.exc_info()[1])
        return self

Example 7

Project: mythbox Source File: test_udp.py
Function: test_portrepr
    def testPortRepr(self):
        client = GoodClient()
        p = reactor.listenUDP(0, client)
        portNo = str(p.getHost().port)
        self.failIf(repr(p).find(portNo) == -1)
        def stoppedListening(ign):
            self.failIf(repr(p).find(portNo) != -1)
        d = defer.maybeDeferred(p.stopListening)
        d.addCallback(stoppedListening)
        return d

Example 8

Project: khashmir Source File: airhook.py
def listenAirhook(port, factory):
    ah = Airhook()
    ah.connection = AirhookConnection
    ah.factory = factory
    reactor.listenUDP(port, ah)
    return ah

Example 9

Project: SubliminalCollaborator Source File: test_udp.py
Function: test_portrepr
    def test_portRepr(self):
        """
        The port number being listened on can be found in the string
        returned from calling repr() on L{twisted.internet.udp.Port}.
        """
        client = GoodClient()
        p = reactor.listenUDP(0, client)
        portNo = str(p.getHost().port)
        self.failIf(repr(p).find(portNo) == -1)
        def stoppedListening(ign):
            self.failIf(repr(p).find(portNo) != -1)
        d = defer.maybeDeferred(p.stopListening)
        d.addCallback(stoppedListening)
        return d

Example 10

Project: vumi Source File: test_metrics_workers.py
    @inlineCallbacks
    def setUp(self):
        self.worker_helper = self.add_helper(WorkerHelper())
        self.broker = BrokerWrapper(self.worker_helper.broker)
        self.udp_protocol = UDPMetricsCatcher()
        self.udp_server = yield reactor.listenUDP(0, self.udp_protocol)
        self.add_cleanup(self.udp_server.stopListening)
        self.worker = yield self.worker_helper.get_worker(
            metrics_workers.UDPMetricsCollector, {
                'metrics_host': '127.0.0.1',
                'metrics_port': self.udp_server.getHost().port,
            })

Example 11

Project: calvin-base Source File: test_append.py
Function: start
    def start(self, port=0, boot_strap=[]):
        self.kserver = self.server_type()
        self.kserver.bootstrap(boot_strap)

        self.port = threads.blockingCallFromThread(reactor, reactor.listenUDP, port, self.kserver.protocol)
        print "Starting server:", self.port

        time.sleep(.2)

        return self.port.getHost().port, self.kserver

Example 12

Project: multi-paxos-example Source File: messenger.py
Function: init
    def __init__(self, uid, peer_addresses, replicated_val):
        self.addrs          = dict(peer_addresses)
        self.replicated_val = replicated_val

        # provide two-way mapping between endpoints and server names
        for k,v in list(self.addrs.items()):
            self.addrs[v] = k

        reactor.listenUDP( peer_addresses[uid][1], self )

Example 13

Project: plugin.video.streamondemand Source File: NetBIOSProtocol.py
Function: init
    def __init__(self, broadcast = True, listen_port = 0):
        """
        Instantiate a NBNSProtocol instance.

        This automatically calls reactor.listenUDP method to start listening for incoming packets, so you **must not** call the listenUDP method again.

        :param boolean broadcast: A boolean flag to indicate if we should setup the listening UDP port in broadcast mode
        :param integer listen_port: Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number.
        """
        self.broadcast = broadcast
        self.pending_trns = { }  # TRN ID -> ( expiry_time, name, Deferred instance )
        self.transport = reactor.listenUDP(listen_port, self)
        if self.broadcast:
            self.transport.getHandle().setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        reactor.callLater(1, self.cleanupPendingTrns)

Example 14

Project: mythbox Source File: test_sip.py
Function: set_up
    def setUp(self):
        self.proxy = sip.RegisterProxy(host="127.0.0.1")
        self.registry = sip.InMemoryRegistry("bell.example.com")
        self.proxy.registry = self.proxy.locator = self.registry
        self.serverPort = reactor.listenUDP(
            0, self.proxy, interface="127.0.0.1")
        self.client = Client()
        self.clientPort = reactor.listenUDP(
            0, self.client, interface="127.0.0.1")
        self.serverAddress = (self.serverPort.getHost().host,
                              self.serverPort.getHost().port)

Example 15

Project: SubliminalCollaborator Source File: test_udp.py
Function: test_oldaddress
    def test_oldAddress(self):
        """
        The C{type} of the host address of a listening L{DatagramProtocol}'s
        transport is C{"UDP"}.
        """
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        p = reactor.listenUDP(0, server, interface="127.0.0.1")
        def cbStarted(ignored):
            addr = p.getHost()
            self.assertEqual(addr.type, 'UDP')
            return p.stopListening()
        return d.addCallback(cbStarted)

Example 16

Project: mythbox Source File: test_udp.py
Function: test_binderror
    def testBindError(self):
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        port = reactor.listenUDP(0, server, interface='127.0.0.1')

        def cbStarted(ignored):
            self.assertEquals(port.getHost(), server.transport.getHost())

            server2 = Server()
            self.assertRaises(
                error.CannotListenError,
                reactor.listenUDP, port.getHost().port, server2,
                interface='127.0.0.1')
        d.addCallback(cbStarted)

        def cbFinished(ignored):
            return port.stopListening()
        d.addCallback(cbFinished)
        return d

Example 17

Project: txstatsd Source File: test_router.py
    def setUp(self):
        self.service = MultiService()
        self.received = []

        class Collect(DatagramProtocol):

            def datagramReceived(cself, data, host_port):
                self.got_data(data)

        self.port = reactor.listenUDP(0, Collect())

        self.processor = TestMessageProcessor()
        self.router = Router(self.processor,
            r"any => redirect_udp 127.0.0.1 %s" %
            (self.port.getHost().port,),
            service=self.service)
        self.service.startService()
        return self.router.ready

Example 18

Project: protobuf-rpc Source File: test_service.py
	def testUdpRpc( self ):
		protocol = tx.UdpChannel( self.udp_listener.getHost().host, 
			self.udp_listener.getHost().port )
		proxy = tx.Proxy( Test_Stub( protocol ) )
		self.udp_proxy_port = reactor.listenUDP( 0, protocol )
		text = "UDP Test"
		request = EchoRequest()
		request.text = text
		echoed = proxy.Test.Echo( request )
		echoed.addCallback( lambda r: self.assertEquals( r.text, text ) )
		return echoed

Example 19

Project: mythbox Source File: test_udp.py
Function: test_rebind
    def testRebind(self):
        # Ensure binding the same DatagramProtocol repeatedly invokes all
        # the right callbacks.
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        p = reactor.listenUDP(0, server, interface="127.0.0.1")

        def cbStarted(ignored, port):
            return port.stopListening()

        def cbStopped(ignored):
            d = server.startedDeferred = defer.Deferred()
            p = reactor.listenUDP(0, server, interface="127.0.0.1")
            return d.addCallback(cbStarted, p)

        return d.addCallback(cbStarted, p)

Example 20

Project: SubliminalCollaborator Source File: test_udp.py
Function: test_bad_connect
    def test_badConnect(self):
        """
        A call to the transport's connect method fails with a L{ValueError}
        when a non-IP address is passed as the host value.

        A call to a transport's connect method fails with a L{RuntimeError}
        when the transport is already connected.
        """
        client = GoodClient()
        port = reactor.listenUDP(0, client, interface="127.0.0.1")
        self.assertRaises(ValueError, client.transport.connect,
                          "localhost", 80)
        client.transport.connect("127.0.0.1", 80)
        self.assertRaises(RuntimeError, client.transport.connect,
                          "127.0.0.1", 80)
        return port.stopListening()

Example 21

Project: tensor Source File: riemann.py
Function: create_client
    def createClient(self):
        """Create a UDP connection to Riemann"""
        server = self.config.get('server', '127.0.0.1')
        port = self.config.get('port', 5555)

        def connect(ip):
            self.protocol = riemann.RiemannUDP(ip, port)
            self.endpoint = reactor.listenUDP(0, self.protocol)

        d = reactor.resolve(server)
        d.addCallback(connect)
        return d

Example 22

Project: tensor Source File: test_tensor.py
    @defer.inlineCallbacks
    def test_udp_riemann(self):

        event = Event('ok', 'sky', 'Sky has not fallen', 1.0, 60.0)
        
        protocol = riemann.RiemannUDP('127.0.0.1', 5555)
        self.endpoint = reactor.listenUDP(0, protocol)

        yield protocol.sendEvents([event])

Example 23

Project: kademlia Source File: network.py
Function: listen
    def listen(self, port, interface=""):
        """
        Start listening on the given port.

        This is the same as calling::

            reactor.listenUDP(port, server.protocol)

        Provide interface="::" to accept ipv6 address
        """
        return reactor.listenUDP(port, self.protocol, interface)

Example 24

Project: snmposter Source File: snmposter.py
    def start(self):
        reactor.listenUDP(
            161, agentprotocol.AgentProtocol(
                snmpVersion='v2c',
                agent=agent.Agent(
                    dataStore=bisectoidstore.BisectOIDStore(
                        OIDs=self.oids,
                        ),
                    ),
                ),
                interface=self.ip,
            )

Example 25

Project: smap Source File: settings.py
def setup_statsd(config):
    from txstatsd.client import TwistedStatsDClient, StatsDClientProtocol
    from txstatsd.metrics.metrics import Metrics
    global metrics
    statsd = TwistedStatsDClient(config['statsd']['host'],
                                 config['statsd']['port'])
    metrics = Metrics(connection=statsd,
                      namespace='smap-archiver.' + config['statsd']['prefix'])
    protocol = StatsDClientProtocol(statsd)
    reactor.listenUDP(0, protocol)

Example 26

Project: calvin-base Source File: dht_server.py
Function: start
    def start(self, port=0, iface='', bootstrap=None):
        if bootstrap is None:
            bootstrap = []
        self.kserver = self.server_type()
        self.kserver.bootstrap(bootstrap)

        self.port = reactor.listenUDP(port, self.kserver.protocol, interface=iface)

        return self.port.getHost().host, self.port.getHost().port

Example 27

Project: Coherence Source File: msearch.py
    def __init__(self, ssdp_server, test=False):
        log.Loggable.__init__(self)
        self.ssdp_server = ssdp_server
        if test == False:
            self.port = reactor.listenUDP(0, self)

            self.double_discover_loop = task.LoopingCall(self.double_discover)
            self.double_discover_loop.start(120.0)

Example 28

Project: python-tx-tftp Source File: test_protocol.py
Function: set_up
    def setUp(self):
        self.temp_dir = FilePath(tempfile.mkdtemp()).asBytesMode()
        with self.temp_dir.child(b'nonempty').open('w') as fd:
            fd.write(b'Something uninteresting')
        self.backend = FilesystemSynchronousBackend(self.temp_dir)
        self.tftp = TFTPWrapper(self.backend)
        self.client = DummyClient()
        reactor.listenUDP(0, self.client)
        self.server_port = reactor.listenUDP(1069, self.tftp)

Example 29

Project: calvin-base Source File: dht_server.py
Function: start
    def start(self, port=0, iface='', bootstrap=None):
        if bootstrap is None:
            bootstrap = []

        self.kserver = self.server_type(id=self.id, node_name=self.node_name)
        self.kserver.bootstrap(bootstrap)

        self.port = reactor.listenUDP(port,
                                        self.kserver.protocol,
                                        interface=iface)

        return self.port.getHost().host, self.port.getHost().port

Example 30

Project: mythbox Source File: test_udp.py
Function: test_bad_connect
    def testBadConnect(self):
        client = GoodClient()
        port = reactor.listenUDP(0, client, interface="127.0.0.1")
        self.assertRaises(ValueError, client.transport.connect,
                          "localhost", 80)
        client.transport.connect("127.0.0.1", 80)
        self.assertRaises(RuntimeError, client.transport.connect,
                          "127.0.0.1", 80)
        return port.stopListening()

Example 31

Project: mythbox Source File: test_internet.py
Function: test_udp
        def testUDP(self):
            p = reactor.listenUDP(0, protocol.DatagramProtocol())
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening()

Example 32

Project: nagcat Source File: query_ntp.py
    def _start(self):
        deferred = defer.Deferred()
        protocol = NTPProtocol(self.addr, self.conf['port'], deferred)
        listener = reactor.listenUDP(0, protocol)
        timeout = reactor.callLater(self.conf['timeout'],
                lambda: deferred.errback(errors.Failure(errors.TestCritical(
                        "Timeout waiting for NTP response"))))

        def stop(result):
            if timeout.active():
                timeout.cancel()
            listener.stopListening()
            return result

        deferred.addBoth(stop)
        return deferred

Example 33

Project: mythbox Source File: test_udp.py
Function: test_oldaddress
    def testOldAddress(self):
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        p = reactor.listenUDP(0, server, interface="127.0.0.1")
        def cbStarted(ignored):
            addr = p.getHost()
            self.assertEquals(addr, ('INET_UDP', addr.host, addr.port))
            return p.stopListening()
        return d.addCallback(cbStarted)

Example 34

Project: scalyr-agent-2 Source File: udp.py
Function: openservermode
    def openServerMode(self, iface):
        try:
            self._lport = reactor.listenUDP(iface[1], self, iface[0])
        except Exception:
            raise error.CarrierError(sys.exc_info()[1])
        return self

Example 35

Project: SubliminalCollaborator Source File: test_udp.py
Function: test_rebind
    def test_rebind(self):
        """
        Re-listening with the same L{DatagramProtocol} re-invokes the
        C{startProtocol} callback.
        """
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        p = reactor.listenUDP(0, server, interface="127.0.0.1")

        def cbStarted(ignored, port):
            return port.stopListening()

        def cbStopped(ignored):
            d = server.startedDeferred = defer.Deferred()
            p = reactor.listenUDP(0, server, interface="127.0.0.1")
            return d.addCallback(cbStarted, p)

        return d.addCallback(cbStarted, p)

Example 36

Project: simple-dns Source File: dns.py
def main(port):
    factory = server.DNSServerFactory(
        clients=[create_resolver(servers=[('114.114.114.114', 53)], hosts='hosts')],
    )
    protocol = dns.DNSDatagramProtocol(controller=factory)

    reactor.listenUDP(port, protocol)
    reactor.listenTCP(port, factory)
    reactor.run()

Example 37

Project: kamaelia_ Source File: RawServer_twisted.py
    def create_udpsocket(port, bind='', reuse=False, tos=0):
        s = SocketProxy(port, bind, reuse, tos, 'udp')
        s.protocol = CallbackDatagramProtocol()
        c = ConnectionWrapper(None, None, None, tos)
        s.connection = c
        s.protocol.connection = c

        if s.reuse == False:
            UnimplementedWarning(_("You asked for reuse to be off when binding. Sorry, I can't do that."))
                         
        try:        
            listening_port = reactor.listenUDP(s.port, s.protocol, interface=s.bind)
        except error.CannotListenError, e:
            raise e.socketError
        listening_port.listening = 1
        s.listening_port = listening_port
        
        return s

Example 38

Project: Subspace Source File: network.py
Function: listen
    def listen(self, port):
        """
        Start listening on the given port.

        This is the same as calling::

            reactor.listenUDP(port, server.protocol)
        """
        return reactor.listenUDP(port, self.protocol)

Example 39

Project: bnw Source File: statsd.py
Function: set_up
def setup(host, port):
    client.host = host
    client.port = port
    reactor.listenUDP(0, client, interface=host if host=='127.0.0.1' else '')

Example 40

Project: tahoe-lafs Source File: iputil.py
def get_local_ip_for(target):
    """Find out what our IP address is for use by a given target.

    @return: the IP address as a dotted-quad string which could be used by
              to connect to us. It might work for them, it might not. If
              there is no suitable address (perhaps we don't currently have an
              externally-visible interface), this will return None.
    """

    try:
        target_ipaddr = socket.gethostbyname(target)
    except socket.gaierror:
        # DNS isn't running, or somehow we encountered an error

        # note: if an interface is configured and up, but nothing is
        # connected to it, gethostbyname("A.ROOT-SERVERS.NET") will take 20
        # seconds to raise socket.gaierror . This is synchronous and occurs
        # for each node being started, so users of
        # test.common.SystemTestMixin (like test_system) will see something
        # like 120s of delay, which may be enough to hit the default trial
        # timeouts. For that reason, get_local_addresses_async() was changed
        # to default to the numerical ip address for A.ROOT-SERVERS.NET, to
        # avoid this DNS lookup. This also makes node startup fractionally
        # faster.
        return None

    try:
        udpprot = DatagramProtocol()
        port = reactor.listenUDP(0, udpprot)
        try:
            # connect() will fail if we're offline (e.g. running tests on a
            # disconnected laptop), which is fine (localip=None), but we must
            # still do port.stopListening() or we'll get a DirtyReactorError
            udpprot.transport.connect(target_ipaddr, 7)
            localip = udpprot.transport.getHost().host
            return localip
        finally:
            d = port.stopListening()
            d.addErrback(log.err)
    except (socket.error, CannotListenError):
        # no route to that host
        localip = None
    return localip

Example 41

Project: txstatsd Source File: test_client.py
Function: build_protocol
    def build_protocol(self):
        protocol = StatsDClientProtocol(self.client)
        reactor.listenUDP(0, protocol)

Example 42

Project: polaris Source File: polaris.py
Function: run
    def run(self):
        reactor.listenUDP(UDP_PORT, self.listener)
        reactor.run()

Example 43

Project: arkc-server Source File: main.py
def main():
    parser = argparse.ArgumentParser(description=None)
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="show detailed logs")
    parser.add_argument("-vv", action="store_true", dest="vv",
                        help="show debug logs")
    parser.add_argument(
        "--version", dest="version", action="store_true", help="show version number")
    parser.add_argument('-kg', '--keygen', dest="kg", action="store_true",
                        help="Generate a key string and quit, overriding other options")
    parser.add_argument('--get-meek', dest="dlmeek", action="store_true",
                        help="Download meek to home directory, overriding normal options")
    parser.add_argument('-c', '--config', dest="config", default=None,
                        help="specify a configuration files, required for ArkC to start")
    parser.add_argument("-t", action="store_true", dest="transmit",
                        help="use transmit server")

    parser.add_argument('-ep', "--use-external-proxy", action="store_true",
                        help="""use an external proxy server or handler running locally,e.g. polipo, for better performance.
Use this option to support other types of proxy other than HTTP, or use authentication at client-end proxy.
Fall back to in-built python proxy server otherwise.""")
    print(
        """ArkC Server V""" + VERSION + """ by ArkC Technology.
The programs is distributed under GNU General Public License Version 2.
""")

    args = parser.parse_args()
    if args.version:
        print("ArkC Server Version " + VERSION)
        sys.exit()
    elif args.kg:
        print("Generating 2048 bit RSA key.")
        print("Writing to home directory " + os.path.expanduser('~'))
        generate_RSA(os.path.expanduser(
            '~') + os.sep + 'arkc_pri.asc', os.path.expanduser('~') + os.sep + 'arkc_pub.asc')
        print(
            "Please save the above settings to client and server side config files.")
        sys.exit()
    elif args.dlmeek:
        if sys.platform == 'linux2':
            link = "https://github.com/projectarkc/meek/releases/download/v0.2.2/meek-client"
            localfile = os.path.expanduser('~') + os.sep + "meek-client"
        elif sys.platform == 'win32':
            link = "https://github.com/projectarkc/meek/releases/download/v0.2.2/meek-client.exe"
            localfile = os.path.expanduser('~') + os.sep + "meek-client.exe"
        else:
            print(
                "MEEK for ArkC has no compiled executable for your OS platform. Please compile and install from source.")
            print(
                "Get source at https://github.com/projectarkc/meek/tree/master/meek-client")
            sys.exit()
        print(
            "Downloading meek plugin (meek-client) from github to " + localfile)
        urllib.urlretrieve(link, localfile)
        if sys.platform == 'linux2':
            st = os.stat(localfile)
            os.chmod(localfile, st.st_mode | stat.S_IEXEC)
            print("File made executable.")
        print("Finished. If no error, you may change obfs_level and update pt_exec to " +
              localfile + " to use meek.")
        sys.exit()
    elif args.config is None:
        logging.fatal("Config file (-c or --config) must be specified.\n")
        parser.print_help()
        sys.exit()

    # mapping client public sha1 --> (RSA key object, client private sha1)
    certs = dict()

    data = {}

    # Load json configuration file
    try:
        data_file = open(args.config)
        data = json.load(data_file)
        data_file.close()
    except Exception as err:
        logging.error("Fatal error while loading configuration file.")
        print(err)  # TODO: improve error processing
        sys.exit()

    try:
        for client in data["clients"]:
            with open(client[0], "r") as f:
                remote_cert_txt = f.read()
                remote_cert = RSA.importKey(remote_cert_txt)
                remote_cert_txt = remote_cert_txt.strip(
                    ' ').lstrip('\n')
                certs[sha1(remote_cert_txt).hexdigest()] =\
                     [remote_cert, client[1]]
    except KeyError:
        pass
    except Exception as err:
        print ("Fatal error while loading client certificate.")
        print (err)
        sys.exit()

    try:
        certsdbpath = data["clients_db"]
    except KeyError:
        certsdbpath = None

    try:
        certs_db = certstorage(certs, certsdbpath)
    except Exception as err:
        print ("Fatal error while loading clients' certificate.")
        print (err)
        sys.exit()

    if args.transmit:
        try:
            with open(data["central_cert"], "r") as f:
                central_cert_txt = f.read()
                central_cert = RSA.importKey(central_cert_txt)
        except Exception as err:
            print ("Fatal error while loading client certificate.")
            print (err)
            sys.exit()
    else:
        central_cert = None

    try:
        with open(data["local_cert_path"], "r") as f:
            local_cert = RSA.importKey(f.read())
        if not local_cert.has_private():
            print("Fatal error, no private key included in local certificate.")
    except IOError as err:
        print ("Fatal error while loading local certificate.")
        print (err)
        sys.exit()

    if args.vv:
        logging.basicConfig(stream=sys.stdout, level=logging.DEBUG,
                            format="%(levelname)s: %(asctime)s; %(message)s")
    elif args.verbose:
        logging.basicConfig(stream=sys.stdout, level=logging.INFO,
                            format="%(levelname)s: %(asctime)s; %(message)s")
    else:
        logging.basicConfig(stream=sys.stdout, level=logging.WARNING,
                            format="%(levelname)s: %(asctime)s; %(message)s")

    if not args.use_external_proxy:
        if "proxy_port" not in data:
            data["proxy_port"] = 8100
        start_proxy(data["proxy_port"])
    else:
        if "proxy_port" not in data:
            data["proxy_port"] = 8123

    if "udp_port" not in data:
        if args.transmit:
            data["udp_port"] = 8000
        else:
            data["udp_port"] = 53

    if "socks_proxy" not in data:
        data["socks_proxy"] = None

    if "delegated_domain" not in data:
        data["delegated_domain"] = "public.arkc.org"

    if "self_domain" not in data:
        data["self_domain"] = "freedom.arkc.org"

    if "pt_exec" not in data:
        data["pt_exec"] = "obfs4proxy"

    if "obfs_level" not in data:
        data["obfs_level"] = 0
    elif 1 <= int(data["obfs_level"]) <= 2:
        logging.error(
            "Support for obfs4proxy is experimental with known bugs. Run this mode at your own risk.")

    if "meek_url" not in data:
        data["meek_url"] = "https://arkc-reflect1.appspot.com/"

    # Start the loop
    try:
        reactor.listenUDP(
            data["udp_port"],
            Coordinator(
                data["proxy_port"],
                data["socks_proxy"],
                local_cert,
                certs_db,
                central_cert,
                data["delegated_domain"],
                data["self_domain"],
                data["pt_exec"],
                data["obfs_level"],
                data["meek_url"],
                args.transmit
            )
        )
    except CannotListenError as err:
        print(err.socketError)
        if data["udp_port"] <= 1024 and str(err.socketError) == "[Errno 13] \
                Permission denied":
            print("root privilege may be required to listen to low ports")
        exit()

    try:
        reactor.run()
    except KeyboardInterrupt:
        pass

Example 44

Project: vertex Source File: test_ptcp.py
    def setUpForATest(self,
                      ServerProtocol=TestProtocol, ClientProtocol=TestProtocol):
        serverProto = ServerProtocol()
        clientProto = ClientProtocol()


        self.serverProto = serverProto
        self.clientProto = clientProto

        sf = protocol.ServerFactory()
        sf.protocol = lambda: serverProto

        cf = Django()
        cf.protocol = lambda: clientProto

        serverTransport = ptcp.PTCP(sf)
        clientTransport = ptcp.PTCP(None)

        self.serverTransport = serverTransport
        self.clientTransport = clientTransport

        serverPort = reactor.listenUDP(0, serverTransport)
        clientPort = reactor.listenUDP(0, clientTransport)

        self.clientPort = clientPort
        self.serverPort = serverPort

        return (
            serverProto, clientProto,
            sf, cf,
            serverTransport, clientTransport,
            serverPort, clientPort
            )

Example 45

Project: foolscap Source File: util.py
def get_local_ip_for(target='A.ROOT-SERVERS.NET'):
    """Find out what our IP address is for use by a given target.

    @return: the IP address as a dotted-quad string which could be used by
              to connect to us. It might work for them, it might not. If
              there is no suitable address (perhaps we don't currently have an
              externally-visible interface), this will return None.
    """
    try:
        target_ipaddr = socket.gethostbyname(target)
    except socket.gaierror:
        # DNS isn't running
        return None
    udpprot = protocol.DatagramProtocol()
    port = reactor.listenUDP(0, udpprot)
    try:
        udpprot.transport.connect(target_ipaddr, 7)
        localip = udpprot.transport.getHost().host
    except socket.error:
        # no route to that host
        localip = None
    port.stopListening() # note, this returns a Deferred
    return localip

Example 46

Project: txstatsd Source File: test_service.py
    def test_monitor_response(self):
        """
        The StatsD service messages the expected response to the
        monitoring agent.
        """
        from twisted.internet import reactor

        options = service.StatsDOptions()
        processor = MessageProcessor()
        statsd_server_protocol = StatsDServerProtocol(
            processor,
            monitor_message=options["monitor-message"],
            monitor_response=options["monitor-response"])
        reactor.listenUDP(options["listen-port"], statsd_server_protocol)

        agent = Agent()
        reactor.listenUDP(0, agent)

        @inlineCallbacks
        def exercise():
            def monitor_send():
                agent.transport.write(
                    options["monitor-message"],
                    ("127.0.0.1", options["listen-port"]))

            def statsd_response(result):
                self.assertEqual(options["monitor-response"],
                                 agent.monitor_response)

            yield monitor_send()

            d = Deferred()
            d.addCallback(statsd_response)
            reactor.callLater(.1, d.callback, None)
            try:
                yield d
            except:
                raise
            finally:
                reactor.stop()

        reactor.callWhenRunning(exercise)
        reactor.run()

Example 47

Project: pyutil Source File: iputil.py
Function: get_local_ip_for
def get_local_ip_for(target):
    """Find out what our IP address is for use by a given target.

    @return: the IP address as a dotted-quad string which could be used by
              to connect to us. It might work for them, it might not. If
              there is no suitable address (perhaps we don't currently have an
              externally-visible interface), this will return None.
    """

    try:
        target_ipaddr = socket.gethostbyname(target)
    except socket.gaierror:
        # DNS isn't running, or somehow we encountered an error

 	# note: if an interface is configured and up, but nothing is connected to it,
 	# gethostbyname("A.ROOT-SERVERS.NET") will take 20 seconds to raise socket.gaierror
 	# . This is synchronous and occurs for each node being started, so users of certain unit
 	# tests will see something like 120s of delay, which may be enough to hit the default
 	# trial timeouts. For that reason, get_local_addresses_async() was changed to default to
 	# the numerical ip address for A.ROOT-SERVERS.NET, to avoid this DNS lookup. This also
 	# makes node startup a tad faster.

        return None
    udpprot = DatagramProtocol()
    port = reactor.listenUDP(0, udpprot)
    try:
        udpprot.transport.connect(target_ipaddr, 7)
        localip = udpprot.transport.getHost().host
    except socket.error:
        # no route to that host
        localip = None
    port.stopListening() # note, this returns a Deferred
    return localip

Example 48

Project: python-tx-tftp Source File: server.py
Function: main
def main():
    random.seed()
    log.startLogging(sys.stdout)
    reactor.listenUDP(1069, TFTP(FilesystemSynchronousBackend('output')))
    reactor.run()

Example 49

Project: SimpleDNS Source File: dnsproxy.py
def main():
    parser = argparse.ArgumentParser(
        description="A lightweight yet useful proxy DNS server")
    parser.add_argument('-b', '--bind-addr', type=str,
                        help='local address to listen',
                        default=DEFAULT_LOCAL_ADDRESS,
                        )
    parser.add_argument('-p', '--bind-port', type=int,
                        help="local port to listen",
                        default=DEFAULT_LOCAL_PORT,
                        )
    parser.add_argument('--upstream-ip', type=str,
                        help="upstream DNS server ip address",
                        default=DEFAULT_UPSTREAM_SERVER)
    parser.add_argument('--upstream-port', type=int,
                        help="upstream DNS server port",
                        default=53)
    parser.add_argument('--query-timeout', type=int,
                        help="time before close port used for querying",
                        default=10)
    parser.add_argument('--min-ttl', type=int,
                        help="the minimum time a record is held in cache",
                        default=0)
    parser.add_argument('--max-ttl', type=int,
                        help="the maximum time a record is held in cache",
                        default=604800)
    parser.add_argument('--cache-size', type=int,
                        help="record cache size",
                        default=1000)
    parser.add_argument('-t', '--tcp-server',
                        help="enables TCP serving",
                        action="store_true")
    parser.add_argument('--hosts-file',
                        help="hosts file",
                        default="")
    parser.add_argument('--dispatch-conf',
                        help="URL dispatch conf file",
                        default=DEFAULT_CONF_PATH)
    parser.add_argument('-v', '--verbosity', type=int,
                        choices=[0, 1, 2],
                        help="output verbosity",
                        default=0)
    parser.add_argument('-q', '--quiet',
                        help="disable output",
                        action='store_true')
    parser.add_argument('-V', '--version',
                        action='version',
                        version="SimpleDNS " + str(__version__))

    args = parser.parse_args()
    if not args.quiet:
        log.startLogging(sys.stdout)

    addr = args.bind_addr
    port = args.bind_port
    log.msg("Listening on " + addr + ':' + str(port))
    log.msg("Using " + args.upstream_ip + ':' +
            str(args.upstream_port) + ' as upstream server')

    hosts_file = None
    if not args.hosts_file:
        hosts_file = DEFAULT_HOSTS_PATH
        if os.environ.__contains__('WINDIR'):
            hosts_file = DEFAULT_WIN_HOSTS_PATH
    else:
        hosts_file = args.hosts_file

    local_cache = None
    if os.path.isfile(DEFAULT_CACHE_PATH):
        local_cache = open(DEFAULT_CACHE_PATH, 'rb')
    factory = ExtendDNSServerFactory(
        caches=[ExtendCacheResolver(
            verbose=args.verbosity,_cache=local_cache, cacheSize=args.cache_size, minTTL=args.min_ttl, maxTTL=args.max_ttl)],
        clients=[
            hosts.Resolver(hosts_file),
            DispatchResolver(args.dispatch_conf, servers=[(args.upstream_ip, args.upstream_port)], minTTL=args.min_ttl, query_timeout=args.query_timeout, verbose=args.verbosity
                             )],
        verbose=args.verbosity
    )
    if local_cache:
        local_cache.close()

    protocol = dns.DNSDatagramProtocol(controller=factory)
    if args.verbosity < 2:
        dns.DNSDatagramProtocol.noisy = False
        server.DNSServerFactory.noisy = False
    try:
        reactor.listenUDP(port, protocol, addr)
        if args.tcp_server:
            reactor.listenTCP(
                port, factory, interface=addr)
        if TORNADO_AVAILABLE:
            if args.verbosity > 1:
                log.msg("Using Tornado ioloop")
            signal.signal(signal.SIGINT, lambda sig, frame: tornado.ioloop.IOLoop.instance().add_callback_from_signal(try_exit_tornado_ioloop))
            tornado.ioloop.IOLoop.instance().start()
        else:
            if args.verbosity > 1:
                log.msg("Using Twisted reactor")
            reactor.run()
    except error.CannotListenError:
        log.msg(
            "Can not listen on " + addr + ':' + str(port))
        log.msg('Check if BIND_PORT is already in use')
        log.msg('Try to run this with sudo')

Example 50

Project: python-tx-tftp Source File: protocol.py
    @inlineCallbacks
    def _startSession(self, datagram, addr, mode):
        # Set up a call context so that we can pass extra arbitrary
        # information to interested backends without adding extra call
        # arguments, or switching to using a request object, for example.
        context = {}
        if self.transport is not None:
            # Add the local and remote addresses to the call context.
            local = self.transport.getHost()
            context["local"] = local.host, local.port
            context["remote"] = addr
        try:
            if datagram.opcode == OP_WRQ:
                fs_interface = yield call(
                    context, self.backend.get_writer, datagram.filename)
            elif datagram.opcode == OP_RRQ:
                fs_interface = yield call(
                    context, self.backend.get_reader, datagram.filename)
        except Unsupported as e:
            self.transport.write(ERRORDatagram.from_code(ERR_ILLEGAL_OP,
                u"{}".format(e).encode("ascii", "replace")).to_wire(), addr)
        except AccessViolation:
            self.transport.write(ERRORDatagram.from_code(ERR_ACCESS_VIOLATION).to_wire(), addr)
        except FileExists:
            self.transport.write(ERRORDatagram.from_code(ERR_FILE_EXISTS).to_wire(), addr)
        except FileNotFound:
            self.transport.write(ERRORDatagram.from_code(ERR_FILE_NOT_FOUND).to_wire(), addr)
        except BackendError as e:
            self.transport.write(ERRORDatagram.from_code(ERR_NOT_DEFINED,
                u"{}".format(e).encode("ascii", "replace")).to_wire(), addr)
        else:
            if datagram.opcode == OP_WRQ:
                if mode == b'netascii':
                    fs_interface = NetasciiReceiverProxy(fs_interface)
                session = RemoteOriginWriteSession(addr, fs_interface,
                                                   datagram.options, _clock=self._clock)
                reactor.listenUDP(0, session)
                returnValue(session)
            elif datagram.opcode == OP_RRQ:
                if mode == b'netascii':
                    fs_interface = NetasciiSenderProxy(fs_interface)
                session = RemoteOriginReadSession(addr, fs_interface,
                                                  datagram.options, _clock=self._clock)
                reactor.listenUDP(0, session)
                returnValue(session)
See More Examples - Go to Next Page
Page 1 Selected Page 2