Compare commits

..

No commits in common. "7390939291cfeae3ddffa08d59d813bd9dbcd066" and "5d858a70ab35091a30f8583ab4509cacc58f639b" have entirely different histories.

11 changed files with 178 additions and 460 deletions

View file

@ -2,7 +2,6 @@ from core.observers.Notifications import Notifications, EventType
from core.models.system.SystemState import SystemState
from core.models.session.SessionState import SessionState
from core.models.enum_models import ProtocolChoice
from core.errors.logger import logger
from dataclasses import dataclass, field
from typing import Optional, Dict
@ -71,7 +70,7 @@ class ProfileStateRepository:
if self.global_state.session_profiles[each_profile_id][ProcessType.ACTIVE] is True:
active_list.append(each_profile_id)
except KeyError:
# print(f"active doesn't exist yet for profile id {each_profile_id}.")
print(f"active doesn't exist yet for profile id {each_profile_id}")
continue
return active_list
@ -121,7 +120,7 @@ class ProfileStateRepository:
def setup_session_profile(self, profile_id: int) -> None:
"""Ensures a session profile exists in the registry without overwriting existing processes."""
self.global_state.session_profiles.setdefault(profile_id, {}).setdefault(ProcessType.ACTIVE, False)
self.global_state.session_profiles.setdefault(profile_id, {})
def add_session_process(self, profile_id: int, process_type: ProcessType, process: subprocess.Popen|bool) -> None:
@ -138,14 +137,9 @@ class ProfileStateRepository:
"""If it has all the pre-reqs, then it sets the status to on."""
for each_type in LIST_OF_PROCESSES:
try:
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
print("Global state is setting the session profile to activated")
self.global_state.session_profiles[profile_id][ProcessType.ACTIVE] = True

View file

@ -9,7 +9,7 @@ from functools import partial
@singleton
@dataclass
class ConnectionRecovery(StatePersistenceMixin):
PAYLOAD_FIELDS = {"prompted_for_port", "asked_to_change_wg_key", "wg_key_changed", "mtu_initially_tested", "location_tested", "location_up", "port_changed_to"}
PAYLOAD_FIELDS = {"prompted_for_port", "asked_to_change_wg_key", "mtu_initially_tested", "location_tested", "location_up"}
KEEP_FIELDS = ["parent_folder", "instance_id", "folder_path", "_data_file"]
# metadata on it's own instance:
@ -26,14 +26,19 @@ class ConnectionRecovery(StatePersistenceMixin):
# PORT
prompted_for_port: bool = False
port_changed_to: int = None
# port_changed: bool = False
# port_changed_to: int|None = None
# port_change_worked: bool = False
# MTU
mtu_initially_tested: bool = False
# mtu_changed: bool = False
# asked_to_change_mtu: bool = False
# WG KEY
asked_to_change_wg_key: bool = False
wg_key_changed: bool = False
# wg_key_confirmed: bool = False
# wg_key_changed: bool = False
# Overall state
attempts: int = 0

View file

@ -1,31 +1,34 @@
from core.services.networking.api_requests.subtools.extract_domain import extract_domain
from core.services.networking.httpx.classify_response import classify_response
from core.observers.Notifications import Notifications, EventType
from core.utils.run_commands import run_generic_command
# models
from core.models.Result import Result, ResultError
from core.services.networking.api_requests.ApiResponseModel import ApiResponse, ErrorType
from core.Constants import Constants
from core.errors.logger import logger
# from essentials.observers.ConnectionObserver import ConnectionObserver
from core.observers.ConnectionObserver import ConnectionObserver
# generic
import time
import random
import asyncio
import httpx
from httpx_socks import AsyncProxyTransport
import httpx_socks
from httpx_socks import ProxyType
import subprocess
from typing import Optional
import socket
import multiprocessing
from threading import Thread, Event
from threading import Thread
from queue import Queue, Empty
# previously:
# from httpx_socks import AsyncProxyTransport
API_ENDPOINT_FORMATS = {
f"{Constants.SP_BASE_URL}/v2/get_ip": 'ip',
"https://api.ipify.org?format=json": "ip",
@ -48,76 +51,13 @@ def is_dns_problem_worker(url: str, queue: multiprocessing.Queue):
except Exception:
queue.put((url, True)) # Failed
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:
def test(connection_observer: Optional[ConnectionObserver], port: Optional[int] = None) -> Result:
endpoint_list = list(API_ENDPOINT_FORMATS.keys())[:MAX_ATTEMPTS]
start_time = time.time()
total_budget = 6.0
# Create a stop signal for the HTTP threads
stop_event = Event()
# 1. DNS PRE-FLIGHT
# 1. DNS PRE-FLIGHT (Using Processes, not Threads)
if port is None:
dns_start = time.time()
dns_queue = multiprocessing.Queue()
processes = []
@ -130,8 +70,10 @@ def test_with_threading(connection_observer: Optional[ConnectionObserver], port:
dns_timeout = 6
try:
while time.time() - dns_start < dns_timeout:
# 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
@ -139,19 +81,17 @@ def test_with_threading(connection_observer: Optional[ConnectionObserver], port:
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()
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
http_start = time.time()
result_queue = Queue()
def attempt_request(url: str, stop_sig: Event): # Pass the event here
# 2. HTTP REQUEST PHASE (Using Daemon Threads)
transport = None
if port:
transport = httpx_socks.SyncProxyTransport(
@ -160,66 +100,45 @@ def test_with_threading(connection_observer: Optional[ConnectionObserver], port:
proxy_port=port,
)
# We use a Queue to get the first successful Result back from daemon threads
result_queue = Queue()
def attempt_request(url: str, index: int, client: httpx.Client):
try:
# Check if we should even start
if stop_sig.is_set():
return
with httpx.Client(transport=transport, http2=False, timeout=3.0) as client:
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
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:
logger.info("returning true in the que")
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}")
return
except Exception:
pass
for url in endpoint_list:
# Pass the stop_event to the thread
t = Thread(target=attempt_request, args=(url, stop_event), daemon=True)
with httpx.Client(transport=transport, http2=False, timeout=3.0) as client:
for i, url in enumerate(endpoint_list):
# daemon=True is CRITICAL.
# It tells Python: "If the main program exits, kill this thread immediately."
t = Thread(target=attempt_request, args=(url, i, client), daemon=True)
t.start()
# Wait for the first success or the budget
# Wait for the first success or the remaining budget
while True:
elapsed = time.time() - http_start
elapsed = time.time() - start_time
remaining = total_budget - elapsed
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
# Block for the remaining budget
return result_queue.get(timeout=remaining)
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.")
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:
"""
Purpose:

View file

@ -3,7 +3,6 @@ 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.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.observers.Notifications import Notifications, EventType
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 ProfileType
@ -30,9 +29,6 @@ def get_profile_ip(profile_id: int, protocol: ProtocolChoice, profile_type: Prof
@type_checker
def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObserver) -> Result:
# ------------------------------------
# PRE-REQ FILTER:
# ------------------------------------
profile_id = profile.id
location_id = profile.location.id
location_name = profile.location.country_name
@ -48,9 +44,17 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs
protocol: {protocol}
""")
# ------------------------------------
# BASIC INTERNET
# ------------------------------------
ip_address = get_profile_ip(profile_id=profile_id, protocol=protocol, profile_type=profile_type)
if ip_address:
ping_result = ping_ip(ip_address)
can_be_pinged = ping_result.valid
print(f"Can {location_name} be pinged? {can_be_pinged}")
else:
logger.error("Skipping IP Address Test.")
can_be_pinged = False
if not can_be_pinged:
do_we_have_internet = test_internet()
print(f"Do you have the internet? {do_we_have_internet}")
@ -58,29 +62,7 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs
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)
if not ip_address:
error_msg = "Can't extract IP address from config."
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.RENEGOTIATION, message=error_msg)
ping_result = ping_ip(ip_address)
can_be_pinged = ping_result.valid
print(f"Can {location_name} be pinged? {can_be_pinged}")
if not can_be_pinged:
error_msg = f"The {location_name} node can't be pinged. We are assuming this is currently down."
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NODE_ERROR, message=error_msg)
# ------------------------------------
# CHECK VS API
# ------------------------------------
# Now check against the official API:
# Now check vs official API:
url = f'{Constants.SP_BASE_URL}/v2/check_location'
payload = {
'location_id': str(location_id)
@ -94,8 +76,8 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs
payload=payload
)
if not result.valid:
error_msg = "Can't even reach the API to check if the node is up. Your connection is unstable."
if not result.valid and not can_be_pinged:
error_msg = "Can't ping the VPN node or even reach the API. Your connection is unstable."
return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NO_INTERNET, message=error_msg)
location_up = result.data
@ -105,34 +87,3 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs
else:
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)
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

View file

@ -1,47 +0,0 @@
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)

View file

@ -1,43 +0,0 @@
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)

View file

@ -127,3 +127,28 @@ def ask_to_change_port(recovery_stats: ConnectionRecovery) -> bool:
else:
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}?")

View file

@ -1,10 +1,3 @@
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 essentials.services.ConnectionService import ConnectionService
from core.services.keys_and_verifications.endpoint_verification import verify_wireguard_endpoint
@ -23,7 +16,6 @@ import subprocess
from pathlib import Path
import tempfile
from typing import Optional
from functools import partial
def start_wireproxy(profile: SessionProfile, session_directory: str, port_number: int) -> Result:
@ -51,27 +43,8 @@ def start_session_networking(
connection_observer: Optional[ConnectionObserver] = None
) -> 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)
print(f"protocol is {protocol}")
session_directory = tempfile.mkdtemp(prefix='hv-')
session_state = SessionStateController.get_or_new(profile.id)
@ -80,37 +53,34 @@ def start_session_networking(
proxy_port_number = None
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
# =================================
#--------------------------------
if protocol == ProtocolChoice.TOR:
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)
# =================================
#--------------------------------
# WIREGUARD
# =================================
#--------------------------------
elif protocol == ProtocolChoice.WIREGUARD:
# Verification
if ConfigurationController.get_endpoint_verification_enabled():
verify_wireguard_endpoint(profile, ignore=ignore)
started_process = start_wireproxy(profile, session_directory, port_number)
connection_result = start_wireproxy(profile, session_directory, port_number)
session_state.network_port_numbers.wireguard.append(port_number)
# =================================
# EVALUATE
# =================================
if not started_process.valid:
return started_process.wrap("Unable to even start the network connection.")
#--------------------------------
# ALL CONNECTIONS
#--------------------------------
if not connection_result.valid:
return connection_result.wrap("Unable to start the network connection.")
network_process = started_process.data
network_process = connection_result.data
# sanity check for all networking processes:
if not network_process:
@ -119,76 +89,53 @@ def start_session_networking(
# Test:
print("Testing IP..")
test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=protocol, connection_observer=connection_observer)
# =================================
# SUCCESS
# =================================
if test_result.valid:
logger.info("Connection worked. Wiping recovery stats")
# wipe failure tracker:
recovery_stats.wipe()
# Update in memory repo,
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)
#--------------------------------
# START FAILURE TESTING.
#--------------------------------
if not test_result.valid:
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
return test_result.wrap(error_msg)
#============== NO RETRY #==============
if location_result.backoff_strategy == BackoffStrategy.NO_RETRY:
recovery_stats.location_up = False
return location_result
# Update in memory repo,
SessionStateController.update_or_create(session_state)
SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
#============== NO SEEMS FINE #==============
recovery_stats.location_up = True
return no_option() # Proceed to attempt 2
final_port = proxy_port_number or port_number
return Result(valid=True, data=final_port)
# =================================
# 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}")
# def kill_session_networking(profile_id: int) -> Result:
# SessionStateController.kill_session_process(profile_id=profile_id, process_type=ProcessType.NETWORK)
# return Result(valid=True)
# =================================
# 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")
recovery_stats.reached_end_of_loop = True
return test_result.wrap("End of session networking loop.")
# # if not profile.connection.is_unprotected():
# if profile.connection.code == 'wireguard':
# test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=ProtocolChoice.WIREGUARD, connection_observer=connection_observer)
# if test_result.valid:
# logger.info("Connection established.")
# if connection_observer:
# connection_observer.notify("connected", "Confirmed")
# else:
# logger.error(test_result.message)
# return test_result.wrap("Unable to connect in ConnectionController.")
# elif profile.connection.code == 'tor':
# await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
# this is a check from SessionConnection of if there's a systemwide with mask
# if profile.connection.is_unprotected():
# if not system_uses_wireguard_interface() and not ConnectionUnprotectedError in ignore:
# error_msg = 'Connection unprotected while the system is not using a WireGuard interface.'
# logger.error(error_msg)
# return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg)
# # from core.services.profiles.profile_connections import disable_profile
# # disable_profile(profile=profile, connection_observer=connection_observer, ticket_observer=ticket_observer)

View file

@ -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.models.BaseProfile import BaseProfile as Profile
from core.services.networking.general_connection_tools.location_evaluation import evaluate_location_and_internet
from core.services.networking.general_connection_tools.location_evaluation import check_if_location_is_up
from core.services.networking.api_requests.ApiResponseModel import BackoffStrategy
from core.models.enum_models import ProtocolChoice, SINGBOX_PROTOCOLS
from core.controllers.profile_state.get_profile_data import get_protocol_enum
@ -235,18 +235,18 @@ def change_port_then_reconnect(
# return message
# def evaluate_location_and_internet(profile: SystemProfile, connection_observer: ConnectionObserver) -> Result:
# """Checks if location is up and returns the backoff strategy."""
# notification = "Checking If Location is Up.."
# Notifications.emit(EventType.STATUS_UPDATE, notification)
# logger.info(notification)
def evaluate_location_and_internet(profile: SystemProfile, connection_observer: ConnectionObserver) -> Result:
"""Checks if location is up and returns 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)
location_result = check_if_location_is_up(profile=profile, connection_observer=connection_observer)
# if location_result.backoff_strategy == BackoffStrategy.RETRY_IMMEDIATE:
# Notifications.emit(EventType.STATUS_UPDATE, "Retrying after Location Check")
if location_result.backoff_strategy == BackoffStrategy.RETRY_IMMEDIATE:
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:
@ -477,23 +477,25 @@ def establish_system_connection(
#============== NO RETRY #==============
if location_result.backoff_strategy == BackoffStrategy.NO_RETRY:
recovery_stats.location_up = False
# logger.error(f"Location check failed: {location_result.message}")
# bottom_left = "Node Down"
# Notifications.emit(EventType.STATUS_UPDATE, bottom_left)
# notification = location_result.message
# Notifications.emit(EventType.SHOW_POPUP, notification)
logger.error(f"Location check failed: {location_result.message}")
bottom_left = "Node Down"
Notifications.emit(EventType.STATUS_UPDATE, bottom_left)
notification = location_result.message
Notifications.emit(EventType.SHOW_POPUP, notification)
return location_result
#============== NO SEEMS FINE #==============
# notification = "Location check passed. Retrying immediately..."
notification = "Location check passed. Retrying immediately..."
recovery_stats.location_up = True
# Notifications.emit(EventType.STATUS_UPDATE, notification)
# logger.info(notification)
Notifications.emit(EventType.STATUS_UPDATE, notification)
logger.info(notification)
return no_option() # Proceed to attempt 2
# =================================
# 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:

View file

@ -1,32 +0,0 @@
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)

View file

@ -108,7 +108,6 @@ def enable_session_profile(
#-----------------------------------
try:
network_result = start_session_networking(profile, ignore=ignore, connection_observer=connection_observer)
print("Completed networking")
except EndpointVerificationError:
return Result(valid=False, error_type=ResultError.ENDPOINT_VERIFICATION, message=f"Verification of the endpoint failed for profile {profile.id}")
@ -116,7 +115,6 @@ def enable_session_profile(
return network_result.wrap("Failed to start the session profile")
port_number = network_result.data
logger.info(f"Networking was successfull, launching the app with network port {port_number}")
#-----------------------------------
# LAUNCH APPLICATION & GRAPHICAL
@ -129,7 +127,6 @@ def enable_session_profile(
if not launched.valid:
return launched.wrap("failed to launch the app")
logger.info("It worked. Returning to the UI")
return Result(valid=True, data=profile.type)