feat(proxy-client): добавлен мастер установки системной службы
- Зачем: установка с нуля и переход из ручного Xray одной командой. - Что: план с подтверждением или --yes, скрытый ввод ссылки, проверка Xray, перенос настроек, запуск службы и переключение домашнего профиля; безопасное продолжение после сбоя и сохранение существующих настроек. - Проверка: cross-review Claude и исправление находок; по 108 тестов на Python 3.8 и 3.14 под PTY, 18 Bash-проверок. После аудита уточнена фикстура повторного запуска и отдельно проверена на обеих версиях Python. Настоящие службы и настройки машины не изменялись.
This commit is contained in:
1 parent
45938cde98
commit
203e515479
5 files changed
+1250
-56
No files matched your search
@@ -13,7 +13,9 @@ import argparse
|
||||
import configparser
|
||||
import fcntl
|
||||
import hashlib
|
||||
import getpass
|
||||
import http.client
|
||||
import io
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
@@ -28,6 +30,7 @@ import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
import warnings
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass
|
||||
@@ -143,13 +146,14 @@ class RuntimeContext:
|
||||
return self.state_dir / "client.json"
|
||||
|
||||
|
||||
def user_context(profile="default"):
|
||||
def user_context(profile="default", home=None):
|
||||
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}", profile):
|
||||
raise ProxyError("недопустимое имя профиля")
|
||||
config_root = os.environ.get("XDG_CONFIG_HOME")
|
||||
state_root = os.environ.get("XDG_STATE_HOME")
|
||||
config_dir = (Path(config_root).expanduser() if config_root else Path.home() / ".config") / "proxy-client"
|
||||
state_dir = (Path(state_root).expanduser() if state_root else Path.home() / ".local/state") / "proxy-client"
|
||||
home = home if home is not None else Path.home()
|
||||
config_dir = (Path(config_root).expanduser() if config_root else home / ".config") / "proxy-client"
|
||||
state_dir = (Path(state_root).expanduser() if state_root else home / ".local/state") / "proxy-client"
|
||||
stop_hint = "Ctrl+C или proxy-client stop"
|
||||
if profile != "default":
|
||||
config_dir = config_dir / "profiles" / profile
|
||||
@@ -208,7 +212,10 @@ def load_config(context):
|
||||
|
||||
def parse_config(text):
|
||||
parser = configparser.ConfigParser(interpolation=None, empty_lines_in_values=False)
|
||||
parser.read_string(text, source="config")
|
||||
try:
|
||||
parser.read_string(text, source="config")
|
||||
except configparser.Error:
|
||||
raise ProxyError("неверный формат config; ожидается секция [proxy] с параметрами") from None
|
||||
if parser.sections() != ["proxy"]:
|
||||
raise ProxyError("нужна ровно одна секция [proxy]")
|
||||
section = parser["proxy"]
|
||||
@@ -1086,25 +1093,389 @@ def install_file(target, data, mode):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
def service_config(text):
|
||||
config = parse_config(text)
|
||||
try:
|
||||
loopback = ipaddress.ip_address(config.address).is_loopback
|
||||
except ValueError:
|
||||
loopback = False
|
||||
if config.proxy_type != "xray" or not loopback:
|
||||
raise ProxyError("службе нужен type=xray и loopback-адрес")
|
||||
return config
|
||||
|
||||
|
||||
def validate_service_source(source):
|
||||
missing = [name for name in ("config", "default.url") if not (source / name).is_file()]
|
||||
if missing:
|
||||
raise ProxyError("не хватает настроек {} в {}; запустите proxy-client service install "
|
||||
"в терминале для настройки или укажите готовый --config-dir".format(
|
||||
", ".join(missing), source))
|
||||
config = service_config((source / "config").read_text(encoding="utf-8"))
|
||||
load_profile(source / "default.url", user_context())
|
||||
return config
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ServiceSetupPlan:
|
||||
"""Снимок перехода; config_text=None означает обновление без изменения HOME."""
|
||||
context: RuntimeContext
|
||||
original_config: Optional[bytes]
|
||||
config_text: Optional[str]
|
||||
profile_text: Optional[str]
|
||||
manual_state: Optional[dict] = None
|
||||
resume: bool = False
|
||||
recovery_file: Optional[str] = None
|
||||
source_profile: Optional[str] = None
|
||||
|
||||
|
||||
def service_is_installed(root):
|
||||
manifest = root / "usr/local/lib/proxy-client/installed.json"
|
||||
return manifest.is_file() or manifest.with_name("installed.pending.json").is_file()
|
||||
|
||||
|
||||
def render_machine_config(config, proxy_type):
|
||||
parser = configparser.ConfigParser(interpolation=None)
|
||||
parser["proxy"] = {"type": proxy_type, "name": config.name,
|
||||
"address": config.address, "port": str(config.port),
|
||||
"no_proxy_extra": ",".join(config.no_proxy_extra)}
|
||||
output = io.StringIO()
|
||||
parser.write(output)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def setup_reset_hint(context):
|
||||
snapshot = context.state_dir / "service-setup.json"
|
||||
return ("Чтобы начать заново, удалите только снимок: rm -- {}\n"
|
||||
"Системные и домашние настройки эта команда не меняет.").format(shlex.quote(str(snapshot)))
|
||||
|
||||
|
||||
def check_setup_source(plan):
|
||||
path = Path(plan.source_profile) if plan.source_profile else plan.context.config_dir / "default.url"
|
||||
if plan.source_profile:
|
||||
changed = not path.is_file() or path.read_text(encoding="utf-8").strip() != plan.profile_text
|
||||
if not changed:
|
||||
load_profile(path, plan.context)
|
||||
else:
|
||||
changed = path.exists() or path.is_symlink()
|
||||
if changed:
|
||||
raise ProxyError("исходный файл VLESS-ссылки изменился; переход остановлен. " +
|
||||
setup_reset_hint(plan.context))
|
||||
|
||||
|
||||
def prepare_service_setup(args):
|
||||
context = user_context(args.profile)
|
||||
pending = context.state_dir / "service-setup.json"
|
||||
if pending.exists():
|
||||
if pending.is_symlink() or pending.stat().st_mode & 0o077:
|
||||
raise ProxyError("снимок перехода должен быть обычным закрытым файлом: {}".format(pending))
|
||||
if args.profile_file or args.port is not None:
|
||||
raise ProxyError("есть незавершённый переход; повторите без --file и --port. " +
|
||||
setup_reset_hint(context))
|
||||
try:
|
||||
data = json.loads(pending.read_text(encoding="utf-8"))
|
||||
original = data["original_config"].encode() if data["original_config"] is not None else None
|
||||
service_config(data["config_text"])
|
||||
parse_vless(data["profile_text"])
|
||||
source_profile = data["source_profile"]
|
||||
if source_profile is not None and not isinstance(source_profile, str):
|
||||
raise ValueError("неверный путь источника")
|
||||
except (KeyError, TypeError, ValueError, AttributeError, ProxyError, configparser.Error):
|
||||
raise ProxyError("снимок незавершённого перехода повреждён или устарел: {}. ".format(pending) +
|
||||
setup_reset_hint(context))
|
||||
manual_state = read_state(context) if managed_xray_running(context) else None
|
||||
plan = ServiceSetupPlan(context, original, data["config_text"], data["profile_text"],
|
||||
manual_state, True, data.get("recovery_file"), source_profile)
|
||||
check_setup_source(plan)
|
||||
return plan
|
||||
config_path = context.config_dir / "config"
|
||||
original = config_path.read_bytes() if config_path.exists() else None
|
||||
config = parse_config(original.decode("utf-8")) if original is not None else None
|
||||
# Установленные файлы ещё не означают завершённый переход из ручного режима.
|
||||
if (Path("/") / "usr/local/lib/proxy-client/installed.json").is_file() and (
|
||||
config is None or config.proxy_type != "xray"):
|
||||
if args.profile_file or args.port is not None:
|
||||
raise ProxyError("настройки службы уже существуют; измените /etc/proxy-client, "
|
||||
"обновление сохраняет их")
|
||||
return ServiceSetupPlan(context, None, None, None)
|
||||
if config_path.is_symlink():
|
||||
raise ProxyError("домашний config является симлинком; используйте --install-only")
|
||||
profile_path = Path(args.profile_file).expanduser() if args.profile_file else context.config_dir / "default.url"
|
||||
if profile_path.is_symlink() and not profile_path.exists():
|
||||
raise ProxyError("{} — битый симлинк; исправьте ссылку или выберите другой --file".format(profile_path))
|
||||
source_profile = None
|
||||
if profile_path.is_file():
|
||||
load_profile(profile_path, context)
|
||||
profile_text = profile_path.read_text(encoding="utf-8").strip()
|
||||
source_profile = str(profile_path.absolute())
|
||||
elif args.profile_file or not sys.stdin.isatty():
|
||||
raise ProxyError("нет VLESS-ссылки; укажите закрытый файл через --file или запустите в терминале")
|
||||
else:
|
||||
# getpass не должен переходить к видимому вводу, если терминал недоступен.
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", getpass.GetPassWarning)
|
||||
try:
|
||||
profile_text = getpass.getpass("VLESS-ссылка (ввод скрыт): ").strip()
|
||||
except getpass.GetPassWarning:
|
||||
raise ProxyError("скрытый ввод недоступен; передайте ссылку через закрытый --file")
|
||||
parse_vless(profile_text)
|
||||
if config is None or config.proxy_type != "xray":
|
||||
port = DEFAULT_PORT if args.port is None else args.port
|
||||
if args.port is None and not args.yes:
|
||||
raw = input("Локальный порт [{}]: ".format(DEFAULT_PORT)).strip()
|
||||
if raw:
|
||||
try:
|
||||
port = int(raw)
|
||||
except ValueError:
|
||||
raise ProxyError("порт должен быть числом от 1 до 65535")
|
||||
config = ProxyConfig("xray", "Xray", "127.0.0.1", port,
|
||||
config.no_proxy_extra if config else DEFAULT_NO_PROXY_EXTRA)
|
||||
elif args.port is not None:
|
||||
config.port = args.port
|
||||
text = render_machine_config(config, "xray")
|
||||
service_config(text)
|
||||
manual_state = read_state(context) if managed_xray_running(context) else None
|
||||
return ServiceSetupPlan(context, original, text, profile_text, manual_state,
|
||||
recovery_file=str(profile_path.resolve()) if args.profile_file else None,
|
||||
source_profile=source_profile)
|
||||
|
||||
|
||||
def find_service_xray(explicit, home, root):
|
||||
if explicit:
|
||||
path = Path(explicit)
|
||||
if not path.is_absolute():
|
||||
raise ProxyError("xray должен быть абсолютным путём")
|
||||
return path
|
||||
local = home / ".local/bin/xray"
|
||||
if local.is_file():
|
||||
return local
|
||||
found = shutil.which("xray")
|
||||
if found:
|
||||
return Path(found).resolve()
|
||||
installed = root / "usr/local/lib/proxy-client/xray"
|
||||
return installed if installed.is_file() else None
|
||||
|
||||
|
||||
def service_systemctl(*arguments, check=True):
|
||||
return subprocess.run(["sudo", "--", "systemctl", *arguments], check=check)
|
||||
|
||||
|
||||
def service_ready(config):
|
||||
return subprocess.run(["systemctl", "is-active", "--quiet", "proxy-client.service"],
|
||||
check=False).returncode == 0 and port_open(config.address, config.port)
|
||||
|
||||
|
||||
def switch_home_to_service(plan):
|
||||
path = plan.context.config_dir / "config"
|
||||
config = service_config(plan.config_text)
|
||||
replacement = render_machine_config(config, "external").encode()
|
||||
current = path.read_bytes() if path.exists() else None
|
||||
if not path.is_symlink() and current == replacement:
|
||||
return
|
||||
if path.is_symlink() or current != plan.original_config:
|
||||
raise ProxyError("домашний config изменился во время установки; он оставлен без изменений. " +
|
||||
setup_reset_hint(plan.context))
|
||||
private_directory(plan.context.config_dir)
|
||||
if plan.original_config is not None:
|
||||
descriptor, backup = tempfile.mkstemp(prefix="config.before-service.", dir=str(path.parent))
|
||||
with os.fdopen(descriptor, "wb") as stream:
|
||||
stream.write(plan.original_config)
|
||||
print("Прежний config сохранён: {}".format(backup))
|
||||
install_file(path, replacement, 0o600)
|
||||
|
||||
|
||||
def apply_service_setup(args, plan, xray):
|
||||
if plan.config_text is None:
|
||||
with tempfile.TemporaryDirectory(prefix="proxy-service-update-") as temporary:
|
||||
if xray is None:
|
||||
xray = Path(temporary) / "xray"
|
||||
install_xray(xray, download_file)
|
||||
options = vars(args).copy()
|
||||
options.update(config_dir=str(plan.context.config_dir), xray=str(xray),
|
||||
profile="default", enable=True, start=False, restart=True)
|
||||
result = service_install(argparse.Namespace(**options))
|
||||
if result == 0:
|
||||
print("Служба обновлена и готова; её настройки и домашний профиль сохранены.")
|
||||
return result
|
||||
config = service_config(plan.config_text)
|
||||
check_setup_source(plan)
|
||||
config_path = plan.context.config_dir / "config"
|
||||
current = config_path.read_bytes() if config_path.exists() else None
|
||||
if config_path.is_symlink() or current not in (
|
||||
plan.original_config, render_machine_config(config, "external").encode()):
|
||||
raise ProxyError("домашний config изменился; переход остановлен без его замены. " +
|
||||
setup_reset_hint(plan.context))
|
||||
replacing_installed = service_is_installed(Path("/"))
|
||||
if not replacing_installed and (plan.manual_state is None or (config.address, config.port) != (
|
||||
plan.manual_state["address"], plan.manual_state["port"])):
|
||||
check_port_available(ipaddress.ip_address(config.address), config.port)
|
||||
with tempfile.TemporaryDirectory(prefix="proxy-service-") as temporary:
|
||||
source = Path(temporary)
|
||||
install_file(source / "config", plan.config_text.encode(), 0o600)
|
||||
install_file(source / "default.url", (plan.profile_text + "\n").encode(), 0o600)
|
||||
if xray is None:
|
||||
print("Скачивание проверенного Xray {}…".format(XRAY_VERSION))
|
||||
xray = source / "xray"
|
||||
install_xray(xray, download_file)
|
||||
check_xray_version(str(xray))
|
||||
generated = source / "client.json"
|
||||
write_private_json(generated, build_xray_config(parse_vless(plan.profile_text),
|
||||
config.address, config.port))
|
||||
run_xray_test(str(xray), generated)
|
||||
private_directory(plan.context.state_dir)
|
||||
pending = plan.context.state_dir / "service-setup.json"
|
||||
install_file(pending, json.dumps({
|
||||
"original_config": plan.original_config.decode() if plan.original_config is not None else None,
|
||||
"config_text": plan.config_text, "profile_text": plan.profile_text,
|
||||
"recovery_file": plan.recovery_file,
|
||||
"source_profile": plan.source_profile,
|
||||
}).encode(), 0o600)
|
||||
options = vars(args).copy()
|
||||
options.update(config_dir=str(source), xray=str(xray), profile="default",
|
||||
enable=False, start=False, restart=False, expect_profile=True)
|
||||
result = service_install(argparse.Namespace(**options))
|
||||
if result:
|
||||
if pending.exists():
|
||||
sys.stderr.write("Снимок сохранён для повторной попытки. " +
|
||||
setup_reset_hint(plan.context) + "\n")
|
||||
return result
|
||||
check_setup_source(plan)
|
||||
if managed_xray_running(plan.context):
|
||||
if read_state(plan.context) != plan.manual_state:
|
||||
raise ProxyError("ручной Xray изменился во время установки; переход остановлен")
|
||||
command_stop(plan.context)
|
||||
try:
|
||||
if replacing_installed:
|
||||
service_systemctl("stop", "proxy-client.service")
|
||||
check_port_available(ipaddress.ip_address(config.address), config.port)
|
||||
service_systemctl("enable", "--now", "proxy-client.service")
|
||||
if not wait_until(lambda: service_ready(config), 10):
|
||||
raise ProxyError("служба не стала готова")
|
||||
except (ProxyError, OSError, subprocess.CalledProcessError, KeyboardInterrupt) as error:
|
||||
cleanup = service_systemctl("disable", "--now", "proxy-client.service", check=False)
|
||||
recovery = ["proxy-client"]
|
||||
if args.profile != "default":
|
||||
recovery.extend(["--profile", args.profile])
|
||||
recovery.append("start")
|
||||
if plan.recovery_file:
|
||||
recovery.extend(["-f", plan.recovery_file])
|
||||
hint = (" Ручной Xray остановлен; вернуть его: {}.".format(
|
||||
" ".join(shlex.quote(part) for part in recovery)) if plan.manual_state else "")
|
||||
if cleanup.returncode:
|
||||
hint += " Не удалось отключить службу; выполните sudo systemctl disable --now proxy-client."
|
||||
raise ProxyError("переход не завершён; домашний config не изменён. "
|
||||
"Проверьте sudo journalctl -u proxy-client -b." + hint) from error
|
||||
try:
|
||||
switch_home_to_service(plan)
|
||||
except (ProxyError, OSError) as error:
|
||||
raise ProxyError("служба уже запущена, но домашний профиль не удалось переключить: {}".format(error))
|
||||
pending.unlink()
|
||||
print("Служба готова на {}:{}. Домашний профиль переключён на external.".format(
|
||||
config.address, config.port))
|
||||
return 0
|
||||
|
||||
|
||||
def setup_service(args):
|
||||
if os.geteuid() == 0:
|
||||
raise ProxyError("для настройки и перехода запустите proxy-client service install без sudo; "
|
||||
"для установки только файлов используйте --install-only")
|
||||
plan = prepare_service_setup(args)
|
||||
xray = find_service_xray(args.xray, Path.home(), Path("/"))
|
||||
if xray is None:
|
||||
print("Xray {} будет скачан и проверен перед установкой.".format(XRAY_VERSION))
|
||||
if plan.config_text is None:
|
||||
print("План: обновить и перезапустить службу, включить автозапуск; настройки сохранить.")
|
||||
else:
|
||||
config = service_config(plan.config_text)
|
||||
print("План: установить системную службу на {}:{}, включить автозапуск "
|
||||
"и переключить текущий профиль.".format(config.address, config.port))
|
||||
if plan.original_config and parse_config(plan.original_config.decode()).proxy_type == "external":
|
||||
print("Текущий внешний прокси будет заменён локальной службой; прежний config сохранится.")
|
||||
if plan.resume:
|
||||
print("Продолжение незавершённого перехода; изменённые настройки не будут заменены.")
|
||||
if plan.manual_state is not None:
|
||||
print("После установки файлов выбранный ручной Xray будет остановлен; "
|
||||
"текущие соединения прервутся.")
|
||||
if not args.yes and input("Продолжить? [y/N]: ").strip().lower() not in ("y", "yes", "д", "да"):
|
||||
print("Установка отменена.")
|
||||
return 0
|
||||
return apply_service_setup(args, plan, xray)
|
||||
|
||||
|
||||
def command_service_install(args):
|
||||
if args.port is not None and not 1 <= args.port <= 65535:
|
||||
raise ProxyError("порт должен быть числом от 1 до 65535")
|
||||
if args.yes and (args.root or args.install_only or args.config_dir):
|
||||
raise ProxyError("--yes нельзя совмещать с --root, --install-only или --config-dir")
|
||||
if (args.profile_file or args.port is not None) and (args.root or args.install_only or args.config_dir):
|
||||
raise ProxyError("--file и --port относятся к настройке; их нельзя совмещать "
|
||||
"с --root, --install-only или --config-dir")
|
||||
if args.yes or (sys.stdin.isatty() and not args.root and not args.install_only
|
||||
and not args.config_dir):
|
||||
return setup_service(args)
|
||||
if not (args.root or args.install_only or args.config_dir):
|
||||
raise ProxyError("без терминала выберите --yes для полного перехода "
|
||||
"или --install-only для установки только файлов")
|
||||
return service_install(args)
|
||||
|
||||
|
||||
def service_install(args):
|
||||
source = Path(args.config_dir)
|
||||
xray = Path(args.xray)
|
||||
if args.config_dir and args.profile != "default":
|
||||
raise ProxyError("выберите --profile или --config-dir, не оба сразу")
|
||||
root = Path(args.root) if args.root else Path("/")
|
||||
if not root.is_absolute():
|
||||
raise ProxyError("root должен быть абсолютным путём")
|
||||
if args.root and (args.enable or args.start or args.restart):
|
||||
raise ProxyError("--root несовместим с --enable, --start и --restart")
|
||||
home = Path.home()
|
||||
if os.geteuid() == 0 and "SUDO_UID" in os.environ and (not args.config_dir or not args.xray):
|
||||
import pwd
|
||||
try:
|
||||
home = Path(pwd.getpwuid(int(os.environ["SUDO_UID"])).pw_dir)
|
||||
except (ValueError, KeyError):
|
||||
raise ProxyError("не удалось определить пользователя sudo; укажите --config-dir и --xray")
|
||||
source = Path(args.config_dir) if args.config_dir else user_context(args.profile, home=home).config_dir
|
||||
xray = find_service_xray(args.xray, home, root)
|
||||
if xray is None:
|
||||
raise ProxyError("Xray не найден; запустите proxy-client service install в терминале "
|
||||
"для настройки или выполните proxy-client install")
|
||||
if not all(path.is_absolute() for path in (source, xray, root)):
|
||||
raise ProxyError("config-dir, xray и root должны быть абсолютными путями")
|
||||
if args.root and (args.enable or args.start):
|
||||
raise ProxyError("--root несовместим с --enable и --start")
|
||||
if not service_is_installed(root):
|
||||
validate_service_source(source)
|
||||
if not args.root and os.geteuid() != 0:
|
||||
raise ProxyError("системная установка требует root")
|
||||
# Пути выбираем до sudo: оно сбрасывает HOME, XDG и PATH.
|
||||
command = ["sudo", "--", sys.executable, str(Path(__file__).resolve()),
|
||||
"service", "install", "--config-dir", str(source), "--xray", str(xray)]
|
||||
if args.enable:
|
||||
command.append("--enable")
|
||||
if args.start:
|
||||
command.append("--start")
|
||||
if args.restart:
|
||||
command.append("--restart")
|
||||
if args.expect_profile:
|
||||
command.append("--expect-profile")
|
||||
print("Установка системной службы через sudo.", flush=True)
|
||||
return exit_code(subprocess.run(command, check=False).returncode)
|
||||
settings = root / "etc/proxy-client"
|
||||
# При обновлении служба уже имеет собственные настройки вне HOME.
|
||||
if not (settings / "config").exists():
|
||||
config = parse_config((source / "config").read_text(encoding="utf-8"))
|
||||
if config.proxy_type != "xray" or not ipaddress.ip_address(config.address).is_loopback:
|
||||
raise ProxyError("службе нужен type=xray и loopback-адрес")
|
||||
if not (settings / "default.url").exists():
|
||||
load_profile(source / "default.url", user_context())
|
||||
config_path = settings / "config" if (settings / "config").exists() else source / "config"
|
||||
config = service_config(config_path.read_text(encoding="utf-8"))
|
||||
profile_path = settings / "default.url" if (settings / "default.url").exists() else source / "default.url"
|
||||
profile_context = service_context(argparse.Namespace(config_dir=config_path.parent,
|
||||
runtime_dir=root / "run/proxy-client", xray=xray)) if profile_path.parent == settings else user_context()
|
||||
profile = load_profile(profile_path, profile_context)
|
||||
if args.expect_profile:
|
||||
expected_config = validate_service_source(source)
|
||||
expected_profile = load_profile(source / "default.url", user_context())
|
||||
if vars(config) != vars(expected_config) or build_xray_config(profile, config.address, config.port) != \
|
||||
build_xray_config(expected_profile, expected_config.address, expected_config.port):
|
||||
raise ProxyError("системные настройки отличаются от снимка перехода; они оставлены без изменений. "
|
||||
"Для их смены отредактируйте /etc/proxy-client отдельно")
|
||||
check_xray_version(str(xray))
|
||||
with tempfile.TemporaryDirectory(prefix="proxy-service-test-") as temporary:
|
||||
generated = Path(temporary) / "client.json"
|
||||
write_private_json(generated, build_xray_config(profile, config.address, config.port))
|
||||
run_xray_test(str(xray), generated)
|
||||
files = {
|
||||
"usr/local/lib/proxy-client/proxy-client": (Path(__file__).read_bytes(), 0o755),
|
||||
"usr/local/lib/proxy-client/xray": (xray.read_bytes(), 0o755),
|
||||
@@ -1166,7 +1537,13 @@ def service_install(args):
|
||||
subprocess.run(["systemctl", "enable", "proxy-client.service"], check=True)
|
||||
if args.start:
|
||||
subprocess.run(["systemctl", "start", "proxy-client.service"], check=True)
|
||||
print("Служба установлена. Конфигурация сохранена; автоматического перезапуска нет.")
|
||||
if args.restart:
|
||||
subprocess.run(["systemctl", "stop", "proxy-client.service"], check=True)
|
||||
check_port_available(ipaddress.ip_address(config.address), config.port)
|
||||
subprocess.run(["systemctl", "start", "proxy-client.service"], check=True)
|
||||
if not wait_until(lambda: service_ready(config), 10):
|
||||
raise ProxyError("служба не стала готова; проверьте sudo journalctl -u proxy-client -b")
|
||||
print("Файлы службы установлены.")
|
||||
report_journal_storage(root)
|
||||
return 0
|
||||
|
||||
@@ -1185,11 +1562,19 @@ def build_parser():
|
||||
serve.add_argument("--runtime-dir", default="/run/proxy-client")
|
||||
serve.add_argument("--xray", default="/usr/local/lib/proxy-client/xray")
|
||||
setup = actions.add_parser("install", help="установить системную службу")
|
||||
setup.add_argument("--config-dir", required=True)
|
||||
setup.add_argument("--xray", required=True)
|
||||
setup.add_argument("--config-dir", help="каталог настроек (по умолчанию текущий профиль)")
|
||||
setup.add_argument("--xray", help="готовый Xray (по умолчанию ~/.local/bin/xray или PATH)")
|
||||
setup.add_argument("--root", help="изолированный корень без systemctl")
|
||||
setup.add_argument("--enable", action="store_true")
|
||||
setup.add_argument("--start", action="store_true")
|
||||
setup.add_argument("--restart", action="store_true", help="перезапустить и проверить готовность службы")
|
||||
setup.add_argument("--yes", "--auto-yes", action="store_true",
|
||||
help="принять план полного перехода без вопроса")
|
||||
setup.add_argument("--install-only", action="store_true",
|
||||
help="установить файлы без мастера и переключения домашнего профиля")
|
||||
setup.add_argument("-f", "--file", dest="profile_file", help="закрытый файл VLESS-ссылки для настройки")
|
||||
setup.add_argument("--port", type=int, help="локальный порт при настройке (по умолчанию 12334)")
|
||||
setup.add_argument("--expect-profile", action="store_true", help=argparse.SUPPRESS)
|
||||
install_parser = subparsers.add_parser("install", help="установить проверенный Xray")
|
||||
install_parser.add_argument(
|
||||
"--replace", action="store_true", help="заменить существующий ~/.local/bin/xray"
|
||||
@@ -1214,10 +1599,10 @@ def main():
|
||||
|
||||
try:
|
||||
if arguments.subcommand == "service":
|
||||
if arguments.profile != "default":
|
||||
raise ProxyError("service не использует пользовательские профили")
|
||||
if arguments.service_action == "install":
|
||||
return service_install(arguments)
|
||||
return command_service_install(arguments)
|
||||
if arguments.profile != "default":
|
||||
raise ProxyError("service run не использует пользовательские профили")
|
||||
context = service_context(arguments)
|
||||
return command_start(load_config(context), None, context)
|
||||
context = user_context(arguments.profile)
|
||||
@@ -1234,6 +1619,9 @@ def main():
|
||||
return command_run(config, arguments.arguments, context)
|
||||
if arguments.subcommand == "start":
|
||||
return command_start(config, arguments.profile_file, context)
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
sys.stderr.write("Установка или команда прервана пользователем.\n")
|
||||
return 130
|
||||
except (ProxyError, OSError, ValueError, subprocess.CalledProcessError) as error:
|
||||
sys.stderr.write("Ошибка: {}\n".format(error))
|
||||
return 1
|
||||
|
||||
Reference in new issue
Block a user