From 0b065fb025d0b5906a1436edf641db9f2d742c93 Mon Sep 17 00:00:00 2001 From: SimplifiedPrivacy Date: Thu, 29 Oct 2026 10:17:38 -0400 Subject: [PATCH] Solved a bug with connections after ticket use, which previously had a threading issue on reconnect. That threading bug had the reconnect hit up wireguard key renegotiation multiple times, causing a subscription error on one of those threads. Now instead, session profiles are still started via a background thread, but when closed via the external X11 window, they trigger a notification to the main UI with @mainthread to disconnect it. This is a temporary workaround to the pre-existing issues with SessionState process management, until that SessionState module can be refactored. --- core/controllers/ApplicationController.py | 15 +- core/controllers/ConfigurationController.py | 5 + core/controllers/ConnectionController.py | 2 +- core/controllers/ProfileController.py | 6 +- .../tickets/TicketPrepController.py | 11 +- core/errors/translate_error.py | 6 +- core/infrastructure/plumbing.py | 219 ++---------------- .../plumbing_tools/resolve_prescription.py | 163 +++++++++++++ core/models/manage/server_reply_tools.py | 10 +- core/observers/Notifications.py | 1 + .../endpoint_verification.py | 2 +- .../keys_and_verifications/wireguard_keys.py | 21 +- .../connection_enable.py | 46 ++-- .../cross_protocol.py | 2 +- .../networking/general_connection_tools/ip.py | 9 +- .../prepare_tickets/ticket_tracker.py | 6 +- core/services/profiles/profile_connections.py | 2 +- .../using_tickets/use_ticket_orchestrator.py | 15 +- 18 files changed, 273 insertions(+), 268 deletions(-) create mode 100644 core/infrastructure/plumbing_tools/resolve_prescription.py diff --git a/core/controllers/ApplicationController.py b/core/controllers/ApplicationController.py index 1bc7fd6..a117e6a 100644 --- a/core/controllers/ApplicationController.py +++ b/core/controllers/ApplicationController.py @@ -5,7 +5,7 @@ from core.models.session.Application import Application from core.models.orm_models.ApplicationVersion import ApplicationVersion from core.observers.ConnectionObserver import ConnectionObserver from core.observers.TicketObserver import TicketObserver - +from core.observers.Notifications import Notifications, EventType from core.models.session.SessionProfile import SessionProfile from core.models.session.SessionState import SessionState from core.observers.ProfileObserver import ProfileObserver @@ -107,10 +107,19 @@ class ApplicationController: sys.exit() else: - + # Launch it: ApplicationController.__run_process(initialization_file_path, profile, display, session_state) + + # when it's finished, this triggers to kill the popen: + Notifications.emit(EventType.SESSION_PROFILE_KILL, profile.id) + + # ProfileController.disable(profile, False, profile_observer=profile_observer, ticket_observer=ticket_observer, connection_observer=connection_observer) - disable_profile(profile, False, profile_observer=profile_observer, ticket_observer=ticket_observer, connection_observer=connection_observer) + # try: + # print("closing..") + # disable_profile(profile, False, profile_observer=profile_observer, ticket_observer=ticket_observer, connection_observer=connection_observer) + # except Exception as e: + # print(str(e)) @staticmethod def _sync(proxies: Optional[dict] = None): diff --git a/core/controllers/ConfigurationController.py b/core/controllers/ConfigurationController.py index 995cd45..3eb7e53 100644 --- a/core/controllers/ConfigurationController.py +++ b/core/controllers/ConfigurationController.py @@ -156,6 +156,11 @@ class ConfigurationController: @staticmethod def change_random_ticket(new_value: bool) -> bool: configuration = ConfigurationController.get() + + # not setup yet.. + if not configuration.tickets_setup: + return False + configuration.use_random = new_value configuration.save() return True diff --git a/core/controllers/ConnectionController.py b/core/controllers/ConnectionController.py index 62dcf5f..f58fca5 100644 --- a/core/controllers/ConnectionController.py +++ b/core/controllers/ConnectionController.py @@ -10,7 +10,7 @@ from core.models.enum_models import ProtocolChoice from collections.abc import Callable from core.Constants import Constants -from core.Errors import InvalidSubscriptionError, MissingSubscriptionError, ConnectionUnprotectedError, ConnectionTerminationError, CommandNotFoundError +from core.Errors import ConnectionUnprotectedError, ConnectionTerminationError, CommandNotFoundError from core.controllers.ConfigurationController import ConfigurationController # from core.controllers.ProfileController import ProfileController from core.controllers.SessionStateController import SessionStateController diff --git a/core/controllers/ProfileController.py b/core/controllers/ProfileController.py index 4024347..bc3b3c2 100644 --- a/core/controllers/ProfileController.py +++ b/core/controllers/ProfileController.py @@ -3,7 +3,7 @@ from core.services.profiles.ProfileRepository import ProfileRepository from core.models.Result import Result, ResultError from core.errors.logger import logger -from core.Errors import InvalidSubscriptionError, MissingSubscriptionError + from core.models.BaseProfile import BaseProfile as Profile from core.models.BaseProfile import ProfileType from core.models.Subscription import Subscription @@ -105,10 +105,10 @@ class ProfileController: # profile.save() # else: - # raise InvalidSubscriptionError() + # raise () # else: - # raise MissingSubscriptionError() + # raise () # @staticmethod diff --git a/core/controllers/tickets/TicketPrepController.py b/core/controllers/tickets/TicketPrepController.py index 3c6f178..aaaa6ea 100644 --- a/core/controllers/tickets/TicketPrepController.py +++ b/core/controllers/tickets/TicketPrepController.py @@ -190,16 +190,11 @@ def respawn_billing_code_into_ticket( ################################################# # EVALUATE RESULTS ################################################# - if not isinstance(ticket_result, dict): - return Result(valid=False, error_type=ResultError.UNKNOWN, message=f"Error! The prepare_tickets function returned an invalid format of {type(ticket_result)} when it should be a dict. This is being recieved in the respawn_ticket function.") - - valid = ticket_result.get('valid', False) - - if not valid: + if not ticket_result.valid: notification = "Error in Respawn Prep!" if ticket_observer is not None: ticket_observer.notify("preparing", subject=notification) - return prep_error_result(ticket_result) + return ticket_result.wrap("Respawn failed to do a new ticket prep.") ################################################# # WIPE LOCAL TICKET DATA @@ -219,7 +214,7 @@ def respawn_billing_code_into_ticket( return Result(valid=True, message=update_msg) -def prep_error_result(ticket_result: dict): +def prep_error_result(ticket_result: dict) -> Result: message = ticket_result.get('message', False) error_code = ticket_result.get('error_code', False) diff --git a/core/errors/translate_error.py b/core/errors/translate_error.py index 4ca6092..842d47b 100644 --- a/core/errors/translate_error.py +++ b/core/errors/translate_error.py @@ -52,9 +52,9 @@ def translate_error(error: Type[Exception], profile_id: int) -> Result: #---------------------- # SUBSCRIPTION #---------------------- - if isinstance(error, (InvalidSubscriptionError, MissingSubscriptionError)): - error_msg = f"Subscription missing or invalid for profile {profile_id}. Do you want to get a new sub?" - return Result(valid=False, error_type=ResultError.SUBSCRIPTION, message=error_msg) + # if isinstance(error, (InvalidSubscriptionError, MissingSubscriptionError)): + # error_msg = f"Subscription missing or invalid for profile {profile_id}. Do you want to get a new sub?" + # return Result(valid=False, error_type=ResultError.SUBSCRIPTION, message=error_msg) #---------------------- # COMMAND NOT FOUND diff --git a/core/infrastructure/plumbing.py b/core/infrastructure/plumbing.py index a77fc70..fc52c3a 100644 --- a/core/infrastructure/plumbing.py +++ b/core/infrastructure/plumbing.py @@ -1,3 +1,4 @@ +from core.infrastructure.plumbing_tools.resolve_prescription import resolve_prescription from core.infrastructure.plumbing_tools.result_chain import unwrap, audit from core.infrastructure.thread_dispatch import MainThreadDispatcher from core.infrastructure.error_popup import PopupProtocol, StackErrorProtocol @@ -9,7 +10,6 @@ from core.errors.logger import logger # generic: import threading from typing import Callable, Any, Optional, Type -import inspect from functools import partial import sys @@ -88,11 +88,10 @@ 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 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) + self.execute_already_on_background(task=double_dip_function) else: logger.info(f"Result asked for a double dip, but there's no valid function to do so. double_dip_function is {double_dip_function}") @@ -206,167 +205,24 @@ class ThreadPlumbing: self.ui_caller(passed_result) + def execute_already_on_background(self, task: Callable): + """The other execute uses a thread, this lighter version assumes you're already on the background thread.""" + try: + result = task() + except Exception as e: + error_msg = f"There was an error: {str(e)}" + logger.error(error_msg) + error_stack = get_traceback_line(e) + error_msg = error_stack.message_for_user + logger.error(error_msg) + result = Result(valid=False, error_stack=error_stack, error_type=ResultError.UNKNOWN, message=error_msg) + finally: + # Process the result: + self._on_complete(original_result=result) + # STANDALONE HELPERS: - -def normalize_seq(s): - """Ensures input is a tuple regardless of if it was a list or tuple.""" - return tuple(s) if s is not None else () - - -def try_original_args_kwargs(sig: inspect.Signature, input_args: tuple, input_kwargs: dict): - - requirements = sig.parameters - - # 1. Filter kwargs to remove any fields the function doesn't accept - filtered_kwargs = { - k: v for k, v in input_kwargs.items() - if k in requirements - } - logger.info("Got the filtered kwargs") - - # 2. Limit positional args to the number of parameters that can accept them - positional_capable = [ - p for p in requirements.values() - if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) - ] - filtered_args = input_args[:len(positional_capable)] - logger.info("Got the limited positional capable") - - # 3. Bind the filtered arguments (raises TypeError if required args are missing) - bound = sig.bind(*filtered_args, **filtered_kwargs) - bound.apply_defaults() - logger.info("Bind worked.") - - # 4. Manually check types based on function annotations - for name, value in bound.arguments.items(): - param = requirements[name] - if param.annotation is not inspect.Parameter.empty: - if not isinstance(value, param.annotation): - raise TypeError(f"Argument '{name}' expected {param.annotation}, got {type(value)}") - logger.info("Type check worked. returning..") - - return bound.arguments - - -def resolve_prescription(result: Result, ENUM_MAP: dict, *args, **kwargs): - """ - Find the correct solution to the type of enum problem, - And then add the args from either the original caller's args, - or the defaults for that error type - """ - logger.info(f"resolve_prescription is being called for {result} with *args, **kwargs of {args} {kwargs}") - - # Priority 1: If the function explicitly provided a full partial, use it. - if result.function_choice: - logger.info("The result object itself has a function choice!") - return result.function_choice - - # Priority 2: Look up the Enum map - logger.info("checking enum map") - if result.error_type not in ENUM_MAP: - # logger.info(f"No solution in the ENUM_MAP of {ENUM_MAP}") - return None # No solution - - enum_value = ENUM_MAP[result.error_type] - logger.info(f"got enum_value {enum_value}") - - # Handle the None case (no solution) - if enum_value is None: - logger.info("No enum") - return None - - # Unpack the enum value - could be just a function or (function, default_args) - if isinstance(enum_value, tuple): - func, default_args = enum_value - else: - func = enum_value - default_args = None - - # What does this function require? - sig = inspect.signature(func) - function_requirements = sig.parameters - - # requires nothing, we're done, return it. - if not function_requirements: - logger.info("Function requires nothing, we return as is..") - return func - - # Priority 3: Does it want the result itself? - if 'result' in function_requirements: - logger.info("result required; baking result into partial.") - - # 1. Prepare the arguments we have available right now - # Start with default_args from the ENUM_MAP if they exist - current_args = {} - if isinstance(default_args, dict): - current_args.update(default_args) - - # Inject the result object - current_args['result'] = result - - # 2. Use bind_partial so it doesn't fail if other args are still missing - bound = sig.bind_partial(**current_args) - - # 3. Fill in any function-defined defaults - bound.apply_defaults() - - # 4. Return the partial with the bound arguments - return partial(func, **bound.arguments) - - - # Priority 4: Use original args/kwargs - try: - logger.info("Attempting to use the filtered original args and kwargs") - final_args = try_original_args_kwargs(sig, args, kwargs) - logger.info("Using the filtered original args and kwargs") - return partial(func, **final_args) - except TypeError: - logger.info("Original args & kwargs are missing data or have wrong types") - pass # Not enough, move to priority 4 - - # Priority 5: Use original args/kwargs PLUS defaults - if default_args is None: - return False - - try: - if isinstance(default_args, dict): - # original kwargs take precedence over default_args - merged_kwargs = {**default_args, **kwargs} - bound = sig.bind(**merged_kwargs) - else: - # 1. Handle Type Mismatch: Normalize both to tuples - d_tuple = normalize_seq(default_args) - o_tuple = normalize_seq(args) - - # 2. Positional Override: Replace defaults with original args by index - merged_args = list(d_tuple) - for i, val in enumerate(o_tuple): - if i < len(merged_args): - merged_args[i] = val # Override default at this position - else: - merged_args.append(val) # Append if original args exceed defaults - - # 3. Collision Fix: Convert positional merge to a name-map first. - # This prevents "multiple values for argument" if the same arg - # is present in both merged_args and kwargs. - pos_bound = sig.bind(*merged_args) - - # Now merge the positional map with kwargs (kwargs win) - final_kwargs = {**pos_bound.arguments, **kwargs} - bound = sig.bind(**final_kwargs) - - bound.apply_defaults() - logger.info("Applying both original with defaults..") - return partial(func, **bound.arguments) - except TypeError: - pass - - logger.error("We got a function, but failed to get the args/kwargs for it. Returning False") - return False # Still args or kwargs lacking - - def convert_to_result(result: Any) -> Result: """Turn a non-Result object into a Result object""" error_msg = "Internal error where the result was returned in the wrong format." @@ -390,44 +246,3 @@ def convert_to_result(result: Any) -> Result: def take_plumbing_action(action: Callable, ui_dispatcher: MainThreadDispatcher, error_implementation: Type[PopupProtocol], ui_caller: Callable, *args, **kwargs): controller = ThreadPlumbing(action, ui_dispatcher, ui_caller, *args, **kwargs) controller.execute() - - - - - -# def execute(self): -# """Entry point: kick off the first attempt""" -# self.attempt_count += 1 -# self._spawn_action(action=self.action, first_time=True) - -# def _spawn_action(self, action: Callable, first_time: bool = None): -# """Spawn action on executor""" -# if first_time: -# future = executor.submit(action, *self.args, **self.kwargs) # original args/kwargs -# else: -# future = executor.submit(action) # this is a pre-loaded partial -# future.add_done_callback(self._on_complete) - - -# result = future.result() -# if not isinstance(result, Result): -# result = convert_to_result(result) - - - - - -# Auto navigate: - -# does this have an auto-navigate page? -# if self.navigator and self.auto_navigate_dict: -# logger.info("checking auto-navigate..") -# self.check_auto_navigation(result) - - -# def check_auto_navigation(self, result: Result): -# auto_navigate_page = self.auto_navigate_dict.get(result.error_type) -# if auto_navigate_page is None: -# return - -# self.navigator.request_navigation.emit(auto_navigate_page) diff --git a/core/infrastructure/plumbing_tools/resolve_prescription.py b/core/infrastructure/plumbing_tools/resolve_prescription.py new file mode 100644 index 0000000..2bc36be --- /dev/null +++ b/core/infrastructure/plumbing_tools/resolve_prescription.py @@ -0,0 +1,163 @@ +from core.models.Result import Result +from core.errors.logger import logger + +import inspect +from functools import partial + + +def normalize_seq(s): + """Ensures input is a tuple regardless of if it was a list or tuple.""" + return tuple(s) if s is not None else () + + +def try_original_args_kwargs(sig: inspect.Signature, input_args: tuple, input_kwargs: dict): + + requirements = sig.parameters + + # 1. Filter kwargs to remove any fields the function doesn't accept + filtered_kwargs = { + k: v for k, v in input_kwargs.items() + if k in requirements + } + logger.info("Got the filtered kwargs") + + # 2. Limit positional args to the number of parameters that can accept them + positional_capable = [ + p for p in requirements.values() + if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) + ] + filtered_args = input_args[:len(positional_capable)] + logger.info("Got the limited positional capable") + + # 3. Bind the filtered arguments (raises TypeError if required args are missing) + bound = sig.bind(*filtered_args, **filtered_kwargs) + bound.apply_defaults() + logger.info("Bind worked.") + + # 4. Manually check types based on function annotations + for name, value in bound.arguments.items(): + param = requirements[name] + if param.annotation is not inspect.Parameter.empty: + if not isinstance(value, param.annotation): + raise TypeError(f"Argument '{name}' expected {param.annotation}, got {type(value)}") + logger.info("Type check worked. returning..") + + return bound.arguments + + +def resolve_prescription(result: Result, ENUM_MAP: dict, *args, **kwargs): + """ + Find the correct solution to the type of enum problem, + And then add the args from either the original caller's args, + or the defaults for that error type + """ + logger.info(f"resolve_prescription is being called for {result} with *args, **kwargs of {args} {kwargs}") + + # Priority 1: If the function explicitly provided a full partial, use it. + if result.function_choice: + logger.info("The result object itself has a function choice!") + return result.function_choice + + # Priority 2: Look up the Enum map + logger.info("checking enum map") + if result.error_type not in ENUM_MAP: + # logger.info(f"No solution in the ENUM_MAP of {ENUM_MAP}") + return None # No solution + + enum_value = ENUM_MAP[result.error_type] + logger.info(f"got enum_value {enum_value}") + + # Handle the None case (no solution) + if enum_value is None: + logger.info("No enum") + return None + + # Unpack the enum value - could be just a function or (function, default_args) + if isinstance(enum_value, tuple): + func, default_args = enum_value + else: + func = enum_value + default_args = None + + # What does this function require? + sig = inspect.signature(func) + function_requirements = sig.parameters + + # requires nothing, we're done, return it. + if not function_requirements: + logger.info("Function requires nothing, we return as is..") + return func + + # Priority 3: Does it want the result itself? + if 'result' in function_requirements: + logger.info("result required; baking result into partial.") + + # 1. Prepare the arguments we have available right now + # Start with default_args from the ENUM_MAP if they exist + current_args = {} + if isinstance(default_args, dict): + current_args.update(default_args) + + # Inject the result object + current_args['result'] = result + + # 2. Use bind_partial so it doesn't fail if other args are still missing + bound = sig.bind_partial(**current_args) + + # 3. Fill in any function-defined defaults + bound.apply_defaults() + + # 4. Return the partial with the bound arguments + return partial(func, **bound.arguments) + + + # Priority 4: Use original args/kwargs + try: + logger.info("Attempting to use the filtered original args and kwargs") + final_args = try_original_args_kwargs(sig, args, kwargs) + logger.info("Using the filtered original args and kwargs") + return partial(func, **final_args) + except TypeError: + logger.info("Original args & kwargs are missing data or have wrong types") + pass # Not enough, move to priority 4 + + # Priority 5: Use original args/kwargs PLUS defaults + if default_args is None: + return False + + try: + if isinstance(default_args, dict): + # original kwargs take precedence over default_args + merged_kwargs = {**default_args, **kwargs} + bound = sig.bind(**merged_kwargs) + else: + # 1. Handle Type Mismatch: Normalize both to tuples + d_tuple = normalize_seq(default_args) + o_tuple = normalize_seq(args) + + # 2. Positional Override: Replace defaults with original args by index + merged_args = list(d_tuple) + for i, val in enumerate(o_tuple): + if i < len(merged_args): + merged_args[i] = val # Override default at this position + else: + merged_args.append(val) # Append if original args exceed defaults + + # 3. Collision Fix: Convert positional merge to a name-map first. + # This prevents "multiple values for argument" if the same arg + # is present in both merged_args and kwargs. + pos_bound = sig.bind(*merged_args) + + # Now merge the positional map with kwargs (kwargs win) + final_kwargs = {**pos_bound.arguments, **kwargs} + bound = sig.bind(**final_kwargs) + + bound.apply_defaults() + logger.info("Applying both original with defaults..") + return partial(func, **bound.arguments) + except TypeError: + pass + + logger.error("We got a function, but failed to get the args/kwargs for it. Returning False") + return False # Still args or kwargs lacking + diff --git a/core/models/manage/server_reply_tools.py b/core/models/manage/server_reply_tools.py index 901d004..c0ac048 100644 --- a/core/models/manage/server_reply_tools.py +++ b/core/models/manage/server_reply_tools.py @@ -1,4 +1,3 @@ -from core.Errors import InvalidSubscriptionError from core.models.manage.validate_dataclass import validate_model from core.models.pydantic_models.ServerReply import ServerReply, ServerError from core.models.Result import Result, ResultError @@ -132,14 +131,7 @@ def api_call_and_extraction( # Layer 1: API failure: print(f"api_response is {api_response}") print(f"api_response is {api_response.data}") - if not api_response.valid and not api_response.error_type in (ErrorType.AUTHENTICATION_ERROR, ErrorType.INVALID_REQUEST): - - # legacy system - if api_response.error_type == ErrorType.AUTHENTICATION_ERROR: - logger.error(f"api_response is {api_response}") - logger.error(f"Server is giving an Authentication error for billing ID: {billing_code}") - raise InvalidSubscriptionError(f"Invalid Subscription for {billing_code}") - + if not api_response.valid: error_msg = f"Connection/500s Error prevented the server from replying: {api_response.error_type} {api_response.message}" logger.error(error_msg) return Result(valid=False, error_type=ResultError.CONNECTION, message=error_msg) diff --git a/core/observers/Notifications.py b/core/observers/Notifications.py index 0888e4e..a1c4708 100644 --- a/core/observers/Notifications.py +++ b/core/observers/Notifications.py @@ -4,6 +4,7 @@ from enum import Enum, auto class EventType(Enum): SESSION_PROFILE_ENABLE = auto() SESSION_PROFILE_DISABLE = auto() + SESSION_PROFILE_KILL = auto() SYSTEM_ENABLE = auto() SYSTEM_DISABLE = auto() PROFILE_CREATED = auto() diff --git a/core/services/keys_and_verifications/endpoint_verification.py b/core/services/keys_and_verifications/endpoint_verification.py index d1344c3..5edfc85 100644 --- a/core/services/keys_and_verifications/endpoint_verification.py +++ b/core/services/keys_and_verifications/endpoint_verification.py @@ -1,7 +1,7 @@ from core.models.session.SessionProfile import SessionProfile from core.models.system.SystemProfile import SystemProfile from core.models.BaseProfile import BaseProfile as Profile -from core.Errors import InvalidSubscriptionError, MissingSubscriptionError, ConnectionTerminationError, ProfileActivationError, ProfileDeactivationError, MissingLocationError, ConnectionUnprotectedError, EndpointVerificationError, ProfileStateConflictError +from core.Errors import ConnectionTerminationError, ProfileActivationError, ProfileDeactivationError, MissingLocationError, ConnectionUnprotectedError, EndpointVerificationError, ProfileStateConflictError from typing import Union, Optional import base64 diff --git a/core/services/keys_and_verifications/wireguard_keys.py b/core/services/keys_and_verifications/wireguard_keys.py index b823211..2370169 100644 --- a/core/services/keys_and_verifications/wireguard_keys.py +++ b/core/services/keys_and_verifications/wireguard_keys.py @@ -10,8 +10,6 @@ from core.models.BaseProfile import ProfileType # from core.models.session.SessionProfile import SessionProfile # from core.models.system.SystemProfile import SystemProfile -from core.Errors import MissingSubscriptionError, MissingLocationError -#, InvalidSubscriptionError # from core.services.WebServiceApiService import WebServiceApiService # from core.controllers.ConnectionController import ConnectionController from core.observers.ConnectionObserver import ConnectionObserver @@ -36,19 +34,24 @@ def register_wireguard_session( ) -> Result: """Register a WireGuard session for the given profile.""" - if not profile.has_subscription(): - raise MissingSubscriptionError() - - if not profile.has_location(): - raise MissingLocationError() - + logger.info("Registering a new wireguard session. First generating keys..") + wireguard_keys = _generate_wireguard_keys() public_key = wireguard_keys.get('public', None) if not public_key: logger.error("No Public Key Generated. Raising ValueError") raise ValueError("No Public Key Generated.") - billing_code = profile.subscription.billing_code + if not profile and not profile.subscription: + logger.error(f"profile: {profile} and {profile.subscription}") + return Result(valid=False, error_type=ResultError.SUBSCRIPTION, message="This is a potential bug to ignore, but register WG was called without a subscription.") + + try: + billing_code = profile.subscription.billing_code + except Exception as e: + logger.error(str(e)) + return Result(valid=False, error_type=ResultError.SUBSCRIPTION, message="This is a potential bug to ignore, but register WG was called without a subscription.") + url = f'{Constants.SP_BASE_URL}/v2/wireguard_config' payload = { diff --git a/core/services/networking/general_connection_tools/connection_enable.py b/core/services/networking/general_connection_tools/connection_enable.py index ce3f24b..6aa9c99 100644 --- a/core/services/networking/general_connection_tools/connection_enable.py +++ b/core/services/networking/general_connection_tools/connection_enable.py @@ -4,11 +4,11 @@ from core.services.networking.systemwide.encrypted_proxy.launch_proxy import lau from core.services.networking.general_connection_tools.testing_evaluating import system_uses_wireguard_interface from core.services.networking.systemwide.systemwide_wireguard import establish_system_connection, terminate_system_connection from core.services.keys_and_verifications.wireguard_keys import register_wireguard_session -from core.services.subscriptions.subscriptions import activate_subscription +# from core.services.subscriptions.subscriptions import activate_subscription #, get_encrypted_proxy_billing_code # from core.services.networking.systemwide.encrypted_proxy.configure_singbox import configure_singbox # from core.services.networking.systemwide.encrypted_proxy.singbox_runner import start_singbox -# from core.models.Result import Result, ResultError +from core.models.Result import Result, ResultError # from core.utils.basic_operations.write_or_read_from_json import get_value_from_json_file # from core.observers.TicketObserver import TicketObserver # from core.services.assassin import assassin_tools @@ -42,8 +42,8 @@ def establish_connection( """Establish a connection for the given profile.""" logger.info("[CONNECTION] Checking subscription..") - if not profile.assassin: # Note: Assassin does it's own billing. This would be redundant - activate_subscription(profile=profile, connection_observer=connection_observer) + # if not profile.assassin: # Note: Assassin does it's own billing. This would be redundant + # activate_subscription(profile=profile, connection_observer=connection_observer) # ========================================= # HYSTERIA2 & VLESS @@ -56,11 +56,15 @@ def establish_connection( # SOCKS5 & WIREGUARD # ========================================= logger.info("[CONNECTION] Checking proxy configuration..") - _ensure_proxy_configured(profile, connection_observer) + sock_proxy_result = _ensure_proxy_configured(profile, connection_observer) + if not sock_proxy_result.valid: + return sock_proxy_result.wrap("Connection Enable Router failed to configure a regular socks5 proxy") logger.info("[CONNECTION] Checking Wireguard configuration..") if profile.connection.code == "wireguard": - _ensure_wireguard_configured(profile, connection_observer) + configure_result = _ensure_wireguard_configured(profile, connection_observer) + if not configure_result.valid: + return configure_result.wrap("Got interupted from connection by a failed setup.") if profile.connection.code == "wireguard" and profile.type == ProfileType.SYSTEM: @@ -79,11 +83,11 @@ def establish_connection( def _ensure_proxy_configured( profile: Union[SessionProfile, SystemProfile], connection_observer: Optional[ConnectionObserver], -): +) -> Result: """Setup UNencrypted regular proxy config if needed.""" if not profile.connection.needs_proxy_configuration(): - return + return Result(valid=True) # doesn't need if not profile.has_proxy_configuration(): logger.info("[CONNECTION] You need a new proxy configuration") @@ -98,10 +102,10 @@ def _ensure_proxy_configured( ) if proxy_config is None: - raise InvalidSubscriptionError() + return Result(valid=False, error_type=ResultError.SUBSCRIPTION, message="Failed to fetch the Socks5 proxy config, likely due to a invalid subscription") profile.attach_proxy_configuration(proxy_config) - + return Result(valid=True) def _ensure_wireguard_configured( profile: Union[SessionProfile, SystemProfile], @@ -109,11 +113,17 @@ def _ensure_wireguard_configured( ): """Setup WireGuard config if needed.""" - logger.info(f"[CONNECTION] Checking if this profile needs a wg config. The profile.connection.code is {profile.connection.code}") + + #----------------------- + # Is Wireguard + #----------------------- if profile.connection.code != "wireguard": - logger.info(f"[CONNECTION] This profile {profile.id} does NOT need a wireguard config") + logger.info("Not a wireguard profile") return - + + #----------------------------- + # Not already active + #----------------------------- if profile.type == ProfileType.SYSTEM: if system_uses_wireguard_interface() and SystemStateController.exists(): logger.info("[CONNECTION] There is a systemwide profile that is already is active.") @@ -122,16 +132,18 @@ def _ensure_wireguard_configured( except ConnectionTerminationError as e: logger.error(f"[CONNECTION] Previous Systemwide Wireguard connection could not be disabled. {e}") - if not profile.assassin: - activate_subscription(profile, connection_observer) - logger.info("[CONNECTION] Checking if the profile already has a wg config..") + + if not profile.has_wireguard_configuration(): logger.info("[CONNECTION] Profile does NOT have WG keys and it needs it. Registering a NEW wg session..") registry_result = register_wireguard_session(profile, connection_observer=connection_observer) logger.info(f"registry_result is {registry_result}") if not registry_result.valid: - return registry_result + return registry_result.wrap("Unable to register in connection enable.") + + return Result(valid=True) + def _establish_with_renegotiation( profile: Union[SessionProfile, SystemProfile], diff --git a/core/services/networking/general_connection_tools/cross_protocol.py b/core/services/networking/general_connection_tools/cross_protocol.py index 04e468a..6932173 100644 --- a/core/services/networking/general_connection_tools/cross_protocol.py +++ b/core/services/networking/general_connection_tools/cross_protocol.py @@ -14,7 +14,7 @@ def kill_any_protocol(current_state: SystemState, active_protocol: ProtocolChoic dns_set = current_state.dns_set if active_protocol == ProtocolChoice.WIREGUARD: - from core.services.networking.systemwide_wireguard import terminate_system_connection + from core.services.networking.systemwide.systemwide_wireguard import terminate_system_connection terminate_system_connection( firewall_setting=firewall, dns_setting=dns_set diff --git a/core/services/networking/general_connection_tools/ip.py b/core/services/networking/general_connection_tools/ip.py index 3a6a995..0fb0de9 100644 --- a/core/services/networking/general_connection_tools/ip.py +++ b/core/services/networking/general_connection_tools/ip.py @@ -67,7 +67,7 @@ def test(connection_observer: Optional[ConnectionObserver], port: Optional[int] processes.append(p) any_resolved = False - dns_timeout = 3 + dns_timeout = 5 try: # Wait for the first successful resolution @@ -94,7 +94,12 @@ def test(connection_observer: Optional[ConnectionObserver], port: Optional[int] # 2. HTTP REQUEST PHASE (Using Daemon Threads) transport = None if port: - transport = httpx_socks.ProxyTransport( + # transport = httpx_socks.ProxyTransport( + # proxy_type=ProxyType.SOCKS5, + # proxy_host="127.0.0.1", + # proxy_port=port, + # ) + transport = httpx_socks.SyncProxyTransport( proxy_type=ProxyType.SOCKS5, proxy_host="127.0.0.1", proxy_port=port, diff --git a/core/services/prepare_tickets/ticket_tracker.py b/core/services/prepare_tickets/ticket_tracker.py index 8ade3f8..7e1ffc6 100644 --- a/core/services/prepare_tickets/ticket_tracker.py +++ b/core/services/prepare_tickets/ticket_tracker.py @@ -10,7 +10,7 @@ import json import os from pathlib import Path import shutil - +import random def does_ticket_tracker_exist() -> tuple: @@ -36,10 +36,10 @@ def get_a_random_ticket() -> Result: valid = results.get("valid") tickets = results.get("data") if valid and tickets: - one_random_ticket = tickets.random() + one_random_ticket = random.choice(tickets) return Result(valid=True, data=one_random_ticket) - message = result.get("message") + message = results.get("message") if message == "no_tickets_left": return Result(valid=False, error_type=ResultError.NO_TICKET, message="You do not have any tickets left, would you like to start a new phase to get them?") diff --git a/core/services/profiles/profile_connections.py b/core/services/profiles/profile_connections.py index 3ba85b3..f00845d 100644 --- a/core/services/profiles/profile_connections.py +++ b/core/services/profiles/profile_connections.py @@ -17,7 +17,7 @@ from core.errors.logger import logger from core.services.payment_phase.payment_state import OverallPaymentCycle from core.services.subscriptions.subscriptions_by_protocol import wipe_billing_cycle_IF_its_this_profile -from core.Errors import InvalidSubscriptionError, MissingSubscriptionError, ConnectionTerminationError, ProfileActivationError, ProfileDeactivationError, MissingLocationError, ConnectionUnprotectedError, EndpointVerificationError, ProfileStateConflictError +from core.Errors import ConnectionTerminationError, ProfileActivationError, ProfileDeactivationError, MissingLocationError, ConnectionUnprotectedError, EndpointVerificationError, ProfileStateConflictError from core.controllers.ApplicationController import ApplicationController from core.controllers.ApplicationVersionController import ApplicationVersionController from core.controllers.SessionStateController import SessionStateController diff --git a/core/services/using_tickets/use_ticket_orchestrator.py b/core/services/using_tickets/use_ticket_orchestrator.py index 4958ea2..569b173 100644 --- a/core/services/using_tickets/use_ticket_orchestrator.py +++ b/core/services/using_tickets/use_ticket_orchestrator.py @@ -42,6 +42,7 @@ def save_ticket_use( notification = "Saving New Billing Code.." Notifications.emit(EventType.STATUS_UPDATE, notification) + logger.info(notification) saved_for_profile = save_billing_code( profile_id=profile_id, @@ -60,11 +61,12 @@ def save_ticket_use( ) if not saved_for_profile.valid: - return saved_for_profile # result object + error_msg = "We used a ticket successfully, but failed to save it." + logger.error(f"{error_msg} {saved_for_profile.message}") + return saved_for_profile.wrap(error_msg) if saved_ticket_tracker: - notification = "It Worked! Got Fresh Identity." - Notifications.emit(EventType.STATUS_UPDATE, notification) + logger.info("Saved to ticket tracker AND to profile.") return Result(valid=True) else: notification = "File Error! Failed to Save New Billing Code" @@ -206,8 +208,11 @@ def use_ticket_orchestrator( # save failed: if not saved.valid: logger.error("Failed to Save") - return saved - + return saved.wrap("At the end of ticket orchestration, we failed near the end on trying to save.") + + notification = "It Worked! Connecting with Fresh Identity.." + Notifications.emit(EventType.STATUS_UPDATE, notification) + # not using it now: if not connect_after: return saved