Session wireguard profiles switched over to the new state management system
This commit is contained in:
parent
af3050106f
commit
257bb952f7
14 changed files with 869 additions and 117 deletions
|
|
@ -8,6 +8,7 @@ from core.observers.TicketObserver import TicketObserver
|
|||
from core.services.networking.systemwide.general_tools.test_any_protocol import test_session_ip
|
||||
from core.models.enum_models import ProtocolChoice
|
||||
|
||||
from core.models.session.SessionState import SessionState
|
||||
from collections.abc import Callable
|
||||
from core.Constants import Constants
|
||||
from core.Errors import ConnectionUnprotectedError, ConnectionTerminationError, CommandNotFoundError
|
||||
|
|
@ -61,71 +62,70 @@ class ConnectionController:
|
|||
return None
|
||||
|
||||
|
||||
@staticmethod
|
||||
def establish_session_connection(profile: SessionProfile, ignore: tuple[type[Exception]] = (), connection_observer: Optional[ConnectionObserver] = None, ticket_observer: Optional[TicketObserver] = None):
|
||||
# @staticmethod
|
||||
# def establish_session_connection(profile: SessionProfile, ignore: tuple[type[Exception]] = (), connection_observer: Optional[ConnectionObserver] = None, ticket_observer: Optional[TicketObserver] = None):
|
||||
|
||||
session_directory = tempfile.mkdtemp(prefix='hv-')
|
||||
session_state = SessionStateController.get_or_new(profile.id)
|
||||
# session_directory = tempfile.mkdtemp(prefix='hv-')
|
||||
# session_state = SessionStateController.get_or_new(profile.id)
|
||||
|
||||
port_number = None
|
||||
proxy_port_number = None
|
||||
# port_number = None
|
||||
# proxy_port_number = None
|
||||
|
||||
# this is a check from SessionConnection of if there's a systemwide with mask
|
||||
if profile.connection.is_unprotected():
|
||||
# # this is a check from SessionConnection of if there's a systemwide with mask
|
||||
# if profile.connection.is_unprotected():
|
||||
|
||||
if not system_uses_wireguard_interface():
|
||||
# if not system_uses_wireguard_interface():
|
||||
|
||||
if not ConnectionUnprotectedError in ignore:
|
||||
raise ConnectionUnprotectedError('Connection unprotected while the system is not using a WireGuard interface.')
|
||||
else:
|
||||
from core.services.profiles.profile_connections import disable_profile
|
||||
disable_profile(profile=profile, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||
# if not ConnectionUnprotectedError in ignore:
|
||||
# raise ConnectionUnprotectedError('Connection unprotected while the system is not using a WireGuard interface.')
|
||||
# else:
|
||||
# from core.services.profiles.profile_connections import disable_profile
|
||||
# disable_profile(profile=profile, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||
|
||||
|
||||
if profile.connection.code == 'tor':
|
||||
# if profile.connection.code == 'tor':
|
||||
|
||||
port_number = ConnectionService.get_random_available_port_number()
|
||||
ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer)
|
||||
# port_number = ConnectionService.get_random_available_port_number()
|
||||
# ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer)
|
||||
|
||||
session_state.network_port_numbers.tor.append(port_number)
|
||||
# session_state.network_port_numbers.tor.append(port_number)
|
||||
|
||||
elif profile.connection.code == 'wireguard':
|
||||
# elif profile.connection.code == 'wireguard':
|
||||
|
||||
if ConfigurationController.get_endpoint_verification_enabled():
|
||||
verify_wireguard_endpoint(profile, ignore=ignore)
|
||||
# if ConfigurationController.get_endpoint_verification_enabled():
|
||||
# verify_wireguard_endpoint(profile, ignore=ignore)
|
||||
|
||||
port_number = ConnectionService.get_random_available_port_number()
|
||||
ConnectionController.establish_wireguard_session_connection(profile, session_directory, port_number)
|
||||
session_state.network_port_numbers.wireguard.append(port_number)
|
||||
# port_number = ConnectionService.get_random_available_port_number()
|
||||
# ConnectionController.establish_wireguard_session_connection(profile, session_directory, port_number)
|
||||
# session_state.network_port_numbers.wireguard.append(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()
|
||||
|
||||
ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number)
|
||||
session_state.network_port_numbers.proxy.append(proxy_port_number)
|
||||
# ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number)
|
||||
# session_state.network_port_numbers.proxy.append(proxy_port_number)
|
||||
|
||||
# if not profile.connection.is_unprotected():
|
||||
# # if not profile.connection.is_unprotected():
|
||||
|
||||
if profile.connection.code == 'wireguard':
|
||||
test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=ProtocolChoice.WIREGUARD, connection_observer=connection_observer)
|
||||
if test_result.valid:
|
||||
logger.info("Connection established.")
|
||||
if connection_observer:
|
||||
connection_observer.notify("connected", "Confirmed")
|
||||
else:
|
||||
logger.error(test_result.message)
|
||||
raise ConnectionError(test_result.message)
|
||||
# if profile.connection.code == 'wireguard':
|
||||
# test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=ProtocolChoice.WIREGUARD, connection_observer=connection_observer)
|
||||
# if test_result.valid:
|
||||
# logger.info("Connection established.")
|
||||
# if connection_observer:
|
||||
# connection_observer.notify("connected", "Confirmed")
|
||||
# else:
|
||||
# logger.error(test_result.message)
|
||||
# return test_result.wrap("Unable to connect in ConnectionController.")
|
||||
|
||||
elif profile.connection.code == 'tor':
|
||||
await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
|
||||
# elif profile.connection.code == 'tor':
|
||||
# await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
|
||||
|
||||
|
||||
SessionStateController.update_or_create(session_state)
|
||||
|
||||
return proxy_port_number or port_number
|
||||
# SessionStateController.update_or_create(session_state)
|
||||
|
||||
# return proxy_port_number or port_number
|
||||
|
||||
|
||||
@staticmethod
|
||||
|
|
@ -149,14 +149,18 @@ class ConnectionController:
|
|||
# tor_module.stop_service()
|
||||
|
||||
@staticmethod
|
||||
def establish_tor_session_connection(port_number: int, connection_observer: Optional[ConnectionObserver] = None):
|
||||
def establish_tor_session_connection(port_number: int, connection_observer: Optional[ConnectionObserver] = None) -> Result:
|
||||
try:
|
||||
tor_module = TorModule(Constants.HV_TOR_STATE_HOME)
|
||||
tor_module.create_session(port_number, connection_observer)
|
||||
return Result(valid=True)
|
||||
except Exception as e:
|
||||
logger.error(f"Tor Can't Start: {e}")
|
||||
error_msg = f"Tor Can't Start: {e}"
|
||||
logger.error(error_msg)
|
||||
if connection_observer is not None:
|
||||
connection_observer.notify('custom_message', "Tor Can't Initialize")
|
||||
return Result(valid=False, error_type=ResultError.TOR, message=error_msg)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def terminate_tor_session_connection(port_number: int):
|
||||
|
|
@ -164,25 +168,25 @@ class ConnectionController:
|
|||
tor_module = TorModule(Constants.HV_TOR_STATE_HOME)
|
||||
tor_module.destroy_session(port_number)
|
||||
|
||||
@staticmethod
|
||||
def establish_wireguard_session_connection(profile: SessionProfile, session_directory: str, port_number: int):
|
||||
# @staticmethod
|
||||
# def establish_wireguard_session_connection(profile: SessionProfile, session_directory: str, port_number: int):
|
||||
|
||||
if not profile.has_wireguard_configuration():
|
||||
raise FileNotFoundError('Web service did not give us a WireGuard configuration, meaning the location is likely down.')
|
||||
# if not profile.has_wireguard_configuration():
|
||||
# raise FileNotFoundError('Web service did not give us a WireGuard configuration, meaning the location is likely down.')
|
||||
|
||||
wireguard_session_directory = f'{session_directory}/wireguard'
|
||||
Path(wireguard_session_directory).mkdir(exist_ok=True, mode=0o700)
|
||||
# wireguard_session_directory = f'{session_directory}/wireguard'
|
||||
# Path(wireguard_session_directory).mkdir(exist_ok=True, mode=0o700)
|
||||
|
||||
wireproxy_configuration_file_path = f'{wireguard_session_directory}/wireproxy.conf'
|
||||
Path(wireproxy_configuration_file_path).touch(exist_ok=True, mode=0o600)
|
||||
# wireproxy_configuration_file_path = f'{wireguard_session_directory}/wireproxy.conf'
|
||||
# Path(wireproxy_configuration_file_path).touch(exist_ok=True, mode=0o600)
|
||||
|
||||
with open(wireproxy_configuration_file_path, 'w') as wireproxy_configuration_file:
|
||||
wireproxy_configuration_file.write(f'WGConfig = {profile.get_wireguard_configuration_path()}\n\n[Socks5]\nBindAddress = 127.0.0.1:{str(port_number)}\n')
|
||||
# with open(wireproxy_configuration_file_path, 'w') as wireproxy_configuration_file:
|
||||
# wireproxy_configuration_file.write(f'WGConfig = {profile.get_wireguard_configuration_path()}\n\n[Socks5]\nBindAddress = 127.0.0.1:{str(port_number)}\n')
|
||||
|
||||
return subprocess.Popen((f'{Constants.HV_RUNTIME_DATA_HOME}/wireproxy/wireproxy', '-c', wireproxy_configuration_file_path), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
# return subprocess.Popen((f'{Constants.HV_RUNTIME_DATA_HOME}/wireproxy/wireproxy', '-c', wireproxy_configuration_file_path), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
|
||||
@staticmethod
|
||||
def establish_proxy_session_connection(profile: SessionProfile, session_directory: str, port_number: int, proxy_port_number: int):
|
||||
def establish_proxy_session_connection(profile: SessionProfile, session_directory: str, port_number: int, proxy_port_number: int) -> Result:
|
||||
|
||||
if shutil.which('proxychains4') is None:
|
||||
raise CommandNotFoundError('proxychains4')
|
||||
|
|
@ -193,7 +197,7 @@ class ConnectionController:
|
|||
if profile.has_proxy_configuration():
|
||||
proxy_configuration = profile.get_proxy_configuration()
|
||||
else:
|
||||
raise FileNotFoundError('No valid proxy configuration file detected.')
|
||||
return Result(valid=False, error_type=ResultError.MISSING_DATA, message='No valid proxy configuration file detected.')
|
||||
|
||||
proxy_session_directory = f'{session_directory}/proxy'
|
||||
Path(proxy_session_directory).mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
|
|
@ -216,7 +220,8 @@ class ConnectionController:
|
|||
with open(proxychains_configuration_file_path, 'w') as proxychains_configuration_file:
|
||||
proxychains_configuration_file.write(proxychains_configuration_file_contents)
|
||||
|
||||
return subprocess.Popen(('proxychains4', '-f', proxychains_configuration_file_path, 'microsocks', '-p', str(proxy_port_number)), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
network_process = subprocess.Popen(('proxychains4', '-f', proxychains_configuration_file_path, 'microsocks', '-p', str(proxy_port_number)), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
return Result(valid=True, data=network_process)
|
||||
|
||||
|
||||
|
||||
|
|
@ -242,3 +247,50 @@ class ConnectionController:
|
|||
ConnectionController.terminate_tor_session_connection(port_number)
|
||||
|
||||
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:
|
||||
|
||||
print("Starting a Tor Session Profile")
|
||||
|
||||
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)
|
||||
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)
|
||||
|
||||
# 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)
|
||||
|
|
|
|||
|
|
@ -1,30 +1,122 @@
|
|||
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
|
||||
# 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
|
||||
|
||||
|
||||
class SessionStateController:
|
||||
@staticmethod
|
||||
def get(id: int):
|
||||
return SessionState.find_by_id(id)
|
||||
def get_model(profile_id: int):
|
||||
return SessionState.find_by_id(profile_id)
|
||||
|
||||
@staticmethod
|
||||
def get_or_new(id: int):
|
||||
session_state = SessionStateController.get(id)
|
||||
def get_or_new(profile_id: int):
|
||||
session_state = SessionStateController.get_model(profile_id)
|
||||
|
||||
if session_state is None:
|
||||
# Update the Singleton Repo
|
||||
repo = ProfileStateRepository()
|
||||
repo.sync_session_added(id)
|
||||
repo.setup_session_profile(profile_id)
|
||||
|
||||
# Create and save the session
|
||||
session_state = SessionState(id)
|
||||
session_state = SessionState(profile_id)
|
||||
session_state.save()
|
||||
return session_state
|
||||
|
||||
return session_state
|
||||
|
||||
|
||||
@staticmethod
|
||||
def kill_session_profile(profile_id: int) -> Result:
|
||||
|
||||
# get process objects from repo:
|
||||
repo = ProfileStateRepository()
|
||||
|
||||
for each_process_type in LIST_OF_PROCESSES:
|
||||
each_process = repo.get_session_process(profile_id=profile_id, process_type=each_process_type)
|
||||
|
||||
try:
|
||||
pid = each_process.pid
|
||||
print(f"Killing process type {each_process_type} with a pid of {pid}")
|
||||
each_process.kill()
|
||||
|
||||
# Wait for the process to actually exit and clean up
|
||||
exit_code = each_process.wait()
|
||||
print(f"Process {each_process_type} terminated with code {exit_code}")
|
||||
continue
|
||||
|
||||
except ProcessLookupError:
|
||||
print("Process was already dead or terminated prior. But we continue")
|
||||
continue
|
||||
|
||||
except AttributeError:
|
||||
print("Process variable was never initialized. But we continue")
|
||||
continue
|
||||
|
||||
except OSError as e:
|
||||
pid_label = pid if 'pid' in locals() else "unknown"
|
||||
# Catch-all for other OS-level failures (e.g., permission issues)
|
||||
error_msg = f"Failed to kill process {each_process_type} with pid: {pid_label} and error: {e}"
|
||||
logger.error(error_msg)
|
||||
return Result(valid=False, error_type=ResultError.STATE, message=error_msg)
|
||||
|
||||
|
||||
# Clear the repo:
|
||||
print("Clearing the repo")
|
||||
repo.remove_session_profile(profile_id)
|
||||
|
||||
# Delete model:
|
||||
SessionState.remove_file(id=profile_id)
|
||||
return Result(valid=True)
|
||||
|
||||
@staticmethod
|
||||
def new(profile_id: int):
|
||||
# model
|
||||
session_state = SessionState(profile_id)
|
||||
session_state.save()
|
||||
|
||||
# repo
|
||||
repo = ProfileStateRepository()
|
||||
repo.setup_session_profile(profile_id)
|
||||
|
||||
@staticmethod
|
||||
def add_process(profile_id: int, process_type: ProcessType, process: subprocess.Popen):
|
||||
repo = ProfileStateRepository()
|
||||
repo.add_session_process(profile_id=profile_id, process_type=process_type, process=process)
|
||||
|
||||
@staticmethod
|
||||
def remove_process(profile_id: int, process_type: ProcessType):
|
||||
repo = ProfileStateRepository()
|
||||
repo.add_session_process(profile_id=profile_id, process_type=process_type, process=None)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def activate(profile_id: int) -> bool:
|
||||
repo = ProfileStateRepository()
|
||||
activated = repo.flip_session_profile_on(profile_id=profile_id)
|
||||
|
||||
if not activated:
|
||||
logger.error("Called activate, when the processes weren't ready to do so.")
|
||||
return False
|
||||
|
||||
# notify UI:
|
||||
logger.info(f"Activated profile {profile_id}")
|
||||
Notifications.emit(EventType.SESSION_PROFILE_ENABLE, profile_id)
|
||||
notification = f"Profile {profile_id} enabled."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
return True
|
||||
|
||||
|
||||
@staticmethod
|
||||
def get_repo(id: int):
|
||||
repo = ProfileStateRepository()
|
||||
return repo.get_entire_session_process_group(int)
|
||||
|
||||
@staticmethod
|
||||
def exists(id: int):
|
||||
return SessionState.exists(id)
|
||||
|
|
@ -42,18 +134,43 @@ class SessionStateController:
|
|||
profile_id = session_state.id
|
||||
|
||||
# Ensure repo knows this session exists
|
||||
ProfileStateRepository().sync_session_added(profile_id)
|
||||
ProfileStateRepository().setup_session_profile(profile_id)
|
||||
|
||||
# notify UI:
|
||||
Notifications.emit(EventType.SESSION_PROFILE_ENABLE, profile_id)
|
||||
# # notify UI:
|
||||
# Notifications.emit(EventType.SESSION_PROFILE_ENABLE, profile_id)
|
||||
|
||||
@staticmethod
|
||||
def remove(profile_id: int):
|
||||
# save to model:
|
||||
print("dissolving model")
|
||||
SessionState.dissolve(profile_id)
|
||||
|
||||
# cache:
|
||||
ProfileStateRepository().sync_session_removed(profile_id)
|
||||
print("removing from cache repo")
|
||||
repo = ProfileStateRepository()
|
||||
repo.remove_session_profile(profile_id)
|
||||
|
||||
# notify UI:
|
||||
print("sending")
|
||||
Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile_id)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def scortched_earth_kill_profile(profile_id: int) -> bool:
|
||||
session_state = SessionStateController.get_model(profile_id)
|
||||
|
||||
if session_state:
|
||||
killed = kill_all_associated_processes(session_state)
|
||||
|
||||
# delete model:
|
||||
SessionState.remove_file(profile_id)
|
||||
|
||||
# cache:
|
||||
print("removing from cache repo")
|
||||
repo = ProfileStateRepository()
|
||||
repo.remove_session_profile(profile_id)
|
||||
|
||||
# notify UI:
|
||||
print("sending")
|
||||
Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile_id)
|
||||
return True
|
||||
|
|
@ -4,19 +4,35 @@ from core.models.session.SessionState import SessionState
|
|||
from core.models.enum_models import ProtocolChoice
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
from typing import Optional, Dict
|
||||
import subprocess
|
||||
from enum import Enum
|
||||
|
||||
class ProcessType(Enum):
|
||||
NETWORK = "network"
|
||||
APP = "app"
|
||||
DISPLAY = "display"
|
||||
ACTIVE = "active"
|
||||
|
||||
|
||||
LIST_OF_PROCESSES = [ProcessType.APP, ProcessType.DISPLAY, ProcessType.NETWORK]
|
||||
|
||||
@dataclass
|
||||
class GlobalState:
|
||||
# systemwide:
|
||||
systemwide_active: bool = False
|
||||
protocol: ProtocolChoice = None
|
||||
firewalled: bool = False
|
||||
dns_set: bool = False
|
||||
systemwide_profile_id: Optional[int] = None
|
||||
session_profile_ids: list[int] = field(default_factory=list)
|
||||
verified_working: bool = False
|
||||
changed_port: bool = False
|
||||
|
||||
# session:
|
||||
# session_profile_ids: list[int] = field(default_factory=list)
|
||||
session_profiles: Dict[str, Dict[ProcessType, subprocess.Popen]] = field(default_factory=dict)
|
||||
|
||||
|
||||
class ProfileStateRepository:
|
||||
_instance = None
|
||||
|
||||
|
|
@ -38,6 +54,24 @@ class ProfileStateRepository:
|
|||
# Load existing session IDs from disk into the list
|
||||
self.global_state.session_profile_ids = [s.id for s in SessionState.all()]
|
||||
|
||||
@property
|
||||
def current_session_ids(self) -> list[int]:
|
||||
"""Returns current session profile ids."""
|
||||
return list(self.global_state.session_profiles.keys())
|
||||
|
||||
@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 = []
|
||||
|
||||
for each_profile_id in current_list:
|
||||
if self.global_state.session_profiles[each_profile_id][ProcessType.ACTIVE] is True:
|
||||
active_list.append(each_profile_id)
|
||||
|
||||
return active_list
|
||||
|
||||
def turn_off_system_connection(self):
|
||||
"""Clear the system-wide memory cache."""
|
||||
self.global_state.systemwide_profile_id = None
|
||||
|
|
@ -59,7 +93,7 @@ class ProfileStateRepository:
|
|||
|
||||
|
||||
def verify_its_up(self, profile_id: int) -> bool:
|
||||
"""Flips on Verification, if the rest of the state matches"""
|
||||
"""Flips on Verification for Systemwide, if the rest of the state matches"""
|
||||
|
||||
if not self.global_state.systemwide_active:
|
||||
return False
|
||||
|
|
@ -73,21 +107,69 @@ class ProfileStateRepository:
|
|||
Notifications.emit(EventType.SYSTEM_ENABLE, profile_id)
|
||||
return True
|
||||
|
||||
|
||||
def sync_session_added(self, profile_id: int):
|
||||
"""Called by SessionStateController to update memory cache."""
|
||||
if profile_id not in self.global_state.session_profile_ids:
|
||||
self.global_state.session_profile_ids.append(profile_id)
|
||||
|
||||
def sync_session_removed(self, profile_id: int):
|
||||
"""Called by SessionStateController to update memory cache."""
|
||||
if profile_id in self.global_state.session_profile_ids:
|
||||
self.global_state.session_profile_ids.remove(profile_id)
|
||||
|
||||
def is_profile_active(self, profile_id: int) -> bool:
|
||||
# Check system profile
|
||||
if self.global_state.systemwide_active and self.global_state.systemwide_profile_id == profile_id:
|
||||
return True
|
||||
# Check session profiles
|
||||
return profile_id in self.global_state.session_profile_ids
|
||||
return profile_id in self.active_session_ids
|
||||
|
||||
|
||||
def setup_session_profile(self, profile_id: int) -> None:
|
||||
"""Ensures a session profile exists in the registry without overwriting existing processes."""
|
||||
self.global_state.session_profiles.setdefault(profile_id, {})
|
||||
|
||||
|
||||
def add_session_process(self, profile_id: int, process_type: ProcessType, process: subprocess.Popen|bool) -> None:
|
||||
"""Adds a live process to a specific profile id group."""
|
||||
self.setup_session_profile(profile_id)
|
||||
self.global_state.session_profiles[profile_id][process_type] = process
|
||||
|
||||
def get_entire_session_process_group(self, profile_id: int) -> Optional[Dict[ProcessType, subprocess.Popen]]:
|
||||
"""Returns the entire dictionary of processes for a group, or None if not found."""
|
||||
return self.global_state.session_profiles.get(profile_id)
|
||||
|
||||
|
||||
def flip_session_profile_on(self, profile_id: int) -> bool:
|
||||
"""If it has all the pre-reqs, then it sets the status to on."""
|
||||
|
||||
for each_type in LIST_OF_PROCESSES:
|
||||
if self.global_state.session_profiles[profile_id][each_type] is None:
|
||||
print(f"Process is none for {each_type}")
|
||||
return False
|
||||
|
||||
print("Global state is setting the session profile to activated")
|
||||
self.global_state.session_profiles[profile_id][ProcessType.ACTIVE] = True
|
||||
return True
|
||||
|
||||
|
||||
def get_session_process(self, profile_id: int, process_type: ProcessType) -> Optional[subprocess.Popen]:
|
||||
"""Gets a single process from the session profile's group."""
|
||||
# 1. Leverage the group getter
|
||||
group = self.get_entire_session_process_group(profile_id)
|
||||
|
||||
# 2. If the group exists, try to get the specific process
|
||||
if group:
|
||||
return group.get(process_type)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def remove_session_profile(self, profile_id: int) -> None:
|
||||
""" 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]
|
||||
|
||||
|
||||
|
||||
|
||||
# def sync_session_added(self, profile_id: int):
|
||||
# """Called by SessionStateController to update memory cache."""
|
||||
# if profile_id not in self.global_state.session_profile_ids:
|
||||
# self.global_state.session_profile_ids.append(profile_id)
|
||||
|
||||
# def sync_session_removed(self, profile_id: int):
|
||||
# """Called by SessionStateController to update memory cache."""
|
||||
# if profile_id in self.global_state.session_profile_ids:
|
||||
# self.global_state.session_profile_ids.remove(profile_id)
|
||||
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ def connected_system_profile_id() -> int|None:
|
|||
def connected_session_profile_ids() -> list|None:
|
||||
"""Returns a list of the currently connected session profile IDs"""
|
||||
state_repo = ProfileStateRepository()
|
||||
return state_repo.global_state.session_profile_ids
|
||||
return state_repo.active_session_ids
|
||||
|
||||
|
||||
def get_all_connected() -> list|None:
|
||||
|
|
@ -225,7 +225,7 @@ def evaluate_state_on_startup() -> Result:
|
|||
if active_session_profiles:
|
||||
for each_session in active_session_profiles:
|
||||
logger.info(f"Killing profile {each_session}")
|
||||
Notifications.emit(EventType.SESSION_PROFILE_KILL, each_session)
|
||||
Notifications.emit(EventType.SESSION_PROFILE_KILL, each_session.id)
|
||||
time.sleep(4)
|
||||
|
||||
return Result(valid=True)
|
||||
|
|
|
|||
35
core/infrastructure/state_management/kill_processes.py
Normal file
35
core/infrastructure/state_management/kill_processes.py
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
|
||||
from core.models.session.SessionState import SessionState
|
||||
|
||||
import psutil
|
||||
|
||||
def kill_all_associated_processes(session_state: SessionState) -> bool:
|
||||
|
||||
associated_process_ids = list(session_state.process_ids)
|
||||
network_connections = psutil.net_connections()
|
||||
|
||||
for network_port_number in session_state.network_port_numbers.isolated:
|
||||
|
||||
for network_connection in network_connections:
|
||||
|
||||
if network_connection.laddr != tuple() and network_connection.laddr.port == network_port_number:
|
||||
|
||||
if network_connection.pid is not None:
|
||||
associated_process_ids.append(network_connection.pid)
|
||||
|
||||
if network_connection.raddr != tuple() and network_connection.raddr.port == network_port_number:
|
||||
|
||||
if network_connection.pid is not None:
|
||||
associated_process_ids.append(network_connection.pid)
|
||||
|
||||
for process in psutil.process_iter():
|
||||
|
||||
if process.pid in associated_process_ids and process.is_running():
|
||||
|
||||
for child_process in process.children(True):
|
||||
child_process.kill()
|
||||
|
||||
print("killing process")
|
||||
process.kill()
|
||||
|
||||
return True
|
||||
|
|
@ -19,6 +19,7 @@ class ResultError(Enum):
|
|||
SETUP_SINGBOX = "setup_singbox"
|
||||
FILE_SYSTEM = "filesystem"
|
||||
CONNECTION = "connection"
|
||||
TOR = "tor"
|
||||
DATABASE = "database"
|
||||
PERMISSION = "permission"
|
||||
SUBSCRIPTION = "subscription"
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ class ProtocolChoice(Enum):
|
|||
HYSTERIA2 = "hysteria2"
|
||||
VLESS = "vless"
|
||||
SOCK5_PROXY = "proxy"
|
||||
TOR = "tor"
|
||||
# MASKED_WIREGUARD = "masked_wireguard"
|
||||
|
||||
SINGBOX_PROTOCOLS = [ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS]
|
||||
|
|
|
|||
|
|
@ -89,6 +89,20 @@ class SessionState:
|
|||
|
||||
return session_states
|
||||
|
||||
|
||||
@staticmethod
|
||||
def remove_file(id: int):
|
||||
|
||||
session_state = SessionState.find_by_id(id)
|
||||
|
||||
if session_state is not None:
|
||||
|
||||
session_state_path = session_state.get_state_path()
|
||||
|
||||
print(f"Removing state file for profile {id}")
|
||||
shutil.rmtree(session_state_path, ignore_errors=True)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def dissolve(id: int):
|
||||
|
||||
|
|
@ -99,6 +113,8 @@ class SessionState:
|
|||
session_state_path = session_state.get_state_path()
|
||||
|
||||
SessionState.__kill_associated_processes(session_state)
|
||||
|
||||
print(f"Removing state file for profile {id}")
|
||||
shutil.rmtree(session_state_path, ignore_errors=True)
|
||||
|
||||
@staticmethod
|
||||
|
|
@ -128,6 +144,7 @@ class SessionState:
|
|||
for child_process in process.children(True):
|
||||
child_process.kill()
|
||||
|
||||
print("killing process")
|
||||
process.kill()
|
||||
|
||||
@staticmethod
|
||||
|
|
|
|||
60
core/services/apps/display.py
Normal file
60
core/services/apps/display.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
from core.models.session.SessionProfile import SessionProfile
|
||||
from core.models.Result import Result, ResultError
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
import shutil
|
||||
|
||||
|
||||
def find_unused_display() -> str:
|
||||
"""Get a string of an unused X11 display port"""
|
||||
|
||||
file_names = os.listdir('/tmp/.X11-unix')
|
||||
active_displays = []
|
||||
|
||||
for file_name in file_names:
|
||||
|
||||
match_object = re.search(r'X(\d+)', file_name)
|
||||
|
||||
if match_object:
|
||||
|
||||
detected_display = int(match_object.group(1))
|
||||
|
||||
if 170 <= detected_display <= 198:
|
||||
active_displays.append(detected_display)
|
||||
|
||||
if len(active_displays) > 0:
|
||||
|
||||
unused_display = sorted(active_displays)[-1] + 1
|
||||
return f':{str(unused_display)}'
|
||||
|
||||
else:
|
||||
return ':170'
|
||||
|
||||
|
||||
|
||||
def launch_xephyr(profile: SessionProfile, display: str) -> Result:
|
||||
"""Run Xephyr with the correct display, and get it's persistent Popen object"""
|
||||
|
||||
if shutil.which('Xephyr') is None:
|
||||
return Result(valid=False, error_type=ResultError.MISSING_DEPENDENCY, message="Xephyr pre-req is missing.")
|
||||
|
||||
virtual_display_process = subprocess.Popen(('Xephyr', '-ac', '-br', '-title', f'HydraVeil - {profile.name or "Unnamed Profile"}', '-screen', profile.resolution, '-no-host-grab', display), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
|
||||
start_time = time.time()
|
||||
timeout = float(10)
|
||||
|
||||
while not os.path.exists(f'/tmp/.X11-unix/X{display[1:]}'):
|
||||
|
||||
if time.time() - start_time < timeout:
|
||||
time.sleep(0.1)
|
||||
|
||||
else:
|
||||
|
||||
virtual_display_process.kill()
|
||||
return
|
||||
|
||||
return Result(valid=True, data=virtual_display_process)
|
||||
|
||||
18
core/services/apps/font_families.py
Normal file
18
core/services/apps/font_families.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
|
||||
|
||||
|
||||
PREFERRED_FONT_FAMILIES = [
|
||||
'adwaita-sans-fonts',
|
||||
'dejavu',
|
||||
'droid',
|
||||
'google-droid-sans-fonts',
|
||||
'google-noto-sans-cjk-vf-fonts',
|
||||
'google-noto-sans-mono-cjk-vf-fonts',
|
||||
'liberation',
|
||||
'liberation-sans-fonts',
|
||||
'libreoffice',
|
||||
'noto',
|
||||
'open-sans',
|
||||
'ubuntu'
|
||||
]
|
||||
|
||||
51
core/services/apps/fonts.py
Normal file
51
core/services/apps/fonts.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
from core.services.apps.font_families import PREFERRED_FONT_FAMILIES
|
||||
from core.models.orm_models.ApplicationVersion import ApplicationVersion
|
||||
from core.models.session.SessionProfile import SessionProfile
|
||||
from core.models.Result import Result
|
||||
|
||||
# generic
|
||||
from pathlib import Path
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
|
||||
|
||||
def _select_random_font(items: list, preferred_items: list, limit: int):
|
||||
"""Select a font from the available choices"""
|
||||
|
||||
available_preferred_items = [item for item in preferred_items if item in items]
|
||||
selectable_items = [item for item in items if item not in preferred_items]
|
||||
|
||||
selected_items = random.sample(selectable_items, random.randint(0, min(limit, len(selectable_items))))
|
||||
|
||||
return selected_items + available_preferred_items
|
||||
|
||||
|
||||
def prepare_fonts(
|
||||
profile: SessionProfile,
|
||||
version: ApplicationVersion,
|
||||
persistent_state_path: str
|
||||
) -> Result:
|
||||
"""Write the fonts for this app version to the bash script's init"""
|
||||
|
||||
font_path = f'{profile.get_data_path()}/fonts'
|
||||
|
||||
if not os.path.isdir(persistent_state_path) or len(os.listdir(persistent_state_path)) == 0:
|
||||
shutil.copytree(f'{version.get_installation_path()}/resources/initial-state', persistent_state_path)
|
||||
|
||||
if (not os.path.isdir(font_path) or len(os.listdir(font_path)) == 0) and os.path.isdir('/usr/share/fonts'):
|
||||
|
||||
if os.path.isdir('/usr/share/fonts/truetype'):
|
||||
truetype_fonts_path = '/usr/share/fonts/truetype'
|
||||
else:
|
||||
truetype_fonts_path = '/usr/share/fonts'
|
||||
|
||||
font_families = [file.name for file in Path(truetype_fonts_path).iterdir() if file.is_dir()]
|
||||
|
||||
font_family_subset = _select_random_font(font_families, PREFERRED_FONT_FAMILIES, 12)
|
||||
|
||||
for font_family in font_family_subset:
|
||||
shutil.copytree(f'{truetype_fonts_path}/{font_family}', f'{font_path}/{font_family}')
|
||||
|
||||
return Result(valid=True)
|
||||
|
||||
150
core/services/apps/launch_app.py
Normal file
150
core/services/apps/launch_app.py
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
from core.observers.Notifications import Notifications, EventType
|
||||
from core.services.apps.display import find_unused_display, launch_xephyr
|
||||
from core.services.apps.fonts import prepare_fonts
|
||||
from core.infrastructure.global_state import ProcessType
|
||||
from core.Constants import Constants
|
||||
from core.controllers.SessionStateController import SessionStateController
|
||||
from core.models.orm_models.ApplicationVersion import ApplicationVersion
|
||||
from core.models.session.SessionProfile import SessionProfile
|
||||
from core.models.Result import Result, ResultError
|
||||
from core.errors.logger import logger
|
||||
|
||||
# generic
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
|
||||
|
||||
def literally_launch_app(
|
||||
initialization_file_path: str,
|
||||
profile: SessionProfile,
|
||||
display: str
|
||||
) -> Result:
|
||||
"""Screen for the required pre-reqs, and launch the bash script with the correct env file."""
|
||||
|
||||
if shutil.which('bwrap') is None:
|
||||
return Result(valid=False, error_type=ResultError.MISSING_DEPENDENCY, message="bwrap pre-req is missing.")
|
||||
|
||||
if shutil.which('ratpoison') is None:
|
||||
return Result(valid=False, error_type=ResultError.MISSING_DEPENDENCY, message="ratpoison pre-req is missing.")
|
||||
|
||||
environment = os.environ.copy()
|
||||
environment.update({'DISPLAY': display})
|
||||
|
||||
app_process = subprocess.Popen(initialization_file_path, env=environment)
|
||||
|
||||
return Result(valid=True, data=app_process)
|
||||
|
||||
|
||||
def prepare_initialization_file(
|
||||
profile: SessionProfile,
|
||||
display: str,
|
||||
time_zone: str,
|
||||
version: ApplicationVersion,
|
||||
port_number: int
|
||||
) -> str:
|
||||
"""Prepare the application's init file"""
|
||||
|
||||
runtime_initialization_file_template = open(f'/{Constants.HV_RUNTIME_DATA_HOME}/.init.ptpl', 'r').read()
|
||||
runtime_initialization_file_contents = runtime_initialization_file_template.format(display=display, time_zone=time_zone, hv_runtime_data_home=Constants.HV_RUNTIME_DATA_HOME)
|
||||
|
||||
application_initialization_file_template = open(f'/{version.get_installation_path()}/.init.ptpl', 'r').read()
|
||||
application_initialization_file_contents = application_initialization_file_template.format(application_version_home=version.get_installation_path(), port_number=port_number or -1, home=Constants.HOME, profile_data_path=profile.get_data_path(), config_home=Constants.CONFIG_HOME, application_version_number=version.version_number)
|
||||
|
||||
initialization_file_contents = runtime_initialization_file_contents + application_initialization_file_contents
|
||||
initialization_file_path = f'{Constants.HV_SESSION_STATE_HOME}/{str(profile.id)}/.init'
|
||||
|
||||
Path(initialization_file_path).touch(exist_ok=True, mode=0o600 | stat.S_IEXEC)
|
||||
|
||||
with open(initialization_file_path, 'w') as initialization_file:
|
||||
initialization_file.write(initialization_file_contents)
|
||||
|
||||
return initialization_file_path
|
||||
|
||||
|
||||
def orchestrate_app_launch(
|
||||
version: ApplicationVersion,
|
||||
profile: SessionProfile,
|
||||
port_number: int = None,
|
||||
) -> Result:
|
||||
|
||||
# ----------------------------------
|
||||
# PREPARE VARIABLES AND STATE
|
||||
# ----------------------------------
|
||||
persistent_state_path = f'{profile.get_data_path()}/persistent-state'
|
||||
|
||||
print("Preparing the fonts")
|
||||
prepared_fonts = prepare_fonts(
|
||||
profile=profile,
|
||||
version=version,
|
||||
persistent_state_path=persistent_state_path
|
||||
)
|
||||
if not prepared_fonts.valid:
|
||||
return prepared_fonts.wrap("Failed to prepare the fonts.")
|
||||
|
||||
print("Getting the display and timezone")
|
||||
display = find_unused_display()
|
||||
time_zone = profile.determine_timezone()
|
||||
|
||||
print("Setting up the init file.")
|
||||
initialization_file_path = prepare_initialization_file(
|
||||
profile=profile,
|
||||
display=display,
|
||||
time_zone=time_zone,
|
||||
version=version,
|
||||
port_number=port_number
|
||||
)
|
||||
|
||||
session_state = SessionStateController.get_or_new(profile.id)
|
||||
|
||||
# ----------------------------------
|
||||
# DISPLAY LAUNCH
|
||||
# ----------------------------------
|
||||
print("Launching Xephyr")
|
||||
xephyr_result = launch_xephyr(profile=profile, display=display)
|
||||
if not xephyr_result.valid:
|
||||
error_msg = "Unable to launch the profile's graphical display."
|
||||
logger.error(error_msg)
|
||||
return xephyr_result.wrap(error_msg)
|
||||
|
||||
virtual_display_process = xephyr_result.data
|
||||
|
||||
# ----------------------------------
|
||||
# APP LAUNCH
|
||||
# ----------------------------------
|
||||
print("Literally launching the application's bash script")
|
||||
app_launch_result = literally_launch_app(
|
||||
initialization_file_path=initialization_file_path,
|
||||
profile=profile,
|
||||
display=display
|
||||
)
|
||||
if not app_launch_result.valid:
|
||||
error_msg = "Failed to launch the app itself. Killing the display."
|
||||
logger.error(error_msg)
|
||||
virtual_display_process.kill()
|
||||
return app_launch_result.wrap(error_msg)
|
||||
|
||||
app_process = app_launch_result.data
|
||||
|
||||
# ----------------------------------
|
||||
# UPDATE STATE
|
||||
# ----------------------------------
|
||||
|
||||
# Update Repo (in memory) with the process objects:
|
||||
print("Updating Repo in memory State..")
|
||||
SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.DISPLAY, process=virtual_display_process)
|
||||
SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.APP, process=app_process)
|
||||
|
||||
# update model (on disk) with pids:
|
||||
print("Updating the model on disk..")
|
||||
session_state.process_ids.extend([virtual_display_process.pid, app_process.pid])
|
||||
SessionStateController.update_or_create(session_state)
|
||||
|
||||
print("It worked. Notify & Returning..")
|
||||
if SessionStateController.activate(profile.id):
|
||||
return Result(valid=True)
|
||||
else:
|
||||
return Result(valid=False, error_type=ResultError.STATE, message="We launched the profile, but failed to activate it via the Controller & Repo")
|
||||
|
||||
141
core/services/networking/session/session_networking.py
Normal file
141
core/services/networking/session/session_networking.py
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
from core.controllers.ConnectionController 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
|
||||
from core.models.session.SessionProfile import SessionProfile
|
||||
from core.observers.ConnectionObserver import ConnectionObserver
|
||||
from core.models.enum_models import ProtocolChoice
|
||||
from core.errors.logger import logger
|
||||
from core.models.Result import Result, ResultError
|
||||
from core.infrastructure.global_state import ProcessType
|
||||
from core.services.networking.systemwide.general_tools.test_any_protocol import test_session_ip
|
||||
from core.controllers.ConfigurationController import ConfigurationController
|
||||
from core.Constants import Constants
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def start_wireproxy(profile: SessionProfile, session_directory: str, port_number: int) -> Result:
|
||||
|
||||
if not profile.has_wireguard_configuration():
|
||||
error_msg = f"Profile {profile.id} does not have a Wireguard configuration, meaning the API or location are down"
|
||||
return Result(valid=False, error_type=ResultError.MISSING_DATA, message=error_msg)
|
||||
|
||||
wireguard_session_directory = f'{session_directory}/wireguard'
|
||||
Path(wireguard_session_directory).mkdir(exist_ok=True, mode=0o700)
|
||||
|
||||
wireproxy_configuration_file_path = f'{wireguard_session_directory}/wireproxy.conf'
|
||||
Path(wireproxy_configuration_file_path).touch(exist_ok=True, mode=0o600)
|
||||
|
||||
with open(wireproxy_configuration_file_path, 'w') as wireproxy_configuration_file:
|
||||
wireproxy_configuration_file.write(f'WGConfig = {profile.get_wireguard_configuration_path()}\n\n[Socks5]\nBindAddress = 127.0.0.1:{str(port_number)}\n')
|
||||
|
||||
wireproxy_process = subprocess.Popen((f'{Constants.HV_RUNTIME_DATA_HOME}/wireproxy/wireproxy', '-c', wireproxy_configuration_file_path), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
return Result(valid=True, data=wireproxy_process)
|
||||
|
||||
|
||||
def start_session_networking(
|
||||
profile: SessionProfile,
|
||||
ignore: tuple[type[Exception]] = (),
|
||||
connection_observer: Optional[ConnectionObserver] = None
|
||||
) -> Result:
|
||||
|
||||
protocol = ProtocolChoice(profile.connection.code)
|
||||
print(f"protocol is {protocol}")
|
||||
|
||||
session_directory = tempfile.mkdtemp(prefix='hv-')
|
||||
session_state = SessionStateController.get_or_new(profile.id)
|
||||
|
||||
port_number = None
|
||||
proxy_port_number = None
|
||||
|
||||
port_number = ConnectionService.get_random_available_port_number()
|
||||
print(f"Openning on port {port_number}")
|
||||
|
||||
#--------------------------------
|
||||
# TOR
|
||||
#--------------------------------
|
||||
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)
|
||||
|
||||
#--------------------------------
|
||||
# WIREGUARD
|
||||
#--------------------------------
|
||||
elif protocol == ProtocolChoice.WIREGUARD:
|
||||
|
||||
# Verification
|
||||
if ConfigurationController.get_endpoint_verification_enabled():
|
||||
verify_wireguard_endpoint(profile, ignore=ignore)
|
||||
|
||||
connection_result = start_wireproxy(profile, session_directory, port_number)
|
||||
session_state.network_port_numbers.wireguard.append(port_number)
|
||||
|
||||
#--------------------------------
|
||||
# ALL CONNECTIONS
|
||||
#--------------------------------
|
||||
if not connection_result.valid:
|
||||
return connection_result.wrap("Unable to start the network connection.")
|
||||
|
||||
network_process = connection_result.data
|
||||
|
||||
# sanity check for all networking processes:
|
||||
if not network_process:
|
||||
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Missing a network process when it was confirmed earlier.")
|
||||
|
||||
# Test:
|
||||
print("Testing IP..")
|
||||
test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=protocol, connection_observer=connection_observer)
|
||||
if not test_result.valid:
|
||||
error_msg = "Test shows IP is not valid."
|
||||
logger.error(error_msg)
|
||||
network_process.kill()
|
||||
logger.info("Killed process")
|
||||
|
||||
return test_result.wrap(error_msg)
|
||||
|
||||
# Update in memory repo,
|
||||
SessionStateController.update_or_create(session_state)
|
||||
SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
|
||||
|
||||
final_port = proxy_port_number or port_number
|
||||
return Result(valid=True, data=final_port)
|
||||
|
||||
|
||||
# def kill_session_networking(profile_id: int) -> Result:
|
||||
# SessionStateController.kill_session_process(profile_id=profile_id, process_type=ProcessType.NETWORK)
|
||||
# return Result(valid=True)
|
||||
|
||||
|
||||
# # if not profile.connection.is_unprotected():
|
||||
|
||||
# if profile.connection.code == 'wireguard':
|
||||
# test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=ProtocolChoice.WIREGUARD, connection_observer=connection_observer)
|
||||
# if test_result.valid:
|
||||
# logger.info("Connection established.")
|
||||
# if connection_observer:
|
||||
# connection_observer.notify("connected", "Confirmed")
|
||||
# else:
|
||||
# logger.error(test_result.message)
|
||||
# return test_result.wrap("Unable to connect in ConnectionController.")
|
||||
|
||||
# elif profile.connection.code == 'tor':
|
||||
# await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# this is a check from SessionConnection of if there's a systemwide with mask
|
||||
# if profile.connection.is_unprotected():
|
||||
# if not system_uses_wireguard_interface() and not ConnectionUnprotectedError in ignore:
|
||||
# error_msg = 'Connection unprotected while the system is not using a WireGuard interface.'
|
||||
# logger.error(error_msg)
|
||||
# return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg)
|
||||
# # from core.services.profiles.profile_connections import disable_profile
|
||||
# # disable_profile(profile=profile, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
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
|
||||
from core.controllers.ConnectionController import ConnectionController
|
||||
from core.controllers.ProfileController import ProfileController
|
||||
|
|
@ -59,7 +61,6 @@ def is_enabled(profile: Union[SessionProfile, SystemProfile]) -> int | None:
|
|||
def enable_session_profile(
|
||||
profile: Union[SessionProfile, SystemProfile],
|
||||
ignore: tuple[type[Exception]] = (),
|
||||
asynchronous: bool = False,
|
||||
profile_observer: ProfileObserver = None,
|
||||
application_version_observer: ApplicationVersionObserver = None,
|
||||
connection_observer: ConnectionObserver = None,
|
||||
|
|
@ -67,13 +68,15 @@ def enable_session_profile(
|
|||
max_resolution: Optional[str] = None
|
||||
) -> Result:
|
||||
"""
|
||||
Launch a session profile.
|
||||
Orchestrate the Launch of a session profile.
|
||||
|
||||
1) by starting a connnection on a port,
|
||||
2) and then starting the application using that networking port
|
||||
"""
|
||||
|
||||
#-----------------------------------
|
||||
# ASSASSIN MODE
|
||||
#-----------------------------------
|
||||
if profile.assassin:
|
||||
assassin_result = assassin_tools.create(
|
||||
profile=profile,
|
||||
|
|
@ -89,22 +92,39 @@ def enable_session_profile(
|
|||
profile = assassin_result.data
|
||||
# CONCLUSION OF ASSASSIN CODE
|
||||
|
||||
|
||||
#-----------------------------------
|
||||
# APPLICATION PRE-REQ
|
||||
#-----------------------------------
|
||||
application_version = profile.application_version
|
||||
|
||||
if not application_version.is_installed():
|
||||
ApplicationVersionController.install(application_version, application_version_observer=application_version_observer, connection_observer=connection_observer)
|
||||
|
||||
#-----------------------------------
|
||||
# NETWORK CONNECTION
|
||||
#-----------------------------------
|
||||
try:
|
||||
port_number = establish_connection(profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||
except ConnectionError:
|
||||
raise ProfileActivationError('The profile could not be enabled.')
|
||||
except ValueError:
|
||||
raise ProfileActivationError('The profile could not be enabled.')
|
||||
network_result = start_session_networking(profile, ignore=ignore, connection_observer=connection_observer)
|
||||
except EndpointVerificationError:
|
||||
return Result(valid=False, error_type=ResultError.ENDPOINT_VERIFICATION, message=f"Verification of the endpoint failed for profile {profile.id}")
|
||||
|
||||
if profile_observer is not None:
|
||||
profile_observer.notify('enabled', profile)
|
||||
if not network_result.valid:
|
||||
return network_result.wrap("Failed to start the session profile")
|
||||
|
||||
port_number = network_result.data
|
||||
|
||||
#-----------------------------------
|
||||
# LAUNCH APPLICATION & GRAPHICAL
|
||||
#-----------------------------------
|
||||
launched = orchestrate_app_launch(
|
||||
version=application_version,
|
||||
profile=profile,
|
||||
port_number=port_number
|
||||
)
|
||||
if not launched.valid:
|
||||
return launched.wrap("failed to launch the app")
|
||||
|
||||
ApplicationController.launch(application_version, profile, port_number, asynchronous=asynchronous, profile_observer=profile_observer, ticket_observer=ticket_observer, connection_observer=connection_observer)
|
||||
return Result(valid=True, data=profile.type)
|
||||
|
||||
|
||||
|
|
@ -113,7 +133,6 @@ def enable_profile(
|
|||
profile: Union[SessionProfile, SystemProfile],
|
||||
ignore: tuple[type[Exception]] = (),
|
||||
pristine: bool = False,
|
||||
asynchronous: bool = False,
|
||||
profile_observer: ProfileObserver = None,
|
||||
application_version_observer: ApplicationVersionObserver = None,
|
||||
connection_observer: ConnectionObserver = None,
|
||||
|
|
@ -140,7 +159,6 @@ def enable_profile(
|
|||
return enable_session_profile(
|
||||
profile=profile,
|
||||
ignore=ignore,
|
||||
asynchronous=asynchronous,
|
||||
profile_observer=profile_observer,
|
||||
application_version_observer=application_version_observer,
|
||||
connection_observer=connection_observer,
|
||||
|
|
@ -188,6 +206,10 @@ def disable_profile(
|
|||
|
||||
"""Orchestrate disabling a profile."""
|
||||
|
||||
# if profile is None:
|
||||
# burned_down = kill_all_associated_processes(profile_id=profile.id)
|
||||
|
||||
|
||||
if profile.is_session_profile():
|
||||
|
||||
# START ASSASSIN SECTION
|
||||
|
|
@ -204,25 +226,30 @@ def disable_profile(
|
|||
raise ProfileDeactivationError(f'Assassin NOT disabled: {assassin_result.message}')
|
||||
# END ASSASSIN SECTION
|
||||
|
||||
if SessionStateController.exists(profile.id):
|
||||
print("Using SessionStateController to kill the profile..")
|
||||
killed = SessionStateController.kill_session_profile(profile_id=profile.id)
|
||||
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):
|
||||
return killed.wrap("Failed to disable the profile.")
|
||||
else:
|
||||
logger.info("psutil worked to kill it.")
|
||||
|
||||
session_state = SessionStateController.get(profile.id)
|
||||
# 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 session_state is not None:
|
||||
# if profile_observer is not None:
|
||||
# profile_observer.notify('disabled', profile, dict(
|
||||
# explicitly=explicitly,
|
||||
# ))
|
||||
|
||||
for port_number in session_state.network_port_numbers.tor:
|
||||
ConnectionController.terminate_tor_session_connection(port_number)
|
||||
|
||||
# session_state.dissolve(session_state.id)
|
||||
SessionStateController.remove(profile.id)
|
||||
|
||||
if profile_observer is not None:
|
||||
|
||||
profile_observer.notify('disabled', profile, dict(
|
||||
explicitly=explicitly,
|
||||
))
|
||||
notification = "Profile Disconnected."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile.id)
|
||||
notification = "Profile Disconnected."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
||||
# ============================================================================
|
||||
# SYSTEMWIDE
|
||||
|
|
|
|||
Loading…
Reference in a new issue