Tor profile cleanup and error handling. Moved more functions out of ConnectionController

This commit is contained in:
SimplifiedPrivacy 2026-11-01 17:42:48 -05:00
parent 257bb952f7
commit da7d912a0c
8 changed files with 143 additions and 43 deletions

View file

@ -1,3 +1,4 @@
from core.infrastructure.global_state import ProcessType
from core.errors.exceptions import *
from core.errors.logger import logger
@ -14,7 +15,7 @@ from core.Constants import Constants
from core.Errors import ConnectionUnprotectedError, ConnectionTerminationError, CommandNotFoundError
from core.controllers.ConfigurationController import ConfigurationController
# from core.controllers.ProfileController import ProfileController
from core.controllers.SessionStateController import SessionStateController
# from core.controllers.SessionStateController import SessionStateController
from core.controllers.SystemStateController import SystemStateController
from core.models.BaseProfile import ProfileType
from core.models.session.SessionProfile import SessionProfile
@ -249,48 +250,50 @@ class ConnectionController:
return task_output
def start_tor_session_networking(
port_number: int,
session_state: SessionState,
profile: SessionProfile,
ignore: tuple[type[Exception]] = (),
connection_observer: Optional[ConnectionObserver] = None
) -> Result:
# def start_tor_session_networking(
# port_number: int,
# session_directory: str,
# session_state: SessionState,
# profile: SessionProfile,
# ignore: tuple[type[Exception]] = (),
# connection_observer: Optional[ConnectionObserver] = None
# ) -> Result:
print("Starting a Tor Session Profile")
# print("Starting a Tor Session Profile")
# proxy_port_number = None
tor_connected = ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer)
if not tor_connected.valid:
return tor_connected.wrap("Failed to start Tor, for Tor->socks5")
# tor_connected = ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer)
# if not tor_connected.valid:
# return tor_connected.wrap("Failed to start Tor, for Tor->socks5")
session_state.network_port_numbers.tor.append(port_number)
# session_state.network_port_numbers.tor.append(port_number)
print(f"Started Tor connection on port {port_number}")
# print(f"Started Tor connection on port {port_number}")
if profile.connection.masked:
# if profile.connection.masked:
while proxy_port_number is None or proxy_port_number == port_number:
proxy_port_number = ConnectionService.get_random_available_port_number()
# while proxy_port_number is None or proxy_port_number == port_number:
# proxy_port_number = ConnectionService.get_random_available_port_number()
sock_proxy_result = ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number)
if not sock_proxy_result.valid:
# Kill the underlying Tor right here:
terminate_tor_session_connection(port_number=port_number)
return sock_proxy_result.wrap("We were able to start Tor, but not the socks5 proxy masking on top of it.")
# sock_proxy_result = ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number)
# if not sock_proxy_result.valid:
# # Kill the underlying Tor right here:
# terminate_tor_session_connection(port_number=port_number)
# return sock_proxy_result.wrap("We were able to start Tor, but not the socks5 proxy masking on top of it.")
network_process = sock_proxy_result.data
session_state.network_port_numbers.proxy.append(proxy_port_number)
# network_process = sock_proxy_result.data
# session_state.network_port_numbers.proxy.append(proxy_port_number)
# Update in memory repo,
SessionStateController.update_or_create(session_state)
SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
# # Update in memory repo,
# SessionStateController.update_or_create(session_state)
# SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
print("Awaiting the connection..")
await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
# print("Awaiting the connection..")
# await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
print("Updating state..")
SessionStateController.update_or_create(session_state)
# print("Updating state..")
# SessionStateController.update_or_create(session_state)
print("Returning final proxy port")
final_proxy_port = proxy_port_number or port_number
return Result(valid=True, data=final_proxy_port)
# print("Returning final proxy port")
# final_proxy_port = proxy_port_number or port_number
# return Result(valid=True, data=final_proxy_port)

View file

@ -1,3 +1,5 @@
from core.services.networking.session.tor_tools import terminate_tor_session_connection
from core.models.enum_models import ProtocolChoice
from core.infrastructure.state_management.kill_processes import kill_all_associated_processes
from core.models.session.SessionState import SessionState
# from core.controllers.ProfileController import ProfileController
@ -32,7 +34,7 @@ class SessionStateController:
@staticmethod
def kill_session_profile(profile_id: int) -> Result:
def kill_session_profile(profile_id: int, protocol: ProtocolChoice) -> Result:
# get process objects from repo:
repo = ProfileStateRepository()
@ -66,6 +68,10 @@ class SessionStateController:
return Result(valid=False, error_type=ResultError.STATE, message=error_msg)
# Tor isn't kept as a subprocess to kill, it has its own method:
if protocol == ProtocolChoice.TOR:
SessionStateController.shut_down_tor_from_state(profile_id)
# Clear the repo:
print("Clearing the repo")
repo.remove_session_profile(profile_id)
@ -74,6 +80,17 @@ class SessionStateController:
SessionState.remove_file(id=profile_id)
return Result(valid=True)
@staticmethod
def shut_down_tor_from_state(profile_id: int):
session_state = SessionStateController.get_model(profile_id)
if session_state:
tor_port = session_state.network_port_numbers.tor
if tor_port:
if isinstance(tor_port, list):
tor_port = tor_port[0]
print(f"Closing Tor on port {tor_port}")
terminate_tor_session_connection(tor_port)
@staticmethod
def new(profile_id: int):
# model
@ -161,6 +178,8 @@ class SessionStateController:
if session_state:
killed = kill_all_associated_processes(session_state)
if not killed:
return False
# delete model:
SessionState.remove_file(profile_id)

View file

@ -28,6 +28,7 @@ class ErrorType(Enum):
DEFAULT_TOR_PORT_DEAD = "default_tor_port_dead"
TOR_WORKS_BUT_UNRELIABLE = "tor_works_but_unreliable"
TOR_NOT_INSTALLED = "tor_not_installed"
UPGRADE_TOR = "upgrade_tor"
REFUSAL_TO_INSTALL_TOR = "refusal_to_install_tor"
PORT_OPEN = "port_open"
PORT_USED = "port_used"

View file

@ -1,4 +1,4 @@
from core.controllers.ConnectionController import start_tor_session_networking
from core.services.networking.session.tor_session import start_tor_session_networking
from essentials.services.ConnectionService import ConnectionService
from core.services.keys_and_verifications.endpoint_verification import verify_wireguard_endpoint
from core.controllers.SessionStateController import SessionStateController
@ -60,7 +60,7 @@ def start_session_networking(
#--------------------------------
if protocol == ProtocolChoice.TOR:
print("Passing off to ConnectionController's Tor system")
return start_tor_session_networking(port_number=port_number, session_state=session_state, profile=profile, ignore=ignore, connection_observer=connection_observer)
return start_tor_session_networking(port_number=port_number, session_directory=session_directory, session_state=session_state, profile=profile, ignore=ignore, connection_observer=connection_observer)
#--------------------------------
# WIREGUARD

View file

@ -0,0 +1,65 @@
from core.controllers.ConnectionController import ConnectionController
from core.services.networking.session.tor_tools import terminate_tor_session_connection
from core.infrastructure.global_state import ProcessType
from core.controllers.SessionStateController import SessionStateController
from core.models.session.SessionProfile import SessionProfile
from core.observers.ConnectionObserver import ConnectionObserver
from core.errors.logger import logger
from core.models.Result import Result
from core.models.session.SessionState import SessionState
from essentials.services.ConnectionService import ConnectionService
from core.services.networking.general_connection_tools.testing_evaluating import await_connection
from typing import Optional
def start_tor_session_networking(
port_number: int,
session_directory: str,
session_state: SessionState,
profile: SessionProfile,
ignore: tuple[type[Exception]] = (),
connection_observer: Optional[ConnectionObserver] = None
) -> Result:
print("Starting a Tor Session Profile")
proxy_port_number = None
tor_connected = ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer)
if not tor_connected.valid:
return tor_connected.wrap("Failed to start Tor, for Tor->socks5")
session_state.network_port_numbers.tor.append(port_number)
print(f"Started Tor connection on port {port_number}")
if profile.connection.masked:
while proxy_port_number is None or proxy_port_number == port_number:
proxy_port_number = ConnectionService.get_random_available_port_number()
sock_proxy_result = ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number)
if not sock_proxy_result.valid:
# Kill the underlying Tor right here:
terminate_tor_session_connection(port_number=port_number)
error_msg = "We were able to start Tor, but not the socks5 proxy masking on top of it."
logger.error(error_msg)
return sock_proxy_result.wrap(error_msg)
network_process = sock_proxy_result.data
session_state.network_port_numbers.proxy.append(proxy_port_number)
# Update in memory repo,
SessionStateController.update_or_create(session_state)
SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
print("Awaiting the connection..")
await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
print("Updating state..")
SessionStateController.update_or_create(session_state)
print("Returning final proxy port")
final_proxy_port = proxy_port_number or port_number
return Result(valid=True, data=final_proxy_port)

View file

@ -0,0 +1,7 @@
from core.Constants import Constants
from essentials.modules.TorModule import TorModule
def terminate_tor_session_connection(port_number: int):
tor_module = TorModule(Constants.HV_TOR_STATE_HOME)
tor_module.destroy_session(port_number)

View file

@ -27,6 +27,7 @@ ERROR_PATTERNS = {
"permission_denied": "permission denied",
"port_in_use": r"(address already in use|port.*in use|cannot assign requested address)",
"not_installed": r"(no such file|command not found|tor: not found)",
"upgrade": "You should upgrade. This version of Tor will not work as a client on the Tor network"
}
class BootstrapStrategy(Enum):
@ -35,6 +36,7 @@ class BootstrapStrategy(Enum):
NEW_FOLDER_AND_PORT = "new_folder_and_port"
REINSTALL_AND_RETRY = "reinstall_and_retry"
GIVE_UP = "give_up"
UPGRADE = "upgrade"
def bootstrap(
@ -95,7 +97,9 @@ def bootstrap(
if not install_tor(observer).valid:
return ApiResponse(valid=False, error_type=ErrorType.INSTALL_FAILED)
use_new_folder = True
elif strategy == BootstrapStrategy.UPGRADE_TOR:
return ApiResponse(valid=False, error_type=ErrorType.UPGRADE_TOR, message="You have to upgrade Tor through your local package manager. This version is not supported.")
# ===== Exhausted All Attempts =====
return ApiResponse(valid=False, error_type=ErrorType.CANT_BOOTSTRAP)
@ -125,7 +129,9 @@ def assign_an_action(diagnosis: Optional[str], attempt: int) -> BootstrapStrateg
return BootstrapStrategy.FRESH_PORT
if diagnosis == "not_installed":
return BootstrapStrategy.REINSTALL_AND_RETRY
if diagnosis == "upgrade":
return BootstrapStrategy.UPGRADE
# No diagnosis case
if attempt <= GIVE_UP_WITH_NO_DIAGNOSIS:
logger.info(f"Attempt {attempt}: trying new folder/port despite no diagnosis")

View file

@ -1,3 +1,4 @@
from core.models.enum_models import ProtocolChoice
from core.services.apps.launch_app import orchestrate_app_launch
from core.services.networking.session.session_networking import start_session_networking
from core.observers.Notifications import Notifications, EventType
@ -206,9 +207,7 @@ def disable_profile(
"""Orchestrate disabling a profile."""
# if profile is None:
# burned_down = kill_all_associated_processes(profile_id=profile.id)
protocol = ProtocolChoice(profile.connection.code)
if profile.is_session_profile():
@ -227,7 +226,7 @@ def disable_profile(
# END ASSASSIN SECTION
print("Using SessionStateController to kill the profile..")
killed = SessionStateController.kill_session_profile(profile_id=profile.id)
killed = SessionStateController.kill_session_profile(profile_id=profile.id, protocol=protocol)
if not killed.valid:
logger.error("Direct kill failed, elevating to psutil scortched earth policy")
if not kill_all_associated_processes(profile_id=profile.id):