Introduced a new polling system in the background, which checks active session profiles for dead subprocesses. This has the effect of auto-closing a profile when the user closes the session profile's graphical window or app.

This commit is contained in:
SimplifiedPrivacy 2026-11-01 21:18:38 -05:00
parent 7c291997b2
commit 5d858a70ab
6 changed files with 138 additions and 19 deletions

View file

@ -1,14 +1,16 @@
from core.infrastructure.global_state import ProfileStateRepository, ProcessType, LIST_OF_PROCESSES
from core.controllers.ProfileController import ProfileController
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
from core.infrastructure.global_state import ProfileStateRepository, ProcessType, LIST_OF_PROCESSES
from core.observers.Notifications import Notifications, EventType
from core.models.Result import Result, ResultError
from core.errors.logger import logger
import subprocess
import time
class SessionStateController:

View file

@ -62,7 +62,6 @@ class ProfileStateRepository:
@property
def active_session_ids(self) -> list[int]:
"""Returns active session profile ids."""
print("getting active session ids")
current_list = self.current_session_ids
active_list = []
@ -163,6 +162,7 @@ class ProfileStateRepository:
""" Completely remove a profile, and it's group of processes from the registry"""
if profile_id in self.global_state.session_profiles:
del self.global_state.session_profiles[profile_id]
Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile_id)

View file

@ -169,3 +169,4 @@ def evaluate_state_on_startup() -> Result:
time.sleep(4)
return Result(valid=True)

View file

@ -57,4 +57,3 @@ def is_connected(profile_id: int) -> bool:
is_session_connected = state_repo.is_profile_active(profile_id)
print(f"Is this session profile connected? {profile_id}")
return is_session_connected

View file

@ -0,0 +1,128 @@
from core.infrastructure.thread_dispatch import MainThreadDispatcher
from core.infrastructure.global_state import ProfileStateRepository, ProcessType, LIST_OF_PROCESSES
from core.controllers.SessionStateController import SessionStateController
from core.controllers.ProfileController import ProfileController
from core.models.enum_models import ProtocolChoice
from core.errors.logger import logger
import threading
import time
def actually_kill_it(profile_id):
"""Attempt to kill the profile via the pre-made process objects, and if not, resort to forceful network port killing."""
profile = ProfileController.get(profile_id)
if not profile:
SessionStateController.scortched_earth_kill_profile(profile_id)
return
# Remove the dead handle from the repo so we stop polling it
result = SessionStateController.kill_session_profile(profile_id=profile_id, protocol=ProtocolChoice(profile.connection.code))
if not result.valid:
SessionStateController.scortched_earth_kill_profile(profile_id)
return
def check_processes() -> list|None:
"""Checks for profiles labeled 'active', but actually have dead subprocess objects."""
# Get all live session profiles from the repo
repo = ProfileStateRepository()
active_profiles = repo.active_session_ids
if not active_profiles:
return None
dead_processes = []
for profile_id in active_profiles:
process_group = repo.get_entire_session_process_group(profile_id)
# see if any processes are dead from the list of ones that should be active:
for process_type, each_process in process_group.items():
# print(f"checking {process_type} for profile {profile_id}")
if process_type in LIST_OF_PROCESSES:
each_status = each_process.poll()
if each_status is not None:
logger.info(f"Found a dead process of type {process_type} for {profile_id}")
dead_processes.append(profile_id)
return dead_processes
class PollState:
_instance = None
def __new__(cls, ui_dispatcher: MainThreadDispatcher):
"""Called before __init__ — controls instance creation"""
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, ui_dispatcher: MainThreadDispatcher):
# Guard: makes sure this entire class only runs once
if hasattr(self, '_initialized'):
return
self._initialized = True
# INSTANCE VARIABLES - created once, persist on the singleton
self.scheduled_event = None
self.is_running = False
self.ui_dispatcher = ui_dispatcher
logger.info("State Poller initialized.")
@classmethod
def get_instance(cls, *args, **kwargs):
if cls._instance is None:
cls(*args, **kwargs)
return cls._instance
def start_polling(self):
logger.info("Starting polling")
if not self.is_running:
self.is_running = True
# We create one long-lived thread that handles the loop
self.poll_thread = threading.Thread(target=self._poll_loop, daemon=True)
self.poll_thread.start()
def stop_polling(self):
"""Stops checking and wipes the instance"""
self.is_running = False # stop checking
PollState._instance = None # wipes instance
logger.info("Polling stopped")
def _poll_loop(self):
logger.info("Starting loop")
while self.is_running:
# 1. Do the work
self._background_work()
# 2. Wait 1 second before the next tick
time.sleep(1)
def _background_work(self):
"""Runs the task on the background thread, then brings the result to the main thread"""
# in the background thread:
dead_processes = check_processes()
# Bring result to main thread:
self.ui_dispatcher.run_on_main_thread(self._on_background_complete, dead_processes)
def _on_background_complete(self, dead_processes: list):
"""On the main thread, kills it if dead"""
if dead_processes is None or len(dead_processes) == 0:
# print("No dead processes")
return
for profile_id in dead_processes:
print(f"killing profile {profile_id}")
actually_kill_it(profile_id)
print(f"killed profile {profile_id}")

View file

@ -226,27 +226,15 @@ def disable_profile(
raise ProfileDeactivationError(f'Assassin NOT disabled: {assassin_result.message}')
# END ASSASSIN SECTION
print("Using SessionStateController to kill the profile..")
# STATE
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")
logger.error("Direct kill failed, elevating to psutil")
if not kill_all_associated_processes(profile_id=profile.id):
return killed.wrap("Failed to disable the profile.")
else:
logger.info("psutil worked to kill it.")
# if SessionStateController.exists(profile.id):
# session_state = SessionStateController.get(profile.id)
# if session_state is not None:
# for port_number in session_state.network_port_numbers.tor:
# ConnectionController.terminate_tor_session_connection(port_number)
# SessionStateController.remove(profile.id)
# if profile_observer is not None:
# profile_observer.notify('disabled', profile, dict(
# explicitly=explicitly,
# ))
Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile.id)
notification = "Profile Disconnected."
Notifications.emit(EventType.STATUS_UPDATE, notification)
@ -370,3 +358,4 @@ def destroy_profile(
profile_observer.notify('destroyed', profile)
return Result(valid=True, message="Deleted Profile")