feat: awg runtime add
This commit is contained in:
39 files changed
+1581
-190
No files matched your search
+276
-10
@@ -65,6 +65,8 @@ Changes and secrets need root or the userControl group.
|
||||
proxy outbounds add [tag] <url|json|-> [--detour <tag>]
|
||||
add an outbound from a link or JSON (-: stdin);
|
||||
--detour: connect through another outbound
|
||||
proxy outbounds add [tag] <vpn://…|file.conf|-> [--container <name>]
|
||||
add an AmneziaWG outbound (runs in wireproxy)
|
||||
proxy outbounds chain <tag> <through-tag> [new tag]
|
||||
add a copy of an outbound that connects through another
|
||||
proxy outbounds rm <tag> remove a runtime outbound
|
||||
@@ -105,6 +107,9 @@ Changes and secrets need root or the userControl group.
|
||||
|
||||
awg [list] AmneziaWG profiles
|
||||
awg on <profile> | off [profile] | toggle [profile] | restart [profile]
|
||||
awg add [name] <vpn://…|file.conf|-> [--container <name>]
|
||||
add a global profile (-: stdin)
|
||||
awg rm <profile> remove a profile added with awg add
|
||||
|
||||
killswitch [status|on|off] block traffic outside the global tunnel;
|
||||
stays on until turned off here or with the tunnel
|
||||
@@ -442,9 +447,35 @@ def _sub_tags():
|
||||
|
||||
|
||||
def _awg_profiles():
|
||||
"""Global AmneziaWG profiles: the declared ones, then those added with `awg add`."""
|
||||
declared = _awg_declared()
|
||||
return declared + [p for p in _awg_runtime_profiles() if p not in declared]
|
||||
|
||||
|
||||
def _awg_declared():
|
||||
return _json_list(env("AWG_PROFILES_FILE"))
|
||||
|
||||
|
||||
def _awg_added(profile):
|
||||
"""Whether a profile was added with `awg add` (a declared one of that name wins)."""
|
||||
return profile in _awg_runtime_profiles() and profile not in _awg_declared()
|
||||
|
||||
|
||||
def _awg_runtime_dir():
|
||||
return env("AWG_RUNTIME_DIR", f"{state_dir()}/amneziawg.d")
|
||||
|
||||
|
||||
def _awg_runtime_profiles():
|
||||
"""Profiles added with `awg add`: <name>.conf in a listable dir, each file root-only."""
|
||||
if env("AWG_RUNTIME_GLOBAL") != "1":
|
||||
return []
|
||||
try:
|
||||
names = os.listdir(_awg_runtime_dir())
|
||||
except OSError:
|
||||
return []
|
||||
return sorted(n.removesuffix(".conf") for n in names if n.endswith(".conf") and AWG_NAME.fullmatch(n.removesuffix(".conf")))
|
||||
|
||||
|
||||
# --- completion ---------------------------------------------------------------
|
||||
#
|
||||
# Candidates for the words already typed, one per line as word<TAB>description.
|
||||
@@ -612,8 +643,12 @@ COMPLETE = {
|
||||
"off": "stop a profile",
|
||||
"toggle": "start a profile if stopped, stop it if running",
|
||||
"restart": "restart a profile",
|
||||
"add": "add a profile from a .conf or vpn:// link",
|
||||
"rm": "remove a profile added with awg add",
|
||||
}
|
||||
},
|
||||
"awg add": {"flags": {"--container": "which container of a vpn:// export"}},
|
||||
"awg rm": {"args": lambda: _names(_awg_runtime_profiles())},
|
||||
"awg on": {"args": lambda: _names(_awg_profiles())},
|
||||
"awg off": {"args": lambda: _names(_awg_profiles())},
|
||||
"awg toggle": {"args": lambda: _names(_awg_profiles())},
|
||||
@@ -770,7 +805,8 @@ def _status_snapshot(states=None):
|
||||
name: {"available": unit in states, "active": states.get(unit) == "active"} for name, unit in SNAPSHOT_UNITS.items()
|
||||
}
|
||||
snapshot["awg"] = {
|
||||
"available": bool(profiles),
|
||||
# With runtime profiles on, `awg add` can add the first one.
|
||||
"available": bool(profiles) or env("AWG_RUNTIME_GLOBAL") == "1",
|
||||
"profiles": profiles,
|
||||
"active": next((p for p in profiles if states.get(_awg_service(p)) == "active"), ""),
|
||||
}
|
||||
@@ -1006,7 +1042,14 @@ def cmd_outbounds(verb="list", *args):
|
||||
del args[i : i + 2]
|
||||
if not detour:
|
||||
usage("proxy outbounds add [tag] <url|json|-> [--detour <tag>]")
|
||||
_runtime_entry_add("outbound", *args, detour=detour)
|
||||
container = ""
|
||||
if "--container" in args:
|
||||
i = args.index("--container")
|
||||
container = args[i + 1] if i + 1 < len(args) else ""
|
||||
del args[i : i + 2]
|
||||
if not container:
|
||||
usage("proxy outbounds add [tag] <vpn://…|file.conf|-> [--container <name>]")
|
||||
_runtime_entry_add("outbound", *args, detour=detour, container=container)
|
||||
elif verb == "chain":
|
||||
cmd_outbound_chain(*args)
|
||||
elif verb in ("rm", "remove", "del"):
|
||||
@@ -1409,13 +1452,13 @@ def _runtime_tags(kind):
|
||||
names = os.listdir(_runtime_dir(kind))
|
||||
except OSError:
|
||||
return []
|
||||
exts = (".url", ".json") if kind == "outbound" else (".url",)
|
||||
exts = (".url", ".json", ".awg") if kind == "outbound" else (".url",)
|
||||
return sorted(os.path.splitext(n)[0] for n in names if n.endswith(exts))
|
||||
|
||||
|
||||
def _runtime_path(kind, tag):
|
||||
"""The file behind a runtime entry, or its .url spelling when there is none."""
|
||||
for ext in (".url", ".json") if kind == "outbound" else (".url",):
|
||||
for ext in (".url", ".json", ".awg") if kind == "outbound" else (".url",):
|
||||
path = os.path.join(_runtime_dir(kind), tag + ext)
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
@@ -1453,6 +1496,8 @@ RUNTIME_TAG_MAX = 32
|
||||
|
||||
def _runtime_source(kind, arg):
|
||||
"""Whether an add argument is the entry itself rather than its tag."""
|
||||
if kind == "outbound" and (_awg_source(arg) or _awg_file(arg)):
|
||||
return True
|
||||
return "://" in arg or (kind == "outbound" and (arg == "-" or arg.lstrip().startswith("{")))
|
||||
|
||||
|
||||
@@ -1516,7 +1561,7 @@ def _unique_runtime_tag(kind, name, fallback):
|
||||
return tag
|
||||
|
||||
|
||||
def _runtime_entry_add(kind, *args, detour=""):
|
||||
def _runtime_entry_add(kind, *args, detour="", container=""):
|
||||
what = "<url|json|-> [--detour <tag>]" if kind == "outbound" else "<url>"
|
||||
shape = f"proxy {_runtime_noun(kind)} add [tag] {what}"
|
||||
if len(args) == 1 and _runtime_source(kind, args[0]):
|
||||
@@ -1534,6 +1579,13 @@ def _runtime_entry_add(kind, *args, detour=""):
|
||||
die(f"Cannot chain through '{detour}': not an outbound. See: proxy-ctl proxy outbounds")
|
||||
if kind == "outbound" and url == "-":
|
||||
url = sys.stdin.read()
|
||||
if kind == "outbound" and _awg_file(url):
|
||||
url = _awg_input(url)
|
||||
if kind == "outbound" and _awg_source(url):
|
||||
_awg_outbound_add(tag, url, detour, container)
|
||||
return
|
||||
if container:
|
||||
die("--container only applies to an AmneziaWG vpn:// link.")
|
||||
if not tag:
|
||||
tag = _runtime_tag_for(kind, url)
|
||||
_check_runtime_tag(kind, tag)
|
||||
@@ -1583,6 +1635,8 @@ def cmd_outbound_chain(tag="", hop="", new_tag="", *_):
|
||||
die(f"'{tag}' cannot chain through itself; name another outbound as the hop.")
|
||||
entry = _outbound_share_entry(tag)
|
||||
source = _s(entry.get("url") or "")
|
||||
if not source and _awg_tunnel_hop(entry.get("outbound") or {}):
|
||||
die(f"'{tag}' is an AmneziaWG outbound: its tunnel dials the peer itself and cannot go through another outbound.")
|
||||
if not source:
|
||||
ob = entry.get("outbound") or {}
|
||||
if not ob:
|
||||
@@ -1610,7 +1664,7 @@ def _runtime_entry_rm(kind, tag="", *_):
|
||||
try:
|
||||
os.unlink(path)
|
||||
# Its hop, and a disable left from it: a new entry of this name would inherit them.
|
||||
for extra in (".detour", ".disabled") if kind == "outbound" else ():
|
||||
for extra in (".detour", ".disabled", ".port") if kind == "outbound" else ():
|
||||
if os.path.exists(os.path.join(_runtime_dir(kind), tag + extra)):
|
||||
os.unlink(os.path.join(_runtime_dir(kind), tag + extra))
|
||||
except FileNotFoundError:
|
||||
@@ -2832,15 +2886,227 @@ def cmd_where(domain="", *_):
|
||||
# --- awg ----------------------------------------------------------------------
|
||||
|
||||
|
||||
AWG_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,31}")
|
||||
|
||||
|
||||
def _awg_service(profile):
|
||||
# Added with `awg add`: an instance of the template, which reads amneziawg.d/<name>.conf.
|
||||
if profile and _awg_added(profile):
|
||||
return f"proxy-suite-awg@{profile}"
|
||||
return f"proxy-suite-awg-{profile}"
|
||||
|
||||
|
||||
# --- AmneziaWG configs added at runtime -----------------------------------------
|
||||
#
|
||||
# A .conf or vpn:// link becomes a global profile (`awg add`, amneziawg.d/<name>.conf) or an
|
||||
# outbound (`proxy outbounds add`, outbounds.d/<tag>.awg with its tunnel's port in <tag>.port).
|
||||
# amneziawg_config.py --import checks and normalizes it, hooks refused. The config always
|
||||
# reaches it on stdin: keys in argv would show in ps.
|
||||
|
||||
|
||||
def _awg_source(text):
|
||||
"""Whether text is an AmneziaWG config itself: a vpn:// link, or .conf text."""
|
||||
t = (text or "").strip()
|
||||
return t.startswith("vpn://") or ("[interface]" in t.lower() and "[peer]" in t.lower())
|
||||
|
||||
|
||||
def _awg_file(arg):
|
||||
"""Whether an add argument names a .conf or vpn:// export on disk."""
|
||||
return bool(arg) and arg.endswith((".conf", ".vpn")) and os.path.isfile(os.path.expanduser(arg))
|
||||
|
||||
|
||||
def _awg_input(arg):
|
||||
"""The config an add argument stands for: stdin (-), the text itself, or a file's."""
|
||||
if arg == "-":
|
||||
return sys.stdin.read()
|
||||
if _awg_source(arg):
|
||||
return arg
|
||||
path = os.path.expanduser(arg)
|
||||
try:
|
||||
return read_text(path)
|
||||
except OSError as e:
|
||||
die(f"Cannot read {path}: {e.strerror or e}")
|
||||
|
||||
|
||||
def _awg_import(text, *args):
|
||||
"""amneziawg_config.py --import on text: its output, or its complaint as ours."""
|
||||
tool = env("AWG_CONFIG_TOOL")
|
||||
if not tool:
|
||||
die("AmneziaWG is not enabled in this configuration.")
|
||||
try:
|
||||
p = subprocess.run([sys.executable, tool, "--import", "-", *args], input=text, capture_output=True, text=True)
|
||||
except OSError as e:
|
||||
die(f"Cannot run {tool}: {e}")
|
||||
if p.returncode:
|
||||
message = p.stderr.strip().removeprefix("amneziawg-config: ") or f"{tool} exited with {p.returncode}"
|
||||
die(message.replace("set vpnContainer", "pick one with --container <name>"))
|
||||
return p.stdout
|
||||
|
||||
|
||||
def _awg_describe(text, container=""):
|
||||
"""What the config says of itself: {"name", "endpoint"}. Dies when it is not one."""
|
||||
out = _awg_import(text, "--describe", *(["--container", container] if container else []))
|
||||
try:
|
||||
described = json.loads(out)
|
||||
except ValueError:
|
||||
described = {}
|
||||
return described if isinstance(described, dict) else {}
|
||||
|
||||
|
||||
def _awg_label(described, fallback):
|
||||
"""A name for an entry added without one: the export's description, else awg-<its host>."""
|
||||
name = _s(described.get("name") or "")
|
||||
host = _s(described.get("endpoint") or "").rsplit(":", 1)[0].strip("[]")
|
||||
if name and name == host:
|
||||
return f"awg-{_host_label(host)}"
|
||||
return name or fallback
|
||||
|
||||
|
||||
def _awg_write(text, path, container=""):
|
||||
"""The normalized config at path, 0600; the directory must let us in."""
|
||||
directory = os.path.dirname(path)
|
||||
if not os.access(directory, os.W_OK | os.X_OK):
|
||||
denied(directory, "write to")
|
||||
_awg_import(text, "--output", path, *(["--container", container] if container else []))
|
||||
|
||||
|
||||
def _awg_tunnel_ports():
|
||||
return range(int(env("AWG_TUNNEL_BASE_PORT", "18800")), int(env("AWG_TUNNEL_BASE_PORT", "18800")) + int(env("AWG_TUNNEL_SLOTS", "32")))
|
||||
|
||||
|
||||
def _awg_tunnel_hop(ob):
|
||||
"""Whether a backend outbound is the SOCKS hop to a runtime AmneziaWG tunnel."""
|
||||
port = ob.get("server_port") or (ob.get("settings") or {}).get("port")
|
||||
server = ob.get("server") or (ob.get("settings") or {}).get("address")
|
||||
return server == "127.0.0.1" and isinstance(port, int) and port in _awg_tunnel_ports()
|
||||
|
||||
|
||||
def _awg_free_port():
|
||||
taken = set()
|
||||
directory = _runtime_dir("outbound")
|
||||
try:
|
||||
names = os.listdir(directory)
|
||||
except OSError:
|
||||
names = []
|
||||
for name in names:
|
||||
if name.endswith(".port"):
|
||||
try:
|
||||
taken.add(int(read_text(os.path.join(directory, name)).split()[0]))
|
||||
except (OSError, ValueError, IndexError):
|
||||
pass
|
||||
port = next((p for p in _awg_tunnel_ports() if p not in taken), None)
|
||||
if port is None:
|
||||
die(f"No free port for another AmneziaWG outbound: all {len(_awg_tunnel_ports())} are taken. Remove one first.")
|
||||
return port
|
||||
|
||||
|
||||
def _awg_outbound_add(tag, text, detour, container):
|
||||
require_enabled("AWG_RUNTIME_OUTBOUNDS", "Adding AmneziaWG outbounds at runtime")
|
||||
if detour:
|
||||
die("An AmneziaWG outbound cannot chain through another: its tunnel dials the peer itself.")
|
||||
described = _awg_describe(text, container)
|
||||
if not tag:
|
||||
tag = _unique_runtime_tag("outbound", _awg_label(described, "awg"), "awg")
|
||||
_check_runtime_tag("outbound", tag)
|
||||
print(f"Tag: {tag} (none given; pass one first to choose it)")
|
||||
directory = _runtime_dir("outbound")
|
||||
if not os.access(directory, os.W_OK | os.X_OK):
|
||||
denied(directory, "write to")
|
||||
port = _awg_free_port()
|
||||
old = os.umask(0o027)
|
||||
try:
|
||||
# The port first: the config is what the start script and the sync unit look for.
|
||||
for extra in (".detour", ".disabled"):
|
||||
if os.path.exists(os.path.join(directory, tag + extra)):
|
||||
os.unlink(os.path.join(directory, tag + extra)) # left from an earlier entry of this name
|
||||
with open(os.path.join(directory, f"{tag}.port"), "w", encoding="utf-8") as f:
|
||||
f.write(f"{port}\n")
|
||||
except OSError:
|
||||
denied(directory, "write to")
|
||||
finally:
|
||||
os.umask(old)
|
||||
_awg_write(text, os.path.join(directory, f"{tag}.awg"), container)
|
||||
_runtime_reload()
|
||||
_runtime_entry_verify("outbound", tag)
|
||||
|
||||
|
||||
def _awg_add(*args):
|
||||
shape = "awg add [name] <vpn://…|file.conf|-> [--container <name>]"
|
||||
args = list(args)
|
||||
container = ""
|
||||
if "--container" in args:
|
||||
i = args.index("--container")
|
||||
container = args[i + 1] if i + 1 < len(args) else ""
|
||||
del args[i : i + 2]
|
||||
if not container:
|
||||
usage(shape)
|
||||
require_enabled("AWG_RUNTIME_GLOBAL", "Adding AmneziaWG profiles at runtime")
|
||||
if len(args) == 1:
|
||||
name, source = "", args[0]
|
||||
elif len(args) == 2 and (_awg_source(args[0]) or args[0] == "-"):
|
||||
die(f"The name goes first, the config after it: proxy-ctl {shape}")
|
||||
elif len(args) == 2:
|
||||
name, source = args
|
||||
else:
|
||||
usage(shape)
|
||||
# "warp" names WARP's own AmneziaWG unit (_warp_unit).
|
||||
taken = {*_awg_profiles(), "warp"}
|
||||
if name == "warp":
|
||||
die("'warp' is reserved for WARP; pick another name.")
|
||||
if name:
|
||||
if not AWG_NAME.fullmatch(name):
|
||||
die(f"Invalid profile name '{name}': up to 32 letters, digits, dashes and underscores, starting with a letter or digit.")
|
||||
if name in taken:
|
||||
die(f"An AmneziaWG profile named '{name}' already exists." + ("" if name in _awg_runtime_profiles() else " It is declared in the NixOS configuration."))
|
||||
text = _awg_input(source)
|
||||
described = _awg_describe(text, container)
|
||||
if not name:
|
||||
base = re.sub(r"[^A-Za-z0-9_-]+", "-", _awg_label(described, "awg")).strip("-_")[:32].strip("-_") or "awg"
|
||||
name, n = base, 1
|
||||
while name in taken:
|
||||
n += 1
|
||||
name = f"{base[: 32 - len(str(n)) - 1]}-{n}"
|
||||
print(f"Name: {name} (none given; pass one first to choose it)")
|
||||
_awg_write(text, os.path.join(_awg_runtime_dir(), f"{name}.conf"), container)
|
||||
print(f"Added AmneziaWG profile: {name} - start it with: proxy-ctl awg on {name}")
|
||||
|
||||
|
||||
def _awg_rm(name="", *_):
|
||||
if not name:
|
||||
usage("awg rm <profile>")
|
||||
if name not in _awg_runtime_profiles():
|
||||
if name in _awg_profiles():
|
||||
die(f"'{name}' is declared in the NixOS configuration; remove it there.")
|
||||
die(f"No AmneziaWG profile named '{name}' was added with awg add.")
|
||||
directory = _awg_runtime_dir()
|
||||
if not os.access(directory, os.W_OK | os.X_OK):
|
||||
denied(directory, "write to")
|
||||
unit = _awg_service(name)
|
||||
if svc_active(unit) or svc_state(unit) == "failed":
|
||||
must("stop", unit)
|
||||
# As `awg off`: the kill switch would otherwise hold with no tunnel to guard.
|
||||
if svc_exists(KILL_SWITCH):
|
||||
systemctl("stop", KILL_SWITCH)
|
||||
try:
|
||||
os.unlink(os.path.join(directory, f"{name}.conf"))
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError:
|
||||
denied(os.path.join(directory, f"{name}.conf"), "remove")
|
||||
print(f"Removed AmneziaWG profile: {name}")
|
||||
|
||||
|
||||
def _active_awg_profiles():
|
||||
return [p for p in _awg_profiles() if svc_active(_awg_service(p))]
|
||||
|
||||
|
||||
def cmd_awg(verb="list", *args):
|
||||
if verb == "add":
|
||||
_awg_add(*args)
|
||||
return
|
||||
if verb in ("rm", "remove", "del"):
|
||||
_awg_rm(*args)
|
||||
return
|
||||
profiles = _awg_profiles()
|
||||
if args and args[0] not in profiles:
|
||||
die(f"Unknown AmneziaWG profile: {args[0]}")
|
||||
@@ -2854,11 +3120,11 @@ def cmd_awg(verb="list", *args):
|
||||
usage("awg toggle <profile>")
|
||||
if verb in ("list", "status"):
|
||||
if not profiles:
|
||||
print("No AmneziaWG profiles configured.")
|
||||
print("No AmneziaWG profiles configured." + (" Add one with: proxy-ctl awg add <vpn://…|file.conf>" if env("AWG_RUNTIME_GLOBAL") == "1" else ""))
|
||||
return
|
||||
print(f" {'PROFILE':<24} STATUS")
|
||||
print(f" {'PROFILE':<24} {'STATUS':<12} SOURCE")
|
||||
for profile in profiles:
|
||||
print(f" {profile:<24} {svc_state(_awg_service(profile)) or 'unknown'}")
|
||||
print(f" {profile:<24} {svc_state(_awg_service(profile)) or 'unknown':<12} {'runtime' if _awg_added(profile) else 'declared'}")
|
||||
elif verb == "on":
|
||||
if not args:
|
||||
usage("awg on <profile>")
|
||||
@@ -2873,7 +3139,7 @@ def cmd_awg(verb="list", *args):
|
||||
if verb == "off" and svc_exists(KILL_SWITCH):
|
||||
systemctl("stop", KILL_SWITCH)
|
||||
else:
|
||||
usage("awg [list] | on <profile> | off [profile] | toggle [profile] | restart [profile]")
|
||||
usage("awg [list] | on <profile> | off [profile] | toggle [profile] | restart [profile] | add [name] <config> | rm <profile>")
|
||||
|
||||
|
||||
# --- wl -----------------------------------------------------------------------
|
||||
|
||||
+14
-12
@@ -953,11 +953,11 @@ class Window(Adw.ApplicationWindow):
|
||||
except GLib.Error as e:
|
||||
self.toast(f"Cannot read the clipboard: {e.message}")
|
||||
return
|
||||
argv, what = model.paste_argv(page.tab.id, text)
|
||||
argv, what, stdin = model.paste_argv(page.tab.id, text)
|
||||
if argv is None:
|
||||
self.toast(what)
|
||||
else:
|
||||
self.app.run_argv("run", argv, self)
|
||||
self.app.run_argv("run", argv, self, stdin=stdin)
|
||||
|
||||
def follow_logs(self):
|
||||
self.app.run_argv("suspend", ["logs"], self)
|
||||
@@ -977,13 +977,14 @@ class Window(Adw.ApplicationWindow):
|
||||
def with_text(text=""):
|
||||
try:
|
||||
argv = action.argv(row, text, self.app.states)
|
||||
stdin = action.stdin(row, text) if action.stdin else None
|
||||
except (ValueError, IndexError) as e:
|
||||
self.toast(f"Cannot run that: {e}")
|
||||
return
|
||||
if model.needs_confirm(action, row):
|
||||
self.app.confirm(argv, lambda: self.app.run_argv(action.mode, argv, self), self)
|
||||
self.app.confirm(argv, lambda: self.app.run_argv(action.mode, argv, self, stdin=stdin), self)
|
||||
else:
|
||||
self.app.run_argv(action.mode, argv, self)
|
||||
self.app.run_argv(action.mode, argv, self, stdin=stdin)
|
||||
|
||||
if not action.prompt:
|
||||
with_text()
|
||||
@@ -1280,9 +1281,10 @@ class ProxySuiteGui(Adw.Application):
|
||||
dialog.connect("response", lambda _, r: r == "run" and then())
|
||||
dialog.present(parent)
|
||||
|
||||
def run_argv(self, mode, argv, win, root=False):
|
||||
def run_argv(self, mode, argv, win, root=False, stdin=None):
|
||||
"""run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard.
|
||||
root, or the elevated toggle: through pkexec. Never `apps run`, which is per user."""
|
||||
root, or the elevated toggle: through pkexec. Never `apps run`, which is per user.
|
||||
stdin: text proxy-ctl reads (argv says "-"), kept out of argv and pkexec's log."""
|
||||
root = (root or self.elevated()) and argv[:1] != ["apps"]
|
||||
command = f"{'pkexec ' if root else ''}proxy-ctl {shlex.join(argv)}"
|
||||
retry_argv = argv
|
||||
@@ -1295,12 +1297,12 @@ class ProxySuiteGui(Adw.Application):
|
||||
dialog.present(win)
|
||||
elif win is not None:
|
||||
win.toast(f"… {command}")
|
||||
threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr, root, retry_argv), daemon=True).start()
|
||||
threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr, root, retry_argv, stdin), daemon=True).start()
|
||||
|
||||
def stream(self, command, argv, mode, win, dialog, qr, root, retry_argv):
|
||||
def stream(self, command, argv, mode, win, dialog, qr, root, retry_argv, stdin=None):
|
||||
out = []
|
||||
try:
|
||||
p = model.popen(argv, "pkexec" if root else None)
|
||||
p = model.popen(argv, "pkexec" if root else None, stdin=stdin)
|
||||
if dialog:
|
||||
GLib.idle_add(lambda: dialog.running(p, stoppable=not root) and False)
|
||||
for line in p.stdout:
|
||||
@@ -1313,13 +1315,13 @@ class ProxySuiteGui(Adw.Application):
|
||||
status = 127
|
||||
if root and status == 126 and not out:
|
||||
out.append("authentication cancelled") # pkexec: the password dialog was dismissed
|
||||
GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv) and False)
|
||||
GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv, stdin) and False)
|
||||
|
||||
def ran(self, command, mode, win, dialog, qr, out, status, retry_argv):
|
||||
def ran(self, command, mode, win, dialog, qr, out, status, retry_argv, stdin=None):
|
||||
last = last_line(out)
|
||||
text = "\n".join(out)
|
||||
output = (command, text)
|
||||
retry = (lambda: self.run_argv(mode, retry_argv, win, root=True)) if model.needs_root(out, status) else None
|
||||
retry = (lambda: self.run_argv(mode, retry_argv, win, root=True, stdin=stdin)) if model.needs_root(out, status) else None
|
||||
if win is not None:
|
||||
win.last_output = output
|
||||
win.last_retry = retry
|
||||
|
||||
+126
-20
@@ -66,6 +66,7 @@ class Action:
|
||||
mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal; pause: suspend, then wait for enter; copy: last line to the clipboard
|
||||
offered: Callable = None # () -> this configuration has it; None: every one does
|
||||
tty: bool = False # it asks on the terminal: only a front end that hands the terminal over offers it
|
||||
stdin: Callable = None # (selected row or None, prompt text) -> text proxy-ctl reads on stdin, or None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -150,6 +151,7 @@ TOGGLES = {
|
||||
"proxy-suite-zapret": ["zapret"],
|
||||
}
|
||||
AWG_PREFIX = ctl._awg_service("")
|
||||
AWG_RUNTIME_PREFIX = "proxy-suite-awg@"
|
||||
ZAPRET_LISTS = (
|
||||
("learned", "zapret-hosts-auto.txt"),
|
||||
("pinned", "zapret-hosts-user.txt"),
|
||||
@@ -183,8 +185,11 @@ def _wl_argv(verb, *extra):
|
||||
|
||||
def _awg_profile(row):
|
||||
"""The global AmneziaWG profile behind a row, or empty."""
|
||||
name = row["unit"].removeprefix(AWG_PREFIX)
|
||||
return name if row["unit"].startswith(AWG_PREFIX) and name in ctl._awg_profiles() else ""
|
||||
unit = row["unit"]
|
||||
for prefix in (AWG_RUNTIME_PREFIX, AWG_PREFIX):
|
||||
if unit.startswith(prefix) and (name := unit.removeprefix(prefix)) in ctl._awg_profiles():
|
||||
return name
|
||||
return ""
|
||||
|
||||
|
||||
def _unit_argv(row, verb):
|
||||
@@ -264,6 +269,44 @@ def outbound_summary():
|
||||
)
|
||||
|
||||
|
||||
def awg_rows(states):
|
||||
return [
|
||||
{
|
||||
"key": p,
|
||||
"profile": p,
|
||||
"unit": ctl._awg_service(p),
|
||||
"state": states.get(ctl._awg_service(p)) or "inactive",
|
||||
"source": "runtime" if ctl._awg_added(p) else "declared",
|
||||
}
|
||||
for p in ctl._awg_profiles()
|
||||
]
|
||||
|
||||
|
||||
def _awg_available(_):
|
||||
return bool(ctl._awg_profiles()) or ctl.env("AWG_RUNTIME_GLOBAL") == "1"
|
||||
|
||||
|
||||
def _awg_add(text):
|
||||
"""[name] <config> as typed: (name or None, the config or a path to it)."""
|
||||
text = text.strip()
|
||||
if ctl._awg_source(text):
|
||||
return None, text
|
||||
parts = text.split(None, 1)
|
||||
return (parts[0], parts[1].strip()) if len(parts) == 2 else (None, text)
|
||||
|
||||
|
||||
def _awg_add_argv(text):
|
||||
name, source = _awg_add(text)
|
||||
# The config itself goes on stdin: in argv its keys would show in ps, sudo's log and here.
|
||||
what = "-" if ctl._awg_source(source) else _path(source)
|
||||
return ["awg", "add", *([name] if name else []), what]
|
||||
|
||||
|
||||
def _awg_add_stdin(text):
|
||||
_, source = _awg_add(text)
|
||||
return source if ctl._awg_source(source) else None
|
||||
|
||||
|
||||
def subscription_rows(_):
|
||||
rows = []
|
||||
for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))):
|
||||
@@ -441,9 +484,19 @@ def _sub_url(row):
|
||||
|
||||
|
||||
def _add_args(text):
|
||||
"""[tag] <url>, or JSON with spaces in it, as `proxy-ctl ... add` takes them."""
|
||||
"""[tag] <url>, or JSON with spaces in it, as `proxy-ctl ... add` takes them.
|
||||
An AmneziaWG config becomes "-": _add_stdin hands it over on stdin."""
|
||||
text = text.strip()
|
||||
return [text] if text.startswith("{") else text.split(None, 1)
|
||||
if text.startswith("{"):
|
||||
return [text]
|
||||
name, source = _awg_add(text)
|
||||
if ctl._awg_source(source):
|
||||
return [*([name] if name else []), "-"]
|
||||
return text.split(None, 1)
|
||||
|
||||
|
||||
def _add_stdin(text):
|
||||
return _awg_add_stdin(text)
|
||||
|
||||
|
||||
def _zapret_auto():
|
||||
@@ -519,6 +572,28 @@ TABS = [
|
||||
),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"awg",
|
||||
"AmneziaWG",
|
||||
_awg_available,
|
||||
[("profile", "Profile"), ("state", "State"), ("source", "Source")],
|
||||
awg_rows,
|
||||
summary=lambda: "Only one global tunnel runs at a time: starting a profile stops TUN, TProxy and any other profile.",
|
||||
actions=[
|
||||
Action("space", "start / stop", lambda r, *_: ["awg", "off" if r["state"] == "active" else "on", r["profile"]], when=ROW),
|
||||
Action("ctrl+r", "restart it", lambda r, *_: ["awg", "restart", r["profile"]], when=lambda r: r["state"] in ("active", "failed")),
|
||||
Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"),
|
||||
Action(
|
||||
"n",
|
||||
"add a profile (name optional)…",
|
||||
lambda r, t, _: _awg_add_argv(t),
|
||||
prompt="[name] <vpn://… or a .conf path> - e.g. home vpn://… (or paste a whole .conf onto the table)",
|
||||
stdin=lambda r, t: _awg_add_stdin(t),
|
||||
offered=lambda: ctl.env("AWG_RUNTIME_GLOBAL") == "1",
|
||||
),
|
||||
Action("d", "remove it", lambda r, *_: ["awg", "rm", r["profile"]], when=lambda r: r["source"] == "runtime", confirm=True),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"routing",
|
||||
"Routing",
|
||||
@@ -557,7 +632,8 @@ TABS = [
|
||||
"n",
|
||||
"add a runtime outbound (tag optional)…",
|
||||
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t)],
|
||||
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
|
||||
prompt="[tag] <url, JSON or vpn://> - e.g. de-1 vless://… or just vless://…",
|
||||
stdin=lambda r, t: _add_stdin(t),
|
||||
),
|
||||
Action(
|
||||
"h",
|
||||
@@ -704,28 +780,42 @@ OUTBOUND_ADD = ["proxy", "outbounds", "add"]
|
||||
|
||||
|
||||
def paste_argv(tab_id, text):
|
||||
"""What pasting the clipboard onto a tab runs: (argv, ""), or (None, why it runs nothing).
|
||||
"""What pasting the clipboard onto a tab runs: (argv, "", stdin), or (None, why it runs nothing, None).
|
||||
|
||||
Dumb on purpose: a share link becomes an outbound, a subscription URL a subscription,
|
||||
a bare host a pinned or learned one. The tag comes from the link, as `add` derives it.
|
||||
a bare host a pinned or learned one, an AmneziaWG vpn:// link or .conf a global profile
|
||||
(an outbound on the outbounds tab). The tag comes from the link, as `add` derives it.
|
||||
"""
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
return None, "Nothing to paste."
|
||||
return None, "Nothing to paste.", None
|
||||
if ctl._awg_source(text):
|
||||
return _awg_paste(tab_id, text)
|
||||
if text.startswith("{"):
|
||||
return [*OUTBOUND_ADD, text], "" # only outbounds take JSON
|
||||
return [*OUTBOUND_ADD, text], "", None # only outbounds take JSON
|
||||
if len(text.splitlines()) > 1:
|
||||
return None, "Paste one link at a time."
|
||||
return None, "Paste one link at a time.", None
|
||||
scheme = text.split("://", 1)[0].lower() if "://" in text else ""
|
||||
if scheme in PROXY_SCHEMES:
|
||||
return [*OUTBOUND_ADD, text], ""
|
||||
return [*OUTBOUND_ADD, text], "", None
|
||||
if scheme in ("http", "https"):
|
||||
return ([*OUTBOUND_ADD, text] if tab_id == "outbounds" else ["proxy", "subs", "add", text]), ""
|
||||
return ([*OUTBOUND_ADD, text] if tab_id == "outbounds" else ["proxy", "subs", "add", text]), "", None
|
||||
if scheme:
|
||||
return None, f"Nothing takes a {scheme}:// link."
|
||||
return None, f"Nothing takes a {scheme}:// link.", None
|
||||
if HOST.fullmatch(text) and tab_id in HOST_ARGV:
|
||||
return [*HOST_ARGV[tab_id], text], ""
|
||||
return None, "Not a share link, a subscription URL or a host."
|
||||
return [*HOST_ARGV[tab_id], text], "", None
|
||||
return None, "Not a share link, a subscription URL or a host.", None
|
||||
|
||||
|
||||
def _awg_paste(tab_id, text):
|
||||
"""An AmneziaWG config, on stdin: an outbound where outbounds are, else a global profile."""
|
||||
outbound = ctl.env("AWG_RUNTIME_OUTBOUNDS") == "1"
|
||||
global_ = ctl.env("AWG_RUNTIME_GLOBAL") == "1"
|
||||
if outbound and (tab_id == "outbounds" or not global_):
|
||||
return [*OUTBOUND_ADD, "-"], "", text
|
||||
if global_:
|
||||
return ["awg", "add", "-"], "", text
|
||||
return None, "AmneziaWG configs cannot be added here: amneziaWg.runtime is off in this configuration.", None
|
||||
|
||||
|
||||
def available_tabs(states):
|
||||
@@ -795,13 +885,28 @@ def load_tab_as_root(tab, via):
|
||||
return None, (p.stderr.strip().splitlines() or [f"exit status {p.returncode}"])[-1]
|
||||
|
||||
|
||||
def popen(argv, root=None):
|
||||
def popen(argv, root=None, stdin=None):
|
||||
"""proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too.
|
||||
root: "pkexec" to run it as root, asking through the desktop's polkit agent."""
|
||||
return subprocess.Popen(
|
||||
elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
|
||||
root: "pkexec" to run it as root, asking through the desktop's polkit agent.
|
||||
stdin: text for it to read (argv then says "-"), kept out of argv, ps and sudo's log."""
|
||||
p = subprocess.Popen(
|
||||
elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.DEVNULL if stdin is None else subprocess.PIPE,
|
||||
text=True, errors="replace", start_new_session=True,
|
||||
)
|
||||
feed(p, stdin)
|
||||
return p
|
||||
|
||||
|
||||
def feed(p, stdin):
|
||||
"""Hands a started process its stdin text, and closes it."""
|
||||
if stdin is None:
|
||||
return
|
||||
try:
|
||||
p.stdin.write(stdin)
|
||||
p.stdin.close()
|
||||
except (BrokenPipeError, OSError):
|
||||
pass # it exited first: its output says why
|
||||
|
||||
|
||||
def stop(proc):
|
||||
@@ -889,7 +994,8 @@ def tray_menu(snap, outbounds=None):
|
||||
if snap[name]["available"]:
|
||||
active = snap[name]["active"]
|
||||
traffic.append(MenuItem(name, label, kind="check", checked=active, argv=["proxy", name, "off" if active else "on"]))
|
||||
if snap["awg"]["available"]:
|
||||
# Available with none added yet: nothing to pick until `awg add`.
|
||||
if snap["awg"]["available"] and snap["awg"]["profiles"]:
|
||||
current = snap["awg"]["active"]
|
||||
traffic.append(
|
||||
MenuItem(
|
||||
|
||||
+23
-15
@@ -433,7 +433,7 @@ class ProxyTui(App):
|
||||
self.typed = {} # prompt title -> what was last typed there
|
||||
self.feedback_timer = None
|
||||
self.last_output = None # (title, text)
|
||||
self.retry = None # (mode, argv) of the last run that only root could do
|
||||
self.retry = None # (mode, argv, stdin) of the last run that only root could do
|
||||
self.animation_level = "none" # tab switches land at once
|
||||
self.register_theme(THEME)
|
||||
self.theme = THEME.name
|
||||
@@ -641,11 +641,11 @@ class ProxyTui(App):
|
||||
if self.screen is not self.main:
|
||||
return
|
||||
event.stop()
|
||||
argv, what = model.paste_argv(self.active_tab(), event.text)
|
||||
argv, what, stdin = model.paste_argv(self.active_tab(), event.text)
|
||||
if argv is None:
|
||||
self.feedback(what, False)
|
||||
else:
|
||||
self.run_argv("run", argv)
|
||||
self.run_argv("run", argv, stdin)
|
||||
|
||||
def action_where(self):
|
||||
self.perform(model.WHERE, None)
|
||||
@@ -705,13 +705,14 @@ class ProxyTui(App):
|
||||
def with_text(text=""):
|
||||
try:
|
||||
argv = action.argv(row, text, self.states)
|
||||
stdin = action.stdin(row, text) if action.stdin else None
|
||||
except (ValueError, IndexError) as e: # an unbalanced quote in a typed command
|
||||
self.feedback(f"Cannot run that: {e}", False)
|
||||
return
|
||||
if model.needs_confirm(action, row):
|
||||
self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv))
|
||||
self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv, stdin))
|
||||
else:
|
||||
self.run_argv(action.mode, argv)
|
||||
self.run_argv(action.mode, argv, stdin)
|
||||
|
||||
def typed(text):
|
||||
if text:
|
||||
@@ -724,7 +725,8 @@ class ProxyTui(App):
|
||||
else:
|
||||
with_text()
|
||||
|
||||
def run_argv(self, mode, argv):
|
||||
def run_argv(self, mode, argv, stdin=None):
|
||||
"""stdin: text proxy-ctl reads (argv says "-"); only for runs that stay in the TUI."""
|
||||
command = f"proxy-ctl {shlex.join(argv)}"
|
||||
if mode in ("suspend", "pause"):
|
||||
self.foreground(mode, [CTL, *argv])
|
||||
@@ -734,7 +736,7 @@ class ProxyTui(App):
|
||||
if dialog:
|
||||
self.push_screen(dialog)
|
||||
self.feedback(f"… {command}")
|
||||
self.stream(command, argv, dialog, mode == "copy")
|
||||
self.stream(command, argv, dialog, mode == "copy", stdin)
|
||||
|
||||
def foreground(self, mode, argv):
|
||||
with self.suspend():
|
||||
@@ -747,10 +749,10 @@ class ProxyTui(App):
|
||||
self.action_reload()
|
||||
|
||||
@work(thread=True)
|
||||
def stream(self, command, argv, dialog, copy=False):
|
||||
def stream(self, command, argv, dialog, copy=False, stdin=None):
|
||||
out = []
|
||||
try:
|
||||
p = model.popen(argv)
|
||||
p = model.popen(argv, stdin=stdin)
|
||||
if dialog:
|
||||
dialog.proc = p
|
||||
for line in p.stdout:
|
||||
@@ -761,9 +763,9 @@ class ProxyTui(App):
|
||||
except OSError as e:
|
||||
out.append(f"cannot run proxy-ctl: {e}")
|
||||
status = 127
|
||||
self.call_from_thread(self.finish, command, argv, dialog, copy, out, status, stream_shown=True)
|
||||
self.call_from_thread(self.finish, command, argv, dialog, copy, out, status, stream_shown=True, stdin=stdin)
|
||||
|
||||
def finish(self, command, argv, dialog, copy, out, status, stream_shown=False):
|
||||
def finish(self, command, argv, dialog, copy, out, status, stream_shown=False, stdin=None):
|
||||
"""A run's end: the feedback line, the clipboard, and the dialog's tail."""
|
||||
if dialog and not stream_shown:
|
||||
for line in out:
|
||||
@@ -784,7 +786,7 @@ class ProxyTui(App):
|
||||
hints = ["o: full output"] if len(out) > 1 and not dialog else []
|
||||
self.retry = None
|
||||
if model.needs_root(out, status):
|
||||
self.retry = ("dialog" if dialog else "copy" if copy else "run", argv)
|
||||
self.retry = ("dialog" if dialog else "copy" if copy else "run", argv, stdin)
|
||||
hints.append("!: retry as root")
|
||||
if dialog:
|
||||
dialog.offer_retry()
|
||||
@@ -795,7 +797,8 @@ class ProxyTui(App):
|
||||
if not self.retry:
|
||||
self.feedback("Nothing to retry as root.")
|
||||
return
|
||||
(mode, argv), self.retry = self.retry, None
|
||||
(mode, argv, *rest), self.retry = self.retry, None
|
||||
stdin = rest[0] if rest else None
|
||||
command = f"sudo proxy-ctl {shlex.join(argv)}"
|
||||
root_argv = model.elevated(argv, "sudo")
|
||||
# sudo asks on the terminal, so the run happens there; the output comes back as usual.
|
||||
@@ -803,7 +806,12 @@ class ProxyTui(App):
|
||||
with self.suspend():
|
||||
print(f"$ {command}", flush=True)
|
||||
try:
|
||||
p = subprocess.Popen(root_argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace")
|
||||
# sudo asks for the password on the terminal itself, so stdin can carry the text.
|
||||
p = subprocess.Popen(
|
||||
root_argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace",
|
||||
**({"stdin": subprocess.PIPE} if stdin is not None else {}),
|
||||
)
|
||||
model.feed(p, stdin)
|
||||
except OSError as e:
|
||||
p, status, out = None, 127, [f"cannot run sudo: {e}"]
|
||||
if p:
|
||||
@@ -821,7 +829,7 @@ class ProxyTui(App):
|
||||
dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None
|
||||
if dialog:
|
||||
self.push_screen(dialog)
|
||||
self.finish(command, argv, dialog, mode == "copy", out, status)
|
||||
self.finish(command, argv, dialog, mode == "copy", out, status, stdin=stdin)
|
||||
|
||||
def action_switch_root(self):
|
||||
def switch(ok):
|
||||
|
||||
@@ -602,7 +602,9 @@ class AutoProxyTest(EnvTest):
|
||||
self.assertIn("proxy-suite group, or re-run with sudo", err)
|
||||
|
||||
|
||||
class RuntimeEntryTest(EnvTest):
|
||||
class RuntimeSpoolTest(EnvTest):
|
||||
"""The runtime spools, and a backend that reads them back on every reload."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
os.environ.update(
|
||||
@@ -636,6 +638,8 @@ class RuntimeEntryTest(EnvTest):
|
||||
self.backend_start()
|
||||
return 0, ""
|
||||
|
||||
|
||||
class RuntimeEntryTest(RuntimeSpoolTest):
|
||||
def test_tag_for(self):
|
||||
tag = ctl._runtime_tag_for
|
||||
self.assertEqual(tag("outbound", "vless://u@de1.example.net:443?security=reality#%F0%9F%87%A9%F0%9F%87%AA%20DE-1"), "DE-1")
|
||||
@@ -754,6 +758,115 @@ class RuntimeEntryTest(EnvTest):
|
||||
self.assertEqual(os.listdir(self.path("outbounds.d")), [])
|
||||
|
||||
|
||||
AWG_CONF = """[Interface]
|
||||
PrivateKey = private
|
||||
Address = 10.8.0.2/32
|
||||
|
||||
[Peer]
|
||||
PublicKey = public
|
||||
AllowedIPs = 0.0.0.0/0
|
||||
Endpoint = vpn.example.com:51820
|
||||
"""
|
||||
|
||||
|
||||
def awg_vpn_link(description):
|
||||
"""A vpn:// export carrying AWG_CONF, as the Amnezia app writes one."""
|
||||
import base64
|
||||
import zlib
|
||||
|
||||
data = json.dumps({"description": description, "containers": [{"container": "amnezia-awg", "awg": {"last_config": json.dumps({"config": AWG_CONF})}}]}).encode()
|
||||
return "vpn://" + base64.urlsafe_b64encode(len(data).to_bytes(4, "big") + zlib.compress(data)).decode().rstrip("=")
|
||||
|
||||
|
||||
class AmneziaWgRuntimeTest(RuntimeSpoolTest):
|
||||
"""`awg add`/`rm` and AmneziaWG outbounds: amneziawg_config.py itself checks and writes them."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
tool = os.environ.get("AWG_CONFIG_TOOL") or os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../scripts/amneziawg_config.py")
|
||||
os.makedirs(self.path("amneziawg.d"))
|
||||
os.environ.update(
|
||||
AWG_CONFIG_TOOL=tool,
|
||||
AWG_RUNTIME_GLOBAL="1",
|
||||
AWG_RUNTIME_OUTBOUNDS="1",
|
||||
AWG_RUNTIME_DIR=self.path("amneziawg.d"),
|
||||
AWG_PROFILES_FILE=self.write("awg-profiles.json", ["home"]),
|
||||
AWG_TUNNEL_BASE_PORT="18800",
|
||||
AWG_TUNNEL_SLOTS="2",
|
||||
)
|
||||
self.active = set()
|
||||
self.patch("svc_active", lambda unit: unit in self.active)
|
||||
self.patch("svc_state", lambda unit: "active" if unit in self.active else "inactive")
|
||||
self.patch("svc_exists", lambda unit: True)
|
||||
|
||||
def test_add_and_rm_global_profiles(self):
|
||||
# Named after the server's host, then after the export's description; the config on stdin.
|
||||
self.assertIn("Name: awg-example (none given", ok(ctl.cmd_awg, "add", AWG_CONF))
|
||||
self.assertIn("Name: awg-example-2", ok(ctl.cmd_awg, "add", AWG_CONF))
|
||||
with mock.patch.object(sys, "stdin", io.StringIO(awg_vpn_link("Work VPN"))):
|
||||
self.assertIn("Name: Work-VPN", ok(ctl.cmd_awg, "add", "-"))
|
||||
conf = self.write("office.conf", AWG_CONF)
|
||||
ok(ctl.cmd_awg, "add", "office", conf)
|
||||
path = self.path("amneziawg.d/office.conf")
|
||||
self.assertEqual(os.stat(path).st_mode & 0o777, 0o600)
|
||||
self.assertIn("Endpoint = vpn.example.com:51820", ctl.read_text(path))
|
||||
self.assertEqual(ctl._awg_profiles(), ["home", "Work-VPN", "awg-example", "awg-example-2", "office"])
|
||||
self.assertEqual(ctl._awg_service("office"), "proxy-suite-awg@office")
|
||||
self.assertEqual(ctl._awg_service("home"), "proxy-suite-awg-home")
|
||||
listing = ok(ctl.cmd_awg, "list")
|
||||
self.assertRegex(listing, r"home\s+inactive\s+declared")
|
||||
self.assertRegex(listing, r"office\s+inactive\s+runtime")
|
||||
self.assertIn("office", ctl._complete_tree("awg", "rm"))
|
||||
# Refused: a taken or reserved name, the wrong order, hooks, and anything but a config.
|
||||
for args, why in [
|
||||
(("home", AWG_CONF), "declared in the NixOS configuration"),
|
||||
(("office", AWG_CONF), "already exists"),
|
||||
(("warp", AWG_CONF), "reserved"),
|
||||
(("bad name", AWG_CONF), "Invalid profile name"),
|
||||
((AWG_CONF, "later"), "The name goes first"),
|
||||
(("hooked", AWG_CONF.replace("Address", "PostUp = id\nAddress")), "privileged"),
|
||||
(("nothing", "vless://u@x.test:443"), "Cannot read"),
|
||||
]:
|
||||
with self.subTest(args=args[0][:10]):
|
||||
status, _, err = run(ctl.cmd_awg, "add", *args)
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn(why, err)
|
||||
self.assertFalse(os.path.exists(self.path("amneziawg.d/hooked.conf")))
|
||||
# rm: only what awg add added; a running one stops first, and its kill switch with it.
|
||||
self.assertIn("remove it there", run(ctl.cmd_awg, "rm", "home")[2])
|
||||
self.active.add("proxy-suite-awg@office")
|
||||
self.assertIn("Removed AmneziaWG profile: office", ok(ctl.cmd_awg, "rm", "office"))
|
||||
self.assertIn(("stop", "proxy-suite-awg@office"), self.started)
|
||||
self.assertIn(("stop", ctl.KILL_SWITCH), self.started)
|
||||
self.assertFalse(os.path.exists(path))
|
||||
self.assertNotIn("office", ctl._awg_profiles())
|
||||
# Off in the configuration: nothing to add to, and nothing listed.
|
||||
os.environ["AWG_RUNTIME_GLOBAL"] = "0"
|
||||
self.assertIn("not enabled", run(ctl.cmd_awg, "add", AWG_CONF)[2])
|
||||
self.assertEqual(ctl._awg_profiles(), ["home"])
|
||||
|
||||
def test_outbounds(self):
|
||||
self.assertIn("Tag: awg-example", ok(ctl.cmd_outbounds, "add", AWG_CONF))
|
||||
self.assertEqual(ctl.read_text(self.path("outbounds.d/awg-example.port")), "18800\n")
|
||||
self.assertEqual(os.stat(self.path("outbounds.d/awg-example.awg")).st_mode & 0o777, 0o600)
|
||||
self.assertIn("proxy-suite-outbound-reload.service", self.started)
|
||||
# A file, with a tag: the next port.
|
||||
self.assertIn("Added outbound: de", ok(ctl.cmd_outbounds, "add", "de", self.write("de.conf", AWG_CONF)))
|
||||
self.assertEqual(ctl.read_text(self.path("outbounds.d/de.port")), "18801\n")
|
||||
self.assertIn("No free port", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF)[2])
|
||||
self.assertIn("cannot chain", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF, "--detour", "primary")[2])
|
||||
self.assertIn("--container only applies", run(ctl.cmd_outbounds, "add", "x", "vless://u@x.test:443", "--container", "c")[2])
|
||||
# A copy through a hop makes no sense for a tunnel that dials its peer itself.
|
||||
self.write("outbound-share.json", {"outbounds": {"de": {"outbound": {"type": "socks", "server": "127.0.0.1", "server_port": 18801}}}})
|
||||
self.assertIn("AmneziaWG outbound", run(ctl.cmd_outbound_chain, "de", "primary")[2])
|
||||
# rm takes the port along, which frees it.
|
||||
ok(ctl.cmd_outbounds, "rm", "de")
|
||||
self.assertFalse(os.path.exists(self.path("outbounds.d/de.port")))
|
||||
self.assertEqual(ctl._awg_free_port(), 18801)
|
||||
os.environ["AWG_RUNTIME_OUTBOUNDS"] = "0"
|
||||
self.assertIn("not enabled", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF)[2])
|
||||
|
||||
|
||||
class ZapretAutoTest(EnvTest):
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes anything")
|
||||
def test_clear_replaces_what_it_cannot_write(self):
|
||||
|
||||
@@ -11,7 +11,10 @@ import unittest
|
||||
from unittest import mock
|
||||
|
||||
import proxy_ctl as ctl
|
||||
import proxy_model as model
|
||||
|
||||
CLI_AWG_PROFILES = ctl._awg_profiles # before setUp patches it
|
||||
|
||||
import proxy_model as model # noqa: E402
|
||||
|
||||
|
||||
def walk(items):
|
||||
@@ -244,10 +247,67 @@ class ModelTest(unittest.TestCase):
|
||||
("zapret", "not a host", "Not a share link"),
|
||||
]:
|
||||
with self.subTest(text=text):
|
||||
argv, message = paste(tab, text)
|
||||
argv, message, stdin = paste(tab, text)
|
||||
self.assertIsNone(argv)
|
||||
self.assertIsNone(stdin)
|
||||
self.assertIn(why, message)
|
||||
|
||||
def test_paste_amneziawg(self):
|
||||
conf = "[Interface]\nPrivateKey = secret\nAddress = 10.8.0.2/32\n\n[Peer]\nPublicKey = p\nAllowedIPs = 0.0.0.0/0\n"
|
||||
runtime = {"AWG_RUNTIME_GLOBAL": "1", "AWG_RUNTIME_OUTBOUNDS": "1"}
|
||||
with mock.patch.dict(os.environ, runtime):
|
||||
# A global profile, but an outbound on the outbounds tab. The config itself only on stdin.
|
||||
self.assertEqual(model.paste_argv("services", conf), (["awg", "add", "-"], "", conf.strip()))
|
||||
self.assertEqual(model.paste_argv("awg", "vpn://AAAA"), (["awg", "add", "-"], "", "vpn://AAAA"))
|
||||
self.assertEqual(model.paste_argv("outbounds", "vpn://AAAA"), (["proxy", "outbounds", "add", "-"], "", "vpn://AAAA"))
|
||||
with mock.patch.dict(os.environ, {"AWG_RUNTIME_GLOBAL": "0", "AWG_RUNTIME_OUTBOUNDS": "1"}):
|
||||
self.assertEqual(model.paste_argv("services", "vpn://AAAA")[0], ["proxy", "outbounds", "add", "-"])
|
||||
with mock.patch.dict(os.environ, {"AWG_RUNTIME_GLOBAL": "0", "AWG_RUNTIME_OUTBOUNDS": "0"}):
|
||||
argv, why, stdin = model.paste_argv("services", conf)
|
||||
self.assertIsNone(argv)
|
||||
self.assertIn("amneziaWg.runtime", why)
|
||||
|
||||
def test_awg_tab(self):
|
||||
tab = next(t for t in model.TABS if t.id == "awg")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
open(os.path.join(d, "added.conf"), "w").close()
|
||||
profiles = os.path.join(d, "profiles.json")
|
||||
with open(profiles, "w") as f:
|
||||
json.dump(["home"], f)
|
||||
env = {"AWG_RUNTIME_GLOBAL": "1", "AWG_RUNTIME_DIR": d, "AWG_PROFILES_FILE": profiles}
|
||||
with mock.patch.dict(os.environ, env), mock.patch.object(ctl, "_awg_profiles", CLI_AWG_PROFILES):
|
||||
self.assertTrue(tab.available({}))
|
||||
rows, _ = model.load_tab(tab, {"proxy-suite-awg@added": "active"})
|
||||
self.assertEqual(
|
||||
[(r["profile"], r["unit"], r["state"], r["source"]) for r in rows],
|
||||
[("home", "proxy-suite-awg-home", "inactive", "declared"), ("added", "proxy-suite-awg@added", "active", "runtime")],
|
||||
)
|
||||
self.assertEqual([a.key for a in model.applicable(tab, rows[0])], ["space", "l", "n"])
|
||||
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["space", "ctrl+r", "l", "n", "d"])
|
||||
act = {a.key: a for a in tab.actions}
|
||||
self.assertEqual(act["space"].argv(rows[1], "", {}), ["awg", "off", "added"])
|
||||
self.assertEqual(act["d"].argv(rows[1], "", {}), ["awg", "rm", "added"])
|
||||
# The Services tab's row for the instance toggles it through `awg` too.
|
||||
self.assertEqual(model.toggle_argv({"unit": "proxy-suite-awg@added", "state": "active"}), ["awg", "off", "added"])
|
||||
add = next(a for a in tab.actions if a.key == "n")
|
||||
self.assertEqual((add.argv(None, "work vpn://AAAA", {}), add.stdin(None, "work vpn://AAAA")), (["awg", "add", "work", "-"], "vpn://AAAA"))
|
||||
self.assertEqual((add.argv(None, "vpn://AAAA", {}), add.stdin(None, "vpn://AAAA")), (["awg", "add", "-"], "vpn://AAAA"))
|
||||
# A path goes as one: proxy-ctl reads it, and it may run as root elsewhere.
|
||||
self.assertEqual((add.argv(None, "work /tmp/w.conf", {}), add.stdin(None, "work /tmp/w.conf")), (["awg", "add", "work", "/tmp/w.conf"], None))
|
||||
outbound_add = next(a for a in next(t for t in model.TABS if t.id == "outbounds").actions if a.key == "n")
|
||||
self.assertEqual(outbound_add.argv(None, "de vpn://AAAA", {}), ["proxy", "outbounds", "add", "de", "-"])
|
||||
self.assertEqual(outbound_add.stdin(None, "de vpn://AAAA"), "vpn://AAAA")
|
||||
self.assertEqual(outbound_add.argv(None, "de vless://x", {}), ["proxy", "outbounds", "add", "de", "vless://x"])
|
||||
self.assertIsNone(outbound_add.stdin(None, "de vless://x"))
|
||||
|
||||
def test_popen_feeds_stdin(self):
|
||||
with mock.patch.object(model, "CTL", "cat"):
|
||||
for stdin, out in (("secret\n", "secret\n"), (None, "")):
|
||||
p = model.popen([], stdin=stdin)
|
||||
with p.stdout:
|
||||
self.assertEqual(p.stdout.read(), out)
|
||||
p.wait()
|
||||
|
||||
def test_load_tab(self):
|
||||
tab = next(t for t in model.TABS if t.id == "outbounds")
|
||||
inventory = {"tags": ["a", "b"], "pinned": "b", "detours": {"a": "b"}, "excluded": ["b"]}
|
||||
|
||||
@@ -54,7 +54,8 @@ class TuiTest(unittest.TestCase):
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.ran = []
|
||||
patcher = mock.patch.object(tui.ProxyTui, "run_argv", lambda app, mode, argv: self.ran.append(argv))
|
||||
# A run with stdin is recorded with it: (argv, stdin).
|
||||
patcher = mock.patch.object(tui.ProxyTui, "run_argv", lambda app, mode, argv, stdin=None: self.ran.append(argv if stdin is None else (argv, stdin)))
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
@@ -69,7 +70,7 @@ class TuiTest(unittest.TestCase):
|
||||
|
||||
def test_retry_root_leaves_sigint_to_sudo(self):
|
||||
"""Ctrl-C at sudo's password prompt is sudo's: raised here it would take the TUI down with it."""
|
||||
app = mock.MagicMock(retry=("run", ["proxy", "on"]))
|
||||
app = mock.MagicMock(retry=("run", ["proxy", "on"], None))
|
||||
app.suspend.return_value = contextlib.nullcontext()
|
||||
before, during = signal.getsignal(signal.SIGINT), []
|
||||
with mock.patch.object(tui.subprocess, "Popen") as popen, contextlib.redirect_stdout(io.StringIO()):
|
||||
@@ -79,6 +80,20 @@ class TuiTest(unittest.TestCase):
|
||||
self.assertEqual(during, [signal.SIG_IGN])
|
||||
self.assertEqual(signal.getsignal(signal.SIGINT), before)
|
||||
self.assertEqual(app.finish.call_args.args[-2:], (["done"], 0))
|
||||
self.assertNotIn("stdin", popen.call_args.kwargs)
|
||||
|
||||
def test_retry_root_carries_stdin(self):
|
||||
"""A config pasted on stdin reaches sudo's proxy-ctl the same way."""
|
||||
app = mock.MagicMock(retry=("run", ["awg", "add", "-"], "vpn://AAAA"))
|
||||
app.suspend.return_value = contextlib.nullcontext()
|
||||
with mock.patch.object(tui.subprocess, "Popen") as popen, contextlib.redirect_stdout(io.StringIO()):
|
||||
popen.return_value.stdout = iter(["Added\n"])
|
||||
popen.return_value.wait.return_value = 0
|
||||
tui.ProxyTui.action_retry_root(app)
|
||||
self.assertEqual(popen.call_args.args[0][-3:], ["awg", "add", "-"])
|
||||
self.assertEqual(popen.call_args.kwargs["stdin"], tui.subprocess.PIPE)
|
||||
popen.return_value.stdin.write.assert_called_once_with("vpn://AAAA")
|
||||
self.assertEqual(app.finish.call_args.kwargs["stdin"], "vpn://AAAA")
|
||||
|
||||
def test_filter_sort_pack(self):
|
||||
rows = [{"key": "a", "host": "a.example", "kind": "learned"}, {"key": "b", "host": "learned.org", "kind": "pinned"}]
|
||||
@@ -139,6 +154,12 @@ class TuiTest(unittest.TestCase):
|
||||
await pilot.pause()
|
||||
self.assertEqual(self.ran, [])
|
||||
self.assertIn("ftp:// link", str(app.main.query_one("#feedback").content))
|
||||
# An AmneziaWG config: its keys go on stdin, never into argv.
|
||||
self.env["AWG_RUNTIME_OUTBOUNDS"] = "1"
|
||||
conf = "[Interface]\nPrivateKey = k\n[Peer]\nPublicKey = p"
|
||||
app.post_message(events.Paste(conf))
|
||||
await pilot.pause()
|
||||
self.assertEqual(self.ran.pop(), (["proxy", "outbounds", "add", "-"], conf))
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
@@ -211,7 +232,16 @@ class TuiTest(unittest.TestCase):
|
||||
self.assertEqual(self.ran.pop(), ["awg", "restart", "p"])
|
||||
app.table().move_cursor(row=list(app.rows["services"]).index("proxy-suite-tun"))
|
||||
|
||||
# Right arrow moves to Routing and its table has focus.
|
||||
# Right arrow moves to AmneziaWG, there with a profile, and its table has focus.
|
||||
await pilot.press("right")
|
||||
await self.settle(app, pilot)
|
||||
self.assertEqual((app.active_tab(), app.focused.id), ("awg", "awg-table"))
|
||||
await pilot.press("space")
|
||||
self.assertEqual(self.ran.pop(), ["awg", "off", "p"])
|
||||
# Declared: nothing removes it here.
|
||||
self.assertNotIn("d", app.screen.active_bindings)
|
||||
|
||||
# On to Routing.
|
||||
await pilot.press("right")
|
||||
await self.settle(app, pilot)
|
||||
self.assertEqual((app.active_tab(), app.focused.id), ("routing", "routing-table"))
|
||||
@@ -263,7 +293,7 @@ class TuiTest(unittest.TestCase):
|
||||
await pilot.press("escape")
|
||||
|
||||
# An empty tab says how to fill it.
|
||||
await pilot.press("4")
|
||||
await pilot.press("5")
|
||||
await self.settle(app, pilot)
|
||||
self.assertIn("Nothing here yet. n: add a runtime subscription", str(app.main.query_one("#subs-summary").content))
|
||||
|
||||
@@ -280,7 +310,7 @@ class TuiTest(unittest.TestCase):
|
||||
# Brackets in a summary are text, not markup.
|
||||
self.env["ZAPRET_CUTOFF_ENABLED"] = "1"
|
||||
self.capture = "Probed: [b] from [/x]\nCutoff: none on this line\n"
|
||||
await pilot.press("5")
|
||||
await pilot.press("6")
|
||||
await self.settle(app, pilot)
|
||||
self.assertIn("[/x]", str(app.main.query_one("#zapret-summary").content))
|
||||
await self.settle(app, pilot)
|
||||
@@ -333,7 +363,7 @@ class TuiTest(unittest.TestCase):
|
||||
self.env["INBOUNDS_ENABLED"] = "1"
|
||||
app.action_reload()
|
||||
await self.settle(app, pilot)
|
||||
await pilot.press("6")
|
||||
await pilot.press("7")
|
||||
await self.settle(app, pilot)
|
||||
await pilot.press("c")
|
||||
self.assertEqual(self.ran.pop(), ["inbounds", "link", "vless", "alice"])
|
||||
|
||||
Reference in new issue
Block a user