Compare commits
No commits in common. "87cc90ffb1d064275f8c6447d7e929bb8d72fa5e" and "ffd1080d03a2856065b85635d5b80c1f98704466" have entirely different histories.
87cc90ffb1
...
ffd1080d03
15 changed files with 239 additions and 137 deletions
|
|
@ -14,6 +14,8 @@ from collections.abc import Callable
|
||||||
from core.Constants import Constants
|
from core.Constants import Constants
|
||||||
from core.Errors import ConnectionUnprotectedError, ConnectionTerminationError, CommandNotFoundError
|
from core.Errors import ConnectionUnprotectedError, ConnectionTerminationError, CommandNotFoundError
|
||||||
from core.controllers.ConfigurationController import ConfigurationController
|
from core.controllers.ConfigurationController import ConfigurationController
|
||||||
|
# from core.controllers.ProfileController import ProfileController
|
||||||
|
# from core.controllers.SessionStateController import SessionStateController
|
||||||
from core.controllers.SystemStateController import SystemStateController
|
from core.controllers.SystemStateController import SystemStateController
|
||||||
from core.models.BaseProfile import ProfileType
|
from core.models.BaseProfile import ProfileType
|
||||||
from core.models.session.SessionProfile import SessionProfile
|
from core.models.session.SessionProfile import SessionProfile
|
||||||
|
|
@ -33,6 +35,8 @@ import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
# import sys
|
||||||
|
# import re
|
||||||
|
|
||||||
|
|
||||||
class ConnectionController:
|
class ConnectionController:
|
||||||
|
|
@ -59,6 +63,72 @@ class ConnectionController:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def establish_session_connection(profile: SessionProfile, ignore: tuple[type[Exception]] = (), connection_observer: Optional[ConnectionObserver] = None, ticket_observer: Optional[TicketObserver] = None):
|
||||||
|
|
||||||
|
# session_directory = tempfile.mkdtemp(prefix='hv-')
|
||||||
|
# session_state = SessionStateController.get_or_new(profile.id)
|
||||||
|
|
||||||
|
# port_number = None
|
||||||
|
# proxy_port_number = None
|
||||||
|
|
||||||
|
# # 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():
|
||||||
|
|
||||||
|
# if not ConnectionUnprotectedError in ignore:
|
||||||
|
# raise ConnectionUnprotectedError('Connection unprotected while the system is not using a WireGuard interface.')
|
||||||
|
# else:
|
||||||
|
# from core.services.profiles.profile_connections import disable_profile
|
||||||
|
# disable_profile(profile=profile, connection_observer=connection_observer, ticket_observer=ticket_observer)
|
||||||
|
|
||||||
|
|
||||||
|
# if profile.connection.code == 'tor':
|
||||||
|
|
||||||
|
# port_number = ConnectionService.get_random_available_port_number()
|
||||||
|
# ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# session_state.network_port_numbers.tor.append(port_number)
|
||||||
|
|
||||||
|
# elif profile.connection.code == 'wireguard':
|
||||||
|
|
||||||
|
# if ConfigurationController.get_endpoint_verification_enabled():
|
||||||
|
# verify_wireguard_endpoint(profile, ignore=ignore)
|
||||||
|
|
||||||
|
# port_number = ConnectionService.get_random_available_port_number()
|
||||||
|
# ConnectionController.establish_wireguard_session_connection(profile, session_directory, port_number)
|
||||||
|
# session_state.network_port_numbers.wireguard.append(port_number)
|
||||||
|
|
||||||
|
# if profile.connection.masked:
|
||||||
|
|
||||||
|
# while proxy_port_number is None or proxy_port_number == port_number:
|
||||||
|
# proxy_port_number = ConnectionService.get_random_available_port_number()
|
||||||
|
|
||||||
|
# ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number)
|
||||||
|
# session_state.network_port_numbers.proxy.append(proxy_port_number)
|
||||||
|
|
||||||
|
# # 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)
|
||||||
|
|
||||||
|
|
||||||
|
# SessionStateController.update_or_create(session_state)
|
||||||
|
|
||||||
|
# return proxy_port_number or port_number
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def establish_tor_connection(connection_observer: Optional[ConnectionObserver] = None):
|
def establish_tor_connection(connection_observer: Optional[ConnectionObserver] = None):
|
||||||
try:
|
try:
|
||||||
|
|
@ -73,6 +143,11 @@ class ConnectionController:
|
||||||
if connection_observer is not None:
|
if connection_observer is not None:
|
||||||
connection_observer.notify('custom_message', "Tor Can't Initialize")
|
connection_observer.notify('custom_message', "Tor Can't Initialize")
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def terminate_tor_connection():
|
||||||
|
|
||||||
|
# tor_module = TorModule(Constants.HV_TOR_STATE_HOME)
|
||||||
|
# tor_module.stop_service()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def establish_tor_session_connection(port_number: int, connection_observer: Optional[ConnectionObserver] = None) -> Result:
|
def establish_tor_session_connection(port_number: int, connection_observer: Optional[ConnectionObserver] = None) -> Result:
|
||||||
|
|
@ -94,6 +169,23 @@ class ConnectionController:
|
||||||
tor_module = TorModule(Constants.HV_TOR_STATE_HOME)
|
tor_module = TorModule(Constants.HV_TOR_STATE_HOME)
|
||||||
tor_module.destroy_session(port_number)
|
tor_module.destroy_session(port_number)
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def establish_wireguard_session_connection(profile: SessionProfile, session_directory: str, port_number: int):
|
||||||
|
|
||||||
|
# if not profile.has_wireguard_configuration():
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
# wireproxy_configuration_file_path = f'{wireguard_session_directory}/wireproxy.conf'
|
||||||
|
# Path(wireproxy_configuration_file_path).touch(exist_ok=True, mode=0o600)
|
||||||
|
|
||||||
|
# with open(wireproxy_configuration_file_path, 'w') as wireproxy_configuration_file:
|
||||||
|
# wireproxy_configuration_file.write(f'WGConfig = {profile.get_wireguard_configuration_path()}\n\n[Socks5]\nBindAddress = 127.0.0.1:{str(port_number)}\n')
|
||||||
|
|
||||||
|
# return subprocess.Popen((f'{Constants.HV_RUNTIME_DATA_HOME}/wireproxy/wireproxy', '-c', wireproxy_configuration_file_path), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def establish_proxy_session_connection(profile: SessionProfile, session_directory: str, port_number: int, proxy_port_number: int) -> Result:
|
def establish_proxy_session_connection(profile: SessionProfile, session_directory: str, port_number: int, proxy_port_number: int) -> Result:
|
||||||
|
|
||||||
|
|
@ -157,3 +249,51 @@ class ConnectionController:
|
||||||
|
|
||||||
return task_output
|
return task_output
|
||||||
|
|
||||||
|
|
||||||
|
# def start_tor_session_networking(
|
||||||
|
# port_number: int,
|
||||||
|
# session_directory: str,
|
||||||
|
# session_state: SessionState,
|
||||||
|
# profile: SessionProfile,
|
||||||
|
# ignore: tuple[type[Exception]] = (),
|
||||||
|
# connection_observer: Optional[ConnectionObserver] = None
|
||||||
|
# ) -> Result:
|
||||||
|
|
||||||
|
# print("Starting a Tor Session Profile")
|
||||||
|
# proxy_port_number = None
|
||||||
|
|
||||||
|
# tor_connected = ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer)
|
||||||
|
# if not tor_connected.valid:
|
||||||
|
# return tor_connected.wrap("Failed to start Tor, for Tor->socks5")
|
||||||
|
|
||||||
|
# session_state.network_port_numbers.tor.append(port_number)
|
||||||
|
|
||||||
|
# print(f"Started Tor connection on port {port_number}")
|
||||||
|
|
||||||
|
# if profile.connection.masked:
|
||||||
|
|
||||||
|
# while proxy_port_number is None or proxy_port_number == port_number:
|
||||||
|
# proxy_port_number = ConnectionService.get_random_available_port_number()
|
||||||
|
|
||||||
|
# sock_proxy_result = ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number)
|
||||||
|
# if not sock_proxy_result.valid:
|
||||||
|
# # Kill the underlying Tor right here:
|
||||||
|
# terminate_tor_session_connection(port_number=port_number)
|
||||||
|
# return sock_proxy_result.wrap("We were able to start Tor, but not the socks5 proxy masking on top of it.")
|
||||||
|
|
||||||
|
# network_process = sock_proxy_result.data
|
||||||
|
# session_state.network_port_numbers.proxy.append(proxy_port_number)
|
||||||
|
|
||||||
|
# # Update in memory repo,
|
||||||
|
# SessionStateController.update_or_create(session_state)
|
||||||
|
# SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process)
|
||||||
|
|
||||||
|
# print("Awaiting the connection..")
|
||||||
|
# await_connection(proxy_port_number or port_number, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# print("Updating state..")
|
||||||
|
# SessionStateController.update_or_create(session_state)
|
||||||
|
|
||||||
|
# print("Returning final proxy port")
|
||||||
|
# final_proxy_port = proxy_port_number or port_number
|
||||||
|
# return Result(valid=True, data=final_proxy_port)
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,7 @@ def get_plans_for_profile(profile_id: int) -> Result:
|
||||||
return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT)
|
return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT)
|
||||||
|
|
||||||
# Get Protocol for that profile:
|
# Get Protocol for that profile:
|
||||||
chosen_protocol = profile.protocol
|
chosen_protocol = ProtocolChoice(profile.connection.code)
|
||||||
|
|
||||||
# create or get the singleton:
|
# create or get the singleton:
|
||||||
billing_data = PaymentData(instance_id=profile_id)
|
billing_data = PaymentData(instance_id=profile_id)
|
||||||
|
|
|
||||||
|
|
@ -2,17 +2,18 @@
|
||||||
from core.errors.logger import logger
|
from core.errors.logger import logger
|
||||||
from core.models.Result import Result, ResultError
|
from core.models.Result import Result, ResultError
|
||||||
from core.services.config_tools.manage_sudo_configs import remove_sudo_config
|
from core.services.config_tools.manage_sudo_configs import remove_sudo_config
|
||||||
from core.models.enum_models import ProtocolChoice, is_valid_protocol
|
|
||||||
from core.services.profiles.model_manipulator import delete_connection_configs
|
|
||||||
|
|
||||||
from core.controllers.ProfileController import ProfileController
|
from core.controllers.ProfileController import ProfileController
|
||||||
from core.models.BaseProfile import BaseProfile as Profile
|
from core.models.BaseProfile import BaseProfile as Profile
|
||||||
from core.models.BaseProfile import ProfileType, PROTOCOL_CHOICES
|
from core.models.BaseProfile import ProfileType
|
||||||
|
|
||||||
from core.models.orm_calls.location_calls import get_profile_location_data
|
from core.models.orm_calls.location_calls import get_profile_location_data
|
||||||
from core.models.orm_calls.application_version_calls import get_application_version
|
from core.models.orm_calls.application_version_calls import get_application_version
|
||||||
from core.models.orm_models.Location import Location
|
from core.models.orm_models.Location import Location
|
||||||
|
|
||||||
|
SYSTEMWIDE_CHOICES = ['wireguard', 'hysteria2', 'vless']
|
||||||
|
SESSION_CHOICES = ['wireguard', 'tor', 'proxy']
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Steps:
|
Steps:
|
||||||
1) Looks up the profile by id number
|
1) Looks up the profile by id number
|
||||||
|
|
@ -32,8 +33,7 @@ Raises Errors:
|
||||||
def update_profile(
|
def update_profile(
|
||||||
profile_id: int,
|
profile_id: int,
|
||||||
key: str,
|
key: str,
|
||||||
new_value: str
|
new_value: str) -> Result:
|
||||||
) -> Result:
|
|
||||||
|
|
||||||
# final_data = None
|
# final_data = None
|
||||||
logger.info(f"[UPDATE PROFILE] Recieved profile_id {profile_id}, key {key}, and new_value {new_value}.")
|
logger.info(f"[UPDATE PROFILE] Recieved profile_id {profile_id}, key {key}, and new_value {new_value}.")
|
||||||
|
|
@ -91,7 +91,7 @@ def update_profile(
|
||||||
country_code=country_code,
|
country_code=country_code,
|
||||||
city_code=city_code
|
city_code=city_code
|
||||||
)
|
)
|
||||||
pre_existing_protocol = profile.protocol
|
pre_existing_protocol = profile.connection.code
|
||||||
if new_location.supports_protocol(pre_existing_protocol):
|
if new_location.supports_protocol(pre_existing_protocol):
|
||||||
profile.location = new_location
|
profile.location = new_location
|
||||||
else:
|
else:
|
||||||
|
|
@ -113,19 +113,10 @@ def update_profile(
|
||||||
|
|
||||||
|
|
||||||
def change_protocol(profile: Profile, new_value: str) -> Result:
|
def change_protocol(profile: Profile, new_value: str) -> Result:
|
||||||
"""Changes the profile's protocol, after evaluating that it's a valid choice."""
|
logger.info(f"changing the protcol to {new_value}")
|
||||||
logger.info(f"evaluating changing the protocol to {new_value}")
|
|
||||||
|
|
||||||
# ============= VALID ENUM =============
|
|
||||||
if not is_valid_protocol(new_value):
|
|
||||||
error_msg = "Invalid protocol choice."
|
|
||||||
logger.error(error_msg)
|
|
||||||
return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT)
|
|
||||||
|
|
||||||
protocol_choice = ProtocolChoice(new_value)
|
|
||||||
|
|
||||||
# ============= SAME VALUE =============
|
# ============= SAME VALUE =============
|
||||||
if profile.protocol == protocol_choice:
|
if profile.connection.code == new_value:
|
||||||
error_msg = f"This is NOT changing the protocol, it already was {new_value}"
|
error_msg = f"This is NOT changing the protocol, it already was {new_value}"
|
||||||
logger.error(error_msg)
|
logger.error(error_msg)
|
||||||
return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT)
|
return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT)
|
||||||
|
|
@ -140,24 +131,46 @@ def change_protocol(profile: Profile, new_value: str) -> Result:
|
||||||
return Result(valid=False, message=error_msg, error_type=ResultError.WRONG_LOCATION)
|
return Result(valid=False, message=error_msg, error_type=ResultError.WRONG_LOCATION)
|
||||||
logger.info("Passed location check")
|
logger.info("Passed location check")
|
||||||
|
|
||||||
# ============= By Type =============
|
# ============= SYSTEMWIDE =============
|
||||||
logger.info(f"Evaluating the profile's connection type of {profile.type}")
|
logger.info(f"Evaluating the profile's connection type of {profile.type}")
|
||||||
choices_for_this_profile = PROTOCOL_CHOICES[profile.type]
|
if profile.type == ProfileType.SYSTEM:
|
||||||
if protocol_choice not in choices_for_this_profile:
|
return change_systemwide_connection(profile, new_value)
|
||||||
error_msg = f"{new_value} is not a {profile.type.value} choice"
|
else:
|
||||||
|
return change_session_connection(profile, new_value)
|
||||||
|
|
||||||
|
|
||||||
|
def change_session_connection(profile: Profile, new_value: str) -> Result:
|
||||||
|
logger.info("This is a session profile")
|
||||||
|
if new_value not in SESSION_CHOICES:
|
||||||
|
error_msg = f"{new_value} is not a session choice"
|
||||||
logger.error(error_msg)
|
logger.error(error_msg)
|
||||||
return Result(valid=False, message=error_msg, error_type=ResultError.NOT_SUPPORTED)
|
return Result(valid=False, message=error_msg, error_type=ResultError.NOT_SUPPORTED)
|
||||||
|
|
||||||
# ============= DELETE PAST CONFIGS =============
|
profile.connection.code = new_value
|
||||||
deleted_configs = delete_connection_configs(profile)
|
profile.protocol = new_value
|
||||||
if not deleted_configs.valid:
|
|
||||||
return deleted_configs.wrap("Couldn't change protocol because of issues deleting the previous configs.")
|
|
||||||
|
|
||||||
# ============= SET NEW CHOICES =============
|
if new_value == 'wireguard':
|
||||||
profile.connection.code = new_value # legacy
|
|
||||||
profile.protocol = protocol_choice
|
|
||||||
|
|
||||||
if profile.type == ProfileType.SESSION and protocol_choice == ProtocolChoice.WIREGUARD:
|
|
||||||
profile.connection.masked = False
|
profile.connection.masked = False
|
||||||
|
|
||||||
return Result(valid=True, data=profile)
|
return Result(valid=True, data=profile)
|
||||||
|
|
||||||
|
|
||||||
|
def change_systemwide_connection(profile: Profile, new_value: str) -> Result:
|
||||||
|
logger.info("This is a systemwide profile")
|
||||||
|
if not new_value in SYSTEMWIDE_CHOICES:
|
||||||
|
error_msg = f"{new_value} is not a systemwide choice"
|
||||||
|
logger.error(error_msg)
|
||||||
|
return Result(valid=False, message=error_msg, error_type=ResultError.NOT_SUPPORTED)
|
||||||
|
|
||||||
|
# REMOVE PAST CONFIG:
|
||||||
|
logger.info("removing the config from sudo slot..")
|
||||||
|
removed = remove_sudo_config(profile)
|
||||||
|
if not removed.valid:
|
||||||
|
error_msg = "You must give permission to delete the previous protocol's config file."
|
||||||
|
return Result(valid=False, message=error_msg, error_type=ResultError.PERMISSION)
|
||||||
|
|
||||||
|
# UPDATE PROFILE
|
||||||
|
logger.info("Literally updating the value..")
|
||||||
|
profile.connection.code = new_value
|
||||||
|
profile.protocol = new_value
|
||||||
|
return Result(valid=True, data=profile)
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
from core.errors.logger import logger
|
|
||||||
|
|
||||||
from pydantic import ValidationError
|
|
||||||
|
|
||||||
def get_failed_validation_fields(e: ValidationError) -> list:
|
|
||||||
missing_fields = []
|
|
||||||
for error in e.errors():
|
|
||||||
if error['type'] == 'missing':
|
|
||||||
error_msg = f"Required field '{error['loc'][0]}' is missing"
|
|
||||||
missing_fields.append(error_msg)
|
|
||||||
logger.error(error_msg)
|
|
||||||
else:
|
|
||||||
error_msg = f"Field '{error['loc'][0]}' error: {error['msg']}"
|
|
||||||
missing_fields.append(error_msg)
|
|
||||||
logger.error(error_msg)
|
|
||||||
|
|
||||||
return missing_fields
|
|
||||||
|
|
@ -2,7 +2,7 @@ from core.infrastructure.thread_dispatch import MainThreadDispatcher
|
||||||
from core.infrastructure.global_state import ProfileStateRepository, ProcessType, LIST_OF_PROCESSES
|
from core.infrastructure.global_state import ProfileStateRepository, ProcessType, LIST_OF_PROCESSES
|
||||||
from core.controllers.SessionStateController import SessionStateController
|
from core.controllers.SessionStateController import SessionStateController
|
||||||
from core.controllers.ProfileController import ProfileController
|
from core.controllers.ProfileController import ProfileController
|
||||||
# from core.models.enum_models import ProtocolChoice
|
from core.models.enum_models import ProtocolChoice
|
||||||
from core.errors.logger import logger
|
from core.errors.logger import logger
|
||||||
|
|
||||||
import threading
|
import threading
|
||||||
|
|
@ -17,7 +17,7 @@ def actually_kill_it(profile_id):
|
||||||
return
|
return
|
||||||
|
|
||||||
# Remove the dead handle from the repo so we stop polling it
|
# Remove the dead handle from the repo so we stop polling it
|
||||||
result = SessionStateController.kill_session_profile(profile_id=profile_id, protocol=profile.protocol)
|
result = SessionStateController.kill_session_profile(profile_id=profile_id, protocol=ProtocolChoice(profile.connection.code))
|
||||||
|
|
||||||
if not result.valid:
|
if not result.valid:
|
||||||
SessionStateController.scortched_earth_kill_profile(profile_id)
|
SessionStateController.scortched_earth_kill_profile(profile_id)
|
||||||
|
|
|
||||||
|
|
@ -18,29 +18,6 @@ class ProfileType(str, Enum):
|
||||||
SESSION = "session"
|
SESSION = "session"
|
||||||
SYSTEM = "system"
|
SYSTEM = "system"
|
||||||
|
|
||||||
SYSTEMWIDE_CHOICES = [ProtocolChoice.WIREGUARD, ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS]
|
|
||||||
SESSION_CHOICES = [ProtocolChoice.WIREGUARD, ProtocolChoice.TOR, ProtocolChoice.SOCK5_PROXY]
|
|
||||||
|
|
||||||
PROTOCOL_CHOICES = {
|
|
||||||
ProfileType.SYSTEM: SYSTEMWIDE_CHOICES,
|
|
||||||
ProfileType.SESSION: SESSION_CHOICES
|
|
||||||
}
|
|
||||||
|
|
||||||
CONFIG_NAME = {
|
|
||||||
ProtocolChoice.WIREGUARD: "wg.conf",
|
|
||||||
ProtocolChoice.TOR: "proxy.json",
|
|
||||||
ProtocolChoice.SOCK5_PROXY: "proxy.json",
|
|
||||||
ProtocolChoice.HYSTERIA2: "proxy.json",
|
|
||||||
ProtocolChoice.VLESS: "proxy.json"
|
|
||||||
}
|
|
||||||
|
|
||||||
SYSTEM_WIDE_BACKUP_CONFIG_NAME = {
|
|
||||||
ProtocolChoice.WIREGUARD: "wg.conf.bak",
|
|
||||||
ProtocolChoice.HYSTERIA2: "proxy.json.bak",
|
|
||||||
ProtocolChoice.VLESS: "proxy.json.bak"
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass_json
|
@dataclass_json
|
||||||
@dataclass
|
@dataclass
|
||||||
class BaseProfile(ABC):
|
class BaseProfile(ABC):
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,6 @@ class ProtocolChoice(StrEnum):
|
||||||
|
|
||||||
SINGBOX_PROTOCOLS = [ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS]
|
SINGBOX_PROTOCOLS = [ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS]
|
||||||
|
|
||||||
|
|
||||||
class Currency(Enum):
|
class Currency(Enum):
|
||||||
MONERO = "monero"
|
MONERO = "monero"
|
||||||
BITCOIN = "bitcoin"
|
BITCOIN = "bitcoin"
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
from core.models.enum_models import ProtocolChoice, SINGBOX_PROTOCOLS
|
|
||||||
from core.services.networking.systemwide.encrypted_proxy.launch_proxy import launch_encrypted_proxy
|
from core.services.networking.systemwide.encrypted_proxy.launch_proxy import launch_encrypted_proxy
|
||||||
# from core.services.networking.general_connection_tools.location_evaluation import check_if_location_is_up
|
# from core.services.networking.general_connection_tools.location_evaluation import check_if_location_is_up
|
||||||
# from core.services.networking.api_requests.ApiResponseModel import BackoffStrategy
|
# from core.services.networking.api_requests.ApiResponseModel import BackoffStrategy
|
||||||
|
|
@ -49,7 +48,7 @@ def establish_connection(
|
||||||
# =========================================
|
# =========================================
|
||||||
# HYSTERIA2 & VLESS
|
# HYSTERIA2 & VLESS
|
||||||
# =========================================
|
# =========================================
|
||||||
if profile.protocol in SINGBOX_PROTOCOLS:
|
if profile.connection.code in ("hysteria2", "vless"):
|
||||||
logger.info("Pulling encrypted proxies off the main flow..")
|
logger.info("Pulling encrypted proxies off the main flow..")
|
||||||
try:
|
try:
|
||||||
return launch_encrypted_proxy(profile, connection_observer)
|
return launch_encrypted_proxy(profile, connection_observer)
|
||||||
|
|
@ -66,13 +65,13 @@ def establish_connection(
|
||||||
return sock_proxy_result.wrap("Connection Enable Router failed to configure a regular socks5 proxy")
|
return sock_proxy_result.wrap("Connection Enable Router failed to configure a regular socks5 proxy")
|
||||||
|
|
||||||
logger.info("[CONNECTION] Checking Wireguard configuration..")
|
logger.info("[CONNECTION] Checking Wireguard configuration..")
|
||||||
if profile.protocol == ProtocolChoice.WIREGUARD:
|
if profile.connection.code == "wireguard":
|
||||||
configure_result = _ensure_wireguard_configured(profile, connection_observer)
|
configure_result = _ensure_wireguard_configured(profile, connection_observer)
|
||||||
if not configure_result.valid:
|
if not configure_result.valid:
|
||||||
return configure_result.wrap("Got interupted from connection by a failed setup.")
|
return configure_result.wrap("Got interupted from connection by a failed setup.")
|
||||||
|
|
||||||
|
|
||||||
if profile.protocol == ProtocolChoice.WIREGUARD and profile.type == ProfileType.SYSTEM:
|
if profile.connection.code == "wireguard" and profile.type == ProfileType.SYSTEM:
|
||||||
logger.info("Doing a systemwide WG connection..")
|
logger.info("Doing a systemwide WG connection..")
|
||||||
return establish_system_connection(profile, ignore, connection_observer, ticket_observer)
|
return establish_system_connection(profile, ignore, connection_observer, ticket_observer)
|
||||||
|
|
||||||
|
|
@ -122,7 +121,7 @@ def _ensure_wireguard_configured(
|
||||||
#-----------------------
|
#-----------------------
|
||||||
# Is Wireguard
|
# Is Wireguard
|
||||||
#-----------------------
|
#-----------------------
|
||||||
if profile.protocol != ProtocolChoice.WIREGUARD:
|
if profile.connection.code != "wireguard":
|
||||||
logger.info("Not a wireguard profile")
|
logger.info("Not a wireguard profile")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -189,8 +188,17 @@ def __should_renegotiate(profile: Union[SessionProfile, SystemProfile]):
|
||||||
if not profile.has_subscription():
|
if not profile.has_subscription():
|
||||||
raise MissingSubscriptionError()
|
raise MissingSubscriptionError()
|
||||||
|
|
||||||
if profile.protocol == ProtocolChoice.WIREGUARD and profile.has_wireguard_configuration():
|
if profile.connection.code == "wireguard" and profile.has_wireguard_configuration():
|
||||||
if profile.subscription.has_been_activated():
|
if profile.subscription.has_been_activated():
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Enums
|
||||||
|
# if profile.type == ProfileType.SYSTEM:
|
||||||
|
# print("This is a system profile")
|
||||||
|
# elif profile.type == ProfileType.SESSION:
|
||||||
|
# print("This is a session profile")
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,8 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs
|
||||||
location_id = profile.location.id
|
location_id = profile.location.id
|
||||||
location_name = profile.location.country_name
|
location_name = profile.location.country_name
|
||||||
profile_type = profile.type
|
profile_type = profile.type
|
||||||
protocol = profile.protocol
|
string_protocol = profile.connection.code
|
||||||
|
protocol = ProtocolChoice(string_protocol)
|
||||||
|
|
||||||
print(f"""
|
print(f"""
|
||||||
profile_id: {profile_id}
|
profile_id: {profile_id}
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,7 @@ def start_session_networking(
|
||||||
# =================================
|
# =================================
|
||||||
# PREPARE PRE-REQS
|
# PREPARE PRE-REQS
|
||||||
# =================================
|
# =================================
|
||||||
protocol = profile.protocol
|
protocol = ProtocolChoice(profile.connection.code)
|
||||||
|
|
||||||
session_directory = tempfile.mkdtemp(prefix='hv-')
|
session_directory = tempfile.mkdtemp(prefix='hv-')
|
||||||
session_state = SessionStateController.get_or_new(profile.id)
|
session_state = SessionStateController.get_or_new(profile.id)
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,7 @@
|
||||||
from core.errors.pydantic_errors import get_failed_validation_fields
|
from core.models.orm_calls.location_calls import get_profile_location_data
|
||||||
from core.services.networking.tor_tools import ports
|
from core.services.networking.tor_tools import ports
|
||||||
from core.services.networking.httpx import connect
|
from core.services.networking.httpx import connect
|
||||||
from core.models.enum_models import ProtocolChoice
|
|
||||||
from core.models.BaseProfile import SYSTEM_WIDE_BACKUP_CONFIG_NAME
|
|
||||||
from core.services.networking.systemwide.encrypted_proxy.hysteria_config import build_hysteria_config
|
from core.services.networking.systemwide.encrypted_proxy.hysteria_config import build_hysteria_config
|
||||||
from core.services.networking.systemwide.encrypted_proxy.vless_config import build_vless_config, parse_vless_link
|
from core.services.networking.systemwide.encrypted_proxy.vless_config import build_vless_config, parse_vless_link
|
||||||
from core.utils.basic_operations.write_or_read_from_json import write_json_to_file
|
from core.utils.basic_operations.write_or_read_from_json import write_json_to_file
|
||||||
|
|
@ -13,11 +12,11 @@ from core.utils.basic_operations.does_file_exist import does_file_exist
|
||||||
# Models
|
# Models
|
||||||
from core.models.pydantic_models.HysteriaData import HysteriaData
|
from core.models.pydantic_models.HysteriaData import HysteriaData
|
||||||
from core.models.pydantic_models.VlessData import VlessData
|
from core.models.pydantic_models.VlessData import VlessData
|
||||||
# from core.services.networking.api_requests.ApiResponseModel import ApiResponse, ErrorType
|
from core.services.networking.api_requests.ApiResponseModel import ApiResponse, ErrorType
|
||||||
from core.models.Result import Result, ResultError
|
from core.models.Result import Result, ResultError
|
||||||
from core.models.session.SessionProfile import SessionProfile
|
from core.models.session.SessionProfile import SessionProfile
|
||||||
from core.models.system.SystemProfile import SystemProfile
|
from core.models.system.SystemProfile import SystemProfile
|
||||||
# from core.models.manage.session_management import get_session
|
from core.models.manage.session_management import get_session
|
||||||
from core.models.manage import pydantic_manager
|
from core.models.manage import pydantic_manager
|
||||||
|
|
||||||
# errors & observers
|
# errors & observers
|
||||||
|
|
@ -29,10 +28,10 @@ from core.Errors import ProfileModificationError, CommandNotFoundError, MissingS
|
||||||
# generic
|
# generic
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
from typing import Union, Optional
|
from typing import Union, Optional
|
||||||
# import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
# import subprocess
|
import subprocess
|
||||||
# import json
|
import json
|
||||||
|
|
||||||
|
|
||||||
def configure_singbox(
|
def configure_singbox(
|
||||||
|
|
@ -50,7 +49,7 @@ def configure_singbox(
|
||||||
###################################
|
###################################
|
||||||
# PREP PAYLOADS
|
# PREP PAYLOADS
|
||||||
###################################
|
###################################
|
||||||
protocol = profile.protocol
|
protocol = profile.connection.code
|
||||||
profile_sudo_filepath = f"{profile.get_system_config_path()}/proxy.json"
|
profile_sudo_filepath = f"{profile.get_system_config_path()}/proxy.json"
|
||||||
profile_regular_filepath = profile.get_config_path()
|
profile_regular_filepath = profile.get_config_path()
|
||||||
|
|
||||||
|
|
@ -63,7 +62,7 @@ def configure_singbox(
|
||||||
logger.info("getting config..")
|
logger.info("getting config..")
|
||||||
config_results = post_operator_proxy(
|
config_results = post_operator_proxy(
|
||||||
billing_code=profile.subscription.billing_code,
|
billing_code=profile.subscription.billing_code,
|
||||||
protocol=protocol.value,
|
protocol=protocol,
|
||||||
connection_observer=connection_observer
|
connection_observer=connection_observer
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -99,7 +98,7 @@ def configure_singbox(
|
||||||
random_port = ports.get_random_available_port()
|
random_port = ports.get_random_available_port()
|
||||||
|
|
||||||
# HYSTERIA
|
# HYSTERIA
|
||||||
if protocol == ProtocolChoice.HYSTERIA2:
|
if protocol == "hysteria2":
|
||||||
real_config = build_hysteria_config(
|
real_config = build_hysteria_config(
|
||||||
username=validated_data.username,
|
username=validated_data.username,
|
||||||
password=validated_data.password,
|
password=validated_data.password,
|
||||||
|
|
@ -109,7 +108,7 @@ def configure_singbox(
|
||||||
)
|
)
|
||||||
|
|
||||||
# VLESS
|
# VLESS
|
||||||
elif protocol == ProtocolChoice.VLESS:
|
elif protocol == "vless":
|
||||||
# parse the link:
|
# parse the link:
|
||||||
vless = parse_vless_link(validated_data.links)
|
vless = parse_vless_link(validated_data.links)
|
||||||
|
|
||||||
|
|
@ -137,8 +136,7 @@ def configure_singbox(
|
||||||
saved_it = attach_config_to_sudo_folder(
|
saved_it = attach_config_to_sudo_folder(
|
||||||
config_data=real_config,
|
config_data=real_config,
|
||||||
sudo_filepath=profile_sudo_filepath,
|
sudo_filepath=profile_sudo_filepath,
|
||||||
backup_folder=profile_regular_filepath,
|
backup_folder=profile_regular_filepath
|
||||||
protocol=protocol
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if saved_it:
|
if saved_it:
|
||||||
|
|
@ -148,16 +146,17 @@ def configure_singbox(
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def verify_proxy_data(data: dict, protocol: ProtocolChoice) -> Result:
|
def verify_proxy_data(data: dict, protocol: str) -> Result:
|
||||||
"""
|
"""
|
||||||
Verify the API's proxy details using a Pydantic model
|
Verify the API's proxy details using a Pydantic model
|
||||||
|
|
||||||
Works for both Hysteria2 & VLESS
|
Works for both Hysteria2 & VLESS
|
||||||
"""
|
"""
|
||||||
|
# session = get_session()
|
||||||
try:
|
try:
|
||||||
if protocol == ProtocolChoice.HYSTERIA2:
|
if protocol == "hysteria2":
|
||||||
validated_data = HysteriaData(**data)
|
validated_data = HysteriaData(**data)
|
||||||
elif protocol == ProtocolChoice.VLESS:
|
elif protocol == "vless":
|
||||||
validated_data = VlessData(**data)
|
validated_data = VlessData(**data)
|
||||||
else:
|
else:
|
||||||
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Unsupported protocol.")
|
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Unsupported protocol.")
|
||||||
|
|
@ -166,23 +165,31 @@ def verify_proxy_data(data: dict, protocol: ProtocolChoice) -> Result:
|
||||||
return Result(valid=True, data=validated_data)
|
return Result(valid=True, data=validated_data)
|
||||||
|
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
missing_fields = get_failed_validation_fields(e)
|
missing_fields = []
|
||||||
|
for error in e.errors():
|
||||||
|
if error['type'] == 'missing':
|
||||||
|
error_msg = f"Required field '{error['loc'][0]}' is missing"
|
||||||
|
missing_fields.append(error_msg)
|
||||||
|
logger.error(error_msg)
|
||||||
|
else:
|
||||||
|
error_msg = f"Field '{error['loc'][0]}' error: {error['msg']}"
|
||||||
|
missing_fields.append(error_msg)
|
||||||
|
logger.error(error_msg)
|
||||||
|
|
||||||
return Result(valid=False, error_type=ResultError.INVALID_API_REPLY, message=f"Missing fields: {missing_fields}")
|
return Result(valid=False, error_type=ResultError.INVALID_API_REPLY, message=f"Missing fields: {missing_fields}")
|
||||||
|
|
||||||
|
|
||||||
def attach_config_to_sudo_folder(
|
def attach_config_to_sudo_folder(
|
||||||
config_data: dict,
|
config_data: dict,
|
||||||
sudo_filepath: str,
|
sudo_filepath: str,
|
||||||
backup_folder: str,
|
backup_folder: str
|
||||||
protocol: ProtocolChoice
|
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
|
||||||
if shutil.which('pkexec') is None:
|
if shutil.which('pkexec') is None:
|
||||||
raise CommandNotFoundError('pkexec')
|
raise CommandNotFoundError('pkexec')
|
||||||
|
|
||||||
logger.info("About to save to backup config path")
|
logger.info("About to save to backup config path")
|
||||||
backup_file_name = SYSTEM_WIDE_BACKUP_CONFIG_NAME[protocol]
|
backup_path = f'{backup_folder}/backup.conf.bak'
|
||||||
backup_path = f'{backup_folder}/{backup_file_name}'
|
|
||||||
|
|
||||||
saved_backup = write_json_to_file(data=config_data, filepath=backup_path)
|
saved_backup = write_json_to_file(data=config_data, filepath=backup_path)
|
||||||
if not saved_backup:
|
if not saved_backup:
|
||||||
|
|
@ -242,8 +249,6 @@ def post_operator_proxy(billing_code: str, protocol: str, connection_observer: C
|
||||||
###################################
|
###################################
|
||||||
# VERIFY LOCATION
|
# VERIFY LOCATION
|
||||||
###################################
|
###################################
|
||||||
# from core.models.orm_calls.location_calls import get_profile_location_data
|
|
||||||
|
|
||||||
# location_country_code= data.get('location_country_code')
|
# location_country_code= data.get('location_country_code')
|
||||||
# location_city_code= data.get('location_city_code')
|
# location_city_code= data.get('location_city_code')
|
||||||
# matched_location = get_profile_location_data(
|
# matched_location = get_profile_location_data(
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ from core.models.system.SystemProfile import SystemProfile
|
||||||
from core.models.BaseProfile import ProfileType
|
from core.models.BaseProfile import ProfileType
|
||||||
from core.models.Result import Result, ResultError
|
from core.models.Result import Result, ResultError
|
||||||
from core.errors.logger import logger
|
from core.errors.logger import logger
|
||||||
# from core.utils.type_checker import type_checker
|
from core.utils.type_checker import type_checker
|
||||||
|
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
|
@ -34,7 +34,7 @@ def create_app_object_by_id(potential_data: dict) -> Result:
|
||||||
|
|
||||||
return Result(valid=True, data=application_version)
|
return Result(valid=True, data=application_version)
|
||||||
|
|
||||||
# @type_checker
|
@type_checker
|
||||||
def create_session_object(
|
def create_session_object(
|
||||||
profile_id: int,
|
profile_id: int,
|
||||||
potential_data: dict,
|
potential_data: dict,
|
||||||
|
|
@ -73,7 +73,7 @@ def create_session_object(
|
||||||
return Result(valid=True, data=profile)
|
return Result(valid=True, data=profile)
|
||||||
|
|
||||||
|
|
||||||
# @type_checker
|
@type_checker
|
||||||
def create_system_object(
|
def create_system_object(
|
||||||
profile_id: int,
|
profile_id: int,
|
||||||
potential_data: dict,
|
potential_data: dict,
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ from core.services.config_tools.manage_sudo_configs import remove_sudo_config
|
||||||
from core.models.session.SessionProfile import SessionProfile
|
from core.models.session.SessionProfile import SessionProfile
|
||||||
from core.models.orm_calls.location_calls import LocationCache
|
from core.models.orm_calls.location_calls import LocationCache
|
||||||
from core.models.BaseProfile import BaseProfile as Profile
|
from core.models.BaseProfile import BaseProfile as Profile
|
||||||
from core.models.BaseProfile import ProfileType, CONFIG_NAME, SYSTEM_WIDE_BACKUP_CONFIG_NAME
|
from core.models.BaseProfile import ProfileType
|
||||||
from core.services.profiles.create_objects import create_session_object, create_system_object
|
from core.services.profiles.create_objects import create_session_object, create_system_object
|
||||||
from core.utils.basic_operations.write_or_read_from_json import read_entire_json
|
from core.utils.basic_operations.write_or_read_from_json import read_entire_json
|
||||||
from core.models.orm_calls.application_version_calls import get_application_version
|
from core.models.orm_calls.application_version_calls import get_application_version
|
||||||
|
|
@ -19,7 +19,7 @@ import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
def get_config_path(id: int):
|
def get_config_path(id: int):
|
||||||
return f'{Constants.HV_PROFILE_CONFIG_HOME}/{str(id)}'
|
return f'{Constants.HV_PROFILE_CONFIG_HOME}/{str(id)}'
|
||||||
|
|
@ -307,27 +307,3 @@ def delete(profile: Profile) -> Result:
|
||||||
shutil.rmtree(get_config_path(profile.id), ignore_errors=True)
|
shutil.rmtree(get_config_path(profile.id), ignore_errors=True)
|
||||||
shutil.rmtree(get_data_path(profile.id), ignore_errors=True)
|
shutil.rmtree(get_data_path(profile.id), ignore_errors=True)
|
||||||
return Result(valid=True)
|
return Result(valid=True)
|
||||||
|
|
||||||
|
|
||||||
def delete_connection_configs(profile: Profile) -> Result:
|
|
||||||
"""Delete both connection configuration and backup connection config files for a given profile."""
|
|
||||||
|
|
||||||
config_path = get_config_path(profile.id)
|
|
||||||
|
|
||||||
# CONFIG NAME:
|
|
||||||
if profile.type == ProfileType.SESSION:
|
|
||||||
config_name = CONFIG_NAME[profile.protocol]
|
|
||||||
elif profile.type == ProfileType.SYSTEM:
|
|
||||||
config_name = SYSTEM_WIDE_BACKUP_CONFIG_NAME[profile.protocol]
|
|
||||||
else:
|
|
||||||
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Invalid protocol choice")
|
|
||||||
|
|
||||||
Path(config_path, config_name).unlink(missing_ok=True)
|
|
||||||
|
|
||||||
# SYSTEMWIDE:
|
|
||||||
if profile.type == ProfileType.SYSTEM:
|
|
||||||
removed = remove_sudo_config(profile)
|
|
||||||
if not removed.valid:
|
|
||||||
return removed.wrap("Unable to delete the systemwide configs behind sudo protection.")
|
|
||||||
|
|
||||||
return Result(valid=True)
|
|
||||||
|
|
@ -402,7 +402,7 @@ def create_individual_invoice(payment_cycle: OverallPaymentCycle, connection_obs
|
||||||
# make sure the protocol is saved in the singleton already,
|
# make sure the protocol is saved in the singleton already,
|
||||||
if not billing_data.protocol_choice:
|
if not billing_data.protocol_choice:
|
||||||
# If not, then get the Protocol for that profile:
|
# If not, then get the Protocol for that profile:
|
||||||
billing_data.protocol_choice = profile.protocol
|
billing_data.protocol_choice = ProtocolChoice(profile.connection.code)
|
||||||
|
|
||||||
# location
|
# location
|
||||||
billing_data.location_id = profile.location.id
|
billing_data.location_id = profile.location.id
|
||||||
|
|
|
||||||
|
|
@ -120,7 +120,7 @@ def use_ticket_orchestrator(
|
||||||
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg)
|
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg)
|
||||||
|
|
||||||
location_id = profile.location.id
|
location_id = profile.location.id
|
||||||
protocol_choice = profile.protocol
|
protocol_choice = ProtocolChoice(profile.connection.code)
|
||||||
PRE_REQS = [profile_id, location_id, protocol_choice, which_ticket]
|
PRE_REQS = [profile_id, location_id, protocol_choice, which_ticket]
|
||||||
if None in PRE_REQS:
|
if None in PRE_REQS:
|
||||||
return Result(valid=False, error_type=ResultError.MISSING_DATA, message="You are missing the profile data to use a ticket with.")
|
return Result(valid=False, error_type=ResultError.MISSING_DATA, message="You are missing the profile data to use a ticket with.")
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue