Compare commits
2 commits
25d69d728c
...
f53661fc60
| Author | SHA1 | Date | |
|---|---|---|---|
| f53661fc60 | |||
| 14e257d091 |
15 changed files with 1023 additions and 499 deletions
66
core/models/ConnectionRecovery.py
Normal file
66
core/models/ConnectionRecovery.py
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
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,6 +57,8 @@ class ResultError(Enum):
|
||||||
NODE_ERROR = "node_error"
|
NODE_ERROR = "node_error"
|
||||||
NO_INTERNET = "no_internet"
|
NO_INTERNET = "no_internet"
|
||||||
PORT = "port"
|
PORT = "port"
|
||||||
|
RENEGOTIATION = "renegotiation"
|
||||||
|
ATTEMPTS = "attempts"
|
||||||
NAVIGATE_TO = "navigate_to"
|
NAVIGATE_TO = "navigate_to"
|
||||||
UNKNOWN = "unknown"
|
UNKNOWN = "unknown"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
from core.models.ConnectionRecovery import ConnectionRecovery
|
||||||
from core.controllers.ConfigurationController import ConfigurationController
|
from core.controllers.ConfigurationController import ConfigurationController
|
||||||
from core.infrastructure.global_state import ProfileStateRepository
|
from core.infrastructure.global_state import ProfileStateRepository
|
||||||
from core.utils.get_raw_string import get_string
|
from core.utils.get_raw_string import get_string
|
||||||
|
|
@ -29,8 +30,6 @@ from functools import partial
|
||||||
|
|
||||||
MIN_MTU = 1280
|
MIN_MTU = 1280
|
||||||
|
|
||||||
PORT_CHOICES = [48271, 52428, 51820]
|
|
||||||
|
|
||||||
def register_wireguard_session(
|
def register_wireguard_session(
|
||||||
profile: Profile,
|
profile: Profile,
|
||||||
connection_observer: Optional[ConnectionObserver] = None
|
connection_observer: Optional[ConnectionObserver] = None
|
||||||
|
|
@ -189,112 +188,3 @@ def expand_newlines(text):
|
||||||
"""
|
"""
|
||||||
return "\n\n".join([line for line in text.splitlines() if line.strip()])
|
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,6 +62,12 @@ def establish_connection(
|
||||||
if profile.connection.code == "wireguard":
|
if profile.connection.code == "wireguard":
|
||||||
_ensure_wireguard_configured(profile, connection_observer)
|
_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 = {
|
establish_fn = {
|
||||||
ProfileType.SESSION: ConnectionController.establish_session_connection,
|
ProfileType.SESSION: ConnectionController.establish_session_connection,
|
||||||
ProfileType.SYSTEM: establish_system_connection,
|
ProfileType.SYSTEM: establish_system_connection,
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,8 @@
|
||||||
|
from core.services.networking.api_requests.subtools.extract_domain import extract_domain
|
||||||
|
|
||||||
from core.services.networking.httpx.classify_response import classify_response
|
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
|
# models
|
||||||
from core.models.Result import Result, ResultError
|
from core.models.Result import Result, ResultError
|
||||||
|
|
@ -6,7 +10,9 @@ from core.services.networking.api_requests.ApiResponseModel import ApiResponse,
|
||||||
|
|
||||||
from core.Constants import Constants
|
from core.Constants import Constants
|
||||||
from core.errors.logger import logger
|
from core.errors.logger import logger
|
||||||
from essentials.observers.ConnectionObserver import ConnectionObserver
|
# from essentials.observers.ConnectionObserver import ConnectionObserver
|
||||||
|
from core.observers.ConnectionObserver import ConnectionObserver
|
||||||
|
|
||||||
|
|
||||||
# generic
|
# generic
|
||||||
import time
|
import time
|
||||||
|
|
@ -18,6 +24,10 @@ import httpx_socks
|
||||||
from httpx_socks import ProxyType
|
from httpx_socks import ProxyType
|
||||||
import subprocess
|
import subprocess
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
import socket
|
||||||
|
import multiprocessing
|
||||||
|
from threading import Thread
|
||||||
|
from queue import Queue, Empty
|
||||||
|
|
||||||
API_ENDPOINT_FORMATS = {
|
API_ENDPOINT_FORMATS = {
|
||||||
f"{Constants.SP_BASE_URL}/v2/get_ip": 'ip',
|
f"{Constants.SP_BASE_URL}/v2/get_ip": 'ip',
|
||||||
|
|
@ -31,64 +41,99 @@ API_ENDPOINT_FORMATS = {
|
||||||
|
|
||||||
MAX_ATTEMPTS = 3
|
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:
|
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]
|
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:
|
if port:
|
||||||
transport = httpx_socks.AsyncProxyTransport(
|
transport = httpx_socks.ProxyTransport(
|
||||||
proxy_type=ProxyType.SOCKS5,
|
proxy_type=ProxyType.SOCKS5,
|
||||||
proxy_host="127.0.0.1",
|
proxy_host="127.0.0.1",
|
||||||
proxy_port=port,
|
proxy_port=port,
|
||||||
)
|
)
|
||||||
client = httpx.AsyncClient(transport=transport, http2=True, timeout=6)
|
|
||||||
else:
|
|
||||||
client = httpx.AsyncClient(http2=True, timeout=6)
|
|
||||||
|
|
||||||
async def attempt_request(url: str, index: int):
|
# We use a Queue to get the first successful Result back from daemon threads
|
||||||
logger.info(f"Attempt {index + 1}: Trying {url}")
|
result_queue = Queue()
|
||||||
# if connection_observer:
|
|
||||||
# connection_observer.notify("connecting", f"Testing IP. Attempt {index + 1}")
|
|
||||||
|
|
||||||
|
def attempt_request(url: str, index: int, client: httpx.Client):
|
||||||
try:
|
try:
|
||||||
raw_response = await client.get(url)
|
raw_response = client.get(url)
|
||||||
filtered_response = classify_response(raw_response)
|
filtered_response = classify_response(raw_response)
|
||||||
|
|
||||||
if filtered_response.valid:
|
if filtered_response.valid:
|
||||||
ip_address = extract_ip_from_response(
|
ip_address = extract_ip_from_response(response=filtered_response.data, api_url=url)
|
||||||
response=filtered_response.data,
|
if ip_address:
|
||||||
api_url=url
|
result_queue.put(Result(valid=True, data=ip_address))
|
||||||
)
|
return
|
||||||
if ip_address is not None:
|
except Exception:
|
||||||
return Result(valid=True, data=ip_address)
|
pass
|
||||||
|
|
||||||
logger.error(f"Skipping {url}")
|
with httpx.Client(transport=transport, http2=False, timeout=3.0) as client:
|
||||||
except Exception as e:
|
for i, url in enumerate(endpoint_list):
|
||||||
logger.error(f"Skipping {url}. Invalid API reply or failed connection {str(e)}")
|
# 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()
|
||||||
|
|
||||||
return Result(valid=False)
|
# 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:
|
try:
|
||||||
# Create tasks for all endpoints to run them concurrently
|
# Block for the remaining budget
|
||||||
tasks = [asyncio.create_task(attempt_request(url, i)) for i, url in enumerate(endpoint_list)]
|
return result_queue.get(timeout=remaining)
|
||||||
|
except Empty:
|
||||||
# Process tasks as they complete
|
break
|
||||||
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
|
|
||||||
|
|
||||||
finally:
|
|
||||||
await client.aclose()
|
|
||||||
|
|
||||||
logger.error(f"We went through {len(endpoint_list)} attempts and could not get a reply.")
|
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.")
|
return Result(valid=False, error_type=ResultError.CONNECTION, message="Could not connect.")
|
||||||
|
|
@ -122,13 +167,16 @@ def extract_ip_from_response(response: dict, api_url: str) -> str | bool:
|
||||||
|
|
||||||
|
|
||||||
def ping_ip(ip: str) -> Result:
|
def ping_ip(ip: str) -> Result:
|
||||||
|
"""Ping an IP using the pre-existing terminal"""
|
||||||
command = ["ping", "-c", "1", "-W", "2", ip]
|
command = ["ping", "-c", "1", "-W", "2", ip]
|
||||||
human_readable_goal = f"Pinging {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)
|
return run_generic_command(command, human_readable_goal, timeout=5)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def ping_ip_worked(ip: str) -> bool:
|
def ping_ip_worked(ip: str) -> bool:
|
||||||
|
"""Test ping in a new subprocess"""
|
||||||
try:
|
try:
|
||||||
# -c 1: send only 1 packet
|
# -c 1: send only 1 packet
|
||||||
# -W 2: wait 2 seconds for a response
|
# -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.api_requests.ApiResponseModel import BackoffStrategy
|
||||||
from core.services.networking.general_connection_tools.test_internet import test_internet
|
from core.services.networking.general_connection_tools.test_internet import test_internet
|
||||||
from core.services.networking.general_connection_tools.ip import ping_ip_worked
|
from core.services.networking.general_connection_tools.ip import ping_ip
|
||||||
from core.services.networking.systemwide.general_tools.test_any_protocol import get_singbox_ip
|
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.services.networking.general_connection_tools.config_tools import extract_endpoint_ip
|
||||||
from core.models.manage.server_reply_tools import api_call_and_extraction, ApiCall
|
from core.models.manage.server_reply_tools import api_call_and_extraction, ApiCall
|
||||||
|
|
@ -47,7 +47,8 @@ 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)
|
ip_address = get_profile_ip(profile_id=profile_id, protocol=protocol, profile_type=profile_type)
|
||||||
|
|
||||||
if ip_address:
|
if ip_address:
|
||||||
can_be_pinged = ping_ip_worked(ip_address)
|
ping_result = ping_ip(ip_address)
|
||||||
|
can_be_pinged = ping_result.valid
|
||||||
print(f"Can {location_name} be pinged? {can_be_pinged}")
|
print(f"Can {location_name} be pinged? {can_be_pinged}")
|
||||||
else:
|
else:
|
||||||
logger.error("Skipping IP Address Test.")
|
logger.error("Skipping IP Address Test.")
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
from core.utils.run_commands import run_generic_command
|
||||||
|
|
||||||
from core.Constants import Constants
|
from core.Constants import Constants
|
||||||
from core.Errors import CommandNotFoundError
|
from core.Errors import CommandNotFoundError
|
||||||
from core.observers.ConnectionObserver import ConnectionObserver
|
from core.observers.ConnectionObserver import ConnectionObserver
|
||||||
|
|
@ -37,15 +39,33 @@ def await_network_interface():
|
||||||
raise ConnectionError('The network interface could not be activated.')
|
raise ConnectionError('The network interface could not be activated.')
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def system_uses_wireguard_interface():
|
def system_uses_wireguard_interface():
|
||||||
|
|
||||||
if shutil.which('ip') is None:
|
if shutil.which('ip') is None:
|
||||||
raise CommandNotFoundError('ip')
|
raise CommandNotFoundError('ip')
|
||||||
|
|
||||||
process = subprocess.Popen(('ip', 'route', 'get', '192.0.2.1'), stdout=subprocess.PIPE)
|
command = ['ip', 'route', 'get', '192.0.2.1']
|
||||||
process_output = str(process.stdout.read())
|
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
|
||||||
|
|
||||||
return bool(re.search('dev wg', str(process_output)))
|
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)))
|
||||||
|
|
||||||
|
|
||||||
def __test_connection(port_number: Optional[int] = None, timeout: float = 4.0):
|
def __test_connection(port_number: Optional[int] = None, timeout: float = 4.0):
|
||||||
|
|
|
||||||
72
core/services/networking/mtu/mtu_orchestrator.py
Normal file
72
core/services/networking/mtu/mtu_orchestrator.py
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
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
|
||||||
|
|
||||||
149
core/services/networking/ports/port_orchestrator.py
Normal file
149
core/services/networking/ports/port_orchestrator.py
Normal file
|
|
@ -0,0 +1,149 @@
|
||||||
|
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,5 +1,9 @@
|
||||||
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.models.ConnectionRecovery import ConnectionRecovery
|
||||||
from core.services.networking.systemwide.wireguard.mtu_tools import loop_through_testing_mtu, mtu_is_fine, MIN_MTU, MAX_MTU
|
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.networking.general_connection_tools.location_evaluation import check_if_location_is_up
|
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.services.networking.api_requests.ApiResponseModel import BackoffStrategy
|
||||||
from core.models.enum_models import ProtocolChoice, SINGBOX_PROTOCOLS
|
from core.models.enum_models import ProtocolChoice, SINGBOX_PROTOCOLS
|
||||||
|
|
@ -23,7 +27,7 @@ from core.utils.run_commands import run_generic_command
|
||||||
from core.observers.TicketObserver import TicketObserver
|
from core.observers.TicketObserver import TicketObserver
|
||||||
|
|
||||||
# from core.Constants import Constants
|
# from core.Constants import Constants
|
||||||
from core.Errors import ConnectionTerminationError, CommandNotFoundError
|
from core.Errors import CommandNotFoundError # ConnectionTerminationError
|
||||||
from core.controllers.ConfigurationController import ConfigurationController
|
from core.controllers.ConfigurationController import ConfigurationController
|
||||||
from core.controllers.SystemStateController import SystemStateController
|
from core.controllers.SystemStateController import SystemStateController
|
||||||
# from core.models.BaseProfile import ProfileType
|
# from core.models.BaseProfile import ProfileType
|
||||||
|
|
@ -31,19 +35,22 @@ from core.controllers.SystemStateController import SystemStateController
|
||||||
from core.models.system.SystemProfile import SystemProfile
|
from core.models.system.SystemProfile import SystemProfile
|
||||||
from core.models.system.SystemState import SystemState
|
from core.models.system.SystemState import SystemState
|
||||||
from core.observers.ConnectionObserver import ConnectionObserver
|
from core.observers.ConnectionObserver import ConnectionObserver
|
||||||
from subprocess import CalledProcessError
|
# from subprocess import CalledProcessError
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
# import os
|
# import os
|
||||||
# import re
|
# import re
|
||||||
import shutil
|
import shutil
|
||||||
# import subprocess
|
# import subprocess
|
||||||
import time
|
import time
|
||||||
import asyncio
|
# import asyncio
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
MAX_ATTEMPTS = 4
|
||||||
|
|
||||||
def terminate_system_connection(
|
def terminate_system_connection(
|
||||||
firewall_setting: Optional[bool] = None,
|
firewall_setting: Optional[bool] = None,
|
||||||
dns_setting: Optional[bool] = None
|
dns_setting: Optional[bool] = None
|
||||||
):
|
) -> Result:
|
||||||
|
|
||||||
# ====== PREREQS =======
|
# ====== PREREQS =======
|
||||||
if firewall_setting is None:
|
if firewall_setting is None:
|
||||||
|
|
@ -63,12 +70,11 @@ def terminate_system_connection(
|
||||||
if dns_setting:
|
if dns_setting:
|
||||||
_ = revert_dns()
|
_ = revert_dns()
|
||||||
|
|
||||||
# ====== NMCLI =======
|
|
||||||
if SystemStateController.exists():
|
|
||||||
|
|
||||||
# ====== SINGBOX =======
|
# ====== SINGBOX =======
|
||||||
# Check if the user is switching from Singbox to Wireguard:
|
# Check if the user is switching from Singbox to Wireguard:
|
||||||
|
if SystemStateController.exists():
|
||||||
current_state = SystemState.get()
|
current_state = SystemState.get()
|
||||||
|
if current_state:
|
||||||
if get_protocol_enum(current_state.profile_id) in SINGBOX_PROTOCOLS:
|
if get_protocol_enum(current_state.profile_id) in SINGBOX_PROTOCOLS:
|
||||||
logger.info("Ending Singbox protocols first..")
|
logger.info("Ending Singbox protocols first..")
|
||||||
from core.services.networking.systemwide.encrypted_proxy.singbox_runner import end_singbox
|
from core.services.networking.systemwide.encrypted_proxy.singbox_runner import end_singbox
|
||||||
|
|
@ -78,8 +84,9 @@ def terminate_system_connection(
|
||||||
command = ['nmcli', 'connection', 'delete', 'wg']
|
command = ['nmcli', 'connection', 'delete', 'wg']
|
||||||
human_readable_goal = "Deleting NMCLI wg interface"
|
human_readable_goal = "Deleting NMCLI wg interface"
|
||||||
delete_completed = run_generic_command(command, human_readable_goal, timeout=8)
|
delete_completed = run_generic_command(command, human_readable_goal, timeout=8)
|
||||||
|
print(f"delete_completed output: {delete_completed}")
|
||||||
|
|
||||||
if delete_completed.valid or not system_uses_wireguard_interface():
|
if not system_uses_wireguard_interface():
|
||||||
command = ['nmcli', 'connection', 'delete', 'hv-ipv6-sink']
|
command = ['nmcli', 'connection', 'delete', 'hv-ipv6-sink']
|
||||||
human_readable_goal = "Deleting NMCLI IPv6 Sink"
|
human_readable_goal = "Deleting NMCLI IPv6 Sink"
|
||||||
sinkhole_deleted = run_generic_command(command, human_readable_goal, timeout=8)
|
sinkhole_deleted = run_generic_command(command, human_readable_goal, timeout=8)
|
||||||
|
|
@ -91,15 +98,139 @@ def terminate_system_connection(
|
||||||
# confirm firewall is off.
|
# confirm firewall is off.
|
||||||
if firewall_setting:
|
if firewall_setting:
|
||||||
check_and_kill_firewall() # on failure, this raises errors, which then bubble up
|
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}')
|
||||||
|
|
||||||
# finally end that profile's JSON state:
|
# finally end that profile's JSON state:
|
||||||
|
if SystemStateController.exists():
|
||||||
SystemState.dissolve()
|
SystemState.dissolve()
|
||||||
|
return Result(valid=True)
|
||||||
|
|
||||||
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:
|
def evaluate_location_and_internet(profile: SystemProfile, connection_observer: ConnectionObserver) -> Result:
|
||||||
|
|
@ -115,57 +246,37 @@ def evaluate_location_and_internet(profile: SystemProfile, connection_observer:
|
||||||
|
|
||||||
return location_result
|
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:
|
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()
|
terminate_tor_connection()
|
||||||
time.sleep(0.3)
|
time.sleep(0.3)
|
||||||
return final_result
|
return final_result
|
||||||
|
|
||||||
|
|
||||||
def changed_mtu(profile: SystemProfile, current_mtu: Optional[int]) -> bool:
|
def _conclude_loop_failure():
|
||||||
notification = "Testing MTU.."
|
"""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"
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
|
error_msg = "Connection failed, but the location is up. We recommend you try a different protocol."
|
||||||
# optimal_mtu = loop_through_testing_mtu()
|
return Result(valid=False, error_type=ResultError.UNKNOWN, message=error_msg)
|
||||||
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(
|
def __establish_system_connection(
|
||||||
profile: SystemProfile,
|
profile: SystemProfile,
|
||||||
firewall_setting: bool = False,
|
firewall_setting: bool = False,
|
||||||
dns_setting: bool = False,
|
dns_setting: bool = False,
|
||||||
connection_observer: Optional[ConnectionObserver] = None):
|
connection_observer: Optional[ConnectionObserver] = None) -> Result:
|
||||||
"""
|
"""
|
||||||
Purpose:
|
Purpose:
|
||||||
Orchestrates the full flow of the connection.
|
Orchestrates the full flow of the connection.
|
||||||
|
|
||||||
Steps:
|
Steps:
|
||||||
1) Check Prereqs
|
|
||||||
2) Disable any pre-existing system connections
|
|
||||||
3) Turn on WG via nmcli
|
3) Turn on WG via nmcli
|
||||||
4) Turn on IPv6 sinkhole
|
4) Turn on IPv6 sinkhole
|
||||||
5) Setup State (JSON file)
|
5) Setup State (JSON file)
|
||||||
|
|
@ -173,17 +284,10 @@ def __establish_system_connection(
|
||||||
7) Set DNS (if enabled), and test it. Let's it slide even if failed.
|
7) Set DNS (if enabled), and test it. Let's it slide even if failed.
|
||||||
8) Testing, confirming, displaying to the end user.
|
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 =============
|
# ============= INITIAL NMCLI CONNECTION =============
|
||||||
notification = "Setting Up WireGuard.."
|
notification = "Setting Up WireGuard.."
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
# if connection_observer:
|
|
||||||
# connection_observer.notify("connecting", notification)
|
|
||||||
wg_config_path = profile.get_wireguard_configuration_path()
|
wg_config_path = profile.get_wireguard_configuration_path()
|
||||||
nmcli_result = setup_nmcli_connection(wg_config_path)
|
nmcli_result = setup_nmcli_connection(wg_config_path)
|
||||||
|
|
||||||
|
|
@ -204,17 +308,6 @@ def __establish_system_connection(
|
||||||
if not sinkhole_result:
|
if not sinkhole_result:
|
||||||
raise ConnectionError('IPv6 Could not be protected.')
|
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 =============
|
# ============= PREP SETTINGS =============
|
||||||
if connection_observer:
|
if connection_observer:
|
||||||
connection_observer.notify("connecting", "Getting Interface Name..")
|
connection_observer.notify("connecting", "Getting Interface Name..")
|
||||||
|
|
@ -260,8 +353,6 @@ def __establish_system_connection(
|
||||||
|
|
||||||
# ============= TESTING =============
|
# ============= TESTING =============
|
||||||
logger.info("If we made it this far, we have nmcli on, ipv6 sinkhole on, firewall on.")
|
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.."
|
notification = "Testing IP address.."
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
|
|
@ -273,16 +364,17 @@ def __establish_system_connection(
|
||||||
if not test_result.valid:
|
if not test_result.valid:
|
||||||
notification = "Test Failed."
|
notification = "Test Failed."
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
|
logger.error("Returning that the test failed..")
|
||||||
return test_result
|
return test_result
|
||||||
|
|
||||||
# ============= UPDATE STATE =============
|
# ============= SETUP STATE =============
|
||||||
if dns_setting and not did_dns_work:
|
logger.info("Setting State JSON..")
|
||||||
current_state.firewalled = firewall_tracker
|
current_state = SystemStateController.create(
|
||||||
current_state.dns_set = did_dns_work
|
profile_id=profile.id,
|
||||||
SystemStateController.update_or_create(current_state)
|
firewalled=firewall_setting,
|
||||||
notification = "DNS Set Did Not Work."
|
dns_set=did_dns_work,
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
protocol=ProtocolChoice.WIREGUARD
|
||||||
|
)
|
||||||
return Result(valid=True, data=current_state)
|
return Result(valid=True, data=current_state)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -293,14 +385,17 @@ def establish_system_connection(
|
||||||
ticket_observer: Optional[TicketObserver] = None # Passed in only for assassin's link to tickets in ConnectionController.establish_session_connection
|
ticket_observer: Optional[TicketObserver] = None # Passed in only for assassin's link to tickets in ConnectionController.establish_session_connection
|
||||||
) -> Result|None:
|
) -> Result|None:
|
||||||
"""
|
"""
|
||||||
Establish connection with a maximum of 2 retries.
|
Establish connection.
|
||||||
|
|
||||||
Steps)
|
Steps)
|
||||||
1) Verify Endpoint's encryption
|
1) Check Prereqs
|
||||||
2) get settings
|
2) Verify Endpoint's encryption
|
||||||
3) Attempt 1 -> (Fail) -> Location Check
|
3) get settings
|
||||||
4) Attempt 2 -> (Fail) -> MTU Check -> Attempt 3
|
4) Disable any pre-existing system connections
|
||||||
"""
|
"""
|
||||||
|
# ================= PRE-REQS =================
|
||||||
|
check_system_prereqs()
|
||||||
|
|
||||||
# ================= VERIFY ENDPOINT =================
|
# ================= VERIFY ENDPOINT =================
|
||||||
if connection_observer:
|
if connection_observer:
|
||||||
connection_observer.notify("connecting", "Verifying endpoint..")
|
connection_observer.notify("connecting", "Verifying endpoint..")
|
||||||
|
|
@ -310,17 +405,36 @@ def establish_system_connection(
|
||||||
# ================= SETTINGS =================
|
# ================= SETTINGS =================
|
||||||
firewall_setting = ConfigurationController.get_firewall_setting()
|
firewall_setting = ConfigurationController.get_firewall_setting()
|
||||||
dns_setting = ConfigurationController.get_dns_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 ================
|
# ================= CONNECT WG ================
|
||||||
# We allow 3 total attempts (Initial + 2 retries)
|
while not recovery_stats.reached_end_of_loop:
|
||||||
for attempt in range(1, 4):
|
recovery_stats.attempts += 1
|
||||||
try:
|
current_try = recovery_stats.attempts
|
||||||
# if connection_observer:
|
|
||||||
# connection_observer.notify("connecting", f"Connecting attempt {attempt} of 3.. ")
|
|
||||||
|
|
||||||
notification = 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 {current_try}.. "
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
|
|
||||||
|
# =================================
|
||||||
|
# CONNECT
|
||||||
|
# =================================
|
||||||
# Attempt the actual system connection
|
# Attempt the actual system connection
|
||||||
connection_result = __establish_system_connection(
|
connection_result = __establish_system_connection(
|
||||||
profile=profile,
|
profile=profile,
|
||||||
|
|
@ -329,94 +443,107 @@ def establish_system_connection(
|
||||||
connection_observer=connection_observer
|
connection_observer=connection_observer
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# =================================
|
||||||
|
# EVALUATE
|
||||||
|
# =================================
|
||||||
if connection_result.valid:
|
if connection_result.valid:
|
||||||
|
recovery_stats.wipe()
|
||||||
return _finish_success(final_result=connection_result, profile_id=profile.id)
|
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.."
|
# ATTEMPT ONE: LOCATION UP?
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
# =================================
|
||||||
raise ConnectionError(notification)
|
if current_try == 1 and not recovery_stats.location_tested:
|
||||||
|
|
||||||
except (ConnectionError, CalledProcessError) as e:
|
|
||||||
|
|
||||||
# single time port is offered forever.
|
|
||||||
if port_was_changed_already_today():
|
|
||||||
# permanent config modify:
|
|
||||||
ConfigurationController.change_port_prompts(False)
|
|
||||||
|
|
||||||
if attempt == 1:
|
|
||||||
# First failure: Evaluate Location and Internet without connection,
|
# First failure: Evaluate Location and Internet without connection,
|
||||||
_cleanup_on_error(firewall_setting, dns_setting)
|
logger.info("Terminating system connection to check location")
|
||||||
|
terminate_system_connection(firewall_setting, dns_setting)
|
||||||
|
|
||||||
location_result = evaluate_location_and_internet(
|
location_result = evaluate_location_and_internet(
|
||||||
profile=profile,
|
profile=profile,
|
||||||
connection_observer=connection_observer
|
connection_observer=connection_observer
|
||||||
)
|
)
|
||||||
|
recovery_stats.location_tested = True
|
||||||
|
|
||||||
|
#============== NO RETRY #==============
|
||||||
if location_result.backoff_strategy == BackoffStrategy.NO_RETRY:
|
if location_result.backoff_strategy == BackoffStrategy.NO_RETRY:
|
||||||
|
recovery_stats.location_up = False
|
||||||
logger.error(f"Location check failed: {location_result.message}")
|
logger.error(f"Location check failed: {location_result.message}")
|
||||||
bottom_left = "Node Down"
|
bottom_left = "Node Down"
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, bottom_left)
|
Notifications.emit(EventType.STATUS_UPDATE, bottom_left)
|
||||||
notification = location_result.message
|
notification = location_result.message
|
||||||
Notifications.emit(EventType.SHOW_POPUP, notification)
|
Notifications.emit(EventType.SHOW_POPUP, notification)
|
||||||
return location_result
|
return location_result
|
||||||
# raise ConnectionError(location_result.message) from e
|
|
||||||
|
|
||||||
|
#============== NO SEEMS FINE #==============
|
||||||
notification = "Location check passed. Retrying immediately..."
|
notification = "Location check passed. Retrying immediately..."
|
||||||
|
recovery_stats.location_up = True
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
logger.info(notification)
|
logger.info(notification)
|
||||||
continue # Proceed to attempt 2
|
continue # Proceed to attempt 2
|
||||||
|
|
||||||
elif attempt == 2:
|
# =================================
|
||||||
# Second failure: Evaluate MTU WITH connection on
|
# ATTEMPT 2+ MTU, PORT, WG KEY
|
||||||
current_mtu = get_mtu(profile_id=profile.id)
|
# =================================
|
||||||
|
|
||||||
if current_mtu != MAX_MTU or not current_mtu:
|
# Connection is still On for MTU testing:
|
||||||
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..."
|
# MTU
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
# =================================
|
||||||
logger.info(notification)
|
should_test_mtu, current_mtu = should_we_even_test_mtu(profile_id=profile.id, recovery_stats=recovery_stats)
|
||||||
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):
|
if should_test_mtu:
|
||||||
logger.info("MTU changed. Retrying connection...")
|
logger.info("We should test (and potentially change) the MTU..")
|
||||||
continue # Proceed to attempt 3
|
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:
|
else:
|
||||||
logger.warning("MTU check performed but no change was made or user rejected it.")
|
logger.info("MTU was tested but NOT changed.")
|
||||||
notification = "MTU was NOT changed."
|
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
|
||||||
else:
|
else:
|
||||||
logger.info("Skipping MTU testing, it's not relevant here.")
|
logger.info("MTU was NOT tested.")
|
||||||
|
|
||||||
# If Port & MTU wasn't changed or wasn't applicable, don't bother with attempt 3
|
# Take down connection for the rest of the tests:
|
||||||
# PORT CHANGE:
|
terminated = terminate_system_connection(firewall_setting, dns_setting)
|
||||||
if should_we_try_to_change_port():
|
if terminated.valid:
|
||||||
print("We should try to change port")
|
logger.info("Took down the system connection for the other tests.")
|
||||||
_cleanup_on_error(firewall_setting, dns_setting)
|
|
||||||
return offer_port_change(profile)
|
|
||||||
else:
|
else:
|
||||||
notification = "Failed to connect."
|
return terminated
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
|
||||||
_cleanup_on_error(firewall_setting, dns_setting)
|
# =================================
|
||||||
raise ConnectionError("Failed to connect.")
|
# 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:
|
else:
|
||||||
# Attempt 3 failed
|
logger.info("Skipping port choice as an offer.")
|
||||||
logger.error("Maximum retries reached. Connection failed.")
|
|
||||||
notification = "Failed to connect."
|
# =================================
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
# WIREGUARD RENEGOTIATION
|
||||||
_cleanup_on_error(firewall_setting, dns_setting)
|
# =================================
|
||||||
raise ConnectionError(notification)
|
terminate_system_connection(firewall_setting, dns_setting)
|
||||||
# return Result(valid=False, error_type=ResultError.CONNECTION, message="Failed to connect.")
|
|
||||||
|
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)
|
||||||
|
|
|
||||||
|
|
@ -1,147 +1,148 @@
|
||||||
from core.models.manage.validate_dataclass import ValidatedDataclass
|
from core.utils.singleton_state import singleton, StatePersistenceMixin
|
||||||
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.Constants import Constants
|
||||||
from core.models.enum_models import Currency, ProtocolChoice, PaymentType, PaymentCategory
|
from core.models.enum_models import Currency, ProtocolChoice, PaymentType, PaymentCategory
|
||||||
from core.errors.logger import logger
|
from core.errors.logger import logger
|
||||||
|
|
||||||
|
|
||||||
from dataclasses import dataclass, fields
|
from dataclasses import dataclass #, fields
|
||||||
import json
|
# import json
|
||||||
import os
|
import os
|
||||||
from functools import wraps
|
# from functools import wraps
|
||||||
from enum import Enum
|
# from enum import Enum
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional
|
||||||
|
|
||||||
def singleton(cls):
|
# def singleton(cls):
|
||||||
instances = {}
|
# instances = {}
|
||||||
|
|
||||||
@wraps(cls)
|
# @wraps(cls)
|
||||||
def get_instance(*args, **kwargs):
|
# def get_instance(*args, **kwargs):
|
||||||
instance_id = kwargs.get('instance_id')
|
# instance_id = kwargs.get('instance_id')
|
||||||
|
|
||||||
# If instance_id provided, use localized mode (one instance per ID)
|
# # If instance_id provided, use localized mode (one instance per ID)
|
||||||
# Otherwise, use global mode (single instance)
|
# # Otherwise, use global mode (single instance)
|
||||||
key = (cls, instance_id) if instance_id else cls
|
# key = (cls, instance_id) if instance_id else cls
|
||||||
|
|
||||||
if key not in instances:
|
# if key not in instances:
|
||||||
print(f"Creating new instance with key: {key}")
|
# print(f"Creating new instance with key: {key}")
|
||||||
instances[key] = cls(*args, **kwargs)
|
# instances[key] = cls(*args, **kwargs)
|
||||||
else:
|
# else:
|
||||||
print(f"Reusing existing instance with key: {key}")
|
# print(f"Reusing existing instance with key: {key}")
|
||||||
|
|
||||||
# either way:
|
# # either way:
|
||||||
return instances[key]
|
# return instances[key]
|
||||||
|
|
||||||
return get_instance
|
# return get_instance
|
||||||
|
|
||||||
|
|
||||||
# for saving.
|
# # for saving.
|
||||||
EXCLUDED_FIELDS = {"parent_folder", "folder_path", "_data_file"}
|
# EXCLUDED_FIELDS = {"parent_folder", "folder_path", "_data_file"}
|
||||||
|
|
||||||
|
|
||||||
class StatePersistenceMixin(ValidatedDataclass):
|
# class StatePersistenceMixin(ValidatedDataclass):
|
||||||
def _serialize_value(self, value):
|
# def _serialize_value(self, value):
|
||||||
"""Helper method to ensure values are JSON-serializable"""
|
# """Helper method to ensure values are JSON-serializable"""
|
||||||
if isinstance(value, Enum):
|
# if isinstance(value, Enum):
|
||||||
return value.value
|
# return value.value
|
||||||
return value
|
# return value
|
||||||
|
|
||||||
|
|
||||||
def prep_payload(self) -> dict|None:
|
# def prep_payload(self) -> dict|None:
|
||||||
"""Orchestrate Save, Validation, and Payload preparation of relevant fields"""
|
# """Orchestrate Save, Validation, and Payload preparation of relevant fields"""
|
||||||
|
|
||||||
if not self.save():
|
# if not self.save():
|
||||||
logger.error("Failed to Save! Not returning a payload")
|
# logger.error("Failed to Save! Not returning a payload")
|
||||||
return None
|
# return None
|
||||||
|
|
||||||
payload = {}
|
# payload = {}
|
||||||
|
|
||||||
for f in fields(self):
|
# for f in fields(self):
|
||||||
# Only add the field if it's in our allowed list
|
# # Only add the field if it's in our allowed list
|
||||||
if f.name in self.PAYLOAD_FIELDS:
|
# if f.name in self.PAYLOAD_FIELDS:
|
||||||
# Get the raw value
|
# # Get the raw value
|
||||||
raw_value = getattr(self, f.name)
|
# raw_value = getattr(self, f.name)
|
||||||
# Clean it (handle Enums)
|
# # Clean it (handle Enums)
|
||||||
clean_value = self._serialize_value(raw_value)
|
# clean_value = self._serialize_value(raw_value)
|
||||||
# Add it to the dictionary
|
# # Add it to the dictionary
|
||||||
payload[f.name] = clean_value
|
# payload[f.name] = clean_value
|
||||||
|
|
||||||
return payload
|
# return payload
|
||||||
|
|
||||||
|
|
||||||
def save(self) -> bool:
|
# def save(self) -> bool:
|
||||||
"""Save state to file"""
|
# """Save state to file"""
|
||||||
|
|
||||||
if not self.validate_payload():
|
# if not self.validate_payload():
|
||||||
return False
|
# return False
|
||||||
|
|
||||||
os.makedirs(self.folder_path, exist_ok=True)
|
# os.makedirs(self.folder_path, exist_ok=True)
|
||||||
|
|
||||||
# 1. Start with an empty dictionary
|
# # 1. Start with an empty dictionary
|
||||||
data = {}
|
# data = {}
|
||||||
|
|
||||||
# 2. Loop through the fields
|
# # 2. Loop through the fields
|
||||||
for f in fields(self):
|
# for f in fields(self):
|
||||||
# Only add the field if it's NOT in the excluded list
|
# # Only add the field if it's NOT in the excluded list
|
||||||
if f.name not in EXCLUDED_FIELDS:
|
# if f.name not in EXCLUDED_FIELDS:
|
||||||
# Get the raw value
|
# # Get the raw value
|
||||||
raw_value = getattr(self, f.name)
|
# raw_value = getattr(self, f.name)
|
||||||
# Clean it (handle Enums)
|
# # Clean it (handle Enums)
|
||||||
clean_value = self._serialize_value(raw_value)
|
# clean_value = self._serialize_value(raw_value)
|
||||||
# Add it to the dictionary
|
# # Add it to the dictionary
|
||||||
data[f.name] = clean_value
|
# data[f.name] = clean_value
|
||||||
|
|
||||||
print(f"saving to {self._data_file}")
|
# print(f"saving to {self._data_file}")
|
||||||
with open(self._data_file, "w") as f:
|
# with open(self._data_file, "w") as f:
|
||||||
json.dump(data, f, indent=4, sort_keys=True)
|
# json.dump(data, f, indent=4, sort_keys=True)
|
||||||
|
|
||||||
return True
|
# return True
|
||||||
|
|
||||||
|
|
||||||
def load(self):
|
# def load(self):
|
||||||
"""Load state from file, if each item passes a type check. With Enum translation"""
|
# """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):
|
# if not os.path.exists(self._data_file):
|
||||||
logger.info("does NOT exist already")
|
# logger.info("does NOT exist already")
|
||||||
return
|
# return
|
||||||
|
|
||||||
with open(self._data_file, "r") as f:
|
# with open(self._data_file, "r") as f:
|
||||||
data = json.load(f)
|
# data = json.load(f)
|
||||||
|
|
||||||
for field in fields(self):
|
# for field in fields(self):
|
||||||
value = data.get(field.name)
|
# value = data.get(field.name)
|
||||||
logger.info(f"testing {field.name} of {value}")
|
# logger.info(f"testing {field.name} of {value}")
|
||||||
if value is None:
|
# if value is None:
|
||||||
continue
|
# continue
|
||||||
|
|
||||||
# Translation: If the expected type is an Enum, convert the raw value back into an Enum member
|
# # 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):
|
# if isinstance(field.type, type) and issubclass(field.type, Enum):
|
||||||
logger.info("testing enum")
|
# logger.info("testing enum")
|
||||||
try:
|
# try:
|
||||||
value = field.type(value)
|
# value = field.type(value)
|
||||||
except ValueError:
|
# except ValueError:
|
||||||
logger.error(f"Invalid enum value {value} for {field.name}")
|
# logger.error(f"Invalid enum value {value} for {field.name}")
|
||||||
continue
|
# continue
|
||||||
|
|
||||||
# type check works because 'value' is now an actual Enum member
|
# # type check works because 'value' is now an actual Enum member
|
||||||
if isinstance(value, field.type):
|
# if isinstance(value, field.type):
|
||||||
setattr(self, field.name, value)
|
# setattr(self, field.name, value)
|
||||||
|
|
||||||
|
|
||||||
def wipe_data_on_disk(self):
|
# def wipe_data_on_disk(self):
|
||||||
logger.info("Starting wipe of pre-existing data")
|
# logger.info("Starting wipe of pre-existing data")
|
||||||
|
|
||||||
if not os.path.exists(self._data_file):
|
# if not os.path.exists(self._data_file):
|
||||||
logger.info("File does NOT exist already")
|
# logger.info("File does NOT exist already")
|
||||||
return
|
# return
|
||||||
|
|
||||||
return delete_file(self._data_file)
|
# return delete_file(self._data_file)
|
||||||
|
|
||||||
|
|
||||||
def exists_already(self) -> bool:
|
# def exists_already(self) -> bool:
|
||||||
return os.path.exists(self._data_file)
|
# return os.path.exists(self._data_file)
|
||||||
|
|
||||||
|
|
||||||
HOW_MANY_PROFILES_DEFAULT = 6
|
HOW_MANY_PROFILES_DEFAULT = 6
|
||||||
|
|
@ -177,13 +178,14 @@ class TicketPaymentData(StatePersistenceMixin):
|
||||||
def wipe(self):
|
def wipe(self):
|
||||||
"""Wipe all data and start over."""
|
"""Wipe all data and start over."""
|
||||||
wiped = self.wipe_data_on_disk()
|
wiped = self.wipe_data_on_disk()
|
||||||
|
logger.info(f"Wiped: {wiped}")
|
||||||
self.currency = None
|
self.currency = None
|
||||||
self.which_key = None
|
self.which_key = None
|
||||||
self.how_many_profiles = 6
|
self.how_many_profiles = 6
|
||||||
self.billing_code = None
|
self.billing_code = None
|
||||||
self.use_random = False
|
self.use_random = False
|
||||||
self.paid = False
|
self.paid = False
|
||||||
sefl.billing_pending = True
|
self.billing_pending = True
|
||||||
|
|
||||||
|
|
||||||
@singleton
|
@singleton
|
||||||
|
|
@ -218,6 +220,7 @@ class PaymentData(StatePersistenceMixin):
|
||||||
def wipe(self):
|
def wipe(self):
|
||||||
"""Wipe all data and start over."""
|
"""Wipe all data and start over."""
|
||||||
wiped = self.wipe_data_on_disk()
|
wiped = self.wipe_data_on_disk()
|
||||||
|
logger.info(f"Wiped: {wiped}")
|
||||||
self.currency = None
|
self.currency = None
|
||||||
self.payment_type = None
|
self.payment_type = None
|
||||||
self.plan_id = None
|
self.plan_id = None
|
||||||
|
|
|
||||||
|
|
@ -156,18 +156,22 @@ def enable_profile(
|
||||||
connection_result = establish_connection(profile, ignore=ignore, connection_observer=connection_observer)
|
connection_result = establish_connection(profile, ignore=ignore, connection_observer=connection_observer)
|
||||||
if not connection_result:
|
if not connection_result:
|
||||||
logger.error("Connection result is empty.")
|
logger.error("Connection result is empty.")
|
||||||
notification = "Connection Failed"
|
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
if not connection_result.valid:
|
logger.info(f"Exiting establish connection with {connection_result}")
|
||||||
return connection_result
|
|
||||||
|
|
||||||
if profile_observer is not None:
|
if connection_result.valid:
|
||||||
profile_observer.notify('enabled', profile)
|
# if profile_observer is not None:
|
||||||
notification = "Enabled."
|
# profile_observer.notify('enabled', profile)
|
||||||
|
|
||||||
|
Notifications.emit(EventType.SYSTEM_ENABLE, profile.id)
|
||||||
|
notification = "Connected."
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
return Result(valid=True, data=profile.type)
|
return Result(valid=True, data=profile.type)
|
||||||
|
|
||||||
|
else:
|
||||||
|
return connection_result
|
||||||
|
|
||||||
except FirewallError:
|
except FirewallError:
|
||||||
return Result(valid=False, error_type=ResultError.FIREWALL, message="Firewall Error.")
|
return Result(valid=False, error_type=ResultError.FIREWALL, message="Firewall Error.")
|
||||||
except ConnectionError as e:
|
except ConnectionError as e:
|
||||||
|
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
161
core/utils/singleton_state.py
Normal file
161
core/utils/singleton_state.py
Normal file
|
|
@ -0,0 +1,161 @@
|
||||||
|
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