Compare commits
3 commits
5d858a70ab
...
7390939291
| Author | SHA1 | Date | |
|---|---|---|---|
| 7390939291 | |||
| 62d2d15858 | |||
| 9ade83b454 |
11 changed files with 462 additions and 180 deletions
|
|
@ -2,6 +2,7 @@ from core.observers.Notifications import Notifications, EventType
|
||||||
from core.models.system.SystemState import SystemState
|
from core.models.system.SystemState import SystemState
|
||||||
from core.models.session.SessionState import SessionState
|
from core.models.session.SessionState import SessionState
|
||||||
from core.models.enum_models import ProtocolChoice
|
from core.models.enum_models import ProtocolChoice
|
||||||
|
from core.errors.logger import logger
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Optional, Dict
|
from typing import Optional, Dict
|
||||||
|
|
@ -70,7 +71,7 @@ class ProfileStateRepository:
|
||||||
if self.global_state.session_profiles[each_profile_id][ProcessType.ACTIVE] is True:
|
if self.global_state.session_profiles[each_profile_id][ProcessType.ACTIVE] is True:
|
||||||
active_list.append(each_profile_id)
|
active_list.append(each_profile_id)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
print(f"active doesn't exist yet for profile id {each_profile_id}")
|
# print(f"active doesn't exist yet for profile id {each_profile_id}.")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
return active_list
|
return active_list
|
||||||
|
|
@ -120,7 +121,7 @@ class ProfileStateRepository:
|
||||||
|
|
||||||
def setup_session_profile(self, profile_id: int) -> None:
|
def setup_session_profile(self, profile_id: int) -> None:
|
||||||
"""Ensures a session profile exists in the registry without overwriting existing processes."""
|
"""Ensures a session profile exists in the registry without overwriting existing processes."""
|
||||||
self.global_state.session_profiles.setdefault(profile_id, {})
|
self.global_state.session_profiles.setdefault(profile_id, {}).setdefault(ProcessType.ACTIVE, False)
|
||||||
|
|
||||||
|
|
||||||
def add_session_process(self, profile_id: int, process_type: ProcessType, process: subprocess.Popen|bool) -> None:
|
def add_session_process(self, profile_id: int, process_type: ProcessType, process: subprocess.Popen|bool) -> None:
|
||||||
|
|
@ -137,10 +138,15 @@ class ProfileStateRepository:
|
||||||
"""If it has all the pre-reqs, then it sets the status to on."""
|
"""If it has all the pre-reqs, then it sets the status to on."""
|
||||||
|
|
||||||
for each_type in LIST_OF_PROCESSES:
|
for each_type in LIST_OF_PROCESSES:
|
||||||
if self.global_state.session_profiles[profile_id][each_type] is None:
|
try:
|
||||||
print(f"Process is none for {each_type}")
|
if self.global_state.session_profiles[profile_id][each_type] is None:
|
||||||
|
print(f"Process is none for {each_type}")
|
||||||
|
return False
|
||||||
|
except KeyError:
|
||||||
|
logger.error(f"Missing the key {each_type}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
print("Global state is setting the session profile to activated")
|
print("Global state is setting the session profile to activated")
|
||||||
self.global_state.session_profiles[profile_id][ProcessType.ACTIVE] = True
|
self.global_state.session_profiles[profile_id][ProcessType.ACTIVE] = True
|
||||||
return True
|
return True
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ from functools import partial
|
||||||
@singleton
|
@singleton
|
||||||
@dataclass
|
@dataclass
|
||||||
class ConnectionRecovery(StatePersistenceMixin):
|
class ConnectionRecovery(StatePersistenceMixin):
|
||||||
PAYLOAD_FIELDS = {"prompted_for_port", "asked_to_change_wg_key", "mtu_initially_tested", "location_tested", "location_up"}
|
PAYLOAD_FIELDS = {"prompted_for_port", "asked_to_change_wg_key", "wg_key_changed", "mtu_initially_tested", "location_tested", "location_up", "port_changed_to"}
|
||||||
KEEP_FIELDS = ["parent_folder", "instance_id", "folder_path", "_data_file"]
|
KEEP_FIELDS = ["parent_folder", "instance_id", "folder_path", "_data_file"]
|
||||||
|
|
||||||
# metadata on it's own instance:
|
# metadata on it's own instance:
|
||||||
|
|
@ -26,19 +26,14 @@ class ConnectionRecovery(StatePersistenceMixin):
|
||||||
|
|
||||||
# PORT
|
# PORT
|
||||||
prompted_for_port: bool = False
|
prompted_for_port: bool = False
|
||||||
# port_changed: bool = False
|
port_changed_to: int = None
|
||||||
# port_changed_to: int|None = None
|
|
||||||
# port_change_worked: bool = False
|
|
||||||
|
|
||||||
# MTU
|
# MTU
|
||||||
mtu_initially_tested: bool = False
|
mtu_initially_tested: bool = False
|
||||||
# mtu_changed: bool = False
|
|
||||||
# asked_to_change_mtu: bool = False
|
|
||||||
|
|
||||||
# WG KEY
|
# WG KEY
|
||||||
asked_to_change_wg_key: bool = False
|
asked_to_change_wg_key: bool = False
|
||||||
# wg_key_confirmed: bool = False
|
wg_key_changed: bool = False
|
||||||
# wg_key_changed: bool = False
|
|
||||||
|
|
||||||
# Overall state
|
# Overall state
|
||||||
attempts: int = 0
|
attempts: int = 0
|
||||||
|
|
|
||||||
|
|
@ -1,34 +1,31 @@
|
||||||
from core.services.networking.api_requests.subtools.extract_domain import extract_domain
|
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.observers.Notifications import Notifications, EventType
|
||||||
from core.utils.run_commands import run_generic_command
|
from core.utils.run_commands import run_generic_command
|
||||||
|
|
||||||
# models
|
|
||||||
from core.models.Result import Result, ResultError
|
from core.models.Result import Result, ResultError
|
||||||
from core.services.networking.api_requests.ApiResponseModel import ApiResponse, ErrorType
|
|
||||||
|
|
||||||
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 core.observers.ConnectionObserver import ConnectionObserver
|
from core.observers.ConnectionObserver import ConnectionObserver
|
||||||
|
|
||||||
|
|
||||||
# generic
|
# generic
|
||||||
import time
|
import time
|
||||||
import random
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import httpx
|
import httpx
|
||||||
from httpx_socks import AsyncProxyTransport
|
|
||||||
import httpx_socks
|
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 socket
|
||||||
import multiprocessing
|
import multiprocessing
|
||||||
from threading import Thread
|
from threading import Thread, Event
|
||||||
from queue import Queue, Empty
|
from queue import Queue, Empty
|
||||||
|
|
||||||
|
# previously:
|
||||||
|
# from httpx_socks import AsyncProxyTransport
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
API_ENDPOINT_FORMATS = {
|
API_ENDPOINT_FORMATS = {
|
||||||
f"{Constants.SP_BASE_URL}/v2/get_ip": 'ip',
|
f"{Constants.SP_BASE_URL}/v2/get_ip": 'ip',
|
||||||
"https://api.ipify.org?format=json": "ip",
|
"https://api.ipify.org?format=json": "ip",
|
||||||
|
|
@ -51,13 +48,76 @@ def is_dns_problem_worker(url: str, queue: multiprocessing.Queue):
|
||||||
except Exception:
|
except Exception:
|
||||||
queue.put((url, True)) # Failed
|
queue.put((url, True)) # Failed
|
||||||
|
|
||||||
def test(connection_observer: Optional[ConnectionObserver], port: Optional[int] = None) -> Result:
|
|
||||||
|
async def attempt_request_async(url: str, port: Optional[int]) -> Optional[str]:
|
||||||
|
"""The async worker for a single request."""
|
||||||
|
# Configure proxy to use the server for the DNS lookup as well, if port is provided
|
||||||
|
proxy = f"socks5h://127.0.0.1:{port}" if port else None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# timeout=3.0 strictly enforces the read/connect timeout for DNS as well with 5h
|
||||||
|
async with httpx.AsyncClient(proxy=proxy, http2=False, timeout=3.0) as client:
|
||||||
|
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:
|
||||||
|
return ip_address
|
||||||
|
except Exception as e:
|
||||||
|
# the orchestrator handles the overall failure
|
||||||
|
logger.debug(f"Request to {url} failed: {e}")
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def async_test_orchestrator(endpoint_list, port, total_budget):
|
||||||
|
"""Test with async. Manages the race and ensures absolute cleanup."""
|
||||||
|
# Create tasks for all URLs
|
||||||
|
tasks = [asyncio.create_task(attempt_request_async(url, port)) for url in endpoint_list]
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Wait for the first task to complete OR the total budget to expire
|
||||||
|
done, pending = await asyncio.wait(
|
||||||
|
tasks,
|
||||||
|
timeout=total_budget,
|
||||||
|
return_when=asyncio.FIRST_COMPLETED
|
||||||
|
)
|
||||||
|
|
||||||
|
for task in done:
|
||||||
|
result = task.result()
|
||||||
|
if result:
|
||||||
|
# SUCCESS: We found an IP. Cancel everything else immediately.
|
||||||
|
for p in pending:
|
||||||
|
p.cancel()
|
||||||
|
|
||||||
|
# We await the cancellation of pending tasks
|
||||||
|
# to ensure sockets are closed before the loop shuts down.
|
||||||
|
await asyncio.gather(*pending, return_exceptions=True)
|
||||||
|
return Result(valid=True, data=result)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Orchestrator error: {e}")
|
||||||
|
finally:
|
||||||
|
# Cleanup any remaining tasks if we timed out or errored
|
||||||
|
for t in tasks:
|
||||||
|
if not t.done():
|
||||||
|
t.cancel()
|
||||||
|
await asyncio.gather(*tasks, return_exceptions=True)
|
||||||
|
|
||||||
|
return Result(valid=False, error_type=ResultError.CONNECTION, message="Could not connect.")
|
||||||
|
|
||||||
|
|
||||||
|
def test_with_threading(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 = 6.0
|
total_budget = 6.0
|
||||||
|
|
||||||
# 1. DNS PRE-FLIGHT (Using Processes, not Threads)
|
# Create a stop signal for the HTTP threads
|
||||||
|
stop_event = Event()
|
||||||
|
|
||||||
|
# 1. DNS PRE-FLIGHT
|
||||||
if port is None:
|
if port is None:
|
||||||
|
dns_start = time.time()
|
||||||
dns_queue = multiprocessing.Queue()
|
dns_queue = multiprocessing.Queue()
|
||||||
processes = []
|
processes = []
|
||||||
|
|
||||||
|
|
@ -70,10 +130,8 @@ def test(connection_observer: Optional[ConnectionObserver], port: Optional[int]
|
||||||
dns_timeout = 6
|
dns_timeout = 6
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Wait for the first successful resolution
|
while time.time() - dns_start < dns_timeout:
|
||||||
while time.time() - start_time < dns_timeout:
|
|
||||||
try:
|
try:
|
||||||
# Non-blocking check of the queue
|
|
||||||
url, is_problem = dns_queue.get(timeout=0.1)
|
url, is_problem = dns_queue.get(timeout=0.1)
|
||||||
if not is_problem:
|
if not is_problem:
|
||||||
any_resolved = True
|
any_resolved = True
|
||||||
|
|
@ -81,64 +139,87 @@ def test(connection_observer: Optional[ConnectionObserver], port: Optional[int]
|
||||||
except Empty:
|
except Empty:
|
||||||
continue
|
continue
|
||||||
finally:
|
finally:
|
||||||
# We kill every single process immediately.
|
|
||||||
# The OS kernel wipes them from memory regardless of where they are stuck.
|
|
||||||
for p in processes:
|
for p in processes:
|
||||||
p.terminate()
|
p.terminate()
|
||||||
p.join() # Clean up the zombie process entry
|
p.join()
|
||||||
|
|
||||||
if not any_resolved:
|
if not any_resolved:
|
||||||
logger.error("Aggressive DNS check failed: No internet.")
|
logger.error("Aggressive DNS check failed: No internet.")
|
||||||
return Result(valid=False, error_type=ResultError.CONNECTION, message="No internet connection.")
|
return Result(valid=False, error_type=ResultError.CONNECTION, message="No internet connection.")
|
||||||
|
|
||||||
# 2. HTTP REQUEST PHASE (Using Daemon Threads)
|
# 2. HTTP REQUEST PHASE
|
||||||
transport = None
|
http_start = time.time()
|
||||||
if port:
|
|
||||||
transport = httpx_socks.SyncProxyTransport(
|
|
||||||
proxy_type=ProxyType.SOCKS5,
|
|
||||||
proxy_host="127.0.0.1",
|
|
||||||
proxy_port=port,
|
|
||||||
)
|
|
||||||
|
|
||||||
# We use a Queue to get the first successful Result back from daemon threads
|
|
||||||
result_queue = Queue()
|
result_queue = Queue()
|
||||||
|
|
||||||
def attempt_request(url: str, index: int, client: httpx.Client):
|
def attempt_request(url: str, stop_sig: Event): # Pass the event here
|
||||||
|
transport = None
|
||||||
|
if port:
|
||||||
|
transport = httpx_socks.SyncProxyTransport(
|
||||||
|
proxy_type=ProxyType.SOCKS5,
|
||||||
|
proxy_host="127.0.0.1",
|
||||||
|
proxy_port=port,
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
raw_response = client.get(url)
|
# Check if we should even start
|
||||||
filtered_response = classify_response(raw_response)
|
if stop_sig.is_set():
|
||||||
if filtered_response.valid:
|
return
|
||||||
ip_address = extract_ip_from_response(response=filtered_response.data, api_url=url)
|
|
||||||
if ip_address:
|
with httpx.Client(transport=transport, http2=False, timeout=3.0) as client:
|
||||||
result_queue.put(Result(valid=True, data=ip_address))
|
raw_response = client.get(url)
|
||||||
|
|
||||||
|
# Check if main thread already found a winner while we were waiting for the network
|
||||||
|
if stop_sig.is_set():
|
||||||
return
|
return
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
with httpx.Client(transport=transport, http2=False, timeout=3.0) as client:
|
filtered_response = classify_response(raw_response)
|
||||||
for i, url in enumerate(endpoint_list):
|
if filtered_response.valid:
|
||||||
# daemon=True is CRITICAL.
|
ip_address = extract_ip_from_response(response=filtered_response.data, api_url=url)
|
||||||
# It tells Python: "If the main program exits, kill this thread immediately."
|
if ip_address:
|
||||||
t = Thread(target=attempt_request, args=(url, i, client), daemon=True)
|
logger.info("returning true in the que")
|
||||||
t.start()
|
result_queue.put(Result(valid=True, data=ip_address))
|
||||||
|
except Exception as e:
|
||||||
|
# ONLY log if the main function is still waiting for a result
|
||||||
|
if not stop_sig.is_set():
|
||||||
|
logger.debug(f"Request to {url} failed: {e}")
|
||||||
|
|
||||||
# Wait for the first success or the remaining budget
|
for url in endpoint_list:
|
||||||
while True:
|
# Pass the stop_event to the thread
|
||||||
elapsed = time.time() - start_time
|
t = Thread(target=attempt_request, args=(url, stop_event), daemon=True)
|
||||||
remaining = total_budget - elapsed
|
t.start()
|
||||||
if remaining <= 0:
|
|
||||||
break
|
|
||||||
|
|
||||||
try:
|
# Wait for the first success or the budget
|
||||||
# Block for the remaining budget
|
while True:
|
||||||
return result_queue.get(timeout=remaining)
|
elapsed = time.time() - http_start
|
||||||
except Empty:
|
remaining = total_budget - elapsed
|
||||||
break
|
if remaining <= 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
try:
|
||||||
|
res = result_queue.get(timeout=remaining)
|
||||||
|
stop_event.set() # <--- SIGNAL ALL OTHER THREADS TO STOP LOGGING/PROCESSING
|
||||||
|
logger.info("returning true")
|
||||||
|
return res
|
||||||
|
except Empty:
|
||||||
|
break
|
||||||
|
|
||||||
|
stop_event.set() # Signal stop even on failure
|
||||||
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.")
|
||||||
|
|
||||||
|
|
||||||
|
def test(connection_observer: Optional[ConnectionObserver], port: Optional[int] = None) -> Result:
|
||||||
|
endpoint_list = list(API_ENDPOINT_FORMATS.keys())[:MAX_ATTEMPTS]
|
||||||
|
total_budget = 6.0
|
||||||
|
|
||||||
|
# with a proxy:
|
||||||
|
if port:
|
||||||
|
return asyncio.run(async_test_orchestrator(endpoint_list, port, total_budget))
|
||||||
|
|
||||||
|
# without systemwide:
|
||||||
|
return test_with_threading(connection_observer=connection_observer)
|
||||||
|
|
||||||
|
|
||||||
def extract_ip_from_response(response: dict, api_url: str) -> str | bool:
|
def extract_ip_from_response(response: dict, api_url: str) -> str | bool:
|
||||||
"""
|
"""
|
||||||
Purpose:
|
Purpose:
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ from core.services.networking.general_connection_tools.test_internet import test
|
||||||
from core.services.networking.general_connection_tools.ip import ping_ip
|
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.observers.Notifications import Notifications, EventType
|
||||||
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
|
||||||
from core.models.BaseProfile import BaseProfile as Profile
|
from core.models.BaseProfile import BaseProfile as Profile
|
||||||
from core.models.BaseProfile import ProfileType
|
from core.models.BaseProfile import ProfileType
|
||||||
|
|
@ -29,6 +30,9 @@ def get_profile_ip(profile_id: int, protocol: ProtocolChoice, profile_type: Prof
|
||||||
@type_checker
|
@type_checker
|
||||||
def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObserver) -> Result:
|
def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObserver) -> Result:
|
||||||
|
|
||||||
|
# ------------------------------------
|
||||||
|
# PRE-REQ FILTER:
|
||||||
|
# ------------------------------------
|
||||||
profile_id = profile.id
|
profile_id = profile.id
|
||||||
location_id = profile.location.id
|
location_id = profile.location.id
|
||||||
location_name = profile.location.country_name
|
location_name = profile.location.country_name
|
||||||
|
|
@ -44,25 +48,39 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs
|
||||||
protocol: {protocol}
|
protocol: {protocol}
|
||||||
""")
|
""")
|
||||||
|
|
||||||
|
# ------------------------------------
|
||||||
|
# BASIC INTERNET
|
||||||
|
# ------------------------------------
|
||||||
|
do_we_have_internet = test_internet()
|
||||||
|
print(f"Do you have the internet? {do_we_have_internet}")
|
||||||
|
|
||||||
|
if not do_we_have_internet:
|
||||||
|
error_msg = "Basic Internet Connection Issues"
|
||||||
|
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NO_INTERNET, message=error_msg)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------
|
||||||
|
# PING
|
||||||
|
# ------------------------------------
|
||||||
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 not ip_address:
|
||||||
ping_result = ping_ip(ip_address)
|
error_msg = "Can't extract IP address from config."
|
||||||
can_be_pinged = ping_result.valid
|
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.RENEGOTIATION, message=error_msg)
|
||||||
print(f"Can {location_name} be pinged? {can_be_pinged}")
|
|
||||||
else:
|
ping_result = ping_ip(ip_address)
|
||||||
logger.error("Skipping IP Address Test.")
|
can_be_pinged = ping_result.valid
|
||||||
can_be_pinged = False
|
print(f"Can {location_name} be pinged? {can_be_pinged}")
|
||||||
|
|
||||||
if not can_be_pinged:
|
if not can_be_pinged:
|
||||||
do_we_have_internet = test_internet()
|
error_msg = f"The {location_name} node can't be pinged. We are assuming this is currently down."
|
||||||
print(f"Do you have the internet? {do_we_have_internet}")
|
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NODE_ERROR, message=error_msg)
|
||||||
|
|
||||||
if not do_we_have_internet:
|
|
||||||
error_msg = "Basic Internet Connection Issues"
|
|
||||||
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NO_INTERNET, message=error_msg)
|
|
||||||
|
|
||||||
# Now check vs official API:
|
# ------------------------------------
|
||||||
|
# CHECK VS API
|
||||||
|
# ------------------------------------
|
||||||
|
# Now check against the official API:
|
||||||
url = f'{Constants.SP_BASE_URL}/v2/check_location'
|
url = f'{Constants.SP_BASE_URL}/v2/check_location'
|
||||||
payload = {
|
payload = {
|
||||||
'location_id': str(location_id)
|
'location_id': str(location_id)
|
||||||
|
|
@ -76,8 +94,8 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs
|
||||||
payload=payload
|
payload=payload
|
||||||
)
|
)
|
||||||
|
|
||||||
if not result.valid and not can_be_pinged:
|
if not result.valid:
|
||||||
error_msg = "Can't ping the VPN node or even reach the API. Your connection is unstable."
|
error_msg = "Can't even reach the API to check if the node is up. Your connection is unstable."
|
||||||
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NO_INTERNET, message=error_msg)
|
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NO_INTERNET, message=error_msg)
|
||||||
|
|
||||||
location_up = result.data
|
location_up = result.data
|
||||||
|
|
@ -87,3 +105,34 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs
|
||||||
else:
|
else:
|
||||||
error_msg = f"The {location_name} node is currently down."
|
error_msg = f"The {location_name} node is currently down."
|
||||||
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NODE_ERROR, message=error_msg)
|
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NODE_ERROR, message=error_msg)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_location_and_internet(profile: Profile, connection_observer: ConnectionObserver) -> Result:
|
||||||
|
"""Provides a Public API & Notifications, to check if a location is up and return the backoff strategy."""
|
||||||
|
|
||||||
|
notification = "Checking If Location is Up.."
|
||||||
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
|
logger.info(notification)
|
||||||
|
|
||||||
|
location_result = check_if_location_is_up(profile=profile, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
if location_result.valid:
|
||||||
|
notification = "Location check passed. Retrying immediately..."
|
||||||
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
|
logger.info(notification)
|
||||||
|
return location_result
|
||||||
|
|
||||||
|
elif location_result.backoff_strategy == BackoffStrategy.RETRY_IMMEDIATE:
|
||||||
|
Notifications.emit(EventType.STATUS_UPDATE, "Retrying after Location Check")
|
||||||
|
|
||||||
|
#============== NO RETRY #==============
|
||||||
|
elif 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
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,47 @@
|
||||||
|
from core.models.ConnectionRecovery import ConnectionRecovery
|
||||||
|
from core.observers.Notifications import Notifications, EventType
|
||||||
|
from core.models.Result import Result, ResultError
|
||||||
|
from core.errors.logger import logger
|
||||||
|
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
def just_reconnect(profile_id: int) -> Result:
|
||||||
|
print(f"Reconnecting profile_id {profile_id}..")
|
||||||
|
return Result(valid=True, double_dip=True, error_type=ResultError.RECONNECT)
|
||||||
|
|
||||||
|
|
||||||
|
def wipe_attempts_and_reconnect(recovery_stats: ConnectionRecovery)-> Result:
|
||||||
|
"""Wipe pre-existing recovery attempts and solutions. And begin fresh."""
|
||||||
|
|
||||||
|
profile_id = recovery_stats.instance_id
|
||||||
|
|
||||||
|
if not profile_id:
|
||||||
|
return Result(valid=False, error_type=ResultError.MISSING_DATA, message="There should have been an instance id to wipe the recovery_stats")
|
||||||
|
|
||||||
|
recovery_stats.wipe()
|
||||||
|
|
||||||
|
notification = "Starting Recovery Fresh"
|
||||||
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
|
logger.info(notification)
|
||||||
|
|
||||||
|
return just_reconnect(profile_id)
|
||||||
|
|
||||||
|
|
||||||
|
def bypass_attempts_and_reconnect(recovery_stats: ConnectionRecovery)-> Result:
|
||||||
|
"""Sets the recovery stats to ignore that it's already asked all the options, and just connect anyway."""
|
||||||
|
|
||||||
|
profile_id = recovery_stats.instance_id
|
||||||
|
|
||||||
|
if not profile_id:
|
||||||
|
return Result(valid=False, error_type=ResultError.MISSING_DATA, message="There should have been an instance id to wipe the recovery_stats")
|
||||||
|
|
||||||
|
recovery_stats.bypass_attempts = True
|
||||||
|
return just_reconnect(profile_id)
|
||||||
|
|
||||||
|
|
||||||
|
def offer_recovery_options(recovery_stats: ConnectionRecovery)-> Result:
|
||||||
|
"""Ask the end-user if they wish to restart their recovery options, or just proceed without them"""
|
||||||
|
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_and_reconnect, recovery_stats=recovery_stats)
|
||||||
|
bypass_choice = partial(bypass_attempts_and_reconnect, recovery_stats=recovery_stats)
|
||||||
|
return Result(valid=False, function_choice=yes_choice, no_option=bypass_choice, error_type=ResultError.ATTEMPTS, message=error_msg)
|
||||||
43
core/services/networking/ports/port_change.py
Normal file
43
core/services/networking/ports/port_change.py
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
from core.services.networking.general_connection_tools.recovery_tools import just_reconnect
|
||||||
|
from core.services.networking.ports.port_orchestrator import change_wg_port
|
||||||
|
from core.models.BaseProfile import BaseProfile as Profile
|
||||||
|
from core.observers.Notifications import Notifications, EventType
|
||||||
|
from core.errors.logger import logger
|
||||||
|
from core.models.Result import Result, ResultError
|
||||||
|
|
||||||
|
from typing import Callable
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
def change_port_then_reconnect(
|
||||||
|
profile: Profile,
|
||||||
|
profile_id: int # it's redundant, but it's for the reconnect's inputs
|
||||||
|
) -> Result:
|
||||||
|
"""
|
||||||
|
Changes the Wireguard config port,
|
||||||
|
and then reconnects using the original function as a pre-loaded partial
|
||||||
|
"""
|
||||||
|
|
||||||
|
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 Result(valid=True, double_dip=True, error_type=ResultError.RECONNECT)
|
||||||
|
|
||||||
|
|
||||||
|
def ask_to_change_port(profile: Profile) -> Result:
|
||||||
|
logger.info("We should ask to try to change port")
|
||||||
|
|
||||||
|
# Offer the choice to the end user:
|
||||||
|
message = "Failed to connect. Do you want to try to change the Wireguard port?"
|
||||||
|
yes_choice = partial(change_port_then_reconnect, profile=profile)
|
||||||
|
no_option = partial(just_reconnect, profile_id=profile.id)
|
||||||
|
return Result(valid=False, function_choice=yes_choice, no_option=no_option, error_type=ResultError.PORT, message=message)
|
||||||
|
|
@ -127,28 +127,3 @@ def ask_to_change_port(recovery_stats: ConnectionRecovery) -> bool:
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# if not ConfigurationController.do_we_allow_port_prompts():
|
|
||||||
# logger.info("We do not allow port changes")
|
|
||||||
# return True
|
|
||||||
|
|
||||||
# state_repo = ProfileStateRepository()
|
|
||||||
# if state_repo.global_state.changed_port:
|
|
||||||
# return
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# 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,3 +1,10 @@
|
||||||
|
from core.services.networking.general_connection_tools.recovery_tools import just_reconnect, offer_recovery_options
|
||||||
|
from core.observers.Notifications import Notifications, EventType
|
||||||
|
from core.services.networking.api_requests.ApiResponseModel import BackoffStrategy
|
||||||
|
from core.services.networking.general_connection_tools.location_evaluation import evaluate_location_and_internet
|
||||||
|
from core.services.networking.wireguard.renegotation import renegotiate_and_reconnect
|
||||||
|
from core.services.networking.ports.port_change import ask_to_change_port
|
||||||
|
from core.models.ConnectionRecovery import ConnectionRecovery
|
||||||
from core.services.networking.session.tor_session import start_tor_session_networking
|
from core.services.networking.session.tor_session import start_tor_session_networking
|
||||||
from essentials.services.ConnectionService import ConnectionService
|
from essentials.services.ConnectionService import ConnectionService
|
||||||
from core.services.keys_and_verifications.endpoint_verification import verify_wireguard_endpoint
|
from core.services.keys_and_verifications.endpoint_verification import verify_wireguard_endpoint
|
||||||
|
|
@ -16,6 +23,7 @@ import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import tempfile
|
import tempfile
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
|
||||||
def start_wireproxy(profile: SessionProfile, session_directory: str, port_number: int) -> Result:
|
def start_wireproxy(profile: SessionProfile, session_directory: str, port_number: int) -> Result:
|
||||||
|
|
@ -43,8 +51,27 @@ def start_session_networking(
|
||||||
connection_observer: Optional[ConnectionObserver] = None
|
connection_observer: Optional[ConnectionObserver] = None
|
||||||
) -> Result:
|
) -> Result:
|
||||||
|
|
||||||
|
# =================================
|
||||||
|
# LOOP MANAGEMENT
|
||||||
|
# =================================
|
||||||
|
recovery_stats = ConnectionRecovery(instance_id=profile.id)
|
||||||
|
no_option = partial(just_reconnect, profile_id=profile.id)
|
||||||
|
|
||||||
|
# already exhausted options, do they want to restart?
|
||||||
|
if recovery_stats.reached_end_of_loop and not recovery_stats.bypass_attempts:
|
||||||
|
return offer_recovery_options(recovery_stats)
|
||||||
|
|
||||||
|
# if they bypass the wipe, its a one-time thing:
|
||||||
|
if recovery_stats.bypass_attempts:
|
||||||
|
recovery_stats.bypass_attempts = False
|
||||||
|
|
||||||
|
recovery_stats.attempts += 1
|
||||||
|
current_try = recovery_stats.attempts
|
||||||
|
|
||||||
|
# =================================
|
||||||
|
# PREPARE PRE-REQS
|
||||||
|
# =================================
|
||||||
protocol = ProtocolChoice(profile.connection.code)
|
protocol = ProtocolChoice(profile.connection.code)
|
||||||
print(f"protocol is {protocol}")
|
|
||||||
|
|
||||||
session_directory = tempfile.mkdtemp(prefix='hv-')
|
session_directory = tempfile.mkdtemp(prefix='hv-')
|
||||||
session_state = SessionStateController.get_or_new(profile.id)
|
session_state = SessionStateController.get_or_new(profile.id)
|
||||||
|
|
@ -53,34 +80,37 @@ def start_session_networking(
|
||||||
proxy_port_number = None
|
proxy_port_number = None
|
||||||
|
|
||||||
port_number = ConnectionService.get_random_available_port_number()
|
port_number = ConnectionService.get_random_available_port_number()
|
||||||
print(f"Openning on port {port_number}")
|
|
||||||
|
|
||||||
#--------------------------------
|
notification = f"Connecting with try {current_try} on local port {port_number}"
|
||||||
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
|
print(notification)
|
||||||
|
|
||||||
|
# =================================
|
||||||
# TOR
|
# TOR
|
||||||
#--------------------------------
|
# =================================
|
||||||
if protocol == ProtocolChoice.TOR:
|
if protocol == ProtocolChoice.TOR:
|
||||||
print("Passing off to ConnectionController's Tor system")
|
print("Passing off to ConnectionController's Tor system")
|
||||||
return start_tor_session_networking(port_number=port_number, session_directory=session_directory, session_state=session_state, profile=profile, ignore=ignore, connection_observer=connection_observer)
|
return start_tor_session_networking(port_number=port_number, session_directory=session_directory, session_state=session_state, profile=profile, ignore=ignore, connection_observer=connection_observer)
|
||||||
|
|
||||||
#--------------------------------
|
# =================================
|
||||||
# WIREGUARD
|
# WIREGUARD
|
||||||
#--------------------------------
|
# =================================
|
||||||
elif protocol == ProtocolChoice.WIREGUARD:
|
elif protocol == ProtocolChoice.WIREGUARD:
|
||||||
|
|
||||||
# Verification
|
# Verification
|
||||||
if ConfigurationController.get_endpoint_verification_enabled():
|
if ConfigurationController.get_endpoint_verification_enabled():
|
||||||
verify_wireguard_endpoint(profile, ignore=ignore)
|
verify_wireguard_endpoint(profile, ignore=ignore)
|
||||||
|
|
||||||
connection_result = start_wireproxy(profile, session_directory, port_number)
|
started_process = start_wireproxy(profile, session_directory, port_number)
|
||||||
session_state.network_port_numbers.wireguard.append(port_number)
|
session_state.network_port_numbers.wireguard.append(port_number)
|
||||||
|
|
||||||
#--------------------------------
|
# =================================
|
||||||
# ALL CONNECTIONS
|
# EVALUATE
|
||||||
#--------------------------------
|
# =================================
|
||||||
if not connection_result.valid:
|
if not started_process.valid:
|
||||||
return connection_result.wrap("Unable to start the network connection.")
|
return started_process.wrap("Unable to even start the network connection.")
|
||||||
|
|
||||||
network_process = connection_result.data
|
network_process = started_process.data
|
||||||
|
|
||||||
# sanity check for all networking processes:
|
# sanity check for all networking processes:
|
||||||
if not network_process:
|
if not network_process:
|
||||||
|
|
@ -89,53 +119,76 @@ def start_session_networking(
|
||||||
# Test:
|
# Test:
|
||||||
print("Testing IP..")
|
print("Testing IP..")
|
||||||
test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=protocol, connection_observer=connection_observer)
|
test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=protocol, connection_observer=connection_observer)
|
||||||
if not test_result.valid:
|
|
||||||
error_msg = "Test shows IP is not valid."
|
|
||||||
logger.error(error_msg)
|
|
||||||
network_process.kill()
|
|
||||||
logger.info("Killed process")
|
|
||||||
|
|
||||||
return test_result.wrap(error_msg)
|
# =================================
|
||||||
|
# SUCCESS
|
||||||
|
# =================================
|
||||||
|
if test_result.valid:
|
||||||
|
logger.info("Connection worked. Wiping recovery stats")
|
||||||
|
|
||||||
# Update in memory repo,
|
# wipe failure tracker:
|
||||||
SessionStateController.update_or_create(session_state)
|
recovery_stats.wipe()
|
||||||
SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
|
|
||||||
|
|
||||||
final_port = proxy_port_number or port_number
|
# Update in memory repo,
|
||||||
return Result(valid=True, data=final_port)
|
logger.info("Updating in memory repo")
|
||||||
|
SessionStateController.update_or_create(session_state)
|
||||||
|
SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
|
||||||
|
|
||||||
|
final_port = proxy_port_number or port_number
|
||||||
|
print(f"returning the final port of {final_port}")
|
||||||
|
return Result(valid=True, data=final_port)
|
||||||
|
|
||||||
# def kill_session_networking(profile_id: int) -> Result:
|
#--------------------------------
|
||||||
# SessionStateController.kill_session_process(profile_id=profile_id, process_type=ProcessType.NETWORK)
|
# START FAILURE TESTING.
|
||||||
# return Result(valid=True)
|
#--------------------------------
|
||||||
|
error_msg = "Test shows IP is not valid."
|
||||||
|
logger.error(error_msg)
|
||||||
|
network_process.kill()
|
||||||
|
logger.info("Killed process")
|
||||||
|
|
||||||
|
# =================================
|
||||||
|
# ATTEMPT ONE: LOCATION UP?
|
||||||
|
# =================================
|
||||||
|
if not recovery_stats.location_tested:
|
||||||
|
# First failure: Evaluate Location and Internet without connection,
|
||||||
|
location_result = evaluate_location_and_internet(
|
||||||
|
profile=profile,
|
||||||
|
connection_observer=connection_observer
|
||||||
|
)
|
||||||
|
recovery_stats.location_tested = True
|
||||||
|
|
||||||
# # if not profile.connection.is_unprotected():
|
#============== NO RETRY #==============
|
||||||
|
if location_result.backoff_strategy == BackoffStrategy.NO_RETRY:
|
||||||
|
recovery_stats.location_up = False
|
||||||
|
return location_result
|
||||||
|
|
||||||
# if profile.connection.code == 'wireguard':
|
#============== NO SEEMS FINE #==============
|
||||||
# test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=ProtocolChoice.WIREGUARD, connection_observer=connection_observer)
|
recovery_stats.location_up = True
|
||||||
# if test_result.valid:
|
return no_option() # Proceed to attempt 2
|
||||||
# logger.info("Connection established.")
|
|
||||||
# if connection_observer:
|
|
||||||
# connection_observer.notify("connected", "Confirmed")
|
|
||||||
# else:
|
|
||||||
# logger.error(test_result.message)
|
|
||||||
# return test_result.wrap("Unable to connect in ConnectionController.")
|
|
||||||
|
|
||||||
# elif profile.connection.code == 'tor':
|
# =================================
|
||||||
# await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
|
# PORT
|
||||||
|
# =================================
|
||||||
|
logger.info(f"entering port question with recovery_stats.prompted_for_port {recovery_stats.prompted_for_port}")
|
||||||
|
if protocol == ProtocolChoice.WIREGUARD and not recovery_stats.prompted_for_port:
|
||||||
|
recovery_stats.prompted_for_port = True
|
||||||
|
return ask_to_change_port(profile=profile)
|
||||||
|
|
||||||
|
logger.info(f"Skipping port choice as an offer. recovery_stats.asked_to_change_wg_key is {recovery_stats.asked_to_change_wg_key}")
|
||||||
|
|
||||||
|
# =================================
|
||||||
|
# WIREGUARD RENEGOTIATION
|
||||||
|
# =================================
|
||||||
|
if protocol == ProtocolChoice.WIREGUARD and not recovery_stats.asked_to_change_wg_key:
|
||||||
|
logger.info("Asking to change WG key..")
|
||||||
|
recovery_stats.asked_to_change_wg_key = True
|
||||||
|
yes_option = partial(renegotiate_and_reconnect, profile=profile, connection_observer=connection_observer)
|
||||||
|
print("made partial")
|
||||||
|
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.)")
|
||||||
|
|
||||||
|
# =================================
|
||||||
|
# CONCLUDE FAILURE
|
||||||
|
# =================================
|
||||||
|
logger.info("entering final loop")
|
||||||
# this is a check from SessionConnection of if there's a systemwide with mask
|
recovery_stats.reached_end_of_loop = True
|
||||||
# if profile.connection.is_unprotected():
|
return test_result.wrap("End of session networking loop.")
|
||||||
# if not system_uses_wireguard_interface() and not ConnectionUnprotectedError in ignore:
|
|
||||||
# error_msg = 'Connection unprotected while the system is not using a WireGuard interface.'
|
|
||||||
# logger.error(error_msg)
|
|
||||||
# return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg)
|
|
||||||
# # from core.services.profiles.profile_connections import disable_profile
|
|
||||||
# # disable_profile(profile=profile, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ from core.services.networking.mtu.mtu_orchestrator import passed_initial_mtu_scr
|
||||||
# from core.services.keys_and_verifications.wireguard_keys import get_mtu
|
# from core.services.keys_and_verifications.wireguard_keys import get_mtu
|
||||||
from core.models.BaseProfile import BaseProfile as Profile
|
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 evaluate_location_and_internet
|
||||||
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
|
||||||
from core.controllers.profile_state.get_profile_data import get_protocol_enum
|
from core.controllers.profile_state.get_profile_data import get_protocol_enum
|
||||||
|
|
@ -235,18 +235,18 @@ def change_port_then_reconnect(
|
||||||
# return message
|
# return message
|
||||||
|
|
||||||
|
|
||||||
def evaluate_location_and_internet(profile: SystemProfile, connection_observer: ConnectionObserver) -> Result:
|
# def evaluate_location_and_internet(profile: SystemProfile, connection_observer: ConnectionObserver) -> Result:
|
||||||
"""Checks if location is up and returns the backoff strategy."""
|
# """Checks if location is up and returns the backoff strategy."""
|
||||||
notification = "Checking If Location is Up.."
|
# notification = "Checking If Location is Up.."
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
# Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
logger.info(notification)
|
# logger.info(notification)
|
||||||
|
|
||||||
location_result = check_if_location_is_up(profile=profile, connection_observer=connection_observer)
|
# location_result = check_if_location_is_up(profile=profile, connection_observer=connection_observer)
|
||||||
|
|
||||||
if location_result.backoff_strategy == BackoffStrategy.RETRY_IMMEDIATE:
|
# if location_result.backoff_strategy == BackoffStrategy.RETRY_IMMEDIATE:
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, "Retrying after Location Check")
|
# Notifications.emit(EventType.STATUS_UPDATE, "Retrying after Location Check")
|
||||||
|
|
||||||
return location_result
|
# return location_result
|
||||||
|
|
||||||
|
|
||||||
def _finish_success(final_result: Result, profile_id: int) -> Result:
|
def _finish_success(final_result: Result, profile_id: int) -> Result:
|
||||||
|
|
@ -477,25 +477,23 @@ def establish_system_connection(
|
||||||
#============== NO RETRY #==============
|
#============== NO RETRY #==============
|
||||||
if location_result.backoff_strategy == BackoffStrategy.NO_RETRY:
|
if location_result.backoff_strategy == BackoffStrategy.NO_RETRY:
|
||||||
recovery_stats.location_up = False
|
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
|
||||||
|
|
||||||
#============== NO SEEMS FINE #==============
|
#============== NO SEEMS FINE #==============
|
||||||
notification = "Location check passed. Retrying immediately..."
|
# notification = "Location check passed. Retrying immediately..."
|
||||||
recovery_stats.location_up = True
|
recovery_stats.location_up = True
|
||||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
# Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
logger.info(notification)
|
# logger.info(notification)
|
||||||
return no_option() # Proceed to attempt 2
|
return no_option() # Proceed to attempt 2
|
||||||
|
|
||||||
# =================================
|
# =================================
|
||||||
# ATTEMPT 2+ MTU, PORT, WG KEY
|
# ATTEMPT 2+ MTU, PORT, WG KEY
|
||||||
# =================================
|
# =================================
|
||||||
# the function packages itself, for multiple callback situations:
|
|
||||||
# no_option = partial(establish_system_connection, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
|
||||||
|
|
||||||
# Connection is still On for MTU testing:
|
# Connection is still On for MTU testing:
|
||||||
|
|
||||||
|
|
|
||||||
32
core/services/networking/wireguard/renegotation.py
Normal file
32
core/services/networking/wireguard/renegotation.py
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
from core.services.keys_and_verifications.wireguard_keys import register_wireguard_session
|
||||||
|
from core.models.BaseProfile import BaseProfile as Profile
|
||||||
|
from core.observers.Notifications import Notifications, EventType
|
||||||
|
from core.errors.logger import logger
|
||||||
|
from core.models.Result import Result, ResultError
|
||||||
|
from core.models.ConnectionRecovery import ConnectionRecovery
|
||||||
|
from core.observers.ConnectionObserver import ConnectionObserver
|
||||||
|
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
|
||||||
|
def renegotiate_and_reconnect(
|
||||||
|
profile: Profile,
|
||||||
|
connection_observer: ConnectionObserver
|
||||||
|
) -> 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 Result(valid=True, double_dip=True, error_type=ResultError.RECONNECT)
|
||||||
|
|
@ -108,6 +108,7 @@ def enable_session_profile(
|
||||||
#-----------------------------------
|
#-----------------------------------
|
||||||
try:
|
try:
|
||||||
network_result = start_session_networking(profile, ignore=ignore, connection_observer=connection_observer)
|
network_result = start_session_networking(profile, ignore=ignore, connection_observer=connection_observer)
|
||||||
|
print("Completed networking")
|
||||||
except EndpointVerificationError:
|
except EndpointVerificationError:
|
||||||
return Result(valid=False, error_type=ResultError.ENDPOINT_VERIFICATION, message=f"Verification of the endpoint failed for profile {profile.id}")
|
return Result(valid=False, error_type=ResultError.ENDPOINT_VERIFICATION, message=f"Verification of the endpoint failed for profile {profile.id}")
|
||||||
|
|
||||||
|
|
@ -115,6 +116,7 @@ def enable_session_profile(
|
||||||
return network_result.wrap("Failed to start the session profile")
|
return network_result.wrap("Failed to start the session profile")
|
||||||
|
|
||||||
port_number = network_result.data
|
port_number = network_result.data
|
||||||
|
logger.info(f"Networking was successfull, launching the app with network port {port_number}")
|
||||||
|
|
||||||
#-----------------------------------
|
#-----------------------------------
|
||||||
# LAUNCH APPLICATION & GRAPHICAL
|
# LAUNCH APPLICATION & GRAPHICAL
|
||||||
|
|
@ -127,6 +129,7 @@ def enable_session_profile(
|
||||||
if not launched.valid:
|
if not launched.valid:
|
||||||
return launched.wrap("failed to launch the app")
|
return launched.wrap("failed to launch the app")
|
||||||
|
|
||||||
|
logger.info("It worked. Returning to the UI")
|
||||||
return Result(valid=True, data=profile.type)
|
return Result(valid=True, data=profile.type)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue