From f7d7977d1abffadd75a945d192ae4e8759ce717a Mon Sep 17 00:00:00 2001 From: Lee Miller Date: Sat, 25 Nov 2023 16:09:32 +0200 Subject: [PATCH] Improve the logic of starting tor: set missing initial port, exit on failure, increase timeout to 90 reducing number of attempts to 20. --- minode/main.py | 8 ++++++++ minode/tor.py | 11 ++++++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/minode/main.py b/minode/main.py index 66fac81..f6dcee0 100644 --- a/minode/main.py +++ b/minode/main.py @@ -283,9 +283,17 @@ def main(): from . import tor except ImportError: logging.info('Failed to import tor module.', exc_info=True) + tor = None else: if not tor.start_tor_service(): logging.warning('Failed to start tor service.') + tor = None + if not tor: + try: + socket.socket().bind(('127.0.0.1', 9050)) + return + except (OSError, socket.error): + pass if shared.ip_enabled and not shared.trusted_peer and not shared.tor: bootstrap_from_dns() diff --git a/minode/tor.py b/minode/tor.py index 28e5b76..96f10fa 100644 --- a/minode/tor.py +++ b/minode/tor.py @@ -37,6 +37,10 @@ def start_tor_service(): logging.info('Failed to create a temp dir.') return + if os.getuid() == 0: + logging.info('Tor is not going to start as root') + return + try: present_permissions = os.stat(socket_dir)[0] disallowed_permissions = stat.S_IRWXG | stat.S_IRWXO @@ -49,17 +53,18 @@ def start_tor_service(): stem.util.log.get_logger().setLevel(logging.WARNING) control_socket = os.path.abspath(os.path.join(socket_dir, 'tor_control')) + port = str(shared.socks_proxy.port) tor_config = { - 'SocksPort': str(shared.socks_proxy.port), + 'SocksPort': port, 'ControlSocket': control_socket} - for attempt in range(50): + for attempt in range(20): if attempt > 0: port = random.randint(32767, 65535) # nosec B311 tor_config['SocksPort'] = str(port) try: stem.process.launch_tor_with_config( - tor_config, take_ownership=True, timeout=20, + tor_config, take_ownership=True, timeout=90, init_msg_handler=logwrite) except OSError: if not attempt: