Compare commits
No commits in common. "f53661fc60c6d1671181967adefbf85cad795089" and "25d69d728c22f8e8cfdca4fbb1b3344e90a3ebd5" have entirely different histories.
f53661fc60
...
25d69d728c
15 changed files with 499 additions and 1023 deletions
|
|
@ -1,66 +0,0 @@
|
|||
from core.utils.singleton_state import singleton, StatePersistenceMixin, wipe_model
|
||||
from core.Constants import Constants
|
||||
from core.errors.logger import logger
|
||||
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from functools import partial
|
||||
|
||||
@singleton
|
||||
@dataclass
|
||||
class ConnectionRecovery(StatePersistenceMixin):
|
||||
PAYLOAD_FIELDS = {"port_changed", "port_changed_to", "port_change_worked", "mtu_tested", "mtu_changed", "wg_key_changed", "location_tested", "location_up"}
|
||||
KEEP_FIELDS = ["parent_folder", "instance_id", "folder_path", "_data_file"]
|
||||
|
||||
# metadata on it's own instance:
|
||||
parent_folder = None
|
||||
instance_id: int = None
|
||||
folder_path: str = None
|
||||
_data_file: str = None
|
||||
|
||||
# actual payload data:
|
||||
|
||||
# LOCATION
|
||||
location_tested: bool = False
|
||||
location_up: bool = False
|
||||
|
||||
# PORT
|
||||
asked_to_change_port: bool = False
|
||||
port_changed: bool = False
|
||||
port_changed_to: int|None = None
|
||||
port_change_worked: bool = False
|
||||
|
||||
# MTU
|
||||
mtu_tested: bool = False
|
||||
mtu_changed: bool = False
|
||||
asked_to_change_mtu: bool = False
|
||||
|
||||
# WG KEY
|
||||
asked_to_change_wg_key: bool = False
|
||||
wg_key_confirmed: bool = False
|
||||
wg_key_changed: bool = False
|
||||
|
||||
# Overall state
|
||||
attempts: int = 0
|
||||
bypass_attempts: bool = False
|
||||
reached_end_of_loop: bool = False
|
||||
|
||||
stashed_partial: partial = None
|
||||
|
||||
def __post_init__(self):
|
||||
# Localized mode: each ID gets its own folder
|
||||
self.parent_folder = Constants.HV_PROFILE_CONFIG_HOME
|
||||
self.folder_path = os.path.join(self.parent_folder, str(self.instance_id))
|
||||
os.makedirs(self.folder_path, exist_ok=True)
|
||||
self._data_file = os.path.join(self.folder_path, "recovery.json")
|
||||
|
||||
logger.info(f"full path of self._data_file {self._data_file}")
|
||||
|
||||
self.load()
|
||||
|
||||
def wipe(self):
|
||||
"""Wipe all data and start over."""
|
||||
wipe_model(model=self, KEEP_FIELDS=self.KEEP_FIELDS)
|
||||
wiped = self.wipe_data_on_disk()
|
||||
logger.info(f"Wiped: {wiped}")
|
||||
|
||||
|
|
@ -57,8 +57,6 @@ class ResultError(Enum):
|
|||
NODE_ERROR = "node_error"
|
||||
NO_INTERNET = "no_internet"
|
||||
PORT = "port"
|
||||
RENEGOTIATION = "renegotiation"
|
||||
ATTEMPTS = "attempts"
|
||||
NAVIGATE_TO = "navigate_to"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
from core.models.ConnectionRecovery import ConnectionRecovery
|
||||
from core.controllers.ConfigurationController import ConfigurationController
|
||||
from core.infrastructure.global_state import ProfileStateRepository
|
||||
from core.utils.get_raw_string import get_string
|
||||
|
|
@ -30,6 +29,8 @@ from functools import partial
|
|||
|
||||
MIN_MTU = 1280
|
||||
|
||||
PORT_CHOICES = [48271, 52428, 51820]
|
||||
|
||||
def register_wireguard_session(
|
||||
profile: Profile,
|
||||
connection_observer: Optional[ConnectionObserver] = None
|
||||
|
|
@ -188,3 +189,112 @@ def expand_newlines(text):
|
|||
"""
|
||||
return "\n\n".join([line for line in text.splitlines() if line.strip()])
|
||||
|
||||
|
||||
def get_port(config: str) -> int:
|
||||
"""Get the wireguard port if you have a config already."""
|
||||
# This regex searches for the "Endpoint" key, ignores optional whitespace around the '=',
|
||||
# skips the IP/hostname part until the colon, and captures the digits following it.
|
||||
match = re.search(r"Endpoint\s*=\s*[^:]+:(\d+)", config, re.IGNORECASE)
|
||||
if match:
|
||||
return int(match.group(1))
|
||||
return None
|
||||
|
||||
def change_port(new_port: int, config: str) -> str:
|
||||
# This regex captures everything from the start of the line up to the colon
|
||||
# in the first group, then matches the existing digits of the port.
|
||||
pattern = r"(Endpoint\s*=\s*[^:]+):(\d+)"
|
||||
|
||||
# We use a lambda function as the replacement to insert the new_port variable
|
||||
# while preserving the captured IP/hostname in group 1 (\1).
|
||||
return re.sub(pattern, lambda m: f"{m.group(1)}:{new_port}", config, flags=re.IGNORECASE)
|
||||
|
||||
|
||||
def get_wg_port(profile: Profile) -> Result:
|
||||
"""Get the Wireguard port with a given profile."""
|
||||
config_path = profile.get_wireguard_configuration_path()
|
||||
if not config_path:
|
||||
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Can't get the path of the config")
|
||||
|
||||
config_data = get_string(config_path)
|
||||
if not config_data:
|
||||
return Result(valid=False, error_type=ResultError.MISSING_DATA, message="Missing the config data, or could not read it.")
|
||||
|
||||
port = get_port(config_data)
|
||||
if port:
|
||||
return Result(valid=True, data=port)
|
||||
else:
|
||||
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Config is not in the correct format to be read.")
|
||||
|
||||
|
||||
def get_random_different_port(current_port: int) -> int|None:
|
||||
"""Get a different port (that's available) from the given choices."""
|
||||
while True:
|
||||
new_port = random.choice(PORT_CHOICES)
|
||||
if str(new_port) != str(current_port):
|
||||
return new_port
|
||||
|
||||
|
||||
def change_wg_port(profile: Profile = None, desired_port: Optional[int] = None) -> Result:
|
||||
"""Change a profile's Wireguard port."""
|
||||
|
||||
logger.info(f"desired_port is {desired_port}")
|
||||
config_path = profile.get_wireguard_configuration_path()
|
||||
config_data = get_string(config_path)
|
||||
current_port = get_port(config_data)
|
||||
logger.info(f"current_port is {current_port}")
|
||||
|
||||
if desired_port and desired_port != current_port and desired_port in PORT_CHOICES:
|
||||
change_to = desired_port
|
||||
else:
|
||||
change_to = get_random_different_port(current_port)
|
||||
logger.info(f"Changing the port to {change_to}")
|
||||
|
||||
new_config = change_port(new_port=change_to, config=config_data)
|
||||
|
||||
# sudo prompts:
|
||||
try:
|
||||
profile.attach_wireguard_configuration(new_config)
|
||||
logger.info("changed the port. updating state..")
|
||||
|
||||
# UPDATE STATE:
|
||||
state_repo = ProfileStateRepository()
|
||||
state_repo.global_state.changed_port = True
|
||||
|
||||
return Result(valid=True, data=change_to)
|
||||
except ProfileModificationError:
|
||||
return Result(valid=False, error_type=ResultError.PERMISSON, message="Failed to swap the port due to permissions")
|
||||
except CommandNotFoundError:
|
||||
return Result(valid=False, error_type=ResultError.MISSING_SOFTWARE, message="Missing the command")
|
||||
|
||||
|
||||
def port_was_changed_already_today() -> bool:
|
||||
state_repo = ProfileStateRepository()
|
||||
return state_repo.global_state.changed_port
|
||||
|
||||
|
||||
def offer_port_change(profile: Profile) -> Result:
|
||||
"""Offer the user the option to change the port"""
|
||||
port_result = get_wg_port(profile)
|
||||
|
||||
if not port_result.valid:
|
||||
return port_result
|
||||
|
||||
current_port = port_result.data
|
||||
desired_port = get_random_different_port(current_port)
|
||||
|
||||
func_choice = partial(change_wg_port, profile=profile, desired_port=desired_port)
|
||||
return Result(valid=False, function_choice=func_choice, error_type=ResultError.PORT, message=f"Failed to connect. Do you want to try to change the port to {desired_port}?")
|
||||
|
||||
|
||||
def should_we_try_to_change_port():
|
||||
"""Returns a boolean if we should change the port"""
|
||||
if not ConfigurationController.do_we_allow_port_prompts():
|
||||
logger.info("We do not allow port changes")
|
||||
return False
|
||||
|
||||
state_repo = ProfileStateRepository()
|
||||
if state_repo.global_state.changed_port:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
|
|
|
|||
|
|
@ -62,18 +62,12 @@ def establish_connection(
|
|||
if profile.connection.code == "wireguard":
|
||||
_ensure_wireguard_configured(profile, connection_observer)
|
||||
|
||||
|
||||
if profile.connection.code == "wireguard" and profile.type == ProfileType.SYSTEM:
|
||||
logger.info("Doing a systemwide WG connection..")
|
||||
return establish_system_connection(profile, ignore, connection_observer, ticket_observer)
|
||||
|
||||
else:
|
||||
establish_fn = {
|
||||
ProfileType.SESSION: ConnectionController.establish_session_connection,
|
||||
ProfileType.SYSTEM: establish_system_connection,
|
||||
}[profile.type]
|
||||
|
||||
return _establish_with_renegotiation(profile, establish_fn, ignore, connection_observer, ticket_observer)
|
||||
establish_fn = {
|
||||
ProfileType.SESSION: ConnectionController.establish_session_connection,
|
||||
ProfileType.SYSTEM: establish_system_connection,
|
||||
}[profile.type]
|
||||
|
||||
return _establish_with_renegotiation(profile, establish_fn, ignore, connection_observer, ticket_observer)
|
||||
|
||||
|
||||
def _ensure_proxy_configured(
|
||||
|
|
|
|||
|
|
@ -1,8 +1,4 @@
|
|||
from core.services.networking.api_requests.subtools.extract_domain import extract_domain
|
||||
|
||||
from core.services.networking.httpx.classify_response import classify_response
|
||||
from core.observers.Notifications import Notifications, EventType
|
||||
from core.utils.run_commands import run_generic_command
|
||||
|
||||
# models
|
||||
from core.models.Result import Result, ResultError
|
||||
|
|
@ -10,9 +6,7 @@ from core.services.networking.api_requests.ApiResponseModel import ApiResponse,
|
|||
|
||||
from core.Constants import Constants
|
||||
from core.errors.logger import logger
|
||||
# from essentials.observers.ConnectionObserver import ConnectionObserver
|
||||
from core.observers.ConnectionObserver import ConnectionObserver
|
||||
|
||||
from essentials.observers.ConnectionObserver import ConnectionObserver
|
||||
|
||||
# generic
|
||||
import time
|
||||
|
|
@ -24,10 +18,6 @@ import httpx_socks
|
|||
from httpx_socks import ProxyType
|
||||
import subprocess
|
||||
from typing import Optional
|
||||
import socket
|
||||
import multiprocessing
|
||||
from threading import Thread
|
||||
from queue import Queue, Empty
|
||||
|
||||
API_ENDPOINT_FORMATS = {
|
||||
f"{Constants.SP_BASE_URL}/v2/get_ip": 'ip',
|
||||
|
|
@ -41,99 +31,64 @@ API_ENDPOINT_FORMATS = {
|
|||
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
def is_dns_problem_worker(url: str, queue: multiprocessing.Queue):
|
||||
"""Checks if DNS is the problem. (It's a Worker function for a separate process)"""
|
||||
domain = extract_domain(url)
|
||||
try:
|
||||
socket.gethostbyname(domain)
|
||||
queue.put((url, False)) # Resolved
|
||||
except Exception:
|
||||
queue.put((url, True)) # Failed
|
||||
|
||||
def test(connection_observer: Optional[ConnectionObserver], port: Optional[int] = None) -> Result:
|
||||
if connection_observer:
|
||||
connection_observer.notify("connecting", "Testing IP..")
|
||||
return asyncio.run(_test(connection_observer, port))
|
||||
|
||||
|
||||
async def _test(connection_observer: Optional[ConnectionObserver], port: Optional[int] = None) -> Result:
|
||||
endpoint_list = list(API_ENDPOINT_FORMATS.keys())[:MAX_ATTEMPTS]
|
||||
start_time = time.time()
|
||||
total_budget = 5.0
|
||||
|
||||
# 1. DNS PRE-FLIGHT (Using Processes, not Threads)
|
||||
if port is None:
|
||||
dns_queue = multiprocessing.Queue()
|
||||
processes = []
|
||||
|
||||
for url in endpoint_list:
|
||||
p = multiprocessing.Process(target=is_dns_problem_worker, args=(url, dns_queue))
|
||||
p.start()
|
||||
processes.append(p)
|
||||
|
||||
any_resolved = False
|
||||
dns_timeout = 3
|
||||
|
||||
try:
|
||||
# Wait for the first successful resolution
|
||||
while time.time() - start_time < dns_timeout:
|
||||
try:
|
||||
# Non-blocking check of the queue
|
||||
url, is_problem = dns_queue.get(timeout=0.1)
|
||||
if not is_problem:
|
||||
any_resolved = True
|
||||
break
|
||||
except Empty:
|
||||
continue
|
||||
finally:
|
||||
# We kill every single process immediately.
|
||||
# The OS kernel wipes them from memory regardless of where they are stuck.
|
||||
for p in processes:
|
||||
p.terminate()
|
||||
p.join() # Clean up the zombie process entry
|
||||
|
||||
if not any_resolved:
|
||||
logger.error("Aggressive DNS check failed: No internet.")
|
||||
return Result(valid=False, error_type=ResultError.CONNECTION, message="No internet connection.")
|
||||
|
||||
# 2. HTTP REQUEST PHASE (Using Daemon Threads)
|
||||
transport = None
|
||||
|
||||
if port:
|
||||
transport = httpx_socks.ProxyTransport(
|
||||
transport = httpx_socks.AsyncProxyTransport(
|
||||
proxy_type=ProxyType.SOCKS5,
|
||||
proxy_host="127.0.0.1",
|
||||
proxy_port=port,
|
||||
)
|
||||
client = httpx.AsyncClient(transport=transport, http2=True, timeout=6)
|
||||
else:
|
||||
client = httpx.AsyncClient(http2=True, timeout=6)
|
||||
|
||||
# We use a Queue to get the first successful Result back from daemon threads
|
||||
result_queue = Queue()
|
||||
|
||||
def attempt_request(url: str, index: int, client: httpx.Client):
|
||||
async def attempt_request(url: str, index: int):
|
||||
logger.info(f"Attempt {index + 1}: Trying {url}")
|
||||
# if connection_observer:
|
||||
# connection_observer.notify("connecting", f"Testing IP. Attempt {index + 1}")
|
||||
|
||||
try:
|
||||
raw_response = client.get(url)
|
||||
raw_response = await client.get(url)
|
||||
filtered_response = classify_response(raw_response)
|
||||
|
||||
if filtered_response.valid:
|
||||
ip_address = extract_ip_from_response(response=filtered_response.data, api_url=url)
|
||||
if ip_address:
|
||||
result_queue.put(Result(valid=True, data=ip_address))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
ip_address = extract_ip_from_response(
|
||||
response=filtered_response.data,
|
||||
api_url=url
|
||||
)
|
||||
if ip_address is not None:
|
||||
return Result(valid=True, data=ip_address)
|
||||
|
||||
logger.error(f"Skipping {url}")
|
||||
except Exception as e:
|
||||
logger.error(f"Skipping {url}. Invalid API reply or failed connection {str(e)}")
|
||||
|
||||
return Result(valid=False)
|
||||
|
||||
with httpx.Client(transport=transport, http2=False, timeout=3.0) as client:
|
||||
for i, url in enumerate(endpoint_list):
|
||||
# daemon=True is CRITICAL.
|
||||
# It tells Python: "If the main program exits, kill this thread immediately."
|
||||
t = Thread(target=attempt_request, args=(url, i, client), daemon=True)
|
||||
t.start()
|
||||
try:
|
||||
# Create tasks for all endpoints to run them concurrently
|
||||
tasks = [asyncio.create_task(attempt_request(url, i)) for i, url in enumerate(endpoint_list)]
|
||||
|
||||
# Process tasks as they complete
|
||||
for future in asyncio.as_completed(tasks):
|
||||
result = await future
|
||||
if result.valid:
|
||||
# Cancel all other pending tasks immediately
|
||||
for t in tasks:
|
||||
if not t.done():
|
||||
t.cancel()
|
||||
return result
|
||||
|
||||
# Wait for the first success or the remaining budget
|
||||
while True:
|
||||
elapsed = time.time() - start_time
|
||||
remaining = total_budget - elapsed
|
||||
if remaining <= 0:
|
||||
break
|
||||
|
||||
try:
|
||||
# Block for the remaining budget
|
||||
return result_queue.get(timeout=remaining)
|
||||
except Empty:
|
||||
break
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
logger.error(f"We went through {len(endpoint_list)} attempts and could not get a reply.")
|
||||
return Result(valid=False, error_type=ResultError.CONNECTION, message="Could not connect.")
|
||||
|
|
@ -167,16 +122,13 @@ def extract_ip_from_response(response: dict, api_url: str) -> str | bool:
|
|||
|
||||
|
||||
def ping_ip(ip: str) -> Result:
|
||||
"""Ping an IP using the pre-existing terminal"""
|
||||
command = ["ping", "-c", "1", "-W", "2", ip]
|
||||
human_readable_goal = f"Pinging {ip}"
|
||||
Notifications.emit(EventType.STATUS_UPDATE, human_readable_goal)
|
||||
return run_generic_command(command, human_readable_goal, timeout=5)
|
||||
|
||||
|
||||
|
||||
def ping_ip_worked(ip: str) -> bool:
|
||||
"""Test ping in a new subprocess"""
|
||||
try:
|
||||
# -c 1: send only 1 packet
|
||||
# -W 2: wait 2 seconds for a response
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
from core.services.networking.api_requests.ApiResponseModel import BackoffStrategy
|
||||
from core.services.networking.general_connection_tools.test_internet import test_internet
|
||||
from core.services.networking.general_connection_tools.ip import ping_ip
|
||||
from core.services.networking.general_connection_tools.ip import ping_ip_worked
|
||||
from core.services.networking.systemwide.general_tools.test_any_protocol import get_singbox_ip
|
||||
from core.services.networking.general_connection_tools.config_tools import extract_endpoint_ip
|
||||
from core.models.manage.server_reply_tools import api_call_and_extraction, ApiCall
|
||||
|
|
@ -47,8 +47,7 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs
|
|||
ip_address = get_profile_ip(profile_id=profile_id, protocol=protocol, profile_type=profile_type)
|
||||
|
||||
if ip_address:
|
||||
ping_result = ping_ip(ip_address)
|
||||
can_be_pinged = ping_result.valid
|
||||
can_be_pinged = ping_ip_worked(ip_address)
|
||||
print(f"Can {location_name} be pinged? {can_be_pinged}")
|
||||
else:
|
||||
logger.error("Skipping IP Address Test.")
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
from core.utils.run_commands import run_generic_command
|
||||
|
||||
from core.Constants import Constants
|
||||
from core.Errors import CommandNotFoundError
|
||||
from core.observers.ConnectionObserver import ConnectionObserver
|
||||
|
|
@ -39,33 +37,15 @@ def await_network_interface():
|
|||
raise ConnectionError('The network interface could not be activated.')
|
||||
|
||||
|
||||
|
||||
def system_uses_wireguard_interface():
|
||||
|
||||
if shutil.which('ip') is None:
|
||||
raise CommandNotFoundError('ip')
|
||||
|
||||
command = ['ip', 'route', 'get', '192.0.2.1']
|
||||
human_readable_goal = "Getting WG interface"
|
||||
get_output = run_generic_command(command, human_readable_goal, timeout=8)
|
||||
if not get_output.valid:
|
||||
return get_output
|
||||
process = subprocess.Popen(('ip', 'route', 'get', '192.0.2.1'), stdout=subprocess.PIPE)
|
||||
process_output = str(process.stdout.read())
|
||||
|
||||
output = get_output.data
|
||||
print(f"output is {output}")
|
||||
return bool(re.search('dev wg', str(output)))
|
||||
|
||||
|
||||
|
||||
# def system_uses_wireguard_interface():
|
||||
|
||||
# if shutil.which('ip') is None:
|
||||
# raise CommandNotFoundError('ip')
|
||||
|
||||
# process = subprocess.Popen(('ip', 'route', 'get', '192.0.2.1'), stdout=subprocess.PIPE)
|
||||
# process_output = str(process.stdout.read())
|
||||
|
||||
# return bool(re.search('dev wg', str(process_output)))
|
||||
return bool(re.search('dev wg', str(process_output)))
|
||||
|
||||
|
||||
def __test_connection(port_number: Optional[int] = None, timeout: float = 4.0):
|
||||
|
|
|
|||
|
|
@ -1,72 +0,0 @@
|
|||
from core.models.ConnectionRecovery import ConnectionRecovery
|
||||
from core.services.keys_and_verifications.wireguard_keys import get_mtu, insert_mtu_into_config_on_disk
|
||||
from core.services.networking.mtu.mtu_tools import loop_through_testing_mtu, mtu_is_fine, MIN_MTU, MAX_MTU
|
||||
from core.observers.Notifications import Notifications, EventType
|
||||
from core.models.BaseProfile import BaseProfile as Profile
|
||||
from core.models.system.SystemProfile import SystemProfile
|
||||
from core.errors.logger import logger
|
||||
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
|
||||
def _changed_mtu(profile: SystemProfile, current_mtu: Optional[int]) -> bool:
|
||||
notification = "Testing MTU.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
||||
# optimal_mtu = loop_through_testing_mtu()
|
||||
optimal_mtu = asyncio.run(loop_through_testing_mtu())
|
||||
logger.info(f"Optimal MTU is {optimal_mtu}")
|
||||
|
||||
if optimal_mtu == current_mtu:
|
||||
return False
|
||||
|
||||
# Assuming it isn't already at the max, there's no need to reset it to the max,
|
||||
if current_mtu != MAX_MTU and optimal_mtu == MAX_MTU:
|
||||
return False
|
||||
|
||||
notification = f"Updating WG MTU with {optimal_mtu}"
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
return insert_mtu_into_config_on_disk(profile=profile, mtu=optimal_mtu)
|
||||
|
||||
def should_we_even_test_mtu(profile_id: int, recovery_stats: ConnectionRecovery) -> bool:
|
||||
if recovery_stats.mtu_tested:
|
||||
return False
|
||||
|
||||
# Evaluate MTU WITH connection on
|
||||
current_mtu = get_mtu(profile_id=profile_id)
|
||||
|
||||
if not current_mtu:
|
||||
return True, current_mtu
|
||||
|
||||
if current_mtu > MIN_MTU:
|
||||
logger.info("Skipping MTU testing, because MTU as at the minimum, so it's not relevant here.")
|
||||
return False, current_mtu
|
||||
else:
|
||||
logger.info("MTU isn't at the min, so we can potentially improve")
|
||||
return True, current_mtu
|
||||
|
||||
def was_mtu_changed(profile: Profile, current_mtu: int, recovery_stats: ConnectionRecovery) -> bool:
|
||||
notification = "Testing MTU..."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
|
||||
if mtu_is_fine(current_mtu):
|
||||
notification = "MTU is NOT the issue."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
|
||||
# MTU wasn't changed or wasn't applicable,
|
||||
return False
|
||||
|
||||
if _changed_mtu(profile=profile, current_mtu=current_mtu):
|
||||
logger.info("MTU changed. We should retry the connection")
|
||||
recovery_stats.mtu_changed = True
|
||||
recovery_stats.save()
|
||||
return True
|
||||
|
||||
else:
|
||||
logger.warning("MTU check performed but no change was made or user rejected it.")
|
||||
notification = "MTU was NOT changed."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
return False
|
||||
|
||||
|
|
@ -1,149 +0,0 @@
|
|||
from core.models.ConnectionRecovery import ConnectionRecovery
|
||||
from core.infrastructure.global_state import ProfileStateRepository
|
||||
from core.controllers.ConfigurationController import ConfigurationController
|
||||
from core.utils.get_raw_string import get_string
|
||||
from core.Errors import ProfileModificationError, CommandNotFoundError
|
||||
from core.models.BaseProfile import BaseProfile as Profile
|
||||
from core.models.Result import Result, ResultError
|
||||
from core.errors.logger import logger
|
||||
|
||||
import re
|
||||
import random
|
||||
# from functools import partial
|
||||
from typing import Optional
|
||||
|
||||
PORT_CHOICES = [48271, 52428, 51820]
|
||||
|
||||
|
||||
def get_port(config: str) -> int:
|
||||
"""Get the wireguard port if you have a config already."""
|
||||
# This regex searches for the "Endpoint" key, ignores optional whitespace around the '=',
|
||||
# skips the IP/hostname part until the colon, and captures the digits following it.
|
||||
match = re.search(r"Endpoint\s*=\s*[^:]+:(\d+)", config, re.IGNORECASE)
|
||||
if match:
|
||||
return int(match.group(1))
|
||||
return None
|
||||
|
||||
def change_port(new_port: int, config: str) -> str:
|
||||
# This regex captures everything from the start of the line up to the colon
|
||||
# in the first group, then matches the existing digits of the port.
|
||||
pattern = r"(Endpoint\s*=\s*[^:]+):(\d+)"
|
||||
|
||||
# We use a lambda function as the replacement to insert the new_port variable
|
||||
# while preserving the captured IP/hostname in group 1 (\1).
|
||||
return re.sub(pattern, lambda m: f"{m.group(1)}:{new_port}", config, flags=re.IGNORECASE)
|
||||
|
||||
|
||||
def get_wg_port(profile: Profile) -> Result:
|
||||
"""Get the Wireguard port with a given profile."""
|
||||
config_path = profile.get_wireguard_configuration_path()
|
||||
if not config_path:
|
||||
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Can't get the path of the config")
|
||||
|
||||
config_data = get_string(config_path)
|
||||
if not config_data:
|
||||
return Result(valid=False, error_type=ResultError.MISSING_DATA, message="Missing the config data, or could not read it.")
|
||||
|
||||
port = get_port(config_data)
|
||||
if port:
|
||||
return Result(valid=True, data=port)
|
||||
else:
|
||||
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Config is not in the correct format to be read.")
|
||||
|
||||
|
||||
def get_random_different_port(current_port: int) -> int|None:
|
||||
"""Get a different port (that's available) from the given choices."""
|
||||
while True:
|
||||
new_port = random.choice(PORT_CHOICES)
|
||||
if str(new_port) != str(current_port):
|
||||
return new_port
|
||||
|
||||
|
||||
def change_wg_port(profile: Profile, desired_port: Optional[int] = None) -> Result:
|
||||
"""Change a profile's Wireguard port."""
|
||||
|
||||
logger.info(f"Starting to change the port for profile {profile.id}")
|
||||
|
||||
# pre-existing data:
|
||||
recovery_stats = ConnectionRecovery()
|
||||
|
||||
# get config path:
|
||||
config_path = profile.get_wireguard_configuration_path()
|
||||
|
||||
# get config data:
|
||||
config_data = get_string(config_path)
|
||||
|
||||
# assess current port on that data:
|
||||
current_port = get_port(config_data)
|
||||
logger.info(f"current_port is {current_port}")
|
||||
|
||||
# changing to what?
|
||||
if not desired_port:
|
||||
desired_port = recovery_stats.port_changed_to
|
||||
else:
|
||||
desired_port = get_random_different_port(current_port)
|
||||
|
||||
# sanity filter:
|
||||
if desired_port == current_port or desired_port not in PORT_CHOICES:
|
||||
desired_port = get_random_different_port(current_port)
|
||||
|
||||
logger.info(f"Changing the port to {desired_port}")
|
||||
new_config = change_port(new_port=desired_port, config=config_data)
|
||||
|
||||
# sudo prompts:
|
||||
try:
|
||||
profile.attach_wireguard_configuration(new_config)
|
||||
logger.info("changed the port. updating state..")
|
||||
|
||||
# UPDATE STATE:
|
||||
recovery_stats.port_changed = True
|
||||
recovery_stats.save()
|
||||
|
||||
state_repo = ProfileStateRepository()
|
||||
state_repo.global_state.changed_port = True
|
||||
|
||||
return Result(valid=True, data=desired_port)
|
||||
except ProfileModificationError:
|
||||
return Result(valid=False, error_type=ResultError.PERMISSION, message="Failed to swap the port due to permissions")
|
||||
except CommandNotFoundError:
|
||||
return Result(valid=False, error_type=ResultError.MISSING_SOFTWARE, message="Missing the command")
|
||||
|
||||
|
||||
def port_was_changed_already_today() -> bool:
|
||||
state_repo = ProfileStateRepository()
|
||||
return state_repo.global_state.changed_port
|
||||
|
||||
|
||||
def should_we_try_to_change_port(recovery_stats: ConnectionRecovery):
|
||||
"""Returns a boolean if we should change the port"""
|
||||
|
||||
# already changed:
|
||||
if recovery_stats.port_changed or recovery_stats.asked_to_change_port:
|
||||
return False
|
||||
|
||||
if not ConfigurationController.do_we_allow_port_prompts():
|
||||
logger.info("We do not allow port changes")
|
||||
return False
|
||||
|
||||
state_repo = ProfileStateRepository()
|
||||
if state_repo.global_state.changed_port:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
# def offer_port_change(profile: Profile, recovery_stats: ConnectionRecovery) -> Result:
|
||||
# """Offer the user the option to change the port"""
|
||||
# port_result = get_wg_port(profile)
|
||||
|
||||
# if not port_result.valid:
|
||||
# return port_result
|
||||
|
||||
# current_port = port_result.data
|
||||
# desired_port = get_random_different_port(current_port)
|
||||
# recovery_stats.port_changed_to = desired_port
|
||||
# recovery_stats.save()
|
||||
|
||||
# # func_choice = partial(change_wg_port, profile=profile, desired_port=desired_port)
|
||||
# return Result(valid=False, error_type=ResultError.PORT, message=f"Failed to connect. Do you want to try to change the port to {desired_port}?")
|
||||
|
||||
|
|
@ -1,9 +1,5 @@
|
|||
from core.models.ConnectionRecovery import ConnectionRecovery
|
||||
from core.services.keys_and_verifications.wireguard_keys import register_wireguard_session
|
||||
from core.services.networking.ports.port_orchestrator import get_wg_port, should_we_try_to_change_port, get_random_different_port, change_wg_port
|
||||
from core.services.networking.mtu.mtu_orchestrator import should_we_even_test_mtu, was_mtu_changed
|
||||
from core.models.BaseProfile import BaseProfile as Profile
|
||||
|
||||
from core.services.keys_and_verifications.wireguard_keys import get_mtu, insert_mtu_into_config_on_disk, offer_port_change, should_we_try_to_change_port, port_was_changed_already_today
|
||||
from core.services.networking.systemwide.wireguard.mtu_tools import loop_through_testing_mtu, mtu_is_fine, MIN_MTU, MAX_MTU
|
||||
from core.services.networking.general_connection_tools.location_evaluation import check_if_location_is_up
|
||||
from core.services.networking.api_requests.ApiResponseModel import BackoffStrategy
|
||||
from core.models.enum_models import ProtocolChoice, SINGBOX_PROTOCOLS
|
||||
|
|
@ -27,7 +23,7 @@ from core.utils.run_commands import run_generic_command
|
|||
from core.observers.TicketObserver import TicketObserver
|
||||
|
||||
# from core.Constants import Constants
|
||||
from core.Errors import CommandNotFoundError # ConnectionTerminationError
|
||||
from core.Errors import ConnectionTerminationError, CommandNotFoundError
|
||||
from core.controllers.ConfigurationController import ConfigurationController
|
||||
from core.controllers.SystemStateController import SystemStateController
|
||||
# from core.models.BaseProfile import ProfileType
|
||||
|
|
@ -35,22 +31,19 @@ from core.controllers.SystemStateController import SystemStateController
|
|||
from core.models.system.SystemProfile import SystemProfile
|
||||
from core.models.system.SystemState import SystemState
|
||||
from core.observers.ConnectionObserver import ConnectionObserver
|
||||
# from subprocess import CalledProcessError
|
||||
from subprocess import CalledProcessError
|
||||
from typing import Optional
|
||||
# import os
|
||||
# import re
|
||||
import shutil
|
||||
# import subprocess
|
||||
import time
|
||||
# import asyncio
|
||||
from functools import partial
|
||||
|
||||
MAX_ATTEMPTS = 4
|
||||
import asyncio
|
||||
|
||||
def terminate_system_connection(
|
||||
firewall_setting: Optional[bool] = None,
|
||||
dns_setting: Optional[bool] = None
|
||||
) -> Result:
|
||||
):
|
||||
|
||||
# ====== PREREQS =======
|
||||
if firewall_setting is None:
|
||||
|
|
@ -70,168 +63,44 @@ def terminate_system_connection(
|
|||
if dns_setting:
|
||||
_ = revert_dns()
|
||||
|
||||
# ====== SINGBOX =======
|
||||
# Check if the user is switching from Singbox to Wireguard:
|
||||
# ====== NMCLI =======
|
||||
if SystemStateController.exists():
|
||||
|
||||
# ====== SINGBOX =======
|
||||
# Check if the user is switching from Singbox to Wireguard:
|
||||
current_state = SystemState.get()
|
||||
if current_state:
|
||||
if get_protocol_enum(current_state.profile_id) in SINGBOX_PROTOCOLS:
|
||||
logger.info("Ending Singbox protocols first..")
|
||||
from core.services.networking.systemwide.encrypted_proxy.singbox_runner import end_singbox
|
||||
return end_singbox()
|
||||
if get_protocol_enum(current_state.profile_id) in SINGBOX_PROTOCOLS:
|
||||
logger.info("Ending Singbox protocols first..")
|
||||
from core.services.networking.systemwide.encrypted_proxy.singbox_runner import end_singbox
|
||||
return end_singbox()
|
||||
|
||||
# ====== FINISH WIREGUARD =======
|
||||
command = ['nmcli', 'connection', 'delete', 'wg']
|
||||
human_readable_goal = "Deleting NMCLI wg interface"
|
||||
delete_completed = run_generic_command(command, human_readable_goal, timeout=8)
|
||||
print(f"delete_completed output: {delete_completed}")
|
||||
# ====== FINISH WIREGUARD =======
|
||||
command = ['nmcli', 'connection', 'delete', 'wg']
|
||||
human_readable_goal = "Deleting NMCLI wg interface"
|
||||
delete_completed = run_generic_command(command, human_readable_goal, timeout=8)
|
||||
|
||||
if not system_uses_wireguard_interface():
|
||||
command = ['nmcli', 'connection', 'delete', 'hv-ipv6-sink']
|
||||
human_readable_goal = "Deleting NMCLI IPv6 Sink"
|
||||
sinkhole_deleted = run_generic_command(command, human_readable_goal, timeout=8)
|
||||
if not sinkhole_deleted.valid:
|
||||
logger.error(f"IPv6 Sinkhole Delete Error: {sinkhole_deleted.error_type} {sinkhole_deleted.message}")
|
||||
if delete_completed.valid or not system_uses_wireguard_interface():
|
||||
command = ['nmcli', 'connection', 'delete', 'hv-ipv6-sink']
|
||||
human_readable_goal = "Deleting NMCLI IPv6 Sink"
|
||||
sinkhole_deleted = run_generic_command(command, human_readable_goal, timeout=8)
|
||||
if not sinkhole_deleted.valid:
|
||||
logger.error(f"IPv6 Sinkhole Delete Error: {sinkhole_deleted.error_type} {sinkhole_deleted.message}")
|
||||
|
||||
terminate_tor_connection()
|
||||
terminate_tor_connection()
|
||||
|
||||
# confirm firewall is off.
|
||||
if firewall_setting:
|
||||
check_and_kill_firewall() # on failure, this raises errors, which then bubble up
|
||||
# else:
|
||||
# error_log = f"Error with deleting the connection: {delete_completed.error_type} {delete_completed.message}"
|
||||
# logger.error(error_log)
|
||||
# raise ConnectionTerminationError(f'The connection could not be terminated. {error_log}')
|
||||
# confirm firewall is off.
|
||||
if firewall_setting:
|
||||
check_and_kill_firewall() # on failure, this raises errors, which then bubble up
|
||||
|
||||
# finally end that profile's JSON state:
|
||||
if SystemStateController.exists():
|
||||
SystemState.dissolve()
|
||||
return Result(valid=True)
|
||||
# finally end that profile's JSON state:
|
||||
SystemState.dissolve()
|
||||
|
||||
else:
|
||||
error_log = f"Error with deleting the connection: {delete_completed.error_type} {delete_completed.message}"
|
||||
logger.error(error_log)
|
||||
raise ConnectionTerminationError(f'The connection could not be terminated. {error_log}')
|
||||
|
||||
|
||||
def renegotiate_and_reconnect(
|
||||
profile: SystemProfile,
|
||||
ignore: tuple[type[Exception]] = (),
|
||||
connection_observer: Optional[ConnectionObserver] = None,
|
||||
ticket_observer: Optional[TicketObserver] = None
|
||||
) -> Result:
|
||||
"""Register a new wireguard session with a new key, and connect."""
|
||||
|
||||
notification = "Renegotating WG Key.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
|
||||
register_wireguard_session(profile=profile, connection_observer=connection_observer)
|
||||
logger.info("Registered new session")
|
||||
|
||||
recovery_stats = ConnectionRecovery()
|
||||
recovery_stats.wg_key_changed = True
|
||||
|
||||
notification = "Reconnecting with new WG Key.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
|
||||
return establish_system_connection(
|
||||
profile=profile,
|
||||
ignore=ignore,
|
||||
connection_observer=connection_observer,
|
||||
ticket_observer=ticket_observer
|
||||
)
|
||||
|
||||
|
||||
def wipe_attempts(
|
||||
recovery_stats: ConnectionRecovery,
|
||||
profile: SystemProfile,
|
||||
ignore: tuple[type[Exception]] = (),
|
||||
connection_observer: Optional[ConnectionObserver] = None,
|
||||
ticket_observer: Optional[TicketObserver] = None
|
||||
)-> Result:
|
||||
"""Wipe pre-existing recovery attempts and solutions. And begin fresh."""
|
||||
recovery_stats.wipe()
|
||||
|
||||
notification = "Starting Recovery Fresh"
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
|
||||
return establish_system_connection(
|
||||
profile=profile,
|
||||
ignore=ignore,
|
||||
connection_observer=connection_observer,
|
||||
ticket_observer=ticket_observer
|
||||
)
|
||||
|
||||
|
||||
def bypass_existing_attempts(
|
||||
recovery_stats: ConnectionRecovery,
|
||||
profile: SystemProfile,
|
||||
ignore: tuple[type[Exception]] = (),
|
||||
connection_observer: Optional[ConnectionObserver] = None,
|
||||
ticket_observer: Optional[TicketObserver] = None
|
||||
)-> Result:
|
||||
"""Stop prompting the user for solutions (ports, mtu, wg-renegotiation)"""
|
||||
|
||||
notification = "Skipping Recovery Strategies"
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
|
||||
recovery_stats.bypass_attempts = True
|
||||
recovery_stats.reached_end_of_loop = False
|
||||
recovery_stats.save()
|
||||
|
||||
return establish_system_connection(
|
||||
profile=profile,
|
||||
ignore=ignore,
|
||||
connection_observer=connection_observer,
|
||||
ticket_observer=ticket_observer
|
||||
)
|
||||
|
||||
|
||||
def change_port_then_reconnect(
|
||||
profile: SystemProfile,
|
||||
ignore: tuple[type[Exception]] = (),
|
||||
connection_observer: Optional[ConnectionObserver] = None,
|
||||
ticket_observer: Optional[TicketObserver] = None
|
||||
) -> Result:
|
||||
|
||||
notification = "Changing the port.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
|
||||
changed = change_wg_port(profile)
|
||||
|
||||
if not changed.valid:
|
||||
return changed
|
||||
|
||||
notification = "Reconnecting with New Port.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
|
||||
return establish_system_connection(
|
||||
profile=profile,
|
||||
ignore=ignore,
|
||||
connection_observer=connection_observer,
|
||||
ticket_observer=ticket_observer
|
||||
)
|
||||
|
||||
def get_port_change_message(profile: Profile, recovery_stats: ConnectionRecovery) -> str:
|
||||
"""Offer the user the option to change the port"""
|
||||
port_result = get_wg_port(profile)
|
||||
|
||||
if not port_result.valid:
|
||||
return port_result
|
||||
|
||||
current_port = port_result.data
|
||||
desired_port = get_random_different_port(current_port)
|
||||
recovery_stats.port_changed_to = desired_port
|
||||
recovery_stats.asked_to_change_port = True
|
||||
recovery_stats.save()
|
||||
|
||||
notification = "Change Port?"
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
||||
message = f"Failed to connect. Do you want to try to change the port to {desired_port}?"
|
||||
return message
|
||||
|
||||
|
||||
def evaluate_location_and_internet(profile: SystemProfile, connection_observer: ConnectionObserver) -> Result:
|
||||
"""Checks if location is up and returns the backoff strategy."""
|
||||
|
|
@ -246,37 +115,57 @@ def evaluate_location_and_internet(profile: SystemProfile, connection_observer:
|
|||
|
||||
return location_result
|
||||
|
||||
def _cleanup_on_error(firewall_setting: bool, dns_setting: bool) -> None:
|
||||
"""Safely terminate connection on error, swallowing cleanup errors."""
|
||||
try:
|
||||
terminate_system_connection(firewall_setting, dns_setting)
|
||||
except ConnectionTerminationError:
|
||||
pass
|
||||
|
||||
|
||||
def _finish_success(final_result: Result, profile_id: int) -> Result:
|
||||
Notifications.emit(EventType.SYSTEM_ENABLE, profile_id)
|
||||
notification = "Connected."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
||||
terminate_tor_connection()
|
||||
time.sleep(0.3)
|
||||
return final_result
|
||||
|
||||
|
||||
def _conclude_loop_failure():
|
||||
"""Finish the loop with a generic error message"""
|
||||
|
||||
logger.info("Saving the loop has concluded.")
|
||||
recovery_stats = ConnectionRecovery()
|
||||
recovery_stats.reached_end_of_loop = True
|
||||
recovery_stats.save()
|
||||
|
||||
notification = "Connection failed"
|
||||
def changed_mtu(profile: SystemProfile, current_mtu: Optional[int]) -> bool:
|
||||
notification = "Testing MTU.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
error_msg = "Connection failed, but the location is up. We recommend you try a different protocol."
|
||||
return Result(valid=False, error_type=ResultError.UNKNOWN, message=error_msg)
|
||||
|
||||
# optimal_mtu = loop_through_testing_mtu()
|
||||
optimal_mtu = asyncio.run(loop_through_testing_mtu())
|
||||
logger.info(f"Optimal MTU is {optimal_mtu}")
|
||||
|
||||
if optimal_mtu == current_mtu:
|
||||
return False
|
||||
|
||||
# Assuming it isn't already at the max, there's no need to reset it to the max,
|
||||
if current_mtu != MAX_MTU and optimal_mtu == MAX_MTU:
|
||||
return False
|
||||
|
||||
notification = f"Updating WG MTU with {optimal_mtu}"
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
return insert_mtu_into_config_on_disk(profile=profile, mtu=optimal_mtu)
|
||||
|
||||
|
||||
|
||||
def __establish_system_connection(
|
||||
profile: SystemProfile,
|
||||
firewall_setting: bool = False,
|
||||
dns_setting: bool = False,
|
||||
connection_observer: Optional[ConnectionObserver] = None) -> Result:
|
||||
connection_observer: Optional[ConnectionObserver] = None):
|
||||
"""
|
||||
Purpose:
|
||||
Orchestrates the full flow of the connection.
|
||||
|
||||
Steps:
|
||||
1) Check Prereqs
|
||||
2) Disable any pre-existing system connections
|
||||
3) Turn on WG via nmcli
|
||||
4) Turn on IPv6 sinkhole
|
||||
5) Setup State (JSON file)
|
||||
|
|
@ -284,10 +173,17 @@ def __establish_system_connection(
|
|||
7) Set DNS (if enabled), and test it. Let's it slide even if failed.
|
||||
8) Testing, confirming, displaying to the end user.
|
||||
"""
|
||||
check_system_prereqs()
|
||||
notification = "Terming existing connections.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
terminate_system_connection(firewall_setting, dns_setting)
|
||||
|
||||
# ============= INITIAL NMCLI CONNECTION =============
|
||||
notification = "Setting Up WireGuard.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
||||
# if connection_observer:
|
||||
# connection_observer.notify("connecting", notification)
|
||||
wg_config_path = profile.get_wireguard_configuration_path()
|
||||
nmcli_result = setup_nmcli_connection(wg_config_path)
|
||||
|
||||
|
|
@ -308,6 +204,17 @@ def __establish_system_connection(
|
|||
if not sinkhole_result:
|
||||
raise ConnectionError('IPv6 Could not be protected.')
|
||||
|
||||
# ============= SETUP STATE =============
|
||||
# Even if firewall is off, we want to save the fact we turned on the VPN tunnel, before we raise errors.
|
||||
|
||||
logger.info("Setting State JSON..")
|
||||
current_state = SystemStateController.create(
|
||||
profile_id=profile.id,
|
||||
firewalled=firewall_setting, # intended setting, not result yet
|
||||
dns_set=dns_setting, # intended setting, not result yet,
|
||||
protocol=ProtocolChoice.WIREGUARD
|
||||
)
|
||||
|
||||
# ============= PREP SETTINGS =============
|
||||
if connection_observer:
|
||||
connection_observer.notify("connecting", "Getting Interface Name..")
|
||||
|
|
@ -353,6 +260,8 @@ def __establish_system_connection(
|
|||
|
||||
# ============= TESTING =============
|
||||
logger.info("If we made it this far, we have nmcli on, ipv6 sinkhole on, firewall on.")
|
||||
# if connection_observer:
|
||||
# connection_observer.notify("connecting", "Testing Connection Health..")
|
||||
|
||||
notification = "Testing IP address.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
|
@ -364,17 +273,16 @@ def __establish_system_connection(
|
|||
if not test_result.valid:
|
||||
notification = "Test Failed."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.error("Returning that the test failed..")
|
||||
return test_result
|
||||
|
||||
# ============= SETUP STATE =============
|
||||
logger.info("Setting State JSON..")
|
||||
current_state = SystemStateController.create(
|
||||
profile_id=profile.id,
|
||||
firewalled=firewall_setting,
|
||||
dns_set=did_dns_work,
|
||||
protocol=ProtocolChoice.WIREGUARD
|
||||
)
|
||||
# ============= UPDATE STATE =============
|
||||
if dns_setting and not did_dns_work:
|
||||
current_state.firewalled = firewall_tracker
|
||||
current_state.dns_set = did_dns_work
|
||||
SystemStateController.update_or_create(current_state)
|
||||
notification = "DNS Set Did Not Work."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
||||
return Result(valid=True, data=current_state)
|
||||
|
||||
|
||||
|
|
@ -385,17 +293,14 @@ def establish_system_connection(
|
|||
ticket_observer: Optional[TicketObserver] = None # Passed in only for assassin's link to tickets in ConnectionController.establish_session_connection
|
||||
) -> Result|None:
|
||||
"""
|
||||
Establish connection.
|
||||
Establish connection with a maximum of 2 retries.
|
||||
|
||||
Steps)
|
||||
1) Check Prereqs
|
||||
2) Verify Endpoint's encryption
|
||||
3) get settings
|
||||
4) Disable any pre-existing system connections
|
||||
1) Verify Endpoint's encryption
|
||||
2) get settings
|
||||
3) Attempt 1 -> (Fail) -> Location Check
|
||||
4) Attempt 2 -> (Fail) -> MTU Check -> Attempt 3
|
||||
"""
|
||||
# ================= PRE-REQS =================
|
||||
check_system_prereqs()
|
||||
|
||||
# ================= VERIFY ENDPOINT =================
|
||||
if connection_observer:
|
||||
connection_observer.notify("connecting", "Verifying endpoint..")
|
||||
|
|
@ -405,145 +310,113 @@ def establish_system_connection(
|
|||
# ================= SETTINGS =================
|
||||
firewall_setting = ConfigurationController.get_firewall_setting()
|
||||
dns_setting = ConfigurationController.get_dns_setting()
|
||||
recovery_stats = ConnectionRecovery(instance_id=profile.id)
|
||||
|
||||
if recovery_stats.reached_end_of_loop:
|
||||
error_msg = "Your previous attempt to enable this profile failed. Do you want to start fresh with your recovery strategies (recommended. if the connection fails then it will check & reask about port, renegotation, and mtu)"
|
||||
yes_choice = partial(wipe_attempts, recovery_stats=recovery_stats, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||
no_option = partial(bypass_existing_attempts, recovery_stats=recovery_stats, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||
return Result(valid=False, function_choice=yes_choice, no_option=no_option, error_type=ResultError.ATTEMPTS, message=error_msg)
|
||||
|
||||
# ================= CONNECT WG ================
|
||||
while not recovery_stats.reached_end_of_loop:
|
||||
recovery_stats.attempts += 1
|
||||
current_try = recovery_stats.attempts
|
||||
# We allow 3 total attempts (Initial + 2 retries)
|
||||
for attempt in range(1, 4):
|
||||
try:
|
||||
# if connection_observer:
|
||||
# connection_observer.notify("connecting", f"Connecting attempt {attempt} of 3.. ")
|
||||
|
||||
# =================================
|
||||
# PRE-EXISTING
|
||||
# =================================
|
||||
logger.info("Terminating pre-existing")
|
||||
terminated = terminate_system_connection(firewall_setting, dns_setting)
|
||||
if terminated.valid:
|
||||
logger.info("Terminated pre-existing")
|
||||
else:
|
||||
logger.error(f"Failed to terminate pre-existing {terminated.message}")
|
||||
return terminated
|
||||
notification = f"Connecting attempt {attempt} of 3.. "
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
||||
notification = f"Connecting attempt {current_try}.. "
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
||||
# =================================
|
||||
# CONNECT
|
||||
# =================================
|
||||
# Attempt the actual system connection
|
||||
connection_result = __establish_system_connection(
|
||||
profile=profile,
|
||||
firewall_setting=firewall_setting,
|
||||
dns_setting=dns_setting,
|
||||
connection_observer=connection_observer
|
||||
)
|
||||
|
||||
# =================================
|
||||
# EVALUATE
|
||||
# =================================
|
||||
if connection_result.valid:
|
||||
recovery_stats.wipe()
|
||||
return _finish_success(final_result=connection_result, profile_id=profile.id)
|
||||
|
||||
# =================================
|
||||
# ATTEMPT ONE: LOCATION UP?
|
||||
# =================================
|
||||
if current_try == 1 and not recovery_stats.location_tested:
|
||||
# First failure: Evaluate Location and Internet without connection,
|
||||
logger.info("Terminating system connection to check location")
|
||||
terminate_system_connection(firewall_setting, dns_setting)
|
||||
|
||||
location_result = evaluate_location_and_internet(
|
||||
profile=profile,
|
||||
# Attempt the actual system connection
|
||||
connection_result = __establish_system_connection(
|
||||
profile=profile,
|
||||
firewall_setting=firewall_setting,
|
||||
dns_setting=dns_setting,
|
||||
connection_observer=connection_observer
|
||||
)
|
||||
recovery_stats.location_tested = True
|
||||
|
||||
#============== NO RETRY #==============
|
||||
if location_result.backoff_strategy == BackoffStrategy.NO_RETRY:
|
||||
recovery_stats.location_up = False
|
||||
logger.error(f"Location check failed: {location_result.message}")
|
||||
bottom_left = "Node Down"
|
||||
Notifications.emit(EventType.STATUS_UPDATE, bottom_left)
|
||||
notification = location_result.message
|
||||
Notifications.emit(EventType.SHOW_POPUP, notification)
|
||||
return location_result
|
||||
|
||||
#============== NO SEEMS FINE #==============
|
||||
notification = "Location check passed. Retrying immediately..."
|
||||
recovery_stats.location_up = True
|
||||
if connection_result.valid:
|
||||
return _finish_success(final_result=connection_result, profile_id=profile.id)
|
||||
|
||||
# If not valid, we treat it as a failure to trigger the except block logic
|
||||
notification = f"{attempt} attempt failed.."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
continue # Proceed to attempt 2
|
||||
raise ConnectionError(notification)
|
||||
|
||||
# =================================
|
||||
# ATTEMPT 2+ MTU, PORT, WG KEY
|
||||
# =================================
|
||||
except (ConnectionError, CalledProcessError) as e:
|
||||
|
||||
# Connection is still On for MTU testing:
|
||||
# single time port is offered forever.
|
||||
if port_was_changed_already_today():
|
||||
# permanent config modify:
|
||||
ConfigurationController.change_port_prompts(False)
|
||||
|
||||
# =================================
|
||||
# MTU
|
||||
# =================================
|
||||
should_test_mtu, current_mtu = should_we_even_test_mtu(profile_id=profile.id, recovery_stats=recovery_stats)
|
||||
if attempt == 1:
|
||||
# First failure: Evaluate Location and Internet without connection,
|
||||
_cleanup_on_error(firewall_setting, dns_setting)
|
||||
|
||||
location_result = evaluate_location_and_internet(
|
||||
profile=profile,
|
||||
connection_observer=connection_observer
|
||||
)
|
||||
|
||||
if location_result.backoff_strategy == BackoffStrategy.NO_RETRY:
|
||||
logger.error(f"Location check failed: {location_result.message}")
|
||||
bottom_left = "Node Down"
|
||||
Notifications.emit(EventType.STATUS_UPDATE, bottom_left)
|
||||
notification = location_result.message
|
||||
Notifications.emit(EventType.SHOW_POPUP, notification)
|
||||
return location_result
|
||||
# raise ConnectionError(location_result.message) from e
|
||||
|
||||
notification = "Location check passed. Retrying immediately..."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
continue # Proceed to attempt 2
|
||||
|
||||
elif attempt == 2:
|
||||
# Second failure: Evaluate MTU WITH connection on
|
||||
current_mtu = get_mtu(profile_id=profile.id)
|
||||
|
||||
if current_mtu != MAX_MTU or not current_mtu:
|
||||
logger.info("MTU is already at the max, no point to change it.")
|
||||
_cleanup_on_error(firewall_setting, dns_setting)
|
||||
raise ConnectionError("Failed to connect.")
|
||||
# return Result(valid=False, error_type=ResultError.CONNECTION, message="Failed to connect.")
|
||||
|
||||
if not current_mtu or current_mtu > MIN_MTU:
|
||||
notification = "Testing MTU..."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
if mtu_is_fine(current_mtu):
|
||||
notification = "MTU is NOT the issue."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
logger.info(notification)
|
||||
# If MTU wasn't changed or wasn't applicable, don't bother with attempt 3
|
||||
_cleanup_on_error(firewall_setting, dns_setting)
|
||||
raise ConnectionError("Failed to connect.")
|
||||
# return Result(valid=False, error_type=ResultError.CONNECTION, message="Failed to connect.")
|
||||
|
||||
if changed_mtu(profile=profile, current_mtu=current_mtu):
|
||||
logger.info("MTU changed. Retrying connection...")
|
||||
continue # Proceed to attempt 3
|
||||
else:
|
||||
logger.warning("MTU check performed but no change was made or user rejected it.")
|
||||
notification = "MTU was NOT changed."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
else:
|
||||
logger.info("Skipping MTU testing, it's not relevant here.")
|
||||
|
||||
# If Port & MTU wasn't changed or wasn't applicable, don't bother with attempt 3
|
||||
# PORT CHANGE:
|
||||
if should_we_try_to_change_port():
|
||||
print("We should try to change port")
|
||||
_cleanup_on_error(firewall_setting, dns_setting)
|
||||
return offer_port_change(profile)
|
||||
else:
|
||||
notification = "Failed to connect."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
_cleanup_on_error(firewall_setting, dns_setting)
|
||||
raise ConnectionError("Failed to connect.")
|
||||
|
||||
if should_test_mtu:
|
||||
logger.info("We should test (and potentially change) the MTU..")
|
||||
if was_mtu_changed(profile=profile, current_mtu=current_mtu, recovery_stats=recovery_stats):
|
||||
logger.info("MTU was changed, so we're trying again.")
|
||||
continue
|
||||
else:
|
||||
logger.info("MTU was tested but NOT changed.")
|
||||
else:
|
||||
logger.info("MTU was NOT tested.")
|
||||
|
||||
# Take down connection for the rest of the tests:
|
||||
terminated = terminate_system_connection(firewall_setting, dns_setting)
|
||||
if terminated.valid:
|
||||
logger.info("Took down the system connection for the other tests.")
|
||||
else:
|
||||
return terminated
|
||||
|
||||
# =================================
|
||||
# PORT
|
||||
# =================================
|
||||
if should_we_try_to_change_port(recovery_stats):
|
||||
logger.info("We should try to change port")
|
||||
|
||||
# Offer the choice to the end user:
|
||||
message = get_port_change_message(profile=profile, recovery_stats=recovery_stats)
|
||||
yes_choice = partial(change_port_then_reconnect, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||
# recovery_stats.stashed_partial = yes_choice
|
||||
return Result(valid=False, function_choice=yes_choice, error_type=ResultError.PORT, message=message)
|
||||
|
||||
else:
|
||||
logger.info("Skipping port choice as an offer.")
|
||||
|
||||
# =================================
|
||||
# WIREGUARD RENEGOTIATION
|
||||
# =================================
|
||||
terminate_system_connection(firewall_setting, dns_setting)
|
||||
|
||||
if not recovery_stats.asked_to_change_wg_key:
|
||||
recovery_stats.asked_to_change_wg_key = True
|
||||
yes_option = partial(renegotiate_and_reconnect, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||
no_option = partial(establish_system_connection, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||
return Result(valid=False, function_choice=yes_option, no_option=no_option, error_type=ResultError.RENEGOTIATION, message="Would you like to try Wireguard key renegotiation? (Note: this invalidates other profiles with the same subscription.)")
|
||||
else:
|
||||
logger.info("entering final loop")
|
||||
return _conclude_loop_failure()
|
||||
|
||||
|
||||
|
||||
# ============= UPDATE STATE =============
|
||||
# if dns_setting and not did_dns_work:
|
||||
# current_state.firewalled = firewall_tracker
|
||||
# current_state.dns_set = did_dns_work
|
||||
# SystemStateController.update_or_create(current_state)
|
||||
# notification = "DNS Set Did Not Work."
|
||||
# Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
# Attempt 3 failed
|
||||
logger.error("Maximum retries reached. Connection failed.")
|
||||
notification = "Failed to connect."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
_cleanup_on_error(firewall_setting, dns_setting)
|
||||
raise ConnectionError(notification)
|
||||
# return Result(valid=False, error_type=ResultError.CONNECTION, message="Failed to connect.")
|
||||
|
|
|
|||
|
|
@ -1,148 +1,147 @@
|
|||
from core.utils.singleton_state import singleton, StatePersistenceMixin
|
||||
# from core.models.manage.validate_dataclass import ValidatedDataclass
|
||||
# from core.utils.basic_operations.file_tools import delete_file
|
||||
from core.models.manage.validate_dataclass import ValidatedDataclass
|
||||
from core.utils.basic_operations.file_tools import delete_file
|
||||
from core.Constants import Constants
|
||||
from core.models.enum_models import Currency, ProtocolChoice, PaymentType, PaymentCategory
|
||||
from core.errors.logger import logger
|
||||
|
||||
|
||||
from dataclasses import dataclass #, fields
|
||||
# import json
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
import os
|
||||
# from functools import wraps
|
||||
# from enum import Enum
|
||||
from functools import wraps
|
||||
from enum import Enum
|
||||
from typing import Any, Optional
|
||||
|
||||
# def singleton(cls):
|
||||
# instances = {}
|
||||
def singleton(cls):
|
||||
instances = {}
|
||||
|
||||
# @wraps(cls)
|
||||
# def get_instance(*args, **kwargs):
|
||||
# instance_id = kwargs.get('instance_id')
|
||||
@wraps(cls)
|
||||
def get_instance(*args, **kwargs):
|
||||
instance_id = kwargs.get('instance_id')
|
||||
|
||||
# # If instance_id provided, use localized mode (one instance per ID)
|
||||
# # Otherwise, use global mode (single instance)
|
||||
# key = (cls, instance_id) if instance_id else cls
|
||||
# If instance_id provided, use localized mode (one instance per ID)
|
||||
# Otherwise, use global mode (single instance)
|
||||
key = (cls, instance_id) if instance_id else cls
|
||||
|
||||
# if key not in instances:
|
||||
# print(f"Creating new instance with key: {key}")
|
||||
# instances[key] = cls(*args, **kwargs)
|
||||
# else:
|
||||
# print(f"Reusing existing instance with key: {key}")
|
||||
if key not in instances:
|
||||
print(f"Creating new instance with key: {key}")
|
||||
instances[key] = cls(*args, **kwargs)
|
||||
else:
|
||||
print(f"Reusing existing instance with key: {key}")
|
||||
|
||||
# # either way:
|
||||
# return instances[key]
|
||||
# either way:
|
||||
return instances[key]
|
||||
|
||||
# return get_instance
|
||||
return get_instance
|
||||
|
||||
|
||||
# # for saving.
|
||||
# EXCLUDED_FIELDS = {"parent_folder", "folder_path", "_data_file"}
|
||||
# for saving.
|
||||
EXCLUDED_FIELDS = {"parent_folder", "folder_path", "_data_file"}
|
||||
|
||||
|
||||
# class StatePersistenceMixin(ValidatedDataclass):
|
||||
# def _serialize_value(self, value):
|
||||
# """Helper method to ensure values are JSON-serializable"""
|
||||
# if isinstance(value, Enum):
|
||||
# return value.value
|
||||
# return value
|
||||
class StatePersistenceMixin(ValidatedDataclass):
|
||||
def _serialize_value(self, value):
|
||||
"""Helper method to ensure values are JSON-serializable"""
|
||||
if isinstance(value, Enum):
|
||||
return value.value
|
||||
return value
|
||||
|
||||
|
||||
# def prep_payload(self) -> dict|None:
|
||||
# """Orchestrate Save, Validation, and Payload preparation of relevant fields"""
|
||||
def prep_payload(self) -> dict|None:
|
||||
"""Orchestrate Save, Validation, and Payload preparation of relevant fields"""
|
||||
|
||||
# if not self.save():
|
||||
# logger.error("Failed to Save! Not returning a payload")
|
||||
# return None
|
||||
if not self.save():
|
||||
logger.error("Failed to Save! Not returning a payload")
|
||||
return None
|
||||
|
||||
# payload = {}
|
||||
payload = {}
|
||||
|
||||
# for f in fields(self):
|
||||
# # Only add the field if it's in our allowed list
|
||||
# if f.name in self.PAYLOAD_FIELDS:
|
||||
# # Get the raw value
|
||||
# raw_value = getattr(self, f.name)
|
||||
# # Clean it (handle Enums)
|
||||
# clean_value = self._serialize_value(raw_value)
|
||||
# # Add it to the dictionary
|
||||
# payload[f.name] = clean_value
|
||||
for f in fields(self):
|
||||
# Only add the field if it's in our allowed list
|
||||
if f.name in self.PAYLOAD_FIELDS:
|
||||
# Get the raw value
|
||||
raw_value = getattr(self, f.name)
|
||||
# Clean it (handle Enums)
|
||||
clean_value = self._serialize_value(raw_value)
|
||||
# Add it to the dictionary
|
||||
payload[f.name] = clean_value
|
||||
|
||||
# return payload
|
||||
return payload
|
||||
|
||||
|
||||
# def save(self) -> bool:
|
||||
# """Save state to file"""
|
||||
def save(self) -> bool:
|
||||
"""Save state to file"""
|
||||
|
||||
# if not self.validate_payload():
|
||||
# return False
|
||||
if not self.validate_payload():
|
||||
return False
|
||||
|
||||
# os.makedirs(self.folder_path, exist_ok=True)
|
||||
os.makedirs(self.folder_path, exist_ok=True)
|
||||
|
||||
# # 1. Start with an empty dictionary
|
||||
# data = {}
|
||||
# 1. Start with an empty dictionary
|
||||
data = {}
|
||||
|
||||
# # 2. Loop through the fields
|
||||
# for f in fields(self):
|
||||
# # Only add the field if it's NOT in the excluded list
|
||||
# if f.name not in EXCLUDED_FIELDS:
|
||||
# # Get the raw value
|
||||
# raw_value = getattr(self, f.name)
|
||||
# # Clean it (handle Enums)
|
||||
# clean_value = self._serialize_value(raw_value)
|
||||
# # Add it to the dictionary
|
||||
# data[f.name] = clean_value
|
||||
# 2. Loop through the fields
|
||||
for f in fields(self):
|
||||
# Only add the field if it's NOT in the excluded list
|
||||
if f.name not in EXCLUDED_FIELDS:
|
||||
# Get the raw value
|
||||
raw_value = getattr(self, f.name)
|
||||
# Clean it (handle Enums)
|
||||
clean_value = self._serialize_value(raw_value)
|
||||
# Add it to the dictionary
|
||||
data[f.name] = clean_value
|
||||
|
||||
# print(f"saving to {self._data_file}")
|
||||
# with open(self._data_file, "w") as f:
|
||||
# json.dump(data, f, indent=4, sort_keys=True)
|
||||
print(f"saving to {self._data_file}")
|
||||
with open(self._data_file, "w") as f:
|
||||
json.dump(data, f, indent=4, sort_keys=True)
|
||||
|
||||
# return True
|
||||
return True
|
||||
|
||||
|
||||
# def load(self):
|
||||
# """Load state from file, if each item passes a type check. With Enum translation"""
|
||||
def load(self):
|
||||
"""Load state from file, if each item passes a type check. With Enum translation"""
|
||||
|
||||
# logger.info("Starting load of pre-existing data")
|
||||
logger.info("Starting load of pre-existing data")
|
||||
|
||||
# if not os.path.exists(self._data_file):
|
||||
# logger.info("does NOT exist already")
|
||||
# return
|
||||
if not os.path.exists(self._data_file):
|
||||
logger.info("does NOT exist already")
|
||||
return
|
||||
|
||||
# with open(self._data_file, "r") as f:
|
||||
# data = json.load(f)
|
||||
with open(self._data_file, "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# for field in fields(self):
|
||||
# value = data.get(field.name)
|
||||
# logger.info(f"testing {field.name} of {value}")
|
||||
# if value is None:
|
||||
# continue
|
||||
for field in fields(self):
|
||||
value = data.get(field.name)
|
||||
logger.info(f"testing {field.name} of {value}")
|
||||
if value is None:
|
||||
continue
|
||||
|
||||
# # Translation: If the expected type is an Enum, convert the raw value back into an Enum member
|
||||
# if isinstance(field.type, type) and issubclass(field.type, Enum):
|
||||
# logger.info("testing enum")
|
||||
# try:
|
||||
# value = field.type(value)
|
||||
# except ValueError:
|
||||
# logger.error(f"Invalid enum value {value} for {field.name}")
|
||||
# continue
|
||||
# Translation: If the expected type is an Enum, convert the raw value back into an Enum member
|
||||
if isinstance(field.type, type) and issubclass(field.type, Enum):
|
||||
logger.info("testing enum")
|
||||
try:
|
||||
value = field.type(value)
|
||||
except ValueError:
|
||||
logger.error(f"Invalid enum value {value} for {field.name}")
|
||||
continue
|
||||
|
||||
# # type check works because 'value' is now an actual Enum member
|
||||
# if isinstance(value, field.type):
|
||||
# setattr(self, field.name, value)
|
||||
# type check works because 'value' is now an actual Enum member
|
||||
if isinstance(value, field.type):
|
||||
setattr(self, field.name, value)
|
||||
|
||||
|
||||
# def wipe_data_on_disk(self):
|
||||
# logger.info("Starting wipe of pre-existing data")
|
||||
def wipe_data_on_disk(self):
|
||||
logger.info("Starting wipe of pre-existing data")
|
||||
|
||||
# if not os.path.exists(self._data_file):
|
||||
# logger.info("File does NOT exist already")
|
||||
# return
|
||||
if not os.path.exists(self._data_file):
|
||||
logger.info("File does NOT exist already")
|
||||
return
|
||||
|
||||
# return delete_file(self._data_file)
|
||||
return delete_file(self._data_file)
|
||||
|
||||
|
||||
# def exists_already(self) -> bool:
|
||||
# return os.path.exists(self._data_file)
|
||||
def exists_already(self) -> bool:
|
||||
return os.path.exists(self._data_file)
|
||||
|
||||
|
||||
HOW_MANY_PROFILES_DEFAULT = 6
|
||||
|
|
@ -178,14 +177,13 @@ class TicketPaymentData(StatePersistenceMixin):
|
|||
def wipe(self):
|
||||
"""Wipe all data and start over."""
|
||||
wiped = self.wipe_data_on_disk()
|
||||
logger.info(f"Wiped: {wiped}")
|
||||
self.currency = None
|
||||
self.which_key = None
|
||||
self.how_many_profiles = 6
|
||||
self.billing_code = None
|
||||
self.use_random = False
|
||||
self.paid = False
|
||||
self.billing_pending = True
|
||||
sefl.billing_pending = True
|
||||
|
||||
|
||||
@singleton
|
||||
|
|
@ -220,7 +218,6 @@ class PaymentData(StatePersistenceMixin):
|
|||
def wipe(self):
|
||||
"""Wipe all data and start over."""
|
||||
wiped = self.wipe_data_on_disk()
|
||||
logger.info(f"Wiped: {wiped}")
|
||||
self.currency = None
|
||||
self.payment_type = None
|
||||
self.plan_id = None
|
||||
|
|
|
|||
|
|
@ -156,22 +156,18 @@ def enable_profile(
|
|||
connection_result = establish_connection(profile, ignore=ignore, connection_observer=connection_observer)
|
||||
if not connection_result:
|
||||
logger.error("Connection result is empty.")
|
||||
notification = "Connection Failed"
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
return
|
||||
|
||||
logger.info(f"Exiting establish connection with {connection_result}")
|
||||
|
||||
if connection_result.valid:
|
||||
# if profile_observer is not None:
|
||||
# profile_observer.notify('enabled', profile)
|
||||
|
||||
Notifications.emit(EventType.SYSTEM_ENABLE, profile.id)
|
||||
notification = "Connected."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
return Result(valid=True, data=profile.type)
|
||||
|
||||
else:
|
||||
if not connection_result.valid:
|
||||
return connection_result
|
||||
|
||||
if profile_observer is not None:
|
||||
profile_observer.notify('enabled', profile)
|
||||
notification = "Enabled."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
return Result(valid=True, data=profile.type)
|
||||
except FirewallError:
|
||||
return Result(valid=False, error_type=ResultError.FIREWALL, message="Firewall Error.")
|
||||
except ConnectionError as e:
|
||||
|
|
|
|||
25
core/utils/singleton.py
Normal file
25
core/utils/singleton.py
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
|
||||
from functools import wraps
|
||||
|
||||
def singleton(cls):
|
||||
instances = {}
|
||||
|
||||
@wraps(cls)
|
||||
def get_instance(*args, **kwargs):
|
||||
instance_id = kwargs.get('instance_id')
|
||||
|
||||
# If instance_id provided, use localized mode (one instance per ID)
|
||||
# Otherwise, use global mode (single instance)
|
||||
key = (cls, instance_id) if instance_id else cls
|
||||
|
||||
if key not in instances:
|
||||
print(f"Creating new instance with key: {key}")
|
||||
instances[key] = cls(*args, **kwargs)
|
||||
else:
|
||||
print(f"Reusing existing instance with key: {key}")
|
||||
|
||||
# either way:
|
||||
return instances[key]
|
||||
|
||||
return get_instance
|
||||
|
||||
|
|
@ -1,161 +0,0 @@
|
|||
from core.models.manage.validate_dataclass import ValidatedDataclass
|
||||
from core.utils.basic_operations.file_tools import delete_file
|
||||
from core.errors.logger import logger
|
||||
|
||||
from dataclasses import fields, MISSING
|
||||
import json
|
||||
import os
|
||||
from functools import wraps
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
|
||||
def singleton(cls):
|
||||
instances = {}
|
||||
|
||||
@wraps(cls)
|
||||
def get_instance(*args, **kwargs):
|
||||
instance_id = kwargs.get('instance_id')
|
||||
|
||||
# If instance_id provided, use localized mode (one instance per ID)
|
||||
# Otherwise, use global mode (single instance)
|
||||
key = (cls, instance_id) if instance_id else cls
|
||||
|
||||
if key not in instances:
|
||||
print(f"Creating new instance with key: {key}")
|
||||
instances[key] = cls(*args, **kwargs)
|
||||
else:
|
||||
print(f"Reusing existing instance with key: {key}")
|
||||
|
||||
# either way:
|
||||
return instances[key]
|
||||
|
||||
return get_instance
|
||||
|
||||
|
||||
# for saving.
|
||||
EXCLUDED_FIELDS = {"parent_folder", "folder_path", "_data_file"}
|
||||
|
||||
|
||||
class StatePersistenceMixin(ValidatedDataclass):
|
||||
def _serialize_value(self, value):
|
||||
"""Helper method to ensure values are JSON-serializable"""
|
||||
if isinstance(value, Enum):
|
||||
return value.value
|
||||
return value
|
||||
|
||||
|
||||
def prep_payload(self) -> dict|None:
|
||||
"""Orchestrate Save, Validation, and Payload preparation of relevant fields"""
|
||||
|
||||
if not self.save():
|
||||
logger.error("Failed to Save! Not returning a payload")
|
||||
return None
|
||||
|
||||
payload = {}
|
||||
|
||||
for f in fields(self):
|
||||
# Only add the field if it's in our allowed list
|
||||
if f.name in self.PAYLOAD_FIELDS:
|
||||
# Get the raw value
|
||||
raw_value = getattr(self, f.name)
|
||||
# Clean it (handle Enums)
|
||||
clean_value = self._serialize_value(raw_value)
|
||||
# Add it to the dictionary
|
||||
payload[f.name] = clean_value
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
def save(self) -> bool:
|
||||
"""Save state to file"""
|
||||
|
||||
if not self.validate_payload():
|
||||
return False
|
||||
|
||||
os.makedirs(self.folder_path, exist_ok=True)
|
||||
|
||||
# 1. Start with an empty dictionary
|
||||
data = {}
|
||||
|
||||
# 2. Loop through the fields
|
||||
for f in fields(self):
|
||||
# Only add the field if it's NOT in the excluded list
|
||||
if f.name not in EXCLUDED_FIELDS:
|
||||
# Get the raw value
|
||||
raw_value = getattr(self, f.name)
|
||||
# Clean it (handle Enums)
|
||||
clean_value = self._serialize_value(raw_value)
|
||||
# Add it to the dictionary
|
||||
data[f.name] = clean_value
|
||||
|
||||
print(f"saving to {self._data_file}")
|
||||
with open(self._data_file, "w") as f:
|
||||
json.dump(data, f, indent=4, sort_keys=True)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def load(self):
|
||||
"""Load state from file, if each item passes a type check. With Enum translation"""
|
||||
|
||||
logger.info("Starting load of pre-existing data")
|
||||
|
||||
if not os.path.exists(self._data_file):
|
||||
logger.info("does NOT exist already")
|
||||
return
|
||||
|
||||
with open(self._data_file, "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
for field in fields(self):
|
||||
value = data.get(field.name)
|
||||
logger.info(f"testing {field.name} of {value}")
|
||||
if value is None:
|
||||
continue
|
||||
|
||||
# Translation: If the expected type is an Enum, convert the raw value back into an Enum member
|
||||
if isinstance(field.type, type) and issubclass(field.type, Enum):
|
||||
logger.info("testing enum")
|
||||
try:
|
||||
value = field.type(value)
|
||||
except ValueError:
|
||||
logger.error(f"Invalid enum value {value} for {field.name}")
|
||||
continue
|
||||
|
||||
# type check works because 'value' is now an actual Enum member
|
||||
if isinstance(value, field.type):
|
||||
setattr(self, field.name, value)
|
||||
|
||||
|
||||
def wipe_data_on_disk(self):
|
||||
logger.info("Starting wipe of pre-existing data")
|
||||
|
||||
if not os.path.exists(self._data_file):
|
||||
logger.info("File does NOT exist already")
|
||||
return
|
||||
|
||||
return delete_file(self._data_file)
|
||||
|
||||
|
||||
def exists_already(self) -> bool:
|
||||
return os.path.exists(self._data_file)
|
||||
|
||||
|
||||
|
||||
def wipe_model(model: Any, KEEP_FIELDS: list) -> Any:
|
||||
for field in fields(model):
|
||||
if field.name not in KEEP_FIELDS:
|
||||
# 1. Check for a static default value (e.g., attempts: int = 0)
|
||||
if field.default is not MISSING:
|
||||
setattr(model, field.name, field.default)
|
||||
|
||||
# 2. Check for a default factory (e.g., items: list = field(default_factory=list))
|
||||
elif field.default_factory is not MISSING:
|
||||
setattr(model, field.name, field.default_factory())
|
||||
|
||||
# 3. Fallback: if no default is defined at all, set it to None.
|
||||
else:
|
||||
setattr(model, field.name, None)
|
||||
|
||||
return model
|
||||
Loading…
Reference in a new issue