Improve the logic of starting tor:

set missing initial port, exit on failure,
increase timeout to 90 reducing number of attempts to 20.
This commit is contained in:
Lee Miller 2023-11-25 16:09:32 +02:00
parent 4a51979966
commit c4df256415
Signed by: lee.miller
GPG Key ID: 4F97A5EA88F4AB63
2 changed files with 16 additions and 3 deletions

View File

@ -279,9 +279,17 @@ def main():
from . import tor from . import tor
except ImportError: except ImportError:
logging.info('Failed to import tor module.', exc_info=True) logging.info('Failed to import tor module.', exc_info=True)
tor = None
else: else:
if not tor.start_tor_service(): if not tor.start_tor_service():
logging.warning('Failed to 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: if shared.ip_enabled and not shared.trusted_peer and not shared.tor:
bootstrap_from_dns() bootstrap_from_dns()

View File

@ -37,6 +37,10 @@ def start_tor_service():
logging.info('Failed to create a temp dir.') logging.info('Failed to create a temp dir.')
return return
if os.getuid() == 0:
logging.info('Tor is not going to start as root')
return
try: try:
present_permissions = os.stat(socket_dir)[0] present_permissions = os.stat(socket_dir)[0]
disallowed_permissions = stat.S_IRWXG | stat.S_IRWXO disallowed_permissions = stat.S_IRWXG | stat.S_IRWXO
@ -49,17 +53,18 @@ def start_tor_service():
stem.util.log.get_logger().setLevel(logging.WARNING) stem.util.log.get_logger().setLevel(logging.WARNING)
control_socket = os.path.abspath(os.path.join(socket_dir, 'tor_control')) control_socket = os.path.abspath(os.path.join(socket_dir, 'tor_control'))
port = str(shared.socks_proxy.port)
tor_config = { tor_config = {
'SocksPort': str(shared.socks_proxy.port), 'SocksPort': port,
'ControlSocket': control_socket} 'ControlSocket': control_socket}
for attempt in range(50): for attempt in range(20):
if attempt > 0: if attempt > 0:
port = random.randint(32767, 65535) # nosec B311 port = random.randint(32767, 65535) # nosec B311
tor_config['SocksPort'] = str(port) tor_config['SocksPort'] = str(port)
try: try:
stem.process.launch_tor_with_config( stem.process.launch_tor_with_config(
tor_config, take_ownership=True, timeout=20, tor_config, take_ownership=True, timeout=90,
init_msg_handler=logwrite) init_msg_handler=logwrite)
except OSError: except OSError:
if not attempt: if not attempt: