feat: per-app keep-running

This commit is contained in:
FUFSoB committed 2026-10-10 16:19:54 +05:00
1 parent 91f2397ac5
commit d70bcb317f
15 files changed
+570 -22

No files matched your search

+9 -3
View File
@@ -672,9 +672,15 @@ let
ExecStart = withArg start;
ExecStop = withArg stop;
}
// lib.optionalAttrs (cfg.proxy.enable && !outbound) {
ExecStopPost = proxyBypassDown;
}
// (
let
# Per-app zapret back once it is down, if kept running.
stopPost =
derived.constants.withPerAppStandby "${spec.unit}${lib.optionalString spec.template "*"}.service"
(if cfg.proxy.enable then proxyBypassDown else null);
in
lib.optionalAttrs (!outbound && stopPost != null) { ExecStopPost = stopPost; }
)
# The Endpoint lookup (ownLookups) gets past the kill switch by this group, so a
# profile that dropped can come back while the kill switch holds.
// lib.optionalAttrs (derived.killSwitchEnabled && !outbound) {
+125
View File
@@ -629,6 +629,109 @@ let
# Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode.
clashApiEnabled = singBoxEnabled;
perAppZapretEnabled = perAppZapretCfg.enable;
# The global units each per-app backend steps aside for (constants.refuseUnderGlobal), as
# systemctl patterns: they stop it as they start, and the standby unit waits them out.
perAppGlobalModes = {
"proxy-suite-per-app-tun" = [ ];
"proxy-suite-per-app-tproxy" = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
];
"proxy-suite-per-app-zapret" = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles)
)
++ lib.optional awgRuntimeGlobal "proxy-suite-awg@*.service";
};
# A tag as proxy-ctl names its via units: in hex, as Python's str.encode().hex().
hexOf =
s:
lib.concatMapStrings (
c: lib.fixedWidthString 2 "0" (lib.toLower (lib.toHexString (lib.strings.charToInt c)))
) (lib.stringToCharacters s);
# What `proxy-ctl apps run` starts for a declared profile (_run_via, cmd_apps_run), null for
# nothing of its own (direct, proxychains): `units`, in order, without ".service"; `modes`,
# the global units they step aside for; `key`, the via instance, if any.
perAppProfileUnits =
profile:
let
target = perAppViaTarget profile.outbound;
hex = hexOf target.name;
viaProfile =
target.kind != "outbound"
&& perAppViaProfiles
&& (target.kind == "awg" || awgGlobalProfiles ? ${target.name});
viaInterface = !viaProfile && builtins.any (ob: ob.tag == target.name) perAppViaInterfaceOutbounds;
backend = "proxy-suite-per-app-${profile.route}";
in
if profile.outbound == null then
if perAppGlobalModes ? ${backend} then
{
key = null;
units = [ backend ];
modes = perAppGlobalModes.${backend};
}
else
null
else if viaProfile then
{
key = "app-${hex}";
# The profile brought up for the apps alone, then the via unit on its slot.
units = [
"proxy-suite-awg-app@${target.name}"
"proxy-suite-per-app-via@app-${hex}"
];
modes = [
"proxy-suite-awg-${target.name}.service"
]
++ lib.optional awgRuntimeGlobal "proxy-suite-awg@${target.name}.service";
}
else if viaInterface then
{
key = "awg-${hex}";
units = [ "proxy-suite-per-app-via@awg-${hex}" ];
modes = [ ];
}
else
{
key = "${profile.route}-${hex}";
units = [ "proxy-suite-per-app-via-${profile.route}@${hex}" ];
modes = perAppGlobalModes."proxy-suite-per-app-tproxy";
};
# What is kept running between apps (perAppRouting.<route>.keepRunning and
# perAppRouting.profiles.*.keepRunning), as perAppProfileUnits gives it; the standby unit
# (service/units.nix) starts it.
perAppKeepRunning = lib.unique (
lib.concatMap
(
route:
lib.optional
(
cfg.perAppRouting.${route}.enable
&& cfg.perAppRouting.${route}.keepRunning
&& (route == "zapret" || proxyEnabled)
)
(perAppProfileUnits {
inherit route;
outbound = null;
})
)
[
"tun"
"tproxy"
"zapret"
]
++ builtins.filter (entry: entry != null) (
map perAppProfileUnits (builtins.filter (profile: profile.keepRunning) cfg.perAppRouting.profiles)
)
);
# The via instances kept: no last app's exit stops them, and no pin is taken back from them.
perAppKeptViaKeys = lib.filter (key: key != null) (map (entry: entry.key) perAppKeepRunning);
# The global modes whose stop brings something kept back (constants.withPerAppStandby).
perAppStandbyGlobalModes = lib.unique (lib.concatMap (entry: entry.modes) perAppKeepRunning);
# The system-wide instance; per-app zapret runs its own.
zapretGlobalEnabled = zapretCfg.enable && zapretCfg.global.enable;
zapretCutoffEnabled =
@@ -808,6 +911,23 @@ let
${cfg.host.systemctl}${managerFlag} stop -- "$unit" 2>/dev/null || true
done
''} ${lib.concatStringsSep " " patterns}";
# A global mode's ExecStopPost (null: none), and after it, if needed, what brings back
# the per-app backends kept running (perAppKeepRunning) that it stopped. `unit`: its
# perAppGlobalModes pattern; a template's, "<name>@*.service", stands for its instances.
# --no-block: the standby unit waits for this stop (After=).
withPerAppStandby =
unit: stopPost:
if
builtins.any (
mode:
mode == unit
|| (lib.hasSuffix "@*.service" unit && lib.hasPrefix (lib.removeSuffix "*.service" unit) mode)
) perAppStandbyGlobalModes
then
lib.optionals (stopPost != null) (lib.toList stopPost)
++ [ "-+${cfg.host.systemctl}${managerFlag} start --no-block proxy-suite-per-app-standby.service" ]
else
stopPost;
# The same for a unit that needs no root at all; "+" ExecStartPre/ExecStopPost
# commands still run privileged.
unprivilegedServiceConfig =
@@ -1127,6 +1247,11 @@ in
zapretEngine
perAppZapretCfg
perAppZapretEnabled
perAppProfileUnits
perAppKeepRunning
perAppKeptViaKeys
perAppGlobalModes
perAppStandbyGlobalModes
zapretGlobalEnabled
zapretCutoffEnabled
zapretCutoffProxyFallback
@@ -20,6 +20,20 @@ let
"10.0.0.0/8"
];
};
# `globalModes`: what it steps aside for (constants.refuseUnderGlobal), or null.
keepRunning =
what: globalModes:
mkOption {
type = types.bool;
default = false;
description = ''
Keep the ${what} backend running from boot, rather than starting it with the first app
and stopping it after the last: apps start without waiting for it.
''
+ lib.optionalString (globalModes != null) ''
Under a global ${globalModes} it stays down, and comes back once that stops.
'';
};
in
{
options.services.proxy-suite.perAppRouting = {
@@ -64,6 +78,7 @@ in
tun = {
enable = mkEnableOption "per-app TUN";
keepRunning = keepRunning "per-app TUN" null;
fwmark = int 16 "Firewall mark for wrapped apps' traffic.";
routeTable = int 101 "Routing table for the per-app TUN.";
localSubnets = localSubnets "Subnets that skip the proxy (DNS still goes through it).";
@@ -85,6 +100,7 @@ in
tproxy = {
enable = mkEnableOption "per-app TProxy";
keepRunning = keepRunning "per-app TProxy" "TUN or TProxy";
fwmark = int 17 "Firewall mark for wrapped apps' traffic.";
routeTable = int 102 "Routing table for the per-app TProxy.";
localSubnets = localSubnets "Subnets that skip the proxy (DNS still goes through it).";
@@ -106,6 +122,7 @@ in
zapret = {
enable = mkEnableOption "per-app zapret, a separate zapret for wrapped apps only";
keepRunning = keepRunning "per-app zapret" "TUN, TProxy or AmneziaWG profile";
filterMark = int 268435456 "Firewall mark bit for wrapped apps' traffic.";
qnum = int 201 "NFQUEUE number. Must differ from the global zapret's.";
};
+11
View File
@@ -94,6 +94,17 @@ let
'';
example = "de";
};
keepRunning = mkOption {
type = types.bool;
default = false;
description = ''
Keep what this profile runs through running from boot, rather than starting it with
the first app and stopping it after the last: its `outbound` (an AmneziaWG
interface or profile, or a pin slot, which then stays taken), or else its `route`'s
backend, as `perAppRouting.<route>.keepRunning` does.
'';
};
};
};
in
+21 -1
View File
@@ -512,7 +512,27 @@ let
"proxy-suite: perAppRouting profile '${profile.name}': '${profile.outbound}' is both a global AmneziaWG profile and an outbound; say \"awg:${target.name}\" or \"outbound:${target.name}\""
)
]
) perAppRoutingCfg.profiles;
++ [
(mkAssertion (!profile.keepRunning || derived.perAppProfileUnits profile != null)
"proxy-suite: perAppRouting profile '${profile.name}': keepRunning has nothing to keep for route \"${profile.route}\" with no outbound"
)
]
) perAppRoutingCfg.profiles
# Kept pins never give their slot back: they have to leave none short.
++
map
(
route:
let
kept = builtins.filter (lib.hasPrefix "${route}-") derived.perAppKeptViaKeys;
in
mkAssertion (builtins.length kept <= derived.perAppPinSlots)
"proxy-suite: perAppRouting profiles keep ${toString (builtins.length kept)} outbounds running through per-app ${route}, more than perAppRouting.via.pinSlots (${toString derived.perAppPinSlots})"
)
[
"tun"
"tproxy"
];
localProxyAuthCfg = proxyCfg.listener.auth;
localProxyAuthUsed =
@@ -73,6 +73,15 @@ let
ipFamily = cidr: if lib.hasInfix ":" cidr then "ip6" else "ip";
# Runs `action` for a via instance kept running (perAppKeptViaKeys), `key` as shell text.
keptCase =
key: action:
lib.optionalString (ctx.perAppKeptViaKeys != [ ]) ''
case ${key} in
${lib.concatStringsSep " | " ctx.perAppKeptViaKeys}) ${action} ;;
esac
'';
# $1, the instance, to $key, $tag and its outbound's $interface, $table and $mark. An
# awg-<hex> instance is an "interface" outbound; app-<hex> a global profile, which
# proxy-suite-awg-app@<name> has brought up on a slot of its own.
@@ -379,7 +388,7 @@ let
${viaUserRule} "$1"
'';
# ExecStopPost of a user's unit: with no other user's left, the via unit goes, and the
# global profile it ran through. perApp members may only start those (polkit.nix):
# global profile it ran through, unless kept running. perApp members may only start those (polkit.nix):
# stopping one under another user's apps would send them out unmarked.
viaRetire = pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
@@ -389,6 +398,7 @@ let
| ${awk} '$3 == "restart" { found = 1 } END { exit !found }'; then
exit 0
fi
${keptCase "$key" "exit 0"}
${viaUsersLock}
others=$(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \
"proxy-suite-per-app-via-user@*-$key.service" \
@@ -597,6 +607,7 @@ let
[[ $other =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || continue
(( $(${pkgs.coreutils}/bin/date +%s) - $(${pkgs.coreutils}/bin/stat -c %Y "$slot_file") >= 60 )) || continue
other_hex=$(printf '%s' "$other" | ${pkgs.coreutils}/bin/od -An -tx1 | ${pkgs.coreutils}/bin/tr -d ' \n')
${keptCase ''"${route}-$other_hex"'' "continue"}
if [[ -z $(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \
"proxy-suite-per-app-via-user@*-${route}-$other_hex.service") ]]; then
echo "proxy-suite: taking back ${route} pin slot $n from '$other': nothing runs through it" >&2
+68 -7
View File
@@ -76,9 +76,56 @@ let
# Or any outbound, through a pin slot: either way, the apps' slices and their marking.
perAppViaEnabled = perAppViaAwg || perAppRouting.pinUp != { };
# A per-app backend every user's apps share. perApp members may only start it (polkit.nix):
# it goes once the last user's marking unit that requires it stops, or the last pin of it.
# it goes once the last user's marking unit that requires it stops, or the last pin of it,
# unless it is kept running (perAppRouting.<route>.keepRunning; the standby unit below).
perAppSharedBackend =
unit: restartOnSwitch (lib.recursiveUpdate unit { unitConfig.StopWhenUnneeded = true; });
name: unit:
restartOnSwitch (
lib.recursiveUpdate unit {
unitConfig.StopWhenUnneeded =
!builtins.elem [ name ] (map (entry: entry.units) ctx.perAppKeepRunning);
}
);
# Starts what is kept running, but what a global mode carrying its traffic holds down
# (constants.refuseUnderGlobal): its stop runs this again (constants.withPerAppStandby).
# A global AmneziaWG profile's copy for apps goes up first, waited for: the via unit reads
# its slot as it starts, so it starts again if the copy was down.
perAppStandbyStart =
entry:
let
units = entry.units;
last = "${lib.last units}.service";
first = "${builtins.head units}.service";
in
lib.optionalString (entry.modes != [ ]) "under_global ${lib.escapeShellArgs entry.modes} || "
+ (
if builtins.length units == 1 then
"$systemctl start --no-block ${last}\n"
else
''
if $systemctl is-active --quiet ${first}; then
$systemctl start --no-block ${last}
else
$systemctl start ${first} && $systemctl restart --no-block ${last}
fi
''
);
perAppStandbyScript = ctx.pkgs.writeShellScript "proxy-suite-per-app" ''
set -u
systemctl=${ctx.constants.systemctl}
# A global mode still stopping, maybe the one whose stop started this, is waited out.
under_global() {
for _ in $(${ctx.seqBin} 1 100); do
[[ -n $($systemctl list-units --plain --no-legend --state=deactivating "$@") ]] || break
${ctx.sleepBin} 0.1
done
[[ -n $($systemctl list-units --plain --no-legend --state=active,activating,reloading "$@") ]]
}
# The waits last: an AmneziaWG handshake.
${lib.concatMapStrings perAppStandbyStart (
builtins.sort (a: b: builtins.length a.units < builtins.length b.units) ctx.perAppKeepRunning
)}
'';
# A switch restarts it rather than stopping it across activation: a shorter gap, and a
# restart keeps the per-app holds (user-rules.nix). [Service] is where the switch reads it.
restartOnSwitch = unit: lib.recursiveUpdate unit { serviceConfig."X-StopIfChanged" = false; };
@@ -432,7 +479,7 @@ let
execStart = tproxyUpScript;
# Post: also after a start that failed partway, whose marking table would
# otherwise outlive it and send marked traffic out past the kill switch.
execStopPost = tproxyDownScript;
execStopPost = ctx.constants.withPerAppStandby "${serviceNames.tproxy}.service" tproxyDownScript;
})
);
}
@@ -457,7 +504,7 @@ let
];
execStart = scripts.startTun;
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
execStopPost = tunCleanupScript;
execStopPost = ctx.constants.withPerAppStandby "${serviceNames.tun}.service" tunCleanupScript;
runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite";
})
@@ -467,7 +514,7 @@ let
enable = proxyEnabled && perAppRoutingTun.enable;
name = serviceNames.perAppTun;
value = reloadAfterFirewall perAppRouting.perAppTunReloadScript (
perAppSharedBackend (mkRestartingService {
perAppSharedBackend serviceNames.perAppTun (mkRestartingService {
description = "proxy-suite per-app-routing TUN backend";
after = [
"network-online.target"
@@ -504,7 +551,7 @@ let
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = serviceNames.perAppTproxy;
value = reloadAfterFirewall perAppRouting.perAppTproxyReloadScript (
perAppSharedBackend (mkOneshotService {
perAppSharedBackend serviceNames.perAppTproxy (mkOneshotService {
description = "proxy-suite per-app-routing TProxy backend";
after = [
"network.target"
@@ -559,7 +606,21 @@ let
{
enable = perAppZapretEnabled;
name = serviceNames.perAppZapret;
value = perAppSharedBackend { };
value = perAppSharedBackend serviceNames.perAppZapret { };
}
{
enable = ctx.perAppKeepRunning != [ ];
name = "proxy-suite-per-app-standby";
value = mkOneshotService {
description = "Start the proxy-suite per-app backends kept running";
# After the global modes: one starting at boot is up by then, and the stop of one that
# started this is over. A template's instances are waited out by the script.
after = builtins.filter (unit: !lib.hasInfix "*" unit) ctx.perAppStandbyGlobalModes;
wantedBy = [ "multi-user.target" ];
execStart = perAppStandbyScript;
# Run again by each global mode's stop.
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = perAppZapretEnabled;
+3 -10
View File
@@ -57,16 +57,9 @@ in
};
# The per-app instance's ExecStartPre: it has nothing to add under a global mode, which
# it never displaces (constants.refuseUnderGlobal); those take it down as they start.
perAppRefuseUnderGlobal = derived.constants.refuseUnderGlobal pkgs (
[
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles)
)
++ lib.optional derived.awgRuntimeGlobal "proxy-suite-awg@*.service"
);
perAppRefuseUnderGlobal =
derived.constants.refuseUnderGlobal pkgs
derived.perAppGlobalModes."proxy-suite-per-app-zapret";
perAppZapretMarkUpScript = pkgs.writeShellScript scriptName ''
set -euo pipefail