How to use the txtorcon.launch function in txtorcon

To help you get started, we’ve selected a few txtorcon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github meejah / txtorcon / test / test_controller.py View on Github external
trans = FakeProcessTransportNoProtocol()
        trans.protocol = self.protocol

        def creator(*args, **kw):
            print("Bad: connection creator called")
            self.fail()

        def on_protocol(proto):
            self.process_proto = proto
            proto.outReceived(b'Bootstrapped 90%\n')
            proto.outReceived(b'Bootstrapped 100%\n')

        reactor = FakeReactor(self, trans, on_protocol, [9052, 9999])

        tor = yield launch(
            reactor=reactor,
            connection_creator=creator,
            tor_binary='/bin/echo',
            socks_port=1234,
            control_port=0,
        )
        self.assertEqual(tor._process_protocol, self.process_proto)
        d = tor.quit()
        reactor.advance(0)
        yield d
        errs = self.flushLoggedErrors()
        self.assertEqual(1, len(errs))
        self.assertTrue("Tor was killed" in str(errs[0]))
github meejah / txtorcon / test / test_controller.py View on Github external
def test_launch_fails(self, ftb):
        trans = FakeProcessTransport()

        def on_proto(protocol):
            protocol.processEnded(
                Failure(error.ProcessTerminated(12, None, 'statusFIXME'))
            )
        reactor = FakeReactor(self, trans, on_proto, [1234, 9052])

        try:
            yield launch(reactor)
            self.fail("Should fail")
        except RuntimeError:
            pass

        errs = self.flushLoggedErrors(RuntimeError)
        self.assertEqual(1, len(errs))
        self.assertTrue(
            "Tor exited with error-code 12" in str(errs[0])
        )
github meejah / txtorcon / test / test_controller.py View on Github external
def test_launch_wrong_stdout(self):
        try:
            yield launch(
                FakeReactor(self, Mock(), Mock()),
                stdout=object(),
                tor_binary='/bin/echo',
            )
            self.fail("Should have thrown an error")
        except RuntimeError as e:
            self.assertTrue("file-like object needed" in str(e).lower())
github meejah / txtorcon / test / test_controller.py View on Github external
reactor = FakeReactor(self, trans, lambda p: None, [1, 2, 3])
        config = TorConfig()

        def boot(arg=None):
            config.post_bootstrap.callback(config)
        config.__dict__['bootstrap'] = Mock(side_effect=boot)
        config.__dict__['attach_protocol'] = Mock(return_value=defer.succeed(None))

        def foo(*args, **kw):
            rtn = Mock()
            rtn.post_bootstrap = defer.succeed(None)
            rtn.when_connected = Mock(return_value=defer.succeed(rtn))
            return rtn
        tpp.side_effect = foo

        tor = yield launch(reactor, _tor_config=config)
        self.assertTrue(isinstance(tor, Tor))
github meejah / txtorcon / test / test_controller.py View on Github external
def test_launch_timeout_exception(self):
        """
        we provide a timeout, and it expires
        """
        trans = Mock()
        trans.signalProcess = Mock(side_effect=error.ProcessExitedAlready)
        trans.loseConnection = Mock()
        on_proto = Mock()
        react = FakeReactor(self, trans, on_proto, [1234])

        def creator():
            return defer.succeed(Mock())

        d = launch(
            reactor=react,
            tor_binary='/bin/echo',
            socks_port=1234,
            timeout=10,
            connection_creator=creator,
        )
        react.advance(12)
        self.assertTrue(trans.loseConnection.called)
        with self.assertRaises(RuntimeError) as ctx:
            yield d
        self.assertTrue("timeout while launching" in str(ctx.exception))
github meejah / txtorcon / test / test_controller.py View on Github external
elif cmd == 'GETINFO signal/names':
                    return defer.succeed('signal/names=')
                elif cmd == 'GETINFO version':
                    return defer.succeed('version=0.1.2.3')
                elif cmd == 'GETINFO events/names':
                    return defer.succeed('events/names=STATUS_CLIENT')
                elif cmd == 'GETINFO config/defaults':
                    return defer.succeed('config/defaults=')
                return defer.succeed(None)
            tpp.queue_command = fake_queue
            proto.makeConnection(Mock())
            return proto
        reactor.connectTCP = connect_tcp
        config = TorConfig()

        tor = yield launch(reactor, _tor_config=config, control_port='1234', timeout=30)
        errs = self.flushLoggedErrors()
        self.assertTrue(isinstance(tor, Tor))
        self.assertEqual(1, len(errs))
github meejah / txtorcon / test / test_controller.py View on Github external
class Connector:
            def __call__(self, proto, trans):
                proto._set_valid_events('STATUS_CLIENT')
                proto.makeConnection(trans)
                proto.post_bootstrap.callback(proto)
                return proto.post_bootstrap

        def on_protocol(proto):
            proto.outReceived(b'Bootstrapped 90%\n')
            proto.outReceived(b'Bootstrapped 100%\n')

        trans = FakeProcessTransport()
        trans.protocol = self.protocol
        creator = functools.partial(Connector(), self.protocol, self.transport)
        d = launch(
            FakeReactor(self, trans, on_protocol, [9052]),
            connection_creator=creator,
            tor_binary='/bin/echo',
            socks_port=1234,
        )

        def check_control_port(proto, tester):
            # we just want to ensure launch() didn't mess with
            # the controlport we set
            tester.assertEqual(config.ControlPort, 4321)

        d.addCallback(check_control_port, self)
        d.addErrback(self.fail)
        return d
github meejah / txtorcon / test / test_controller.py View on Github external
def __call__(self, proto, trans):
                proto._set_valid_events('STATUS_CLIENT')
                proto.makeConnection(trans)
                proto.post_bootstrap.callback(proto)
                return proto.post_bootstrap

        def on_protocol(proto):
            proto.outReceived(b'Bootstrapped 90%\n')

        with TempDir() as tmp:
            my_dir = str(tmp)
            config.DataDirectory = my_dir
            trans = FakeProcessTransport()
            trans.protocol = self.protocol
            creator = functools.partial(Connector(), self.protocol, self.transport)
            d = launch(
                FakeReactor(self, trans, on_protocol, [1234, 9051]),
                connection_creator=creator,
                tor_binary='/bin/echo',
                data_directory=my_dir,
                control_port=0,
            )

            def still_have_data_dir(tor, tester):
                tor._process_protocol.cleanup()  # FIXME? not really unit-testy as this is sort of internal function
                tester.assertTrue(os.path.exists(my_dir))

            d.addCallback(still_have_data_dir, self)
            d.addErrback(self.fail)
            return d
github AnemoneLabs / unmessage / unmessage / peer.py View on Github external
    @inlineCallbacks
    def _start_tor(self, launch_tor):
        if launch_tor:
            self._notify_bootstrap('Launching Tor')

            def display_bootstrap_lines(prog, tag, summary):
                self._notify_bootstrap('{}%: {}'.format(prog, summary))

            self._tor = yield txtorcon.launch(
                self._reactor,
                progress_updates=display_bootstrap_lines,
                data_directory=self._paths.tor_data_dir,
                socks_port=self._port_tor_socks)
        else:
            self._notify_bootstrap('Connecting to existing Tor')

            endpoint = TCP4ClientEndpoint(self._reactor,
                                          HOST,
                                          self._port_tor_control)
            self._tor = yield txtorcon.connect(self._reactor, endpoint)

        self._notify_bootstrap('Controlling Tor process')

        onion_service_string = '{} {}:{}'.format(self._port_local_server,
                                                 self._ip_local_server,
github meejah / txtorcon / examples / launch_tor_unix_sockets.py View on Github external
def main(reactor):
    # we must have a directory owned by us with 0700 permissions to
    # contain our Unix sockets or Tor is sad.
    tmp = tempfile.mkdtemp()
    reactor.addSystemEventTrigger(
        'after', 'shutdown',
        shutil.rmtree, tmp,
    )

    control_path = join(tmp, 'control_socket')
    socks_path = join(tmp, 'socks')
    # note that you can pass a few options as kwargs
    # (e.g. data_directory=, or socks_port= ). For other torrc
    # changes, see below.
    tor = yield txtorcon.launch(
        reactor,
        data_directory="./tordata",
        stdout=sys.stdout,
        control_port='unix:{}'.format(control_path),
        socks_port='unix:{}'.format(socks_path),
    )
    print("Connected to Tor version '{}'".format(tor.protocol.version))

    state = yield tor.create_state()

    print("This Tor has PID {}".format(state.tor_pid))
    print("This Tor has the following {} Circuits:".format(len(state.circuits)))
    for c in state.circuits.values():
        print("  {}".format(c))

    config = yield tor.get_config()