Compare commits
5 commits
257bb952f7
...
5d858a70ab
| Author | SHA1 | Date | |
|---|---|---|---|
| 5d858a70ab | |||
| 7c291997b2 | |||
| df751949a4 | |||
| 039c162976 | |||
| da7d912a0c |
14 changed files with 366 additions and 131 deletions
|
|
@ -1,3 +1,4 @@
|
||||||
|
from core.infrastructure.global_state import ProcessType
|
||||||
from core.errors.exceptions import *
|
from core.errors.exceptions import *
|
||||||
from core.errors.logger import logger
|
from core.errors.logger import logger
|
||||||
|
|
||||||
|
|
@ -14,7 +15,7 @@ from core.Constants import Constants
|
||||||
from core.Errors import ConnectionUnprotectedError, ConnectionTerminationError, CommandNotFoundError
|
from core.Errors import ConnectionUnprotectedError, ConnectionTerminationError, CommandNotFoundError
|
||||||
from core.controllers.ConfigurationController import ConfigurationController
|
from core.controllers.ConfigurationController import ConfigurationController
|
||||||
# from core.controllers.ProfileController import ProfileController
|
# 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.controllers.SystemStateController import SystemStateController
|
||||||
from core.models.BaseProfile import ProfileType
|
from core.models.BaseProfile import ProfileType
|
||||||
from core.models.session.SessionProfile import SessionProfile
|
from core.models.session.SessionProfile import SessionProfile
|
||||||
|
|
@ -249,48 +250,50 @@ class ConnectionController:
|
||||||
return task_output
|
return task_output
|
||||||
|
|
||||||
|
|
||||||
def start_tor_session_networking(
|
# def start_tor_session_networking(
|
||||||
port_number: int,
|
# port_number: int,
|
||||||
session_state: SessionState,
|
# session_directory: str,
|
||||||
profile: SessionProfile,
|
# session_state: SessionState,
|
||||||
ignore: tuple[type[Exception]] = (),
|
# profile: SessionProfile,
|
||||||
connection_observer: Optional[ConnectionObserver] = None
|
# ignore: tuple[type[Exception]] = (),
|
||||||
) -> Result:
|
# 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)
|
# tor_connected = ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer)
|
||||||
if not tor_connected.valid:
|
# if not tor_connected.valid:
|
||||||
return tor_connected.wrap("Failed to start Tor, for Tor->socks5")
|
# 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:
|
# while proxy_port_number is None or proxy_port_number == port_number:
|
||||||
proxy_port_number = ConnectionService.get_random_available_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)
|
# sock_proxy_result = ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number)
|
||||||
if not sock_proxy_result.valid:
|
# if not sock_proxy_result.valid:
|
||||||
# Kill the underlying Tor right here:
|
# # Kill the underlying Tor right here:
|
||||||
terminate_tor_session_connection(port_number=port_number)
|
# 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.")
|
# 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
|
# network_process = sock_proxy_result.data
|
||||||
session_state.network_port_numbers.proxy.append(proxy_port_number)
|
# session_state.network_port_numbers.proxy.append(proxy_port_number)
|
||||||
|
|
||||||
# Update in memory repo,
|
# # Update in memory repo,
|
||||||
SessionStateController.update_or_create(session_state)
|
# SessionStateController.update_or_create(session_state)
|
||||||
SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
|
# SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
|
||||||
|
|
||||||
print("Awaiting the connection..")
|
# print("Awaiting the connection..")
|
||||||
await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
|
# await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
|
||||||
|
|
||||||
print("Updating state..")
|
# print("Updating state..")
|
||||||
SessionStateController.update_or_create(session_state)
|
# SessionStateController.update_or_create(session_state)
|
||||||
|
|
||||||
print("Returning final proxy port")
|
# print("Returning final proxy port")
|
||||||
final_proxy_port = proxy_port_number or port_number
|
# final_proxy_port = proxy_port_number or port_number
|
||||||
return Result(valid=True, data=final_proxy_port)
|
# return Result(valid=True, data=final_proxy_port)
|
||||||
|
|
|
||||||
|
|
@ -1,12 +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.infrastructure.state_management.kill_processes import kill_all_associated_processes
|
||||||
from core.models.session.SessionState import SessionState
|
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.observers.Notifications import Notifications, EventType
|
||||||
from core.models.Result import Result, ResultError
|
from core.models.Result import Result, ResultError
|
||||||
from core.errors.logger import logger
|
from core.errors.logger import logger
|
||||||
|
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class SessionStateController:
|
class SessionStateController:
|
||||||
|
|
@ -32,7 +36,7 @@ class SessionStateController:
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def kill_session_profile(profile_id: int) -> Result:
|
def kill_session_profile(profile_id: int, protocol: ProtocolChoice) -> Result:
|
||||||
|
|
||||||
# get process objects from repo:
|
# get process objects from repo:
|
||||||
repo = ProfileStateRepository()
|
repo = ProfileStateRepository()
|
||||||
|
|
@ -66,6 +70,10 @@ class SessionStateController:
|
||||||
return Result(valid=False, error_type=ResultError.STATE, message=error_msg)
|
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:
|
# Clear the repo:
|
||||||
print("Clearing the repo")
|
print("Clearing the repo")
|
||||||
repo.remove_session_profile(profile_id)
|
repo.remove_session_profile(profile_id)
|
||||||
|
|
@ -74,6 +82,17 @@ class SessionStateController:
|
||||||
SessionState.remove_file(id=profile_id)
|
SessionState.remove_file(id=profile_id)
|
||||||
return Result(valid=True)
|
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
|
@staticmethod
|
||||||
def new(profile_id: int):
|
def new(profile_id: int):
|
||||||
# model
|
# model
|
||||||
|
|
@ -161,6 +180,8 @@ class SessionStateController:
|
||||||
|
|
||||||
if session_state:
|
if session_state:
|
||||||
killed = kill_all_associated_processes(session_state)
|
killed = kill_all_associated_processes(session_state)
|
||||||
|
if not killed:
|
||||||
|
return False
|
||||||
|
|
||||||
# delete model:
|
# delete model:
|
||||||
SessionState.remove_file(profile_id)
|
SessionState.remove_file(profile_id)
|
||||||
|
|
@ -173,4 +194,4 @@ class SessionStateController:
|
||||||
# notify UI:
|
# notify UI:
|
||||||
print("sending")
|
print("sending")
|
||||||
Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile_id)
|
Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile_id)
|
||||||
return True
|
return True
|
||||||
|
|
|
||||||
|
|
@ -62,13 +62,16 @@ class ProfileStateRepository:
|
||||||
@property
|
@property
|
||||||
def active_session_ids(self) -> list[int]:
|
def active_session_ids(self) -> list[int]:
|
||||||
"""Returns active session profile ids."""
|
"""Returns active session profile ids."""
|
||||||
print("getting active session ids")
|
|
||||||
current_list = self.current_session_ids
|
current_list = self.current_session_ids
|
||||||
active_list = []
|
active_list = []
|
||||||
|
|
||||||
for each_profile_id in current_list:
|
for each_profile_id in current_list:
|
||||||
if self.global_state.session_profiles[each_profile_id][ProcessType.ACTIVE] is True:
|
try:
|
||||||
active_list.append(each_profile_id)
|
if self.global_state.session_profiles[each_profile_id][ProcessType.ACTIVE] is True:
|
||||||
|
active_list.append(each_profile_id)
|
||||||
|
except KeyError:
|
||||||
|
print(f"active doesn't exist yet for profile id {each_profile_id}")
|
||||||
|
continue
|
||||||
|
|
||||||
return active_list
|
return active_list
|
||||||
|
|
||||||
|
|
@ -159,6 +162,7 @@ class ProfileStateRepository:
|
||||||
""" Completely remove a profile, and it's group of processes from the registry"""
|
""" Completely remove a profile, and it's group of processes from the registry"""
|
||||||
if profile_id in self.global_state.session_profiles:
|
if profile_id in self.global_state.session_profiles:
|
||||||
del self.global_state.session_profiles[profile_id]
|
del self.global_state.session_profiles[profile_id]
|
||||||
|
Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile_id)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,8 @@
|
||||||
from core.services.networking.general_connection_tools.connection_enable import establish_connection
|
from core.services.networking.general_connection_tools.connection_enable import establish_connection
|
||||||
from core.controllers.ConfigurationController import ConfigurationController
|
from core.controllers.ConfigurationController import ConfigurationController
|
||||||
from core.infrastructure.global_state import ProfileStateRepository
|
|
||||||
from core.controllers.ProfileController import ProfileController
|
from core.controllers.ProfileController import ProfileController
|
||||||
from core.controllers.SystemStateController import SystemStateController
|
from core.controllers.SystemStateController import SystemStateController
|
||||||
from core.controllers.SessionStateController import SessionStateController
|
from core.controllers.SessionStateController import SessionStateController
|
||||||
from core.models.system.SystemState import SystemState
|
|
||||||
from core.models.enum_models import ProtocolChoice
|
from core.models.enum_models import ProtocolChoice
|
||||||
from core.models.Result import Result, ResultError
|
from core.models.Result import Result, ResultError
|
||||||
from core.services.networking.systemwide import killswitch
|
from core.services.networking.systemwide import killswitch
|
||||||
|
|
@ -22,68 +20,10 @@ from core.errors.logger import logger
|
||||||
from functools import partial
|
from functools import partial
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
||||||
SINGBOX_PROTOCOLS = (ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS)
|
SINGBOX_PROTOCOLS = (ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS)
|
||||||
|
|
||||||
|
|
||||||
def is_systemwide_on() -> bool:
|
|
||||||
"""Returns a boolean if systemwide is connected. True is Yes, False is No"""
|
|
||||||
state_repo = ProfileStateRepository()
|
|
||||||
if not state_repo.global_state.verified_working:
|
|
||||||
return False
|
|
||||||
|
|
||||||
return state_repo.global_state.systemwide_active
|
|
||||||
|
|
||||||
|
|
||||||
def verified_system_profile_id() -> int|None:
|
|
||||||
state_repo = ProfileStateRepository()
|
|
||||||
if not state_repo.global_state.verified_working:
|
|
||||||
return False
|
|
||||||
else:
|
|
||||||
return state_repo.global_state.systemwide_profile_id
|
|
||||||
|
|
||||||
|
|
||||||
def connected_system_profile_id() -> int|None:
|
|
||||||
"""Returns a single number of the connected system profile"""
|
|
||||||
state_repo = ProfileStateRepository()
|
|
||||||
print(f"state_repo is {state_repo.global_state}")
|
|
||||||
return state_repo.global_state.systemwide_profile_id
|
|
||||||
|
|
||||||
def connected_session_profile_ids() -> list|None:
|
|
||||||
"""Returns a list of the currently connected session profile IDs"""
|
|
||||||
state_repo = ProfileStateRepository()
|
|
||||||
return state_repo.active_session_ids
|
|
||||||
|
|
||||||
|
|
||||||
def get_all_connected() -> list|None:
|
|
||||||
profile_ids = connected_session_profile_ids()
|
|
||||||
system = connected_system_profile_id()
|
|
||||||
if system:
|
|
||||||
profile_ids.append(system)
|
|
||||||
return profile_ids
|
|
||||||
|
|
||||||
def quantity_connected() -> list|None:
|
|
||||||
connected = get_all_connected()
|
|
||||||
if connected:
|
|
||||||
return len(connected)
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def is_connected(profile_id: int) -> bool:
|
|
||||||
"""Returns a boolean if a given profile is connected"""
|
|
||||||
|
|
||||||
# system-wide:
|
|
||||||
systemwide_profile_id = connected_system_profile_id()
|
|
||||||
if profile_id == systemwide_profile_id:
|
|
||||||
return True
|
|
||||||
|
|
||||||
# session:
|
|
||||||
state_repo = ProfileStateRepository()
|
|
||||||
is_session_connected = state_repo.is_profile_active(profile_id)
|
|
||||||
print(f"Is this session profile connected? {profile_id}")
|
|
||||||
return is_session_connected
|
|
||||||
|
|
||||||
|
|
||||||
def coordinate_evaluation(connection_observer: ConnectionObserver) -> Result:
|
def coordinate_evaluation(connection_observer: ConnectionObserver) -> Result:
|
||||||
"""See if a connection can be salvaged. If not, rip it down & start over."""
|
"""See if a connection can be salvaged. If not, rip it down & start over."""
|
||||||
|
|
||||||
|
|
@ -229,3 +169,4 @@ def evaluate_state_on_startup() -> Result:
|
||||||
time.sleep(4)
|
time.sleep(4)
|
||||||
|
|
||||||
return Result(valid=True)
|
return Result(valid=True)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,59 @@
|
||||||
|
from core.infrastructure.global_state import ProfileStateRepository
|
||||||
|
|
||||||
|
def is_systemwide_on() -> bool:
|
||||||
|
"""Returns a boolean if systemwide is connected. True is Yes, False is No"""
|
||||||
|
state_repo = ProfileStateRepository()
|
||||||
|
if not state_repo.global_state.verified_working:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return state_repo.global_state.systemwide_active
|
||||||
|
|
||||||
|
|
||||||
|
def verified_system_profile_id() -> int|None:
|
||||||
|
state_repo = ProfileStateRepository()
|
||||||
|
if not state_repo.global_state.verified_working:
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
return state_repo.global_state.systemwide_profile_id
|
||||||
|
|
||||||
|
|
||||||
|
def connected_system_profile_id() -> int|None:
|
||||||
|
"""Returns a single number of the connected system profile"""
|
||||||
|
state_repo = ProfileStateRepository()
|
||||||
|
print(f"state_repo is {state_repo.global_state}")
|
||||||
|
return state_repo.global_state.systemwide_profile_id
|
||||||
|
|
||||||
|
def connected_session_profile_ids() -> list|None:
|
||||||
|
"""Returns a list of the currently connected session profile IDs"""
|
||||||
|
state_repo = ProfileStateRepository()
|
||||||
|
return state_repo.active_session_ids
|
||||||
|
|
||||||
|
|
||||||
|
def get_all_connected() -> list|None:
|
||||||
|
profile_ids = connected_session_profile_ids()
|
||||||
|
system = connected_system_profile_id()
|
||||||
|
if system:
|
||||||
|
profile_ids.append(system)
|
||||||
|
return profile_ids
|
||||||
|
|
||||||
|
def quantity_connected() -> list|None:
|
||||||
|
connected = get_all_connected()
|
||||||
|
if connected:
|
||||||
|
return len(connected)
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def is_connected(profile_id: int) -> bool:
|
||||||
|
"""Returns a boolean if a given profile is connected"""
|
||||||
|
|
||||||
|
# system-wide:
|
||||||
|
systemwide_profile_id = connected_system_profile_id()
|
||||||
|
if profile_id == systemwide_profile_id:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# session:
|
||||||
|
state_repo = ProfileStateRepository()
|
||||||
|
is_session_connected = state_repo.is_profile_active(profile_id)
|
||||||
|
print(f"Is this session profile connected? {profile_id}")
|
||||||
|
return is_session_connected
|
||||||
128
core/infrastructure/state_management/state_poll_loop.py
Normal file
128
core/infrastructure/state_management/state_poll_loop.py
Normal 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}")
|
||||||
|
|
@ -28,6 +28,7 @@ class ErrorType(Enum):
|
||||||
DEFAULT_TOR_PORT_DEAD = "default_tor_port_dead"
|
DEFAULT_TOR_PORT_DEAD = "default_tor_port_dead"
|
||||||
TOR_WORKS_BUT_UNRELIABLE = "tor_works_but_unreliable"
|
TOR_WORKS_BUT_UNRELIABLE = "tor_works_but_unreliable"
|
||||||
TOR_NOT_INSTALLED = "tor_not_installed"
|
TOR_NOT_INSTALLED = "tor_not_installed"
|
||||||
|
UPGRADE_TOR = "upgrade_tor"
|
||||||
REFUSAL_TO_INSTALL_TOR = "refusal_to_install_tor"
|
REFUSAL_TO_INSTALL_TOR = "refusal_to_install_tor"
|
||||||
PORT_OPEN = "port_open"
|
PORT_OPEN = "port_open"
|
||||||
PORT_USED = "port_used"
|
PORT_USED = "port_used"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
from core.controllers.SessionStateController import SessionStateController
|
||||||
|
from core.models.Result import Result, ResultError
|
||||||
|
from core.errors.logger import logger
|
||||||
|
|
||||||
|
|
||||||
|
def kill_profile_from_grave(profile_id: int) -> Result:
|
||||||
|
"""Uses the JSON state to kill all related process ids. Good for recovered bootups"""
|
||||||
|
killed = SessionStateController.scortched_earth_kill_profile(profile_id)
|
||||||
|
|
||||||
|
if killed:
|
||||||
|
logger.info("psutil worked to kill it.")
|
||||||
|
return Result(valid=True)
|
||||||
|
else:
|
||||||
|
error_msg = "Even psutil scortched earth failed to kill the profile."
|
||||||
|
logger.error(error_msg)
|
||||||
|
return Result(valid=False, error_type=ResultError.STATE, message=error_msg)
|
||||||
|
|
@ -54,7 +54,7 @@ def is_dns_problem_worker(url: str, queue: multiprocessing.Queue):
|
||||||
def test(connection_observer: Optional[ConnectionObserver], port: Optional[int] = None) -> Result:
|
def test(connection_observer: Optional[ConnectionObserver], port: Optional[int] = None) -> Result:
|
||||||
endpoint_list = list(API_ENDPOINT_FORMATS.keys())[:MAX_ATTEMPTS]
|
endpoint_list = list(API_ENDPOINT_FORMATS.keys())[:MAX_ATTEMPTS]
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
total_budget = 5.0
|
total_budget = 6.0
|
||||||
|
|
||||||
# 1. DNS PRE-FLIGHT (Using Processes, not Threads)
|
# 1. DNS PRE-FLIGHT (Using Processes, not Threads)
|
||||||
if port is None:
|
if port is None:
|
||||||
|
|
@ -67,7 +67,7 @@ def test(connection_observer: Optional[ConnectionObserver], port: Optional[int]
|
||||||
processes.append(p)
|
processes.append(p)
|
||||||
|
|
||||||
any_resolved = False
|
any_resolved = False
|
||||||
dns_timeout = 5
|
dns_timeout = 6
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Wait for the first successful resolution
|
# Wait for the first successful resolution
|
||||||
|
|
@ -94,11 +94,6 @@ def test(connection_observer: Optional[ConnectionObserver], port: Optional[int]
|
||||||
# 2. HTTP REQUEST PHASE (Using Daemon Threads)
|
# 2. HTTP REQUEST PHASE (Using Daemon Threads)
|
||||||
transport = None
|
transport = None
|
||||||
if port:
|
if port:
|
||||||
# transport = httpx_socks.ProxyTransport(
|
|
||||||
# proxy_type=ProxyType.SOCKS5,
|
|
||||||
# proxy_host="127.0.0.1",
|
|
||||||
# proxy_port=port,
|
|
||||||
# )
|
|
||||||
transport = httpx_socks.SyncProxyTransport(
|
transport = httpx_socks.SyncProxyTransport(
|
||||||
proxy_type=ProxyType.SOCKS5,
|
proxy_type=ProxyType.SOCKS5,
|
||||||
proxy_host="127.0.0.1",
|
proxy_host="127.0.0.1",
|
||||||
|
|
|
||||||
|
|
@ -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 essentials.services.ConnectionService import ConnectionService
|
||||||
from core.services.keys_and_verifications.endpoint_verification import verify_wireguard_endpoint
|
from core.services.keys_and_verifications.endpoint_verification import verify_wireguard_endpoint
|
||||||
from core.controllers.SessionStateController import SessionStateController
|
from core.controllers.SessionStateController import SessionStateController
|
||||||
|
|
@ -60,7 +60,7 @@ def start_session_networking(
|
||||||
#--------------------------------
|
#--------------------------------
|
||||||
if protocol == ProtocolChoice.TOR:
|
if protocol == ProtocolChoice.TOR:
|
||||||
print("Passing off to ConnectionController's Tor system")
|
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
|
# WIREGUARD
|
||||||
|
|
|
||||||
65
core/services/networking/session/tor_session.py
Normal file
65
core/services/networking/session/tor_session.py
Normal 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)
|
||||||
|
|
||||||
7
core/services/networking/session/tor_tools.py
Normal file
7
core/services/networking/session/tor_tools.py
Normal 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)
|
||||||
|
|
@ -27,6 +27,7 @@ ERROR_PATTERNS = {
|
||||||
"permission_denied": "permission denied",
|
"permission_denied": "permission denied",
|
||||||
"port_in_use": r"(address already in use|port.*in use|cannot assign requested address)",
|
"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)",
|
"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):
|
class BootstrapStrategy(Enum):
|
||||||
|
|
@ -35,6 +36,7 @@ class BootstrapStrategy(Enum):
|
||||||
NEW_FOLDER_AND_PORT = "new_folder_and_port"
|
NEW_FOLDER_AND_PORT = "new_folder_and_port"
|
||||||
REINSTALL_AND_RETRY = "reinstall_and_retry"
|
REINSTALL_AND_RETRY = "reinstall_and_retry"
|
||||||
GIVE_UP = "give_up"
|
GIVE_UP = "give_up"
|
||||||
|
UPGRADE = "upgrade"
|
||||||
|
|
||||||
|
|
||||||
def bootstrap(
|
def bootstrap(
|
||||||
|
|
@ -95,7 +97,9 @@ def bootstrap(
|
||||||
if not install_tor(observer).valid:
|
if not install_tor(observer).valid:
|
||||||
return ApiResponse(valid=False, error_type=ErrorType.INSTALL_FAILED)
|
return ApiResponse(valid=False, error_type=ErrorType.INSTALL_FAILED)
|
||||||
use_new_folder = True
|
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 =====
|
# ===== Exhausted All Attempts =====
|
||||||
return ApiResponse(valid=False, error_type=ErrorType.CANT_BOOTSTRAP)
|
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
|
return BootstrapStrategy.FRESH_PORT
|
||||||
if diagnosis == "not_installed":
|
if diagnosis == "not_installed":
|
||||||
return BootstrapStrategy.REINSTALL_AND_RETRY
|
return BootstrapStrategy.REINSTALL_AND_RETRY
|
||||||
|
if diagnosis == "upgrade":
|
||||||
|
return BootstrapStrategy.UPGRADE
|
||||||
|
|
||||||
# No diagnosis case
|
# No diagnosis case
|
||||||
if attempt <= GIVE_UP_WITH_NO_DIAGNOSIS:
|
if attempt <= GIVE_UP_WITH_NO_DIAGNOSIS:
|
||||||
logger.info(f"Attempt {attempt}: trying new folder/port despite no diagnosis")
|
logger.info(f"Attempt {attempt}: trying new folder/port despite no diagnosis")
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
from core.infrastructure.state_management.kill_processes import kill_all_associated_processes
|
||||||
|
from core.models.enum_models import ProtocolChoice
|
||||||
from core.services.apps.launch_app import orchestrate_app_launch
|
from core.services.apps.launch_app import orchestrate_app_launch
|
||||||
from core.services.networking.session.session_networking import start_session_networking
|
from core.services.networking.session.session_networking import start_session_networking
|
||||||
from core.observers.Notifications import Notifications, EventType
|
from core.observers.Notifications import Notifications, EventType
|
||||||
|
|
@ -206,9 +208,7 @@ def disable_profile(
|
||||||
|
|
||||||
"""Orchestrate disabling a profile."""
|
"""Orchestrate disabling a profile."""
|
||||||
|
|
||||||
# if profile is None:
|
protocol = ProtocolChoice(profile.connection.code)
|
||||||
# burned_down = kill_all_associated_processes(profile_id=profile.id)
|
|
||||||
|
|
||||||
|
|
||||||
if profile.is_session_profile():
|
if profile.is_session_profile():
|
||||||
|
|
||||||
|
|
@ -226,27 +226,15 @@ def disable_profile(
|
||||||
raise ProfileDeactivationError(f'Assassin NOT disabled: {assassin_result.message}')
|
raise ProfileDeactivationError(f'Assassin NOT disabled: {assassin_result.message}')
|
||||||
# END ASSASSIN SECTION
|
# END ASSASSIN SECTION
|
||||||
|
|
||||||
print("Using SessionStateController to kill the profile..")
|
# STATE
|
||||||
killed = SessionStateController.kill_session_profile(profile_id=profile.id)
|
killed = SessionStateController.kill_session_profile(profile_id=profile.id, protocol=protocol)
|
||||||
if not killed.valid:
|
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):
|
if not kill_all_associated_processes(profile_id=profile.id):
|
||||||
return killed.wrap("Failed to disable the profile.")
|
return killed.wrap("Failed to disable the profile.")
|
||||||
else:
|
else:
|
||||||
logger.info("psutil worked to kill it.")
|
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)
|
Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile.id)
|
||||||
notification = "Profile Disconnected."
|
notification = "Profile Disconnected."
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
|
|
@ -370,3 +358,4 @@ def destroy_profile(
|
||||||
profile_observer.notify('destroyed', profile)
|
profile_observer.notify('destroyed', profile)
|
||||||
|
|
||||||
return Result(valid=True, message="Deleted Profile")
|
return Result(valid=True, message="Deleted Profile")
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue