diff --git a/core/controllers/ConnectionController.py b/core/controllers/ConnectionController.py index 3e218c1..62dcf5f 100644 --- a/core/controllers/ConnectionController.py +++ b/core/controllers/ConnectionController.py @@ -168,7 +168,7 @@ class ConnectionController: def establish_wireguard_session_connection(profile: SessionProfile, session_directory: str, port_number: int): if not profile.has_wireguard_configuration(): - raise FileNotFoundError('No valid WireGuard configuration file detected.') + raise FileNotFoundError('Web service did not give us a WireGuard configuration, meaning the location is likely down.') wireguard_session_directory = f'{session_directory}/wireguard' Path(wireguard_session_directory).mkdir(exist_ok=True, mode=0o700) diff --git a/core/controllers/SystemStateController.py b/core/controllers/SystemStateController.py index 4de90c9..d22601a 100644 --- a/core/controllers/SystemStateController.py +++ b/core/controllers/SystemStateController.py @@ -40,6 +40,8 @@ class SystemStateController: @staticmethod def dissolve(): + logger.info("Dissolving state") + # get singleton: state_repo = ProfileStateRepository() @@ -53,6 +55,7 @@ class SystemStateController: state_repo.turn_off_system_connection() # notify UI with that past id: + logger.info("emitting to the UI to disable") Notifications.emit(EventType.SYSTEM_DISABLE, profile_id) diff --git a/core/infrastructure/plumbing.py b/core/infrastructure/plumbing.py index 6f5fe27..a77fc70 100644 --- a/core/infrastructure/plumbing.py +++ b/core/infrastructure/plumbing.py @@ -41,13 +41,13 @@ class ThreadPlumbing: # 1. Create the partial immediately in the main thread task = partial(self.action, *self.args, **self.kwargs) else: - logger.info(f"Using inserted task of {task}") + logger.info("Using inserted task") # 2. Define a simple wrapper to run the task and then handle the result def wrapper(): try: result = task() # Run the partial - logger.info(f"post complete result here is {result}") + # logger.info(f"post complete result here is {result}") except Exception as e: error_msg = f"There was an error: {str(e)}" logger.error(error_msg) @@ -88,8 +88,8 @@ class ThreadPlumbing: elif result.double_dip: logger.info("Getting a double dip function.") double_dip_function = resolve_prescription(result, self.ENUM_MAP, *self.args, **self.kwargs) - logger.info(f"double_dip_function is {double_dip_function}") - if not double_dip_function or double_dip_function is not None: + # logger.info(f"double_dip_function is {double_dip_function}") + if double_dip_function is not None: # self.kwargs.update(ui_caller=self.ui_caller) logger.info("Executing a double dip function.") self.execute(task=double_dip_function) @@ -116,9 +116,6 @@ class ThreadPlumbing: def _back_on_main_thread(self, result: Result): """Decide: retry, show popup, or final callback""" - - logger.info(f"We are on the main thread with result {result}") - #---------------------------- # OUTRIGHT ERROR STACK #---------------------------- @@ -143,7 +140,7 @@ class ThreadPlumbing: #---------------------------- if result.valid or self.attempt_count >= MAX_ATTEMPTS: if self.ui_caller: - print("calling back with result") + logger.info("calling back with result due to max tries") if not result: result = Result(valid=False, error_type=ResultError.UNKNOWN, message="Plumbing is missing a result.") self.ui_caller(result) @@ -198,7 +195,7 @@ class ThreadPlumbing: # if the result originally prescribed it's own "no option": no_option = passed_result.no_option if no_option: - no_option() + self.execute(task=no_option) return #--------------------- diff --git a/core/models/ConnectionRecovery.py b/core/models/ConnectionRecovery.py index 90eb490..a80ce74 100644 --- a/core/models/ConnectionRecovery.py +++ b/core/models/ConnectionRecovery.py @@ -9,7 +9,7 @@ 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"} + 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: @@ -25,28 +25,26 @@ class ConnectionRecovery(StatePersistenceMixin): 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 + prompted_for_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 + 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_confirmed: bool = False - wg_key_changed: 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 @@ -62,5 +60,9 @@ class ConnectionRecovery(StatePersistenceMixin): """Wipe all data and start over.""" wipe_model(model=self, KEEP_FIELDS=self.KEEP_FIELDS) wiped = self.wipe_data_on_disk() + self.prompted_for_port = False + self.asked_to_change_wg_key = False + self.location_tested = False + self.mtu_initially_tested = False logger.info(f"Wiped: {wiped}") diff --git a/core/models/Result.py b/core/models/Result.py index 6928860..9e52acb 100644 --- a/core/models/Result.py +++ b/core/models/Result.py @@ -54,6 +54,7 @@ class ResultError(Enum): WRONG_LOCATION = "wrong_location" SERVER_SIDE = "server_side" MTU = "mtu" + TEST_MTU = "test_mtu" TOR_NEEDED = "tor_needed" API_DOWN = "api_down" NODE_ERROR = "node_error" diff --git a/core/services/networking/mtu/mtu_orchestrator.py b/core/services/networking/mtu/mtu_orchestrator.py index b7c35a2..3d9ca24 100644 --- a/core/services/networking/mtu/mtu_orchestrator.py +++ b/core/services/networking/mtu/mtu_orchestrator.py @@ -5,15 +5,18 @@ 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 +from core.models.Result import Result, ResultError + import asyncio from typing import Optional +from functools import partial +from typing import Callable -def _changed_mtu(profile: SystemProfile, current_mtu: Optional[int]) -> bool: +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}") @@ -58,7 +61,7 @@ def was_mtu_changed(profile: Profile, current_mtu: int, recovery_stats: Connecti # MTU wasn't changed or wasn't applicable, return False - if _changed_mtu(profile=profile, current_mtu=current_mtu): + 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() @@ -70,3 +73,38 @@ def was_mtu_changed(profile: Profile, current_mtu: int, recovery_stats: Connecti Notifications.emit(EventType.STATUS_UPDATE, notification) return False + + +def test_and_change_mtu(profile: Profile, current_mtu: int, recovery_stats: ConnectionRecovery) -> Result: + 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() + 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) + + # Either way, we are reconnecting: + return Result(valid=True, double_dip=True, error_type=ResultError.RECONNECT) + + +def passed_initial_mtu_screen(profile: Profile, recovery_stats: ConnectionRecovery, no_option: Callable) -> Result: + logger.info(f"Did we alreaedy do the MTU evaluation: {recovery_stats.mtu_initially_tested}") + + if recovery_stats.mtu_initially_tested: + return Result(valid=True) + + current_mtu = get_mtu(profile_id=profile.id) + + mtu_ok = mtu_is_fine(current_mtu) + + recovery_stats.mtu_initially_tested = True + + if mtu_ok: + return Result(valid=True) + + error_msg = "MTU is likely an issue. Can we do a full test and change the Wireguard configuration?" + logger.error(error_msg) + yes_option = partial(test_and_change_mtu, profile=profile, current_mtu=current_mtu, recovery_stats=recovery_stats) + return Result(valid=False, function_choice=yes_option, no_option=no_option, error_type=ResultError.MTU, message=error_msg) diff --git a/core/services/networking/ports/port_orchestrator.py b/core/services/networking/ports/port_orchestrator.py index 86ae98a..e744a6e 100644 --- a/core/services/networking/ports/port_orchestrator.py +++ b/core/services/networking/ports/port_orchestrator.py @@ -114,22 +114,27 @@ def port_was_changed_already_today() -> bool: return state_repo.global_state.changed_port -def should_we_try_to_change_port(recovery_stats: ConnectionRecovery): +def ask_to_change_port(recovery_stats: ConnectionRecovery) -> bool: """Returns a boolean if we should change the port""" + print(f"recovery_stats.prompted_for_port is {recovery_stats.prompted_for_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: + if not recovery_stats.prompted_for_port: + print("changing port to true") + recovery_stats.prompted_for_port = True # stops repeat asks return True + 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: diff --git a/core/services/networking/systemwide/systemwide_wireguard.py b/core/services/networking/systemwide/systemwide_wireguard.py index a38b19c..deb7137 100644 --- a/core/services/networking/systemwide/systemwide_wireguard.py +++ b/core/services/networking/systemwide/systemwide_wireguard.py @@ -1,7 +1,8 @@ from core.models.ConnectionRecovery import ConnectionRecovery from core.services.keys_and_verifications.wireguard_keys import register_wireguard_session -from core.services.networking.ports.port_orchestrator import get_wg_port, should_we_try_to_change_port, get_random_different_port, change_wg_port -from core.services.networking.mtu.mtu_orchestrator import should_we_even_test_mtu, was_mtu_changed +from core.services.networking.ports.port_orchestrator import get_wg_port, ask_to_change_port, get_random_different_port, change_wg_port +from core.services.networking.mtu.mtu_orchestrator import passed_initial_mtu_screen +# 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 check_if_location_is_up @@ -105,7 +106,8 @@ def terminate_system_connection( # finally end that profile's JSON state: if SystemStateController.exists(): - SystemState.dissolve() + logger.info("Using controller to dissolve..") + SystemStateController.dissolve() return Result(valid=True) @@ -213,24 +215,24 @@ def change_port_then_reconnect( 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) +# 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 +# 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() +# 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) +# 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 +# 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: @@ -415,133 +417,126 @@ def establish_system_connection( dns_setting = ConfigurationController.get_dns_setting() recovery_stats = ConnectionRecovery(instance_id=profile.id) + # ================= LOOP MANAGEMENT ================ + no_option = partial(establish_system_connection, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer) + if recovery_stats.reached_end_of_loop: error_msg = "Your previous attempt to enable this profile failed. Do you want to start fresh with your recovery strategies (recommended. if the connection fails then it will check & reask about port, renegotation, and mtu)" yes_choice = partial(wipe_attempts, recovery_stats=recovery_stats, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer) - no_option = partial(bypass_existing_attempts, recovery_stats=recovery_stats, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer) return Result(valid=False, function_choice=yes_choice, no_option=no_option, error_type=ResultError.ATTEMPTS, message=error_msg) - # ================= CONNECT WG ================ - while not recovery_stats.reached_end_of_loop: - recovery_stats.attempts += 1 - current_try = recovery_stats.attempts + recovery_stats.attempts += 1 + current_try = recovery_stats.attempts - # ================================= - # 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 + # ================================= + # 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) + notification = f"Connecting attempt {current_try}.. " + Notifications.emit(EventType.STATUS_UPDATE, notification) - # ================================= - # CONNECT - # ================================= - # Attempt the actual system connection - connection_result = __establish_system_connection( - profile=profile, - firewall_setting=firewall_setting, - dns_setting=dns_setting, - connection_observer=connection_observer - ) + # ================================= + # CONNECT + # ================================= + # Attempt the actual system connection + connection_result = __establish_system_connection( + profile=profile, + firewall_setting=firewall_setting, + dns_setting=dns_setting, + connection_observer=connection_observer + ) - # ================================= - # EVALUATE - # ================================= - if connection_result.valid: - recovery_stats.wipe() - return _finish_success(final_result=connection_result, profile_id=profile.id) + # ================================= + # EVALUATE + # ================================= + if connection_result.valid: + recovery_stats.wipe() + return _finish_success(final_result=connection_result, profile_id=profile.id) - # ================================= - # ATTEMPT ONE: LOCATION UP? - # ================================= - if current_try == 1 and not recovery_stats.location_tested: - # First failure: Evaluate Location and Internet without connection, - logger.info("Terminating system connection to check location") - terminate_system_connection(firewall_setting, dns_setting) - - location_result = evaluate_location_and_internet( - profile=profile, - connection_observer=connection_observer - ) - recovery_stats.location_tested = True - - #============== NO RETRY #============== - if location_result.backoff_strategy == BackoffStrategy.NO_RETRY: - recovery_stats.location_up = False - logger.error(f"Location check failed: {location_result.message}") - bottom_left = "Node Down" - Notifications.emit(EventType.STATUS_UPDATE, bottom_left) - notification = location_result.message - Notifications.emit(EventType.SHOW_POPUP, notification) - return location_result - - #============== NO SEEMS FINE #============== - notification = "Location check passed. Retrying immediately..." - recovery_stats.location_up = True - Notifications.emit(EventType.STATUS_UPDATE, notification) - logger.info(notification) - continue # Proceed to attempt 2 - - # ================================= - # ATTEMPT 2+ MTU, PORT, WG KEY - # ================================= - - # Connection is still On for MTU testing: - - # ================================= - # MTU - # ================================= - should_test_mtu, current_mtu = should_we_even_test_mtu(profile_id=profile.id, recovery_stats=recovery_stats) - - if should_test_mtu: - logger.info("We should test (and potentially change) the MTU..") - if was_mtu_changed(profile=profile, current_mtu=current_mtu, recovery_stats=recovery_stats): - logger.info("MTU was changed, so we're trying again.") - continue - else: - logger.info("MTU was tested but NOT changed.") - else: - logger.info("MTU was NOT tested.") - - # Take down connection for the rest of the tests: - terminated = terminate_system_connection(firewall_setting, dns_setting) - if terminated.valid: - logger.info("Took down the system connection for the other tests.") - else: - return terminated - - # ================================= - # PORT - # ================================= - if should_we_try_to_change_port(recovery_stats): - logger.info("We should try to change port") - - # Offer the choice to the end user: - message = get_port_change_message(profile=profile, recovery_stats=recovery_stats) - yes_choice = partial(change_port_then_reconnect, profile=profile, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_observer) - # recovery_stats.stashed_partial = yes_choice - return Result(valid=False, function_choice=yes_choice, error_type=ResultError.PORT, message=message) - - else: - logger.info("Skipping port choice as an offer.") - - # ================================= - # WIREGUARD RENEGOTIATION - # ================================= + # ================================= + # ATTEMPT ONE: LOCATION UP? + # ================================= + if not recovery_stats.location_tested: + # First failure: Evaluate Location and Internet without connection, + logger.info("Terminating system connection to check location") terminate_system_connection(firewall_setting, dns_setting) - 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() + location_result = evaluate_location_and_internet( + profile=profile, + connection_observer=connection_observer + ) + recovery_stats.location_tested = True + + #============== NO RETRY #============== + if location_result.backoff_strategy == BackoffStrategy.NO_RETRY: + recovery_stats.location_up = False + logger.error(f"Location check failed: {location_result.message}") + bottom_left = "Node Down" + Notifications.emit(EventType.STATUS_UPDATE, bottom_left) + notification = location_result.message + Notifications.emit(EventType.SHOW_POPUP, notification) + return location_result + + #============== NO SEEMS FINE #============== + notification = "Location check passed. Retrying immediately..." + recovery_stats.location_up = True + 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: + + # ================================= + # MTU + # ================================= + mtu_result = passed_initial_mtu_screen(profile=profile, recovery_stats=recovery_stats, no_option=no_option) + if not mtu_result.valid: + return mtu_result.wrap("Initial screen failed, taking off the main systemwide wireguard loop..") + + # Take down connection for the rest of the tests: + terminated = terminate_system_connection(firewall_setting, dns_setting) + if terminated.valid: + logger.info("Took down the system connection for the other tests.") + else: + return terminated.wrap("We had issues taking down the systemwide connection , after the 2nd attempt, for further testing.") + + # ================================= + # PORT + # ================================= + logger.info(f"entering port question with recovery_stats.prompted_for_port {recovery_stats.prompted_for_port}") + if not recovery_stats.prompted_for_port: + logger.info("We should try to change port") + recovery_stats.prompted_for_port = True + + # Offer the choice to the end user: + message = message = "Failed to connect. Do you want to try to change the port?" + yes_choice = partial(change_port_then_reconnect, 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.PORT, message=message) + + 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 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, ignore=ignore, connection_observer=connection_observer, ticket_observer=ticket_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.)") + else: + logger.info("entering final loop") + return _conclude_loop_failure()