twisted.internet.endpoints.TCP4ClientEndpoint

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

53 Examples 7

Example 1

Project: pappy-proxy
Source File: test_http_proxy.py
View license
def test_no_tcp():
    from twisted.internet.endpoints import SSL4ClientEndpoint, TCP4ClientEndpoint
    from txsocksx.client import SOCKS5ClientEndpoint
    from txsocksx.tls import TLSWrapClientEndpoint
    with pytest.raises(NotImplementedError):
        SSL4ClientEndpoint('aasdfasdf.sdfwerqwer')
    with pytest.raises(NotImplementedError):
        TCP4ClientEndpoint('aasdfasdf.sdfwerqwer')
    with pytest.raises(NotImplementedError):
        SOCKS5ClientEndpoint('aasdfasdf.sdfwerqwer')
    with pytest.raises(NotImplementedError):
        TLSWrapClientEndpoint('asdf.2341')

Example 2

Project: tahoe-lafs
Source File: test_connections.py
View license
    def test_controlport(self):
        h1 = mock.Mock()
        with mock.patch("foolscap.connections.tor.control_endpoint",
                        return_value=h1) as f:
            n = FakeNode(BASECONFIG+"[tor]\ncontrol.port = tcp:localhost:1234\n")
            h = n._make_tor_handler()
            self.assertEqual(len(f.mock_calls), 1)
            ep = f.mock_calls[0][1][0]
            self.assertIsInstance(ep, endpoints.TCP4ClientEndpoint)
            self.assertIdentical(h, h1)

Example 3

Project: tahoe-lafs
Source File: test_connections.py
View license
    def test_samport(self):
        n = FakeNode(BASECONFIG+"[i2p]\nsam.port = tcp:localhost:1234\n")
        h1 = mock.Mock()
        with mock.patch("foolscap.connections.i2p.sam_endpoint",
                        return_value=h1) as f:
            h = n._make_i2p_handler()
            self.assertEqual(len(f.mock_calls), 1)
            ep = f.mock_calls[0][1][0]
            self.assertIsInstance(ep, endpoints.TCP4ClientEndpoint)
            self.assertIdentical(h, h1)

Example 4

Project: foolscap
Source File: test_connection.py
View license
    @inlineCallbacks
    def test_default(self):
        with mock.patch("foolscap.connections.i2p.SAMI2PStreamClientEndpoint") as sep:
            sep.new = n = mock.Mock()
            n.return_value = expected_ep = object()
            h = i2p.default(reactor)
            res = yield h.hint_to_endpoint("i2p:fppym.b32.i2p", reactor)
        self.assertEqual(len(n.mock_calls), 1)
        args = n.mock_calls[0][1]
        got_sep, got_host, got_portnum = args
        self.assertIsInstance(got_sep, endpoints.TCP4ClientEndpoint)
        self.failUnlessEqual(got_sep._host, "127.0.0.1") # fragile
        self.failUnlessEqual(got_sep._port, 7656)
        self.failUnlessEqual(got_host, "fppym.b32.i2p")
        self.failUnlessEqual(got_portnum, None)
        ep, host = res
        self.assertIdentical(ep, expected_ep)
        self.assertEqual(host, "fppym.b32.i2p")

Example 5

Project: zmqproto
Source File: zmqsocket.py
View license
    def connect(self, address):
        from twisted.internet import reactor
        from twisted.internet.endpoints import TCP4ClientEndpoint
        self.address = address
        host, port = self.parse_address(address)
        if DEBUG:
            print "Connecting to", host, port
        point = TCP4ClientEndpoint(reactor, host, port)
        d = point.connect(self.factory)
        d.addCallback(self.on_protocol)
        d.addErrback(self.on_connection_error)
        return d

Example 6

Project: tensor
Source File: test_tensor.py
View license
    @defer.inlineCallbacks
    def test_tcp_riemann(self):

        event = Event('ok', 'sky', 'Sky has not fallen', 1.0, 60.0)

        end = TCP4ClientEndpoint(reactor, "localhost", 5555)
       
        p = yield connectProtocol(end, riemann.RiemannProtocol())

        yield p.sendEvents([event])

        p.transport.loseConnection()

Example 7

Project: txsocksx
Source File: get-ip-http.py
View license
def main(reactor):
    torEndpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 9050)
    agent = SOCKS5Agent(reactor, proxyEndpoint=torEndpoint)
    d = agent.request('GET', 'http://api.externalip.net/ip/')
    d.addCallback(readBody)
    d.addCallback(print)
    return d

Example 8

Project: txsocksx
Source File: get-ip-socks4.py
View license
def main(reactor):
    torEndpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 9050)
    proxiedEndpoint = SOCKS4ClientEndpoint('api.externalip.net', 80, torEndpoint)
    d = proxiedEndpoint.connect(TerribleHTTPClientFactory())
    d.addCallback(lambda proto: proto.deferred)
    d.addCallback(print)
    return d

Example 9

Project: txsocksx
Source File: get-ip.py
View license
def main(reactor):
    torEndpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 9050)
    proxiedEndpoint = SOCKS5ClientEndpoint('api.externalip.net', 80, torEndpoint)
    d = proxiedEndpoint.connect(TerribleHTTPClientFactory())
    d.addCallback(lambda proto: proto.deferred)
    d.addCallback(print)
    return d

Example 10

Project: txsocksx
Source File: tor-irc.py
View license
def main(reactor):
    torEndpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 9050)
    # freenode's tor endpoint
    ircEndpoint = SOCKS5ClientEndpoint('lgttsalmpw3qo4no.onion', 6667, torEndpoint)
    d = ircEndpoint.connect(SpewingFactory(TorIRCFactory()))
    d.addCallback(lambda proto: proto.wrappedProtocol.deferred)
    return d

Example 11

Project: golem
Source File: tcpnetwork.py
View license
    def __try_to_connect_to_address(self, address, port, established_callback, failure_callback, **kwargs):
        logger.debug("Connection to host {}: {}".format(address, port))

        use_ipv6 = False
        try:
            ip = ip_address(address.decode())
            use_ipv6 = ip.version == 6
        except ValueError:
            logger.warning("{} address is invalid".format(address))
        if use_ipv6:
            endpoint = TCP6ClientEndpoint(self.reactor, address, port, self.timeout)
        else:
            endpoint = TCP4ClientEndpoint(self.reactor, address, port, self.timeout)

        defer = endpoint.connect(self.protocol_factory)

        defer.addCallback(self.__connection_established, established_callback, **kwargs)
        defer.addErrback(self.__connection_failure, failure_callback, **kwargs)

Example 12

Project: ccs-calendarserver
Source File: amphub.py
View license
    @classmethod
    @inlineCallbacks
    def start(cls, hostsAndPorts):
        """
        Instantiates the AMPHub singleton and connects to the hosts.

        @param hostsAndPorts: The hosts and ports to connect to
        @type hostsAndPorts: A list of (hostname, port) tuples
        """

        cls._hub = cls()

        for host, port in hostsAndPorts:
            endpoint = TCP4ClientEndpoint(reactor, host, port)
            factory = AMPPushClientFactory(cls._hub._pushReceived)
            protocol = yield endpoint.connect(factory)
            cls._hub.protocols.append(protocol)

Example 13

Project: ccs-calendarserver
Source File: amphub.py
View license
    @classmethod
    @inlineCallbacks
    def start(cls, hostsAndPorts):
        """
        Instantiates the AMPHub singleton and connects to the hosts.

        @param hostsAndPorts: The hosts and ports to connect to
        @type hostsAndPorts: A list of (hostname, port) tuples
        """

        cls._hub = cls()

        for host, port in hostsAndPorts:
            endpoint = TCP4ClientEndpoint(reactor, host, port)
            factory = AMPPushClientFactory(cls._hub._pushReceived)
            protocol = yield endpoint.connect(factory)
            cls._hub.protocols.append(protocol)

Example 14

View license
    def setUp(self):
        """
        Create a L{MemCachePool}.
        """
        TestCase.setUp(self)
        self.reactor = StubReactor()
        self.pool = MemCachePool(
            TCP4ClientEndpoint(self.reactor, MC_ADDRESS.host, MC_ADDRESS.port),
            maxClients=5, reactor=self.reactor
        )
        realClientFactory = self.pool.clientFactory
        self.clientFactories = []

        def capturingClientFactory(*a, **k):
            cf = realClientFactory(*a, **k)
            self.clientFactories.append(cf)
            return cf
        self.pool.clientFactory = capturingClientFactory

Example 15

View license
    def setUp(self):
        """
        Create a L{MemCachePool}.
        """
        TestCase.setUp(self)
        self.reactor = StubReactor()
        self.pool = MemCachePool(
            TCP4ClientEndpoint(self.reactor, MC_ADDRESS.host, MC_ADDRESS.port),
            maxClients=5, reactor=self.reactor
        )
        realClientFactory = self.pool.clientFactory
        self.clientFactories = []

        def capturingClientFactory(*a, **k):
            cf = realClientFactory(*a, **k)
            self.clientFactories.append(cf)
            return cf
        self.pool.clientFactory = capturingClientFactory

Example 16

Project: txtorcon
Source File: endpoints.py
View license
    def _parseClient(self, host=None, port=None,
                     socksHostname=None, socksPort=None,
                     socksUsername=None, socksPassword=None):
        if port is not None:
            port = int(port)
        if socksHostname is None:
            socksHostname = '127.0.0.1'
        if socksPort is not None:
            socksPort = int(socksPort)

        ep = None
        if socksPort is not None:
            ep = TCP4ClientEndpoint(reactor, socksHostname, socksPort)
        return TorClientEndpoint(
            host, port,
            socks_endpoint=ep,
            socks_username=socksUsername,
            socks_password=socksPassword,
        )

Example 17

Project: txtorcon
Source File: endpoints.py
View license
    def _parseClient(self, host=None, port=None,
                     socksHostname=None, socksPort=None,
                     socksUsername=None, socksPassword=None):
        if port is not None:
            port = int(port)
        if socksHostname is None:
            socksHostname = '127.0.0.1'
        if socksPort is not None:
            socksPort = int(socksPort)

        ep = None
        if socksPort is not None:
            ep = TCP4ClientEndpoint(reactor, socksHostname, socksPort)
        return TorClientEndpoint(
            host, port,
            socks_endpoint=ep,
            socks_username=socksUsername,
            socks_password=socksPassword,
        )

Example 18

Project: txtorcon
Source File: 0_connection.py
View license
@inlineCallbacks
def main(reactor):
    # change the port to 9151 for Tor Browser Bundle
    connection = TCP4ClientEndpoint(reactor, "localhost", 9051)

    state = yield txtorcon.build_tor_connection(connection)
    print("Connected to tor {state.protocol.version}".format(state=state))
    print("Current circuits:")
    for circ in state.circuits.values():
        path = '->'.join([r.name for r in circ.path])
        print("  {circ.id}: {circ.state}, {path}".format(circ=circ, path=path))

    # can also do "low level" things with the protocol
    proto = state.protocol
    answer = yield proto.queue_command("GETINFO version")
    print("GETINFO version: {answer}".format(answer=answer))

Example 19

Project: txtorcon
Source File: 0_connection.py
View license
@inlineCallbacks
def main(reactor):
    # change the port to 9151 for Tor Browser Bundle
    connection = TCP4ClientEndpoint(reactor, "localhost", 9051)

    state = yield txtorcon.build_tor_connection(connection)
    print("Connected to tor {state.protocol.version}".format(state=state))
    print("Current circuits:")
    for circ in state.circuits.values():
        path = '->'.join([r.name for r in circ.path])
        print("  {circ.id}: {circ.state}, {path}".format(circ=circ, path=path))

    # can also do "low level" things with the protocol
    proto = state.protocol
    answer = yield proto.queue_command("GETINFO version")
    print("GETINFO version: {answer}".format(answer=answer))

Example 20

Project: worker
Source File: graphite.py
View license
    def connect(self, reconnecting=False):
        if self.connecting and not reconnecting:
            return
        self.connecting = True
        end_point = TCP4ClientEndpoint(reactor, self.host, self.port, 10)
        d = end_point.connect(Factory.forProtocol(GraphiteProtocol))

        def success(connection):
            self.connecting = False
            log.info('Connected to {replica}', replica=self)
            self.connection = connection

        def failed(error):
            log.error('Connect to {replica} failed: {error}', replica=self, error=error)
            reactor.callLater(10, self.connect, True)
        d.addCallbacks(success, failed)

Example 21

Project: SubliminalCollaborator
Source File: test_tls.py
View license
    def client(self, reactor, serverAddress):
        """
        Construct a TCP client endpoint wrapped to immediately start TLS.
        """
        return StartTLSClientEndpoint(
            TCP4ClientEndpoint(
                reactor, '127.0.0.1', serverAddress.port),
            ClientContextFactory())

Example 22

Project: SubliminalCollaborator
Source File: test_tls.py
View license
    def client(self, reactor, serverAddress):
        """
        Construct a TCP client endpoint wrapped to immediately start TLS.
        """
        return StartTLSClientEndpoint(
            TCP4ClientEndpoint(
                reactor, '127.0.0.1', serverAddress.port),
            ClientContextFactory())

Example 23

Project: eth-proxy
Source File: socket_transport.py
View license
def sockswrapper(proxy, dest):
    endpoint = endpoints.TCP4ClientEndpoint(reactor, dest[0], dest[1])
    return socksclient.SOCKSWrapper(reactor, proxy[0], proxy[1], endpoint)

Example 24

Project: arkc-server
Source File: control.py
View license
    def __init__(self, initiator, signature_to_client, client_sha1, client_pub, client_pri_sha1,
                 host, port, main_pw, req_num, certs_str=None):
        self.initiator = initiator
        self.signature_to_client = signature_to_client
        self.socksproxy = self.initiator.socksproxy
        self.close_char = chr(4) * 5
        self.client_sha1 = client_sha1
        self.obfs_level = self.initiator.obfs_level
        self.client_pub = client_pub
        self.client_pri_sha1 = client_pri_sha1
        self.original_host = self.host = host
        self.original_port = self.port = port
        self.main_pw = main_pw
        self.req_num = req_num
        self.certs_str = certs_str
        self.max_retry = 5
        self.retry_count = 0
        self.swap_count = 0

        self.preferred_conn = None

        # None -> no connection
        # 1 -> connection in authentication
        # ClientConnector -> connection ready
        self.client_connectors_pool = [None] * req_num
        # each entry is a dict: conn_id -> queue
        # a queue is formed by (index, data) pairs in order
        self.client_buf_pool = [{}] * req_num

        # maps ID to ProxyConnectors
        self.proxy_connectors_dict = dict()

        # maps ID to decrypted data segments
        self.proxy_write_queues_dict = dict()
        self.proxy_write_queues_index_dict = dict()
        self.proxy_recv_index_dict = dict()

        self.client_recv_index_dict = [{}] * req_num

        # maps ID to the index of the LAST segment to be transmitted with this
        # ID, updated when the proxy server closes a connection
        self.proxy_max_index_dict = dict()

        # Create an endpoint for the HTTP proxy
        host, port = "127.0.0.1", self.initiator.proxy_port
        self.proxy_point = TCP4ClientEndpoint(reactor, host, port)

        # ptproxy (obfs4)
        if self.certs_str:
            self.ptproxy_local_port = random.randint(30000, 40000)
            while self.ptproxy_local_port in initiator.usedports:
                self.ptproxy_local_port += 1
            initiator.usedports.append(self.ptproxy_local_port)
            pt = threading.Thread(
                target=self.ptinit)
            pt.setDaemon(True)
            self.check = threading.Event()
            pt.start()
            self.check.wait(100)

        # meek (GAE) init
        if self.obfs_level == 3:
            self.ptproxy_local_port = None
            if "appspot.com" in self.initiator.meek_url:
                logging.info("Using GAE mode for appspot.com detected in URL.")
                cmdline = self.initiator.pt_exec + \
                    " --url=" + self.initiator.meek_url + \
                    " --desturl=http://" + self.host + \
                    ":" + str(self.port) + "/"
            else:
                logging.info("Using CDN mode with " + self.initiator.meek_url)
                cmdline = self.initiator.pt_exec + \
                    " --url=" + self.initiator.meek_url
            self.check = threading.Event()
            meek_var = {
                "ptexec": cmdline,
                "localport": self.ptproxy_local_port,
                "LOCK": self.check
            }
            self.meek = meek(self, meek_var)
            pt = threading.Thread(
                target=self.meek.meekinit)
            pt.setDaemon(True)
            pt.start()
            self.check.wait(100)

Example 25

Project: arkc-server
Source File: control.py
View license
    def connect(self):
        """Connect client."""
        if any(_ is None for _ in self.client_connectors_pool):

            connector = ClientConnector(self)

            # connect through Tor if required, direct connection otherwise
            if self.socksproxy:
                proxy = random.choice(self.socksproxy)
                # Further settings and check
                socks_point = TCP4ClientEndpoint(reactor, proxy[0], proxy[1])
                point = SOCKS5Point(self.host, self.port, socks_point)
            elif self.obfs_level == 3:
                meek_point = TCP4ClientEndpoint(
                    reactor, "127.0.0.1", self.ptproxy_local_port)
                point = SOCKS4Point(self.host, self.port, meek_point)
            else:
                point = TCP4ClientEndpoint(reactor, self.host, self.port)

            deferred = connectProtocol(point, connector)
            # trigger success or failure action depending on the result
            deferred.addCallback(self.success)
            deferred.addErrback(lambda ignored: self.retry(connector))

Example 26

Project: cache-busters
Source File: tap.py
View license
def makeService(options):
    from twisted.internet import task as cooperator
    from twisted.internet import reactor
    from twisted.python import log

    with open(options['config']) as f:
        data = f.read()
        config = yaml.safe_load(data)
        key_maker = FormattingKeyMaker(data["on_update"])

    cache_backend = MultiCache([
        MemcachedCache(TCP4ClientEndpoint(reactor, cache, DEFAULT_PORT))
        for cache in config['caches']
    ])

    driver = Driver(key_maker, cache_backend, log)

    connection = BinLogStreamReader(connection_settings=config['database'])

    listener = MySQLDatabaseListener(reactor, connection, driver, log)

    return DatabaseListenerService(cooperator, listener, log)

Example 27

Project: pappy-proxy
Source File: proxy.py
View license
def make_proxied_connection(protocol_factory, target_host, target_port, use_ssl,
                            socks_config=None, log_id=None, http_error_transport=None):
    from twisted.internet.endpoints import SSL4ClientEndpoint, TCP4ClientEndpoint
    from txsocksx.client import SOCKS5ClientEndpoint
    from txsocksx.tls import TLSWrapClientEndpoint
    from pappyproxy.pappy import session

    if socks_config is not None:
        log("Connecting to socks proxy", id=log_id)
        sock_host = socks_config['host']
        sock_port = int(socks_config['port'])
        methods = {'anonymous': ()}
        if 'username' in socks_config and 'password' in socks_config:
            methods['login'] = (socks_config['username'], socks_config['password'])
        tcp_endpoint = TCP4ClientEndpoint(reactor, sock_host, sock_port)
        socks_endpoint = SOCKS5ClientEndpoint(target_host, target_port, tcp_endpoint, methods=methods)
        if use_ssl:
            log("Using SSL over proxy to connect to %s:%d ssl=%s" % (target_host, target_port, use_ssl), id=log_id)
            endpoint = TLSWrapClientEndpoint(ssl.ClientContextFactory(), socks_endpoint)
        else:
            log("Using TCP over proxy to connect to %s:%d ssl=%s" % (target_host, target_port, use_ssl), id=log_id)
            endpoint = socks_endpoint
    else:
        log("Connecting directly to host", id=log_id)
        if use_ssl:
            log("Using SSL to connect to %s:%d ssl=%s" % (target_host, target_port, use_ssl), id=log_id)
            #context = BrowserLikePolicyForHTTPS().creatorForNetloc(target_host, target_port)
            context = ssl.ClientContextFactory()
            endpoint = SSL4ClientEndpoint(reactor, target_host, target_port, context)
        else:
            log("Using TCP to connect to %s:%d ssl=%s" % (target_host, target_port, use_ssl), id=log_id)
            endpoint = TCP4ClientEndpoint(reactor, target_host, target_port)

    connection_deferred = endpoint.connect(protocol_factory)
    if http_error_transport:
        connection_deferred.addErrback(connection_error_http_response,
                                       http_error_transport, log_id)

Example 28

Project: ooni-backend
Source File: http_helpers.py
View license
    @defer.inlineCallbacks
    def tcp_connect(self, socket):
        cached_value = yield self.lookup('tcp_connect', socket)
        if cached_value is not None:
            defer.returnValue(cached_value)

        socket_info = {
            'status': None,
            'failure': None
        }

        ip_address, port = socket.split(":")
        try:
            point = TCP4ClientEndpoint(reactor, ip_address, int(port))
            yield point.connect(TCPConnectFactory())
            socket_info['status'] = True
        except TimeoutError:
            socket_info['status'] = False
            socket_info['failure'] = 'generic_timeout_error'
        except ConnectionRefusedError:
            socket_info['status'] = False
            socket_info['failure'] = 'connection_refused_error'
        except ConnectError:
            socket_info['status'] = False
            socket_info['failure'] = 'connect_error'
        except:
            socket_info['status'] = False
            socket_info['failure'] = 'unknown_error'
        yield self.cache_value('tcp_connect', socket, socket_info)
        defer.returnValue(socket_info)

Example 29

Project: foolscap
Source File: test_connection.py
View license
    @inlineCallbacks
    def test_default_with_portnum(self):
        # I2P addresses generally don't use port numbers, but the parser is
        # supposed to handle them
        with mock.patch("foolscap.connections.i2p.SAMI2PStreamClientEndpoint") as sep:
            sep.new = n = mock.Mock()
            n.return_value = expected_ep = object()
            h = i2p.default(reactor)
            res = yield h.hint_to_endpoint("i2p:fppym.b32.i2p:1234", reactor)
        self.assertEqual(len(n.mock_calls), 1)
        args = n.mock_calls[0][1]
        got_sep, got_host, got_portnum = args
        self.assertIsInstance(got_sep, endpoints.TCP4ClientEndpoint)
        self.failUnlessEqual(got_sep._host, "127.0.0.1") # fragile
        self.failUnlessEqual(got_sep._port, 7656)
        self.failUnlessEqual(got_host, "fppym.b32.i2p")
        self.failUnlessEqual(got_portnum, 1234)
        ep, host = res
        self.assertIdentical(ep, expected_ep)
        self.assertEqual(host, "fppym.b32.i2p")

Example 30

Project: txdbus
Source File: endpoints.py
View license
def getDBusEndpoints(reactor, busAddress, client=True):
    """
    Creates DBus endpoints.

    @param busAddress: 'session', 'system', or a valid bus address as defined by
                       the DBus specification. If 'session' (the default) or 'system'
                       is supplied, the contents of the DBUS_SESSION_BUS_ADDRESS or
                       DBUS_SYSTEM_BUS_ADDRESS environment variables will be used for
                       the bus address, respectively. If DBUS_SYSTEM_BUS_ADDRESS is not
                       set, the well-known address unix:path=/var/run/dbus/system_bus_socket
                       will be used.
    @type busAddress: C{string}
    
    @rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint}
    @returns: A list of endpoint instances
    """

    if busAddress == 'session':
        addrString = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None)
        if addrString is None:
            raise Exception('DBus Session environment variable not set')

    elif busAddress == 'system':
        addrString = os.environ.get('DBUS_SYSTEM_BUS_ADDRESS',
                                    'unix:path=/var/run/dbus/system_bus_socket')

    else:
        addrString = busAddress
    
    #XXX Add documentation about extra key=value parameters in address string
    #    such as nonce-tcp vs tcp which use same endpoint class
    epl = list()

    for ep_addr in addrString.split(';'):
        d    = dict()
        kind = None
        ep   = None
        
        for c in ep_addr.split(','):
            if c.startswith('unix:'):
                kind = 'unix'
                c = c[5:]
            elif c.startswith('tcp:'):
                kind = 'tcp'
                c = c[4:]
            elif c.startswith('nonce-tcp:'):
                kind = 'tcp'
                c = c[10:]
                d['nonce-tcp'] = True
            elif c.startswith('launchd:'):
                kind = 'launchd'
                c = c[7:]

            if '=' in c:
                k,v = c.split('=')
                d[k] = v

        if kind == 'unix':
            if 'path' in d:
                path = d['path']
            elif 'tmpdir' in d:
                path = d['tmpdir'] + '/dbus-' + str(os.getpid())
            elif 'abstract' in d:
                path = '\0' + d['abstract']

            if client:
                ep = UNIXClientEndpoint(reactor, path=path)
            else:
                ep = UNIXServerEndpoint(reactor, address=path)

        elif kind == 'tcp':
            if client:
                ep = TCP4ClientEndpoint(reactor, d['host'], int(d['port']))
            else:
                ep = TCP4ServerEndpoint(reactor, int(d['port']), interface=d['host'])

        if ep:
            ep.dbus_args = d
            epl.append(ep)

    return epl

Example 31

Project: crossbar
Source File: endpoint.py
View license
def create_connecting_endpoint_from_config(config, cbdir, reactor, log):
    """
    Create a Twisted stream client endpoint from a Crossbar.io transport configuration.

    See: https://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IStreamClientEndpoint.html

    :param config: The transport configuration.
    :type config: dict
    :param cbdir: Crossbar.io node directory (we need this for Unix domain socket paths and TLS key/certificates).
    :type cbdir: str
    :param reactor: The reactor to use for endpoint creation.
    :type reactor: obj

    :returns obj -- An instance implementing IStreamClientEndpoint
    """
    endpoint = None

    # a TCP endpoint
    #
    if config['type'] == 'tcp':

        # the TCP protocol version (v4 or v6)
        #
        version = int(config.get('version', 4))

        # the host to connect to
        #
        host = str(config['host'])

        # the port to connect to
        #
        port = int(config['port'])

        # connection timeout in seconds
        #
        timeout = int(config.get('timeout', 10))

        if 'tls' in config:
            # create a TLS client endpoint
            #
            if _HAS_TLS:
                # TLS client context
                context = _create_tls_client_context(config['tls'], cbdir, log)

                if version == 4:
                    endpoint = SSL4ClientEndpoint(
                        reactor,
                        host,
                        port,
                        context,
                        timeout=timeout,
                    )
                elif version == 6:
                    raise Exception("TLS on IPv6 not implemented")
                else:
                    raise Exception("invalid TCP protocol version {}".format(version))

            else:
                raise Exception("TLS transport requested, but TLS packages not available:\n{}".format(_LACKS_TLS_MSG))

        else:
            # create a non-TLS client endpoint
            #
            if version == 4:
                endpoint = TCP4ClientEndpoint(reactor,
                                              host,
                                              port,
                                              timeout=timeout)
            elif version == 6:
                endpoint = TCP6ClientEndpoint(reactor,
                                              host,
                                              port,
                                              timeout=timeout)
            else:
                raise Exception("invalid TCP protocol version {}".format(version))

    # a Unix Domain Socket endpoint
    #
    elif config['type'] == 'unix':

        # the path
        #
        path = abspath(join(cbdir, config['path']))

        # connection timeout in seconds
        #
        timeout = int(config.get('timeout', 10))

        # create the endpoint
        #
        endpoint = UNIXClientEndpoint(reactor, path, timeout=timeout)

    else:
        raise Exception("invalid endpoint type '{}'".format(config['type']))

    return endpoint

Example 32

Project: twitty-twister
Source File: twitter.py
View license
    def __init__(self, *args, **kwargs):
        self.proxy_username = None
        if "proxy_host" in kwargs:
            port = 80
            if "proxy_port" in kwargs:
                port = kwargs["proxy_port"] 
                del kwargs["proxy_port"]
            if "proxy_username" in kwargs:
                self.proxy_username = kwargs["proxy_username"] 
                del kwargs["proxy_username"]
            if "proxy_password" in kwargs:
                self.proxy_password = kwargs["proxy_password"] 
                del kwargs["proxy_password"]

            endpoint = endpoints.TCP4ClientEndpoint(reactor, kwargs["proxy_host"], port)
            self.agent = client.ProxyAgent(endpoint)
            del kwargs["proxy_host"]
        else:
            self.agent = client.Agent(reactor)

        Twitter.__init__(self, *args, **kwargs)

Example 33

Project: rscoin
Source File: rsc.py
View license
def broadcast(small_dir, data):
    d_list = []
    responses = []
    # d = defer.Deferred()

    def gotProtocol(p):
        p.sendLine(data)

    for (kid, ip, port) in small_dir:
        _stats[ip] += 1
        point = TCP4ClientEndpoint(reactor, ip, int(port), timeout=10)
        f = RSCfactory()

        d = point.connect(f)
        d.addCallback(gotProtocol)
        d.addErrback(f.d.errback)
        # f.d.errback

        d_list += [ f.d ]

    d_all = defer.gatherResults(d_list)
    return d_all

Example 34

Project: GlobaLeaks
Source File: mailutils.py
View license
def sendmail(to_address, subject, body):
    """
    Sends an email using SMTPS/SMTP+TLS and torify the connection

    @param to_address: the to address field of the email
    @param subject: the mail subject
    @param body: the mail body
    @param event: the event description, needed to keep track of failure/success
    """
    try:
        if GLSettings.disable_mail_notification:
            return defer.succeed(None)

        if to_address == "":
            return

        result_deferred = defer.Deferred()

        def errback(reason, *args, **kwargs):
            # TODO: here it should be written a complete debugging of the possible
            #       errors by writing clear log lines in relation to all the stack:
            #       e.g. it should debugged all errors related to: TCP/SOCKS/TLS/SSL/SMTP/SFIGA
            if isinstance(reason, Failure):
                log.err("SMTP connection failed (Exception: %s)" % reason.value)
                log.debug(reason)

            return result_deferred.errback(reason)

        authentication_username=GLSettings.memory_copy.notif.username
        authentication_password=GLSettings.memory_copy.private.smtp_password
        from_address=GLSettings.memory_copy.notif.source_email
        smtp_host=GLSettings.memory_copy.notif.server
        smtp_port=GLSettings.memory_copy.notif.port
        security=GLSettings.memory_copy.notif.security

        message = MIME_mail_build(GLSettings.memory_copy.notif.source_name,
                                  GLSettings.memory_copy.notif.source_email,
                                  to_address,
                                  to_address,
                                  subject,
                                  body)

        log.debug('Sending email to %s using SMTP server [%s:%d] [%s]' %
                  (to_address, smtp_host, smtp_port, security))

        context_factory = GLClientContextFactory()

        esmtp_deferred = defer.Deferred()
        esmtp_deferred.addCallbacks(result_deferred.callback, errback)

        factory = ESMTPSenderFactory(
            authentication_username.encode('utf-8'),
            authentication_password.encode('utf-8'),
            from_address,
            to_address,
            message,
            esmtp_deferred,
            contextFactory=context_factory,
            requireAuthentication=True,
            requireTransportSecurity=(security != 'SSL'),
            retries=0,
            timeout=GLSettings.mail_timeout)

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

        if GLSettings.testing:
            #  Hooking the test down to here is a trick to be able to test all the above code :)
            return defer.succeed(None)

        if not GLSettings.disable_mail_torification:
            socksProxy = TCP4ClientEndpoint(reactor, GLSettings.socks_host, GLSettings.socks_port, timeout=GLSettings.mail_timeout)
            endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'), smtp_port, socksProxy)
        else:
            endpoint = TCP4ClientEndpoint(reactor, smtp_host.encode('utf-8'), smtp_port, timeout=GLSettings.mail_timeout)

        d = endpoint.connect(factory)
        d.addErrback(errback)

        return result_deferred

    except Exception as excep:
        # we strongly need to avoid raising exception inside email logic to avoid chained errors
        log.err("Unexpected exception in sendmail: %s" % str(excep))
        return defer.fail()

Example 35

Project: txsni
Source File: test_txsni.py
View license
def handshake(client_factory, server_factory, hostname, server_endpoint):
    """
    Connect a basic Twisted TLS client endpoint to the provided TxSNI
    TLSEndpoint. Returns a Deferred that fires when the connection has been
    established with a tuple of an instance of the client protocol and the
    listening port.
    """
    def connect_client(listening_port):
        port_number = listening_port.getHost().port

        client = endpoints.TCP4ClientEndpoint(
            reactor, '127.0.0.1', port_number
        )
        options = optionsForClientTLS(
            hostname=hostname, trustRoot=PEM_ROOT
        )
        client = endpoints.wrapClientTLS(options, client)
        connectDeferred = client.connect(client_factory)

        def aggregate(client_proto):
            return (client_proto, listening_port)

        connectDeferred.addCallback(aggregate)
        return connectDeferred

    listenDeferred = server_endpoint.listen(server_factory)
    listenDeferred.addCallback(connect_client)
    return listenDeferred

Example 36

Project: mythbox
Source File: test_endpoints.py
View license
    def createClientEndpoint(self, reactor, clientFactory, **connectArgs):
        """
        Create an L{TCP4ClientEndpoint} and return the values needed to verify
        its behavior.

        @param reactor: A fake L{IReactorTCP} that L{TCP4ClientEndpoint} can
            call L{IReactorTCP.connectTCP} on.
        @param clientFactory: The thing that we expect to be passed to our
            L{IStreamClientEndpoint.connect} implementation.
        @param connectArgs: Optional dictionary of arguments to
            L{IReactorTCP.connectTCP}
        """
        address = IPv4Address("TCP", "localhost", 80)

        return (endpoints.TCP4ClientEndpoint(reactor,
                                             address.host,
                                             address.port,
                                             **connectArgs),
                (address.host, address.port, clientFactory,
                 connectArgs.get('timeout', 30),
                 connectArgs.get('bindAddress', None)),
                address)

Example 37

Project: mythbox
Source File: test_endpoints.py
View license
    def createClientEndpoint(self, reactor, clientFactory, **connectArgs):
        """
        Create an L{TCP4ClientEndpoint} and return the values needed to verify
        its behavior.

        @param reactor: A fake L{IReactorTCP} that L{TCP4ClientEndpoint} can
            call L{IReactorTCP.connectTCP} on.
        @param clientFactory: The thing that we expect to be passed to our
            L{IStreamClientEndpoint.connect} implementation.
        @param connectArgs: Optional dictionary of arguments to
            L{IReactorTCP.connectTCP}
        """
        address = IPv4Address("TCP", "localhost", 80)

        return (endpoints.TCP4ClientEndpoint(reactor,
                                             address.host,
                                             address.port,
                                             **connectArgs),
                (address.host, address.port, clientFactory,
                 connectArgs.get('timeout', 30),
                 connectArgs.get('bindAddress', None)),
                address)

Example 38

Project: twisted-socks
Source File: http.py
View license
    def sockswrapper(self, proxy, url):
        dest = urlparse(url)
        assert dest.port is not None, 'Must specify port number.'
        endpoint = endpoints.TCP4ClientEndpoint(reactor, dest.hostname, dest.port)
        return SOCKSWrapper(reactor, proxy[1], proxy[2], endpoint, self.timestamps)

Example 39

Project: twisted-socks
Source File: http.py
View license
    def sockswrapper(self, proxy, url):
        dest = urlparse(url)
        assert dest.port is not None, 'Must specify port number.'
        endpoint = endpoints.TCP4ClientEndpoint(reactor, dest.hostname, dest.port)
        return SOCKSWrapper(reactor, proxy[1], proxy[2], endpoint, self.timestamps)

Example 40

Project: ccs-calendarserver
Source File: amppush.py
View license
@inlineCallbacks
def subscribeToIDs(host, port, ids, callback, reactor=None):
    """
    Clients can call this helper method to register a callback which
    will get called whenever a push notification is fired for any
    id in the ids list.

    @param host: AMP host name to connect to
    @type host: string
    @param port: AMP port to connect to
    @type port: integer
    @param ids: The push IDs to subscribe to
    @type ids: list of strings
    @param callback: The method to call whenever a notification is
        received.
    @type callback: callable which is passed an id (string)
    """

    if reactor is None:
        from twisted.internet import reactor

    token = str(uuid.uuid4())
    endpoint = TCP4ClientEndpoint(reactor, host, port)
    factory = AMPPushClientFactory(callback)
    protocol = yield endpoint.connect(factory)
    for id in ids:
        yield protocol.callRemote(SubscribeToID, token=token, id=id)

    returnValue(factory)

Example 41

Project: ccs-calendarserver
Source File: amppush.py
View license
@inlineCallbacks
def subscribeToIDs(host, port, ids, callback, reactor=None):
    """
    Clients can call this helper method to register a callback which
    will get called whenever a push notification is fired for any
    id in the ids list.

    @param host: AMP host name to connect to
    @type host: string
    @param port: AMP port to connect to
    @type port: integer
    @param ids: The push IDs to subscribe to
    @type ids: list of strings
    @param callback: The method to call whenever a notification is
        received.
    @type callback: callable which is passed an id (string)
    """

    if reactor is None:
        from twisted.internet import reactor

    token = str(uuid.uuid4())
    endpoint = TCP4ClientEndpoint(reactor, host, port)
    factory = AMPPushClientFactory(callback)
    protocol = yield endpoint.connect(factory)
    for id in ids:
        yield protocol.callRemote(SubscribeToID, token=token, id=id)

    returnValue(factory)

Example 42

View license
@defer.inlineCallbacks
def main(reactor):
    ep = TCP4ClientEndpoint(reactor, "localhost", 9251)
    tor_protocol = yield txtorcon.build_tor_connection(ep, build_state=False)
    print "Connected to Tor"

    hs_public_port = 80
    hs_port = yield txtorcon.util.available_tcp_port(reactor)
    hs_string = '%s 127.0.0.1:%d' % (hs_public_port, hs_port)
    print "Adding ephemeral service", hs_string
    print "(this can take some time; please be patient)"
    hs = txtorcon.EphemeralHiddenService([hs_string])
    yield hs.add_to_tor(tor_protocol)
    print "Added ephemeral HS to Tor:", hs.hostname

    print "Starting site"
    site = server.Site(Simple())
    hs_endpoint = TCP4ServerEndpoint(reactor, hs_port, interface='127.0.0.1')
    yield hs_endpoint.listen(site)

    # in 5 seconds, remove the hidden service -- obviously this is
    # where you'd do your "real work" or whatever.
    d = defer.Deferred()

    @defer.inlineCallbacks
    def remove():
        print "Removing the hiddenservice. Private key was"
        print hs.private_key
        yield hs.remove_from_tor(tor_protocol)
        d.callback(None)
    if False:
        reactor.callLater(5, remove)
        print "waiting 5 seconds"
    else:
        print "waiting forever"
    yield d

Example 43

View license
@defer.inlineCallbacks
def main(reactor):
    ep = TCP4ClientEndpoint(reactor, "localhost", 9251)
    tor_protocol = yield txtorcon.build_tor_connection(ep, build_state=False)
    print "Connected to Tor"

    hs_public_port = 80
    hs_port = yield txtorcon.util.available_tcp_port(reactor)
    hs_string = '%s 127.0.0.1:%d' % (hs_public_port, hs_port)
    print "Adding ephemeral service", hs_string
    print "(this can take some time; please be patient)"
    hs = txtorcon.EphemeralHiddenService([hs_string])
    yield hs.add_to_tor(tor_protocol)
    print "Added ephemeral HS to Tor:", hs.hostname

    print "Starting site"
    site = server.Site(Simple())
    hs_endpoint = TCP4ServerEndpoint(reactor, hs_port, interface='127.0.0.1')
    yield hs_endpoint.listen(site)

    # in 5 seconds, remove the hidden service -- obviously this is
    # where you'd do your "real work" or whatever.
    d = defer.Deferred()

    @defer.inlineCallbacks
    def remove():
        print "Removing the hiddenservice. Private key was"
        print hs.private_key
        yield hs.remove_from_tor(tor_protocol)
        d.callback(None)
    if False:
        reactor.callLater(5, remove)
        print "waiting 5 seconds"
    else:
        print "waiting forever"
    yield d

Example 44

Project: txtorcon
Source File: endpoints.py
View license
    def __init__(self, host, port,
                 socks_endpoint=None,
                 socks_username=None, socks_password=None,
                 tls=False, **kw):
        if host is None or port is None:
            raise ValueError('host and port must be specified')

        self.host = host
        self.port = int(port)
        self.socks_endpoint = socks_endpoint
        self.socks_username = socks_username
        self.socks_password = socks_password
        self.tls = tls

        if self.tls and not _HAVE_TLS:
            raise ValueError(
                "'tls=True' but we don't have TLS support"
            )

        # backwards-compatibility: you used to specify a TCP SOCKS
        # endpoint via socks_hostname= and socks_port= kwargs
        if self.socks_endpoint is None:
            try:
                self.socks_endpoint = TCP4ClientEndpoint(
                    reactor,
                    kw['socks_hostname'],
                    kw['socks_port'],
                )
                # XXX should deprecation-warn here
            except KeyError:
                pass

        # this is a separate "if" from above in case socks_endpoint
        # was None but the user specified the (old)
        # socks_hostname/socks_port (in which case we do NOT want
        # guessing_enabled
        if self.socks_endpoint is None:
            self._socks_port_iter = iter(self.socks_ports_to_try)
            self._socks_guessing_enabled = True
        else:
            self._socks_guessing_enabled = False

Example 45

Project: txtorcon
Source File: endpoints.py
View license
    @defer.inlineCallbacks
    def connect(self, protocolfactory):
        last_error = None
        kwargs = dict()
        if self.socks_username is not None and self.socks_password is not None:
            kwargs['methods'] = dict(
                login=(self.socks_username, self.socks_password),
            )
        if self.socks_endpoint is not None:
            args = (self.host, self.port, self.socks_endpoint)
            socks_ep = SOCKS5ClientEndpoint(*args, **kwargs)
            if self.tls:
                context = optionsForClientTLS(unicode(self.host))
                socks_ep = TLSWrapClientEndpoint(context, socks_ep)
            proto = yield socks_ep.connect(protocolfactory)
            defer.returnValue(proto)
        else:
            for socks_port in self._socks_port_iter:
                tor_ep = TCP4ClientEndpoint(
                    reactor,
                    "127.0.0.1",
                    socks_port,
                )
                args = (self.host, self.port, tor_ep)
                socks_ep = SOCKS5ClientEndpoint(*args, **kwargs)
                if self.tls:
                    # XXX only twisted 14+
                    context = optionsForClientTLS(unicode(self.host))
                    socks_ep = TLSWrapClientEndpoint(context, socks_ep)

                try:
                    proto = yield socks_ep.connect(protocolfactory)
                    defer.returnValue(proto)

                except error.ConnectError as e0:
                    last_error = e0
            if last_error is not None:
                raise last_error

Example 46

Project: txtorcon
Source File: endpoints.py
View license
    def __init__(self, host, port,
                 socks_endpoint=None,
                 socks_username=None, socks_password=None,
                 tls=False, **kw):
        if host is None or port is None:
            raise ValueError('host and port must be specified')

        self.host = host
        self.port = int(port)
        self.socks_endpoint = socks_endpoint
        self.socks_username = socks_username
        self.socks_password = socks_password
        self.tls = tls

        if self.tls and not _HAVE_TLS:
            raise ValueError(
                "'tls=True' but we don't have TLS support"
            )

        # backwards-compatibility: you used to specify a TCP SOCKS
        # endpoint via socks_hostname= and socks_port= kwargs
        if self.socks_endpoint is None:
            try:
                self.socks_endpoint = TCP4ClientEndpoint(
                    reactor,
                    kw['socks_hostname'],
                    kw['socks_port'],
                )
                # XXX should deprecation-warn here
            except KeyError:
                pass

        # this is a separate "if" from above in case socks_endpoint
        # was None but the user specified the (old)
        # socks_hostname/socks_port (in which case we do NOT want
        # guessing_enabled
        if self.socks_endpoint is None:
            self._socks_port_iter = iter(self.socks_ports_to_try)
            self._socks_guessing_enabled = True
        else:
            self._socks_guessing_enabled = False

Example 47

Project: txtorcon
Source File: endpoints.py
View license
    @defer.inlineCallbacks
    def connect(self, protocolfactory):
        last_error = None
        kwargs = dict()
        if self.socks_username is not None and self.socks_password is not None:
            kwargs['methods'] = dict(
                login=(self.socks_username, self.socks_password),
            )
        if self.socks_endpoint is not None:
            args = (self.host, self.port, self.socks_endpoint)
            socks_ep = SOCKS5ClientEndpoint(*args, **kwargs)
            if self.tls:
                context = optionsForClientTLS(unicode(self.host))
                socks_ep = TLSWrapClientEndpoint(context, socks_ep)
            proto = yield socks_ep.connect(protocolfactory)
            defer.returnValue(proto)
        else:
            for socks_port in self._socks_port_iter:
                tor_ep = TCP4ClientEndpoint(
                    reactor,
                    "127.0.0.1",
                    socks_port,
                )
                args = (self.host, self.port, tor_ep)
                socks_ep = SOCKS5ClientEndpoint(*args, **kwargs)
                if self.tls:
                    # XXX only twisted 14+
                    context = optionsForClientTLS(unicode(self.host))
                    socks_ep = TLSWrapClientEndpoint(context, socks_ep)

                try:
                    proto = yield socks_ep.connect(protocolfactory)
                    defer.returnValue(proto)

                except error.ConnectError as e0:
                    last_error = e0
            if last_error is not None:
                raise last_error

Example 48

Project: txtorcon
Source File: torstate.py
View license
def build_tor_connection(connection, build_state=True, wait_for_proto=True,
                         password_function=lambda: None):
    """
    This is used to build a valid TorState (which has .protocol for
    the TorControlProtocol). For example::

        from twisted.internet import reactor
        from twisted.internet.endpoints import TCP4ClientEndpoint
        import txtorcon

        def example(state):
            print "Fully bootstrapped state:",state
            print "   with bootstrapped protocol:",state.protocol

        d = txtorcon.build_tor_connection(TCP4ClientEndpoint(reactor,
                                                             "localhost",
                                                             9051))
        d.addCallback(example)
        reactor.run()

    :param password_function:
        See :class:`txtorcon.TorControlProtocol`

    :param build_state:
        If True (the default) a TorState object will be
        built as well. If False, just a TorControlProtocol will be
        returned via the Deferred.

    :return:
        a Deferred that fires with a TorControlProtocol or, if you
        specified build_state=True, a TorState. In both cases, the
        object has finished bootstrapping
        (i.e. TorControlProtocol.post_bootstrap or
        TorState.post_bootstap has fired, as needed)
    """

    if IStreamClientEndpoint.providedBy(connection):
        endpoint = connection

    elif isinstance(connection, tuple):
        if len(connection) == 2:
            reactor, socket = connection
            if (os.path.exists(socket) and
                os.stat(socket).st_mode & (stat.S_IRGRP | stat.S_IRUSR |
                                           stat.S_IROTH)):
                endpoint = UNIXClientEndpoint(reactor, socket)
            else:
                raise ValueError('Can\'t use "%s" as a socket' % (socket, ))
        elif len(connection) == 3:
            endpoint = TCP4ClientEndpoint(*connection)
        else:
            raise TypeError('Expected either a (reactor, socket)- or a '
                            '(reactor, host, port)-tuple for argument '
                            '"connection", got %s' % (connection, ))
    else:
        raise TypeError('Expected a (reactor, socket)- or a (reactor, host, '
                        'port)-tuple or an object implementing IStreamClient'
                        'Endpoint for argument "connection", got %s' %
                        (connection, ))

    d = endpoint.connect(
        TorProtocolFactory(
            password_function=password_function
        )
    )
    if build_state:
        d.addCallback(build_state
                      if isinstance(build_state, collections.Callable)
                      else _build_state)
    elif wait_for_proto:
        d.addCallback(wait_for_proto
                      if isinstance(wait_for_proto, collections.Callable)
                      else _wait_for_proto)
    return d

Example 49

Project: txtorcon
Source File: torstate.py
View license
def build_tor_connection(connection, build_state=True, wait_for_proto=True,
                         password_function=lambda: None):
    """
    This is used to build a valid TorState (which has .protocol for
    the TorControlProtocol). For example::

        from twisted.internet import reactor
        from twisted.internet.endpoints import TCP4ClientEndpoint
        import txtorcon

        def example(state):
            print "Fully bootstrapped state:",state
            print "   with bootstrapped protocol:",state.protocol

        d = txtorcon.build_tor_connection(TCP4ClientEndpoint(reactor,
                                                             "localhost",
                                                             9051))
        d.addCallback(example)
        reactor.run()

    :param password_function:
        See :class:`txtorcon.TorControlProtocol`

    :param build_state:
        If True (the default) a TorState object will be
        built as well. If False, just a TorControlProtocol will be
        returned via the Deferred.

    :return:
        a Deferred that fires with a TorControlProtocol or, if you
        specified build_state=True, a TorState. In both cases, the
        object has finished bootstrapping
        (i.e. TorControlProtocol.post_bootstrap or
        TorState.post_bootstap has fired, as needed)
    """

    if IStreamClientEndpoint.providedBy(connection):
        endpoint = connection

    elif isinstance(connection, tuple):
        if len(connection) == 2:
            reactor, socket = connection
            if (os.path.exists(socket) and
                os.stat(socket).st_mode & (stat.S_IRGRP | stat.S_IRUSR |
                                           stat.S_IROTH)):
                endpoint = UNIXClientEndpoint(reactor, socket)
            else:
                raise ValueError('Can\'t use "%s" as a socket' % (socket, ))
        elif len(connection) == 3:
            endpoint = TCP4ClientEndpoint(*connection)
        else:
            raise TypeError('Expected either a (reactor, socket)- or a '
                            '(reactor, host, port)-tuple for argument '
                            '"connection", got %s' % (connection, ))
    else:
        raise TypeError('Expected a (reactor, socket)- or a (reactor, host, '
                        'port)-tuple or an object implementing IStreamClient'
                        'Endpoint for argument "connection", got %s' %
                        (connection, ))

    d = endpoint.connect(
        TorProtocolFactory(
            password_function=password_function
        )
    )
    if build_state:
        d.addCallback(build_state
                      if isinstance(build_state, collections.Callable)
                      else _build_state)
    elif wait_for_proto:
        d.addCallback(wait_for_proto
                      if isinstance(wait_for_proto, collections.Callable)
                      else _wait_for_proto)
    return d

Example 50

Project: txtorcon
Source File: 2_monitor.py
View license
@inlineCallbacks
def main(reactor):
    # change the port to 9151 for Tor Browser Bundle
    tor_ep = TCP4ClientEndpoint(reactor, "localhost", 9051)
    connection = yield txtorcon.build_tor_connection(tor_ep, build_state=False)
    version = yield connection.get_info('version', 'events/names')
    print("Connected to Tor {version}".format(**version))
    print("Events:", version['events/names'])

    print("Building state.")
    state = yield txtorcon.TorState.from_protocol(connection)

    print("listening for circuit events")
    state.add_circuit_listener(MyCircuitListener())

    print("Issuing NEWNYM.")
    yield connection.signal('NEWNYM')
    print("OK.")

    print("Existing circuits:")
    for c in state.circuits.values():
        print(' ', c)

    print("listening for INFO events")
    def print_info(i):
        print("INFO:", i)
    connection.add_event_listener('INFO', print_info)

    done = Deferred()
    yield done  # never callback()s so infinite loop