formatting

This commit is contained in:
FUFSoB committed 2026-04-19 12:11:01 +05:00
1 parent 744a769e73
commit 4d6802e194
21 files changed
+640 -379

No files matched your search

+6 -1
View File
@@ -27,7 +27,12 @@
inherit nixpkgs pkgsFor proxySuiteModule; inherit nixpkgs pkgsFor proxySuiteModule;
}; };
mkReadmeDoc = import ./nix/readme-doc.nix { mkReadmeDoc = import ./nix/readme-doc.nix {
inherit nixpkgs pkgsFor proxySuiteModule zapret; inherit
nixpkgs
pkgsFor
proxySuiteModule
zapret
;
}; };
in in
{ {
+12 -3
View File
@@ -9,7 +9,12 @@
let let
derived = import ./derived.nix { inherit lib cfg; }; derived = import ./derived.nix { inherit lib cfg; };
inherit (derived) singBoxCfg globalTun globalTproxy clashApiEnabled; inherit (derived)
singBoxCfg
globalTun
globalTproxy
clashApiEnabled
;
perAppTun = derived.perAppRoutingTun; perAppTun = derived.perAppRoutingTun;
direct = rules.direct; direct = rules.direct;
@@ -24,7 +29,9 @@ let
// lib.optionalAttrs (detour != null) { inherit detour; }; // lib.optionalAttrs (detour != null) { inherit detour; };
mkDnsConfig = mkDnsConfig =
{ localDetour ? null }: {
localDetour ? null,
}:
{ {
servers = [ servers = [
(mkDnsServer "remote" singBoxCfg.dns.remote "proxy") (mkDnsServer "remote" singBoxCfg.dns.remote "proxy")
@@ -160,7 +167,9 @@ let
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate); tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate); tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" (builtins.toJSON perAppTunTemplate); perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" (
builtins.toJSON perAppTunTemplate
);
in in
{ {
+14 -2
View File
@@ -48,7 +48,14 @@ in
cfg cfg
; ;
inherit (configs) tproxyFile tunFile perAppTunFile; inherit (configs) tproxyFile tunFile perAppTunFile;
inherit (nftr) nftablesRulesFile perAppTproxyRulesFile perAppZapretRulesFile perAppTunChainFile ip nft; inherit (nftr)
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
}) })
(lib.mkIf cfg.zapret.enable ( (lib.mkIf cfg.zapret.enable (
@@ -65,7 +72,12 @@ in
(lib.mkIf cfg.tgWsProxy.enable ( (lib.mkIf cfg.tgWsProxy.enable (
import ./tg-ws-proxy.nix { import ./tg-ws-proxy.nix {
inherit lib pkgs packages cfg; inherit
lib
pkgs
packages
cfg
;
} }
)) ))
+8 -2
View File
@@ -14,7 +14,11 @@ let
userControlCfg = cfg.userControl; userControlCfg = cfg.userControl;
selectionMode = singBoxCfg.selection; selectionMode = singBoxCfg.selection;
builtinTags = [ "proxy" "direct" "block" ]; builtinTags = [
"proxy"
"direct"
"block"
];
outboundTags = map (ob: ob.tag) singBoxCfg.outbounds; outboundTags = map (ob: ob.tag) singBoxCfg.outbounds;
subscriptionTags = map (sub: sub.tag) singBoxCfg.subscriptions; subscriptionTags = map (sub: sub.tag) singBoxCfg.subscriptions;
@@ -27,7 +31,9 @@ let
invalidRoutingTargets = lib.unique ( invalidRoutingTargets = lib.unique (
map (rule: rule.outbound) ( map (rule: rule.outbound) (
builtins.filter (rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)) singBoxCfg.routing.rules builtins.filter (
rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)
) singBoxCfg.routing.rules
) )
); );
in in
+11 -2
View File
@@ -27,7 +27,9 @@ let
} }
''; '';
mkLocalSubnetLines = subnets: lib.concatMapStrings (cidr: '' mkLocalSubnetLines =
subnets:
lib.concatMapStrings (cidr: ''
ip daddr ${cidr} tcp dport != 53 return ip daddr ${cidr} tcp dport != 53 return
ip daddr ${cidr} udp dport != 53 return ip daddr ${cidr} udp dport != 53 return
'') subnets; '') subnets;
@@ -118,5 +120,12 @@ ${lib.concatMapStrings (cidr: ''
in in
{ {
inherit nftablesRulesFile perAppTproxyRulesFile perAppZapretRulesFile perAppTunChainFile ip nft; inherit
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
} }
+11 -4
View File
@@ -55,7 +55,9 @@ let
zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ]; zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ];
zapretCustomDomains = zapretCustomDomains =
if syncZapretDirectDomains then if syncZapretDirectDomains then
lib.unique (lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.domains) zapretCfg.hostlistRules) lib.unique (
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.domains) zapretCfg.hostlistRules
)
else else
[ ]; [ ];
zapretExcludedDomains = zapretExcludedDomains =
@@ -90,8 +92,12 @@ let
geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru"); geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru");
}; };
mkRule = field: tag: items: mkRule =
lib.optional (items != [ ]) { ${field} = items; outbound = tag; }; field: tag: items:
lib.optional (items != [ ]) {
${field} = items;
outbound = tag;
};
mkDomainRule = mkRule "domain_suffix"; mkDomainRule = mkRule "domain_suffix";
mkIPRule = mkRule "ip_cidr"; mkIPRule = mkRule "ip_cidr";
mkRulesetRule = mkRule "rule_set"; mkRulesetRule = mkRule "rule_set";
@@ -100,7 +106,8 @@ let
# so any per-outbound routing tag that isn't direct/block/proxy must map # so any per-outbound routing tag that isn't direct/block/proxy must map
# to "proxy" instead of the original tag (which won't exist in sing-box). # to "proxy" instead of the original tag (which won't exist in sing-box).
resolveTag = resolveTag =
tag: if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then "proxy" else tag; tag:
if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then "proxy" else tag;
# Collect per-outbound routing attached directly to outbound definitions. # Collect per-outbound routing attached directly to outbound definitions.
perOutboundRules = lib.concatMap ( perOutboundRules = lib.concatMap (
+115 -126
View File
@@ -37,128 +37,109 @@ let
; ;
featureAssertions = [ featureAssertions = [
(requireAvailable (requireAvailable singBoxCfg.enable (
singBoxCfg.enable singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ]
(singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ]) ) "proxy-suite: at least one outbound or subscription is required when singBox.enable = true")
"proxy-suite: at least one outbound or subscription is required when singBox.enable = true") (uniqueValues singBoxCfg.enable outboundTags "proxy-suite: outbound tags must be unique")
(uniqueValues (uniqueValues singBoxCfg.enable subscriptionTags
singBoxCfg.enable "proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes"
outboundTags )
"proxy-suite: outbound tags must be unique") (mkAssertion (
(uniqueValues !singBoxCfg.enable || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags
singBoxCfg.enable ) "proxy-suite: outbound tags must not use reserved names: proxy, direct, block")
subscriptionTags (mkAssertion (!singBoxCfg.enable || invalidRoutingTargets == [ ])
"proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes") "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
(mkAssertion )
(!singBoxCfg.enable || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags) (requireEnabled globalTun.enable singBoxCfg.enable
"proxy-suite: outbound tags must not use reserved names: proxy, direct, block") "proxy-suite: singBox.tun.enable requires singBox.enable = true"
(mkAssertion )
(!singBoxCfg.enable || invalidRoutingTargets == [ ]) (requireEnabled globalTproxy.enable singBoxCfg.enable
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}") "proxy-suite: singBox.tproxy.enable requires singBox.enable = true"
(requireEnabled globalTun.enable singBoxCfg.enable "proxy-suite: singBox.tun.enable requires singBox.enable = true") )
(requireEnabled globalTproxy.enable singBoxCfg.enable "proxy-suite: singBox.tproxy.enable requires singBox.enable = true") (requireEnabled globalTun.autostart globalTun.enable
(requireEnabled globalTun.autostart globalTun.enable "proxy-suite: singBox.tun.autostart requires singBox.tun.enable = true") "proxy-suite: singBox.tun.autostart requires singBox.tun.enable = true"
(requireEnabled globalTproxy.autostart globalTproxy.enable "proxy-suite: singBox.tproxy.autostart requires singBox.tproxy.enable = true") )
(requireEnabled globalTproxy.autostart globalTproxy.enable
"proxy-suite: singBox.tproxy.autostart requires singBox.tproxy.enable = true"
)
(mkAssertion (mkAssertion
(!(globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart)) (!(globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart))
"proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time") "proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time"
)
]; ];
perAppRoutingAssertions = [ perAppRoutingAssertions = [
(requireAvailable (requireAvailable (perAppRoutingCfg.profiles != [ ]) perAppRoutingCfg.enable
(perAppRoutingCfg.profiles != [ ]) "proxy-suite: perAppRouting.profiles requires perAppRouting.enable = true"
perAppRoutingCfg.enable )
"proxy-suite: perAppRouting.profiles requires perAppRouting.enable = true") (requireEnabled perAppRoutingCfg.proxychains.enable perAppRoutingCfg.enable
(requireEnabled "proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true"
perAppRoutingCfg.proxychains.enable )
perAppRoutingCfg.enable (requireEnabled perAppRoutingCfg.proxychains.enable singBoxCfg.enable
"proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true") "proxy-suite: perAppRouting.proxychains.enable requires singBox.enable = true"
(requireEnabled )
perAppRoutingCfg.proxychains.enable (uniqueValues true effectivePerAppRoutingProfileNames
singBoxCfg.enable "proxy-suite: perAppRouting profile names must be unique"
"proxy-suite: perAppRouting.proxychains.enable requires singBox.enable = true") )
(uniqueValues (requireAvailable hasProxychainsProfiles perAppRoutingCfg.proxychains.enable
true "proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true"
effectivePerAppRoutingProfileNames )
"proxy-suite: perAppRouting profile names must be unique") (requireAvailable hasProxychainsProfiles singBoxCfg.enable
(requireAvailable "proxy-suite: route=proxychains in perAppRouting.profiles requires singBox.enable = true"
hasProxychainsProfiles )
perAppRoutingCfg.proxychains.enable (requireEnabled perAppRoutingTun.enable perAppRoutingCfg.enable
"proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true") "proxy-suite: singBox.tun.perApp.enable requires perAppRouting.enable = true"
(requireAvailable )
hasProxychainsProfiles (requireEnabled perAppRoutingTun.enable singBoxCfg.enable
singBoxCfg.enable "proxy-suite: singBox.tun.perApp.enable requires singBox.enable = true"
"proxy-suite: route=proxychains in perAppRouting.profiles requires singBox.enable = true") )
(requireEnabled (requireAvailable hasTunProfiles perAppRoutingTun.enable
perAppRoutingTun.enable "proxy-suite: route=tun in perAppRouting.profiles requires singBox.tun.perApp.enable = true"
perAppRoutingCfg.enable )
"proxy-suite: singBox.tun.perApp.enable requires perAppRouting.enable = true") (requireAvailable hasTunProfiles singBoxCfg.enable
(requireEnabled "proxy-suite: route=tun in perAppRouting.profiles requires singBox.enable = true"
perAppRoutingTun.enable )
singBoxCfg.enable (requireEnabled perAppRoutingTproxy.enable perAppRoutingCfg.enable
"proxy-suite: singBox.tun.perApp.enable requires singBox.enable = true") "proxy-suite: singBox.tproxy.perApp.enable requires perAppRouting.enable = true"
(requireAvailable )
hasTunProfiles (requireEnabled perAppRoutingTproxy.enable singBoxCfg.enable
perAppRoutingTun.enable "proxy-suite: singBox.tproxy.perApp.enable requires singBox.enable = true"
"proxy-suite: route=tun in perAppRouting.profiles requires singBox.tun.perApp.enable = true") )
(requireAvailable (requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable
hasTunProfiles "proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.tproxy.perApp.enable = true"
singBoxCfg.enable )
"proxy-suite: route=tun in perAppRouting.profiles requires singBox.enable = true") (requireAvailable hasTproxyProfiles singBoxCfg.enable
(requireEnabled "proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.enable = true"
perAppRoutingTproxy.enable )
perAppRoutingCfg.enable (requireEnabled perAppZapretCfg.enable perAppRoutingCfg.enable
"proxy-suite: singBox.tproxy.perApp.enable requires perAppRouting.enable = true") "proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true"
(requireEnabled )
perAppRoutingTproxy.enable (requireEnabled perAppZapretCfg.enable cfg.zapret.enable
singBoxCfg.enable "proxy-suite: zapret.perApp.enable requires zapret.enable = true"
"proxy-suite: singBox.tproxy.perApp.enable requires singBox.enable = true") )
(requireAvailable (requireAvailable hasZapretProfiles (perAppZapretCfg.enable && cfg.zapret.enable)
hasTproxyProfiles "proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true and zapret.enable = true"
perAppRoutingTproxy.enable )
"proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.tproxy.perApp.enable = true")
(requireAvailable
hasTproxyProfiles
singBoxCfg.enable
"proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.enable = true")
(requireEnabled
perAppZapretCfg.enable
perAppRoutingCfg.enable
"proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true")
(requireEnabled
perAppZapretCfg.enable
cfg.zapret.enable
"proxy-suite: zapret.perApp.enable requires zapret.enable = true")
(requireAvailable
hasZapretProfiles
(perAppZapretCfg.enable && cfg.zapret.enable)
"proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true and zapret.enable = true")
]; ];
collisionAssertions = map ( collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [
item:
notEqualWhen item.condition item.left item.right item.message
) [
{ {
condition = perAppRoutingTun.enable && globalTproxy.enable; condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark; left = perAppRoutingTun.fwmark;
right = globalTproxy.fwmark; right = globalTproxy.fwmark;
message = message = "proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.fwmark when global TProxy is enabled";
"proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.fwmark when global TProxy is enabled";
} }
{ {
condition = perAppRoutingTun.enable && globalTproxy.enable; condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark; left = perAppRoutingTun.fwmark;
right = globalTproxy.proxyMark; right = globalTproxy.proxyMark;
message = message = "proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.proxyMark when global TProxy is enabled";
"proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.proxyMark when global TProxy is enabled";
} }
{ {
condition = perAppRoutingTun.enable && globalTproxy.enable; condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.routeTable; left = perAppRoutingTun.routeTable;
right = globalTproxy.routeTable; right = globalTproxy.routeTable;
message = message = "proxy-suite: singBox.tun.perApp.routeTable must differ from singBox.tproxy.routeTable when global TProxy is enabled";
"proxy-suite: singBox.tun.perApp.routeTable must differ from singBox.tproxy.routeTable when global TProxy is enabled";
} }
{ {
condition = perAppRoutingTproxy.enable; condition = perAppRoutingTproxy.enable;
@@ -216,77 +197,85 @@ let
} }
]; ];
forbiddenValueAssertions = map ( forbiddenValueAssertions =
item: map (item: forbiddenValues item.condition item.value item.disallowed item.message)
forbiddenValues item.condition item.value item.disallowed item.message [
) [
{ {
condition = perAppZapretCfg.enable; condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark; value = perAppZapretCfg.filterMark;
disallowed = [ 536870912 1073741824 ]; disallowed = [
536870912
1073741824
];
message = "proxy-suite: zapret.perApp.filterMark must not use zapret internal desync mark bits"; message = "proxy-suite: zapret.perApp.filterMark must not use zapret internal desync mark bits";
} }
{ {
condition = perAppZapretCfg.enable; condition = perAppZapretCfg.enable;
value = globalTproxy.fwmark; value = globalTproxy.fwmark;
disallowed = [ 67108864 134217728 ]; disallowed = [
67108864
134217728
];
message = "proxy-suite: singBox.tproxy.fwmark must not use per-app-zapret internal desync mark bits"; message = "proxy-suite: singBox.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
} }
{ {
condition = perAppZapretCfg.enable; condition = perAppZapretCfg.enable;
value = globalTproxy.proxyMark; value = globalTproxy.proxyMark;
disallowed = [ 67108864 134217728 ]; disallowed = [
67108864
134217728
];
message = "proxy-suite: singBox.tproxy.proxyMark must not use per-app-zapret internal desync mark bits"; message = "proxy-suite: singBox.tproxy.proxyMark must not use per-app-zapret internal desync mark bits";
} }
{ {
condition = perAppRoutingTun.enable && perAppZapretCfg.enable; condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
value = perAppRoutingTun.fwmark; value = perAppRoutingTun.fwmark;
disallowed = [ 67108864 134217728 ]; disallowed = [
67108864
134217728
];
message = "proxy-suite: singBox.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits"; message = "proxy-suite: singBox.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits";
} }
{ {
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable; condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
value = perAppRoutingTproxy.fwmark; value = perAppRoutingTproxy.fwmark;
disallowed = [ 67108864 134217728 ]; disallowed = [
67108864
134217728
];
message = "proxy-suite: singBox.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits"; message = "proxy-suite: singBox.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits";
} }
{ {
condition = perAppZapretCfg.enable; condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark; value = perAppZapretCfg.filterMark;
disallowed = [ 67108864 134217728 ]; disallowed = [
67108864
134217728
];
message = "proxy-suite: zapret.perApp.filterMark must not use per-app-zapret internal desync mark bits"; message = "proxy-suite: zapret.perApp.filterMark must not use per-app-zapret internal desync mark bits";
} }
]; ];
secretAssertions = [ secretAssertions = [
(exactlyOneOf (exactlyOneOf tgWsProxyCfg.enable [
tgWsProxyCfg.enable
[
tgWsProxyCfg.secret tgWsProxyCfg.secret
tgWsProxyCfg.secretFile tgWsProxyCfg.secretFile
] ] "proxy-suite: tgWsProxy requires exactly one of secret or secretFile")
"proxy-suite: tgWsProxy requires exactly one of secret or secretFile")
]; ];
outboundAssertions = lib.concatMap (ob: [ outboundAssertions = lib.concatMap (ob: [
(exactlyOneOf (exactlyOneOf singBoxCfg.enable [
singBoxCfg.enable
[
ob.urlFile ob.urlFile
ob.url ob.url
ob.json ob.json
] ] "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json")
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json")
]) singBoxCfg.outbounds; ]) singBoxCfg.outbounds;
subscriptionAssertions = lib.concatMap (sub: [ subscriptionAssertions = lib.concatMap (sub: [
(exactlyOneOf (exactlyOneOf singBoxCfg.enable [
singBoxCfg.enable
[
sub.urlFile sub.urlFile
sub.url sub.url
] ] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
"proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
]) singBoxCfg.subscriptions; ]) singBoxCfg.subscriptions;
in in
featureAssertions featureAssertions
+15 -7
View File
@@ -3,21 +3,29 @@
rec { rec {
mkAssertion = assertion: message: { inherit assertion message; }; mkAssertion = assertion: message: { inherit assertion message; };
requireEnabled = featureEnabled: dependencyEnabled: message: requireEnabled =
featureEnabled: dependencyEnabled: message:
mkAssertion (!featureEnabled || dependencyEnabled) message; mkAssertion (!featureEnabled || dependencyEnabled) message;
requireAvailable = featureUsed: dependencyEnabled: message: requireAvailable =
featureUsed: dependencyEnabled: message:
mkAssertion (!featureUsed || dependencyEnabled) message; mkAssertion (!featureUsed || dependencyEnabled) message;
uniqueValues = condition: values: message: uniqueValues =
condition: values: message:
mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message; mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message;
notEqualWhen = condition: left: right: message: notEqualWhen =
condition: left: right: message:
mkAssertion (!(condition && left == right)) message; mkAssertion (!(condition && left == right)) message;
forbiddenValues = condition: value: disallowed: message: forbiddenValues =
condition: value: disallowed: message:
mkAssertion (!(condition && builtins.elem value disallowed)) message; mkAssertion (!(condition && builtins.elem value disallowed)) message;
exactlyOneOf = condition: values: message: exactlyOneOf =
mkAssertion (!condition || builtins.length (builtins.filter (value: value != null) values) == 1) message; condition: values: message:
mkAssertion (
!condition || builtins.length (builtins.filter (value: value != null) values) == 1
) message;
} }
+13 -6
View File
@@ -15,7 +15,14 @@ let
preStart ? null, preStart ? null,
}: }:
{ {
inherit description after wantedBy wants requires conflicts; inherit
description
after
wantedBy
wants
requires
conflicts
;
} }
// lib.optionalAttrs (preStart != null) { inherit preStart; }; // lib.optionalAttrs (preStart != null) { inherit preStart; };
in in
@@ -23,7 +30,9 @@ rec {
mkNamedUnits = mkNamedUnits =
entries: entries:
lib.listToAttrs ( lib.listToAttrs (
map (entry: lib.nameValuePair entry.name entry.value) (builtins.filter (entry: entry.enable) entries) map (entry: lib.nameValuePair entry.name entry.value) (
builtins.filter (entry: entry.enable) entries
)
); );
mkRestartingService = mkRestartingService =
@@ -54,8 +63,7 @@ rec {
; ;
}) })
// { // {
serviceConfig = serviceConfig = {
{
ExecStart = execStart; ExecStart = execStart;
Restart = "on-failure"; Restart = "on-failure";
RestartSec = 5; RestartSec = 5;
@@ -97,8 +105,7 @@ rec {
; ;
}) })
// { // {
serviceConfig = serviceConfig = {
{
Type = "oneshot"; Type = "oneshot";
RemainAfterExit = true; RemainAfterExit = true;
ExecStart = execStart; ExecStart = execStart;
+34 -4
View File
@@ -55,17 +55,47 @@ let
}; };
scripts = import ./scripts.nix { scripts = import ./scripts.nix {
inherit lib pkgs singBoxCfg perAppRoutingTun selectionMode collapseNamedOutbounds hasSubscriptions; inherit
inherit jq python3 singBox parserScriptsPythonPath buildOutboundPy fetchSubscriptionPy; lib
pkgs
singBoxCfg
perAppRoutingTun
selectionMode
collapseNamedOutbounds
hasSubscriptions
;
inherit
jq
python3
singBox
parserScriptsPythonPath
buildOutboundPy
fetchSubscriptionPy
;
inherit tproxyFile tunFile perAppTunFile; inherit tproxyFile tunFile perAppTunFile;
}; };
perAppRouting = import ./per-app-routing.nix { perAppRouting = import ./per-app-routing.nix {
inherit lib pkgs cfg singBoxCfg perAppRoutingCfg perAppRoutingTun perAppRoutingTproxy; inherit
lib
pkgs
cfg
singBoxCfg
perAppRoutingCfg
perAppRoutingTun
perAppRoutingTproxy
;
perAppZapretCfg = perAppZapretCfg; perAppZapretCfg = perAppZapretCfg;
inherit perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile; inherit perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile;
inherit ip nft; inherit ip nft;
inherit awk grepBin findBin headBin seqBin sleepBin; inherit
awk
grepBin
findBin
headBin
seqBin
sleepBin
;
}; };
control = import ./control.nix { control = import ./control.nix {
+13 -9
View File
@@ -217,20 +217,17 @@ let
{ {
enable = perAppRoutingTun.enable; enable = perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-anchor"; name = "${serviceNames.perAppTun}-anchor";
value = value = mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
} }
{ {
enable = perAppRoutingTproxy.enable; enable = perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-anchor"; name = "${serviceNames.perAppTproxy}-anchor";
value = value = mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
} }
{ {
enable = perAppZapretEnabled; enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-anchor"; name = "${serviceNames.perAppZapret}-anchor";
value = value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
} }
]; ];
@@ -262,7 +259,8 @@ in
}; };
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true; security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true;
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (lib.mkAfter '' security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (
lib.mkAfter ''
polkit.addRule(function(action, subject) { polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) { if (!subject.isInGroup("${userControlCfg.group}")) {
return null; return null;
@@ -277,14 +275,20 @@ in
return null; return null;
}); });
''); ''
);
systemd.user.services = mkNamedUnits userServiceEntries; systemd.user.services = mkNamedUnits userServiceEntries;
assertions = import ../service-assertions.nix { assertions = import ../service-assertions.nix {
inherit lib cfg derived; inherit lib cfg derived;
tgWsProxyCfg = cfg.tgWsProxy; tgWsProxyCfg = cfg.tgWsProxy;
inherit builtinTags outboundTags subscriptionTags invalidRoutingTargets; inherit
builtinTags
outboundTags
subscriptionTags
invalidRoutingTargets
;
inherit (perAppRouting) inherit (perAppRouting)
effectivePerAppRoutingProfileNames effectivePerAppRoutingProfileNames
hasProxychainsProfiles hasProxychainsProfiles
@@ -58,7 +58,9 @@ let
); );
effectivePerAppRoutingProfiles = effectivePerAppRoutingProfiles =
perAppRoutingCfg.profiles perAppRoutingCfg.profiles
++ builtins.filter (profile: !(builtins.elem profile.name perAppRoutingProfileNames)) defaultPerAppRoutingProfiles; ++ builtins.filter (
profile: !(builtins.elem profile.name perAppRoutingProfileNames)
) defaultPerAppRoutingProfiles;
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles; effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" ( perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" (
@@ -77,10 +79,16 @@ let
''; '';
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q "; proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
hasProxychainsProfiles = builtins.any (profile: profile.route == "proxychains") effectivePerAppRoutingProfiles; hasProxychainsProfiles = builtins.any (
profile: profile.route == "proxychains"
) effectivePerAppRoutingProfiles;
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles; hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles;
hasTproxyProfiles = builtins.any (profile: profile.route == "tproxy") effectivePerAppRoutingProfiles; hasTproxyProfiles = builtins.any (
hasZapretProfiles = builtins.any (profile: profile.route == "zapret") effectivePerAppRoutingProfiles; profile: profile.route == "tproxy"
) effectivePerAppRoutingProfiles;
hasZapretProfiles = builtins.any (
profile: profile.route == "zapret"
) effectivePerAppRoutingProfiles;
perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" '' perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" ''
set -euo pipefail set -euo pipefail
+8 -2
View File
@@ -1,5 +1,9 @@
# Polkit rules granting proxy-suite group members passwordless control over services. # Polkit rules granting proxy-suite group members passwordless control over services.
{ lib, cfg, userControlCfg }: {
lib,
cfg,
userControlCfg,
}:
let let
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable; userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
@@ -18,4 +22,6 @@ let
} }
''; '';
in in
{ inherit userControlEnabled userControlPolkitRules; } {
inherit userControlEnabled userControlPolkitRules;
}
+7 -4
View File
@@ -100,9 +100,11 @@ let
fi fi
if [ -f "$CACHE_FILE" ]; then if [ -f "$CACHE_FILE" ]; then
SUB_JSON=$(cat "$CACHE_FILE") SUB_JSON=$(cat "$CACHE_FILE")
${lib.optionalString (routingMark != null) '' ${
lib.optionalString (routingMark != null) ''
SUB_JSON=$(${jq} --argjson m ${toString routingMark} 'map(. + {routing_mark: $m})' <<< "$SUB_JSON") SUB_JSON=$(${jq} --argjson m ${toString routingMark} 'map(. + {routing_mark: $m})' <<< "$SUB_JSON")
''}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON") ''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
fi fi
''; '';
@@ -117,8 +119,9 @@ let
else else
lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) singBoxCfg.outbounds; lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) singBoxCfg.outbounds;
subscriptionBlocks = subscriptionBlocks = lib.concatMapStrings (
lib.concatMapStrings (sub: mkSubscriptionBlock sub routingMark) singBoxCfg.subscriptions; sub: mkSubscriptionBlock sub routingMark
) singBoxCfg.subscriptions;
wrapperBlock = wrapperBlock =
if collapseNamedOutbounds then if collapseNamedOutbounds then
+55 -29
View File
@@ -45,10 +45,7 @@ let
if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default; if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default;
mkOptionalHostlistFile = mkOptionalHostlistFile =
fileName: entries: fileName: entries:
if entries != [ ] then if entries != [ ] then pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n") else null;
pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n")
else
null;
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral; listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral;
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude; listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude;
@@ -160,15 +157,31 @@ let
} }
${lib.concatMapStrings ${lib.concatMapStrings
({ name, file }: lib.optionalString (file != null) '' (
{ name, file }:
lib.optionalString (file != null) ''
append_list_file ${name} ${file} append_list_file ${name} ${file}
'') ''
)
[ [
{ name = "list-general-user.txt"; file = listGeneralFile; } {
{ name = "list-exclude-user.txt"; file = listExcludeFile; } name = "list-general-user.txt";
{ name = "ipset-all.txt"; file = ipsetAllFile; } file = listGeneralFile;
{ name = "ipset-exclude-user.txt"; file = ipsetExcludeFile; } }
]} {
name = "list-exclude-user.txt";
file = listExcludeFile;
}
{
name = "ipset-all.txt";
file = ipsetAllFile;
}
{
name = "ipset-exclude-user.txt";
file = ipsetExcludeFile;
}
]
}
rm -f "$out/opt/zapret/hostlists/.game_filter.enabled" rm -f "$out/opt/zapret/hostlists/.game_filter.enabled"
${lib.optionalString (gameFilter != "null") '' ${lib.optionalString (gameFilter != "null") ''
@@ -193,15 +206,28 @@ let
set_config_var FILTER_MARK "" set_config_var FILTER_MARK ""
''} ''}
${lib.concatMapStrings ${lib.concatMapStrings
({ var, value }: lib.optionalString (value != null) '' (
{ var, value }:
lib.optionalString (value != null) ''
hex=$(printf '0x%x' ${toString value}) hex=$(printf '0x%x' ${toString value})
set_config_var ${var} "$hex" set_config_var ${var} "$hex"
'') ''
)
[ [
{ var = "FILTER_MARK"; value = filterMark; } {
{ var = "DESYNC_MARK"; value = desyncMark; } var = "FILTER_MARK";
{ var = "DESYNC_MARK_POSTNAT"; value = desyncMarkPostnat; } value = filterMark;
]} }
{
var = "DESYNC_MARK";
value = desyncMark;
}
{
var = "DESYNC_MARK_POSTNAT";
value = desyncMarkPostnat;
}
]
}
${lib.optionalString (qnum != null) '' ${lib.optionalString (qnum != null) ''
set_config_var QNUM ${toString qnum} set_config_var QNUM ${toString qnum}
''} ''}
@@ -224,7 +250,8 @@ let
pidDir = "/run/proxy-suite-zapret"; pidDir = "/run/proxy-suite-zapret";
gameFilter = zapretCfg.gameFilter; gameFilter = zapretCfg.gameFilter;
forceDisableFilterMark = true; forceDisableFilterMark = true;
customScript = if perAppZapretCfg.enable then mkGlobalBypassScript (toString perAppZapretCfg.filterMark) else null; customScript =
if perAppZapretCfg.enable then mkGlobalBypassScript (toString perAppZapretCfg.filterMark) else null;
}; };
perAppZapretPackage = mkDerivedZapretPackage { perAppZapretPackage = mkDerivedZapretPackage {
@@ -290,13 +317,14 @@ in
message = "proxy-suite: each zapret.hostlistRules entry must define at least one domain"; message = "proxy-suite: each zapret.hostlistRules entry must define at least one domain";
} }
{ {
assertion = builtins.all (rule: rule.preset != null || rule.nfqwsArgs != [ ]) zapretCfg.hostlistRules; assertion = builtins.all (
rule: rule.preset != null || rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must set preset, nfqwsArgs, or both"; message = "proxy-suite: each zapret.hostlistRules entry must set preset, nfqwsArgs, or both";
} }
]; ];
environment.systemPackages = environment.systemPackages = lib.mkBefore (
lib.mkBefore (
[ globalZapretPackage ] ++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ] [ globalZapretPackage ] ++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
); );
@@ -314,8 +342,7 @@ in
}; };
}; };
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable ( systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
mkOneshotService {
description = "proxy-suite per-app-routing zapret backend"; description = "proxy-suite per-app-routing zapret backend";
after = [ "network.target" ]; after = [ "network.target" ];
conflicts = [ conflicts = [
@@ -329,17 +356,16 @@ in
execStartPre = "${perAppZapretMarkUpScript}"; execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}"; execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = perAppZapretEnv; extraServiceConfig.Environment = perAppZapretEnv;
} });
);
systemd.services.proxy-suite-zapret-vm-exempt = lib.mkIf zapretCfg.cidrExemption.enable ( systemd.services.proxy-suite-zapret-vm-exempt =
mkOneshotService { lib.mkIf zapretCfg.cidrExemption.enable
(mkOneshotService {
description = "Exempt CIDRs from zapret NFQUEUE"; description = "Exempt CIDRs from zapret NFQUEUE";
after = [ "zapret-discord-youtube.service" ]; after = [ "zapret-discord-youtube.service" ];
wants = [ "zapret-discord-youtube.service" ]; wants = [ "zapret-discord-youtube.service" ];
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
execStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart; execStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart;
execStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop; execStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop;
} });
);
} }
+5 -5
View File
@@ -19,9 +19,7 @@
let let
unwrapped = pkgs.writeShellScriptBin "proxy-ctl" ( unwrapped = pkgs.writeShellScriptBin "proxy-ctl" (
builtins.readFile ./proxy-ctl-lib.sh builtins.readFile ./proxy-ctl-lib.sh + "\n" + builtins.readFile ./proxy-ctl.sh
+ "\n"
+ builtins.readFile ./proxy-ctl.sh
); );
in in
pkgs.symlinkJoin { pkgs.symlinkJoin {
@@ -30,7 +28,8 @@ pkgs.symlinkJoin {
nativeBuildInputs = [ pkgs.makeWrapper ]; nativeBuildInputs = [ pkgs.makeWrapper ];
postBuild = '' postBuild = ''
wrapProgram "$out/bin/proxy-ctl" \ wrapProgram "$out/bin/proxy-ctl" \
--prefix PATH : "${lib.makeBinPath [ --prefix PATH : "${
lib.makeBinPath [
pkgs.coreutils pkgs.coreutils
pkgs.curl pkgs.curl
pkgs.gawk pkgs.gawk
@@ -38,7 +37,8 @@ pkgs.symlinkJoin {
pkgs.jq pkgs.jq
pkgs.proxychains-ng pkgs.proxychains-ng
pkgs.systemd pkgs.systemd
]}" \ ]
}" \
--set CLASH_API ${lib.escapeShellArg clashApi} \ --set CLASH_API ${lib.escapeShellArg clashApi} \
--set SELECTION ${lib.escapeShellArg selection} \ --set SELECTION ${lib.escapeShellArg selection} \
--set SUB_TAGS_FILE ${lib.escapeShellArg (toString subscriptionTagsFile)} \ --set SUB_TAGS_FILE ${lib.escapeShellArg (toString subscriptionTagsFile)} \
+264 -158
View File
@@ -12,7 +12,6 @@
#define PROXY_CTL_BIN "/run/current-system/sw/bin/proxy-ctl" #define PROXY_CTL_BIN "/run/current-system/sw/bin/proxy-ctl"
#endif #endif
static AppIndicator *indicator; static AppIndicator *indicator;
static GtkWidget *menu; static GtkWidget *menu;
static GtkWidget *status_item; static GtkWidget *status_item;
@@ -31,7 +30,8 @@ static GtkWidget *controls_tproxy_button;
static GtkWidget *controls_tun_button; static GtkWidget *controls_tun_button;
static GtkWidget *controls_zapret_button; static GtkWidget *controls_zapret_button;
typedef struct { typedef struct
{
gboolean loaded; gboolean loaded;
gboolean socks_available; gboolean socks_available;
gboolean tproxy_available; gboolean tproxy_available;
@@ -46,16 +46,19 @@ typedef struct {
static ServiceState initial_state; static ServiceState initial_state;
static gboolean command_succeeds(gchar **argv) { static gboolean command_succeeds(gchar **argv)
{
GError *error = NULL; GError *error = NULL;
gint wait_status = 0; gint wait_status = 0;
if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, NULL, NULL, &wait_status, &error)) { if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, NULL, NULL, &wait_status, &error))
{
g_clear_error(&error); g_clear_error(&error);
return FALSE; return FALSE;
} }
if (!g_spawn_check_wait_status(wait_status, &error)) { if (!g_spawn_check_wait_status(wait_status, &error))
{
g_clear_error(&error); g_clear_error(&error);
return FALSE; return FALSE;
} }
@@ -63,17 +66,20 @@ static gboolean command_succeeds(gchar **argv) {
return TRUE; return TRUE;
} }
static gboolean command_stdout(gchar **argv, gchar **stdout_text) { static gboolean command_stdout(gchar **argv, gchar **stdout_text)
{
GError *error = NULL; GError *error = NULL;
gint wait_status = 0; gint wait_status = 0;
*stdout_text = NULL; *stdout_text = NULL;
if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, stdout_text, NULL, &wait_status, &error)) { if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, stdout_text, NULL, &wait_status, &error))
{
g_clear_error(&error); g_clear_error(&error);
return FALSE; return FALSE;
} }
if (!g_spawn_check_wait_status(wait_status, &error)) { if (!g_spawn_check_wait_status(wait_status, &error))
{
g_clear_error(&error); g_clear_error(&error);
g_clear_pointer(stdout_text, g_free); g_clear_pointer(stdout_text, g_free);
return FALSE; return FALSE;
@@ -82,22 +88,28 @@ static gboolean command_stdout(gchar **argv, gchar **stdout_text) {
return TRUE; return TRUE;
} }
static gboolean on_controls_delete(GtkWidget *widget, GdkEvent *event, gpointer data) { static gboolean on_controls_delete(GtkWidget *widget, GdkEvent *event, gpointer data)
(void)event; (void)data; {
(void)event;
(void)data;
gtk_widget_hide(widget); gtk_widget_hide(widget);
return TRUE; return TRUE;
} }
static void on_close_controls(GtkWidget *item, gpointer data) { static void on_close_controls(GtkWidget *item, gpointer data)
(void)item; (void)data; {
if (controls_window) { (void)item;
(void)data;
if (controls_window)
{
gtk_widget_hide(controls_window); gtk_widget_hide(controls_window);
} }
} }
static void on_open_controls(GtkWidget *item, gpointer data); static void on_open_controls(GtkWidget *item, gpointer data);
static gboolean on_open_controls_idle(gpointer data) { static gboolean on_open_controls_idle(gpointer data)
{
(void)data; (void)data;
on_open_controls(NULL, NULL); on_open_controls(NULL, NULL);
return G_SOURCE_REMOVE; return G_SOURCE_REMOVE;
@@ -107,13 +119,16 @@ static GDBusMessage *on_session_bus_message(
GDBusConnection *connection, GDBusConnection *connection,
GDBusMessage *message, GDBusMessage *message,
gboolean incoming, gboolean incoming,
gpointer user_data gpointer user_data)
) { {
(void)connection; (void)user_data; (void)connection;
if (!incoming || !message) { (void)user_data;
if (!incoming || !message)
{
return message; return message;
} }
if (g_dbus_message_get_message_type(message) != G_DBUS_MESSAGE_TYPE_METHOD_CALL) { if (g_dbus_message_get_message_type(message) != G_DBUS_MESSAGE_TYPE_METHOD_CALL)
{
return message; return message;
} }
@@ -124,50 +139,55 @@ static GDBusMessage *on_session_bus_message(
if (iface && member && path && if (iface && member && path &&
strcmp(iface, "org.kde.StatusNotifierItem") == 0 && strcmp(iface, "org.kde.StatusNotifierItem") == 0 &&
strcmp(member, "Activate") == 0 && strcmp(member, "Activate") == 0 &&
g_str_has_prefix(path, "/org/ayatana/NotificationItem/")) { g_str_has_prefix(path, "/org/ayatana/NotificationItem/"))
{
g_idle_add(on_open_controls_idle, NULL); g_idle_add(on_open_controls_idle, NULL);
} }
return message; return message;
} }
static gboolean run_proxy_ctl1(const char *arg1) { static gboolean run_proxy_ctl1(const char *arg1)
{
gchar *argv[] = { gchar *argv[] = {
(gchar *)PROXY_CTL_BIN, (gchar *)PROXY_CTL_BIN,
(gchar *)arg1, (gchar *)arg1,
NULL NULL};
};
return command_succeeds(argv); return command_succeeds(argv);
} }
static gboolean run_proxy_ctl2(const char *arg1, const char *arg2) { static gboolean run_proxy_ctl2(const char *arg1, const char *arg2)
{
gchar *argv[] = { gchar *argv[] = {
(gchar *)PROXY_CTL_BIN, (gchar *)PROXY_CTL_BIN,
(gchar *)arg1, (gchar *)arg1,
(gchar *)arg2, (gchar *)arg2,
NULL NULL};
};
return command_succeeds(argv); return command_succeeds(argv);
} }
static gboolean parse_proxy_ctl_bool(const char *value) { static gboolean parse_proxy_ctl_bool(const char *value)
{
return value && strcmp(value, "true") == 0; return value && strcmp(value, "true") == 0;
} }
static const char *pick_icon_name( static const char *pick_icon_name(
const char *const *candidates, const char *const *candidates,
gsize candidates_len, gsize candidates_len,
const char *fallback const char *fallback)
) { {
GtkIconTheme *theme = gtk_icon_theme_get_default(); GtkIconTheme *theme = gtk_icon_theme_get_default();
if (!theme) { if (!theme)
{
return fallback; return fallback;
} }
for (gsize i = 0; i < candidates_len; ++i) { for (gsize i = 0; i < candidates_len; ++i)
if (gtk_icon_theme_has_icon(theme, candidates[i])) { {
if (gtk_icon_theme_has_icon(theme, candidates[i]))
{
return candidates[i]; return candidates[i];
} }
} }
@@ -175,51 +195,72 @@ static const char *pick_icon_name(
return fallback; return fallback;
} }
static ServiceState get_service_state(void) { static ServiceState get_service_state(void)
{
ServiceState state = {0}; ServiceState state = {0};
gchar *stdout_text = NULL; gchar *stdout_text = NULL;
gchar *argv[] = { gchar *argv[] = {
(gchar *)PROXY_CTL_BIN, (gchar *)PROXY_CTL_BIN,
(gchar *)"status", (gchar *)"status",
(gchar *)"--tray", (gchar *)"--tray",
NULL NULL};
};
if (!command_stdout(argv, &stdout_text)) { if (!command_stdout(argv, &stdout_text))
{
return state; return state;
} }
state.loaded = TRUE; state.loaded = TRUE;
gchar **lines = g_strsplit(stdout_text, "\n", -1); gchar **lines = g_strsplit(stdout_text, "\n", -1);
for (gchar **line = lines; line && *line; ++line) { for (gchar **line = lines; line && *line; ++line)
if ((*line)[0] == '\0') { {
if ((*line)[0] == '\0')
{
continue; continue;
} }
gchar **parts = g_strsplit(*line, "=", 2); gchar **parts = g_strsplit(*line, "=", 2);
if (!parts[0] || !parts[1]) { if (!parts[0] || !parts[1])
{
g_strfreev(parts); g_strfreev(parts);
continue; continue;
} }
if (strcmp(parts[0], "socks_available") == 0) { if (strcmp(parts[0], "socks_available") == 0)
{
state.socks_available = parse_proxy_ctl_bool(parts[1]); state.socks_available = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "socks_active") == 0) { }
else if (strcmp(parts[0], "socks_active") == 0)
{
state.socks = parse_proxy_ctl_bool(parts[1]); state.socks = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "tproxy_available") == 0) { }
else if (strcmp(parts[0], "tproxy_available") == 0)
{
state.tproxy_available = parse_proxy_ctl_bool(parts[1]); state.tproxy_available = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "tproxy_active") == 0) { }
else if (strcmp(parts[0], "tproxy_active") == 0)
{
state.tproxy = parse_proxy_ctl_bool(parts[1]); state.tproxy = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "tun_available") == 0) { }
else if (strcmp(parts[0], "tun_available") == 0)
{
state.tun_available = parse_proxy_ctl_bool(parts[1]); state.tun_available = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "tun_active") == 0) { }
else if (strcmp(parts[0], "tun_active") == 0)
{
state.tun = parse_proxy_ctl_bool(parts[1]); state.tun = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "zapret_available") == 0) { }
else if (strcmp(parts[0], "zapret_available") == 0)
{
state.zapret_available = parse_proxy_ctl_bool(parts[1]); state.zapret_available = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "zapret_active") == 0) { }
else if (strcmp(parts[0], "zapret_active") == 0)
{
state.zapret = parse_proxy_ctl_bool(parts[1]); state.zapret = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "subscription_update_available") == 0) { }
else if (strcmp(parts[0], "subscription_update_available") == 0)
{
state.subscription_update_available = parse_proxy_ctl_bool(parts[1]); state.subscription_update_available = parse_proxy_ctl_bool(parts[1]);
} }
@@ -232,51 +273,59 @@ static ServiceState get_service_state(void) {
return state; return state;
} }
static const char *traffic_mode_label(const ServiceState *state) { static const char *traffic_mode_label(const ServiceState *state)
if (state->tun) { {
if (state->tun)
{
return "TUN tunnel enabled"; return "TUN tunnel enabled";
} }
if (state->tproxy) { if (state->tproxy)
{
return "TProxy interception enabled"; return "TProxy interception enabled";
} }
return "System-wide routing disabled"; return "System-wide routing disabled";
} }
static const char *indicator_label_text(const ServiceState *state) { static const char *indicator_label_text(const ServiceState *state)
if (state->socks && (state->tproxy || state->tun) && state->zapret) { {
if (state->socks && (state->tproxy || state->tun) && state->zapret)
{
return "Proxy + traffic + zapret"; return "Proxy + traffic + zapret";
} }
if (state->socks && (state->tproxy || state->tun)) { if (state->socks && (state->tproxy || state->tun))
{
return "Proxy + traffic"; return "Proxy + traffic";
} }
if (state->socks && state->zapret) { if (state->socks && state->zapret)
{
return "Proxy + zapret"; return "Proxy + zapret";
} }
if (state->socks) { if (state->socks)
{
return "Proxy only"; return "Proxy only";
} }
if (state->zapret) { if (state->zapret)
{
return "Zapret only"; return "Zapret only";
} }
return "Inactive"; return "Inactive";
} }
static void update_status(void) { static void update_status(void)
{
ServiceState state = get_service_state(); ServiceState state = get_service_state();
/* Gold: TUN/TProxy active (highest priority) */ /* Gold: TUN/TProxy active (highest priority) */
static const char *const tunnel_icons[] = { static const char *const tunnel_icons[] = {
"proxy-suite-tunnel", "proxy-suite-tunnel",
"proxy-suite-tunnel-symbolic", "proxy-suite-tunnel-symbolic",
"network-vpn", "network-vpn",
"network-vpn-symbolic" "network-vpn-symbolic"};
};
/* Green: proxy + zapret, no tunnel */ /* Green: proxy + zapret, no tunnel */
static const char *const active_icons[] = { static const char *const active_icons[] = {
"proxy-suite-active", "proxy-suite-active",
"proxy-suite-active-symbolic", "proxy-suite-active-symbolic",
"network-vpn", "network-vpn",
"network-vpn-symbolic" "network-vpn-symbolic"};
};
/* Orange: proxy only */ /* Orange: proxy only */
static const char *const proxy_icons[] = { static const char *const proxy_icons[] = {
"proxy-suite-proxy", "proxy-suite-proxy",
@@ -284,8 +333,7 @@ static void update_status(void) {
"network-vpn-acquiring", "network-vpn-acquiring",
"network-vpn-acquiring-symbolic", "network-vpn-acquiring-symbolic",
"network-vpn", "network-vpn",
"network-vpn-symbolic" "network-vpn-symbolic"};
};
/* Blue: zapret only */ /* Blue: zapret only */
static const char *const zapret_icons[] = { static const char *const zapret_icons[] = {
"proxy-suite-zapret", "proxy-suite-zapret",
@@ -293,8 +341,7 @@ static void update_status(void) {
"network-vpn-acquiring", "network-vpn-acquiring",
"network-vpn-acquiring-symbolic", "network-vpn-acquiring-symbolic",
"network-vpn", "network-vpn",
"network-vpn-symbolic" "network-vpn-symbolic"};
};
/* Red: everything disabled */ /* Red: everything disabled */
static const char *const disabled_icons[] = { static const char *const disabled_icons[] = {
"proxy-suite-disabled", "proxy-suite-disabled",
@@ -306,29 +353,33 @@ static void update_status(void) {
"network-vpn-disconnected-symbolic", "network-vpn-disconnected-symbolic",
"network-offline-symbolic", "network-offline-symbolic",
"network-error-symbolic", "network-error-symbolic",
"dialog-error-symbolic" "dialog-error-symbolic"};
};
if (!state.loaded) { if (!state.loaded)
{
app_indicator_set_icon( app_indicator_set_icon(
indicator, indicator,
pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected") pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected"));
);
app_indicator_set_label(indicator, "Status unavailable", ""); app_indicator_set_label(indicator, "Status unavailable", "");
if (status_item) { if (status_item)
{
gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), "[Status] proxy-ctl status unavailable"); gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), "[Status] proxy-ctl status unavailable");
} }
if (controls_summary_label) { if (controls_summary_label)
{
gtk_label_set_text(GTK_LABEL(controls_summary_label), "[Status] proxy-ctl status unavailable"); gtk_label_set_text(GTK_LABEL(controls_summary_label), "[Status] proxy-ctl status unavailable");
} }
if (controls_core_status_label) { if (controls_core_status_label)
{
gtk_label_set_text(GTK_LABEL(controls_core_status_label), "[Core] SOCKS proxy: Unknown"); gtk_label_set_text(GTK_LABEL(controls_core_status_label), "[Core] SOCKS proxy: Unknown");
} }
if (controls_traffic_status_label) { if (controls_traffic_status_label)
{
gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), "[Traffic] Mode: Unknown"); gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), "[Traffic] Mode: Unknown");
} }
if (controls_zapret_status_label) { if (controls_zapret_status_label)
{
gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), "[Zapret] zapret-discord-youtube: Unknown"); gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), "[Zapret] zapret-discord-youtube: Unknown");
} }
return; return;
@@ -341,97 +392,109 @@ static void update_status(void) {
"[Status] %s | Traffic: %s | Zapret: %s", "[Status] %s | Traffic: %s | Zapret: %s",
state.socks ? "Proxy ready" : "Proxy down", state.socks ? "Proxy ready" : "Proxy down",
traffic, traffic,
zapret zapret);
);
gchar *core_text = g_strdup_printf( gchar *core_text = g_strdup_printf(
"[Core] SOCKS proxy: %s", "[Core] SOCKS proxy: %s",
state.socks ? "Running" : "Stopped" state.socks ? "Running" : "Stopped");
);
gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic); gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic);
gchar *zapret_text = g_strdup_printf( gchar *zapret_text = g_strdup_printf(
"[Zapret] zapret-discord-youtube: %s", "[Zapret] zapret-discord-youtube: %s",
zapret zapret);
);
if (state.tproxy || state.tun) { if (state.tproxy || state.tun)
{
app_indicator_set_icon( app_indicator_set_icon(
indicator, indicator,
pick_icon_name(tunnel_icons, G_N_ELEMENTS(tunnel_icons), "network-vpn") pick_icon_name(tunnel_icons, G_N_ELEMENTS(tunnel_icons), "network-vpn"));
); }
} else if (state.socks && state.zapret) { else if (state.socks && state.zapret)
{
app_indicator_set_icon( app_indicator_set_icon(
indicator, indicator,
pick_icon_name(active_icons, G_N_ELEMENTS(active_icons), "network-vpn") pick_icon_name(active_icons, G_N_ELEMENTS(active_icons), "network-vpn"));
); }
} else if (state.socks) { else if (state.socks)
{
app_indicator_set_icon( app_indicator_set_icon(
indicator, indicator,
pick_icon_name(proxy_icons, G_N_ELEMENTS(proxy_icons), "network-vpn-acquiring") pick_icon_name(proxy_icons, G_N_ELEMENTS(proxy_icons), "network-vpn-acquiring"));
); }
} else if (state.zapret) { else if (state.zapret)
{
app_indicator_set_icon( app_indicator_set_icon(
indicator, indicator,
pick_icon_name(zapret_icons, G_N_ELEMENTS(zapret_icons), "network-vpn-acquiring") pick_icon_name(zapret_icons, G_N_ELEMENTS(zapret_icons), "network-vpn-acquiring"));
); }
} else { else
{
app_indicator_set_icon( app_indicator_set_icon(
indicator, indicator,
pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected") pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected"));
);
} }
app_indicator_set_label(indicator, summary, ""); app_indicator_set_label(indicator, summary, "");
if (status_item) { if (status_item)
{
gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), summary_text); gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), summary_text);
} }
if (controls_summary_label) { if (controls_summary_label)
{
gtk_label_set_text(GTK_LABEL(controls_summary_label), summary_text); gtk_label_set_text(GTK_LABEL(controls_summary_label), summary_text);
} }
if (controls_core_status_label) { if (controls_core_status_label)
{
gtk_label_set_text(GTK_LABEL(controls_core_status_label), core_text); gtk_label_set_text(GTK_LABEL(controls_core_status_label), core_text);
} }
if (controls_traffic_status_label) { if (controls_traffic_status_label)
{
gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), traffic_text); gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), traffic_text);
} }
if (controls_zapret_status_label) { if (controls_zapret_status_label)
{
gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), zapret_text); gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), zapret_text);
} }
if (proxy_item) { if (proxy_item)
{
gtk_menu_item_set_label(GTK_MENU_ITEM(proxy_item), gtk_menu_item_set_label(GTK_MENU_ITEM(proxy_item),
state.socks ? "[Core] Stop SOCKS Proxy" : "[Core] Start SOCKS Proxy"); state.socks ? "[Core] Stop SOCKS Proxy" : "[Core] Start SOCKS Proxy");
} }
if (controls_proxy_button) { if (controls_proxy_button)
{
gtk_button_set_label(GTK_BUTTON(controls_proxy_button), gtk_button_set_label(GTK_BUTTON(controls_proxy_button),
state.socks ? "Stop SOCKS Proxy" : "Start SOCKS Proxy"); state.socks ? "Stop SOCKS Proxy" : "Start SOCKS Proxy");
} }
if (tproxy_item) { if (tproxy_item)
{
gtk_menu_item_set_label(GTK_MENU_ITEM(tproxy_item), gtk_menu_item_set_label(GTK_MENU_ITEM(tproxy_item),
state.tproxy ? "[Traffic] Stop TProxy Mode" : "[Traffic] Start TProxy Mode"); state.tproxy ? "[Traffic] Stop TProxy Mode" : "[Traffic] Start TProxy Mode");
} }
if (controls_tproxy_button) { if (controls_tproxy_button)
{
gtk_button_set_label(GTK_BUTTON(controls_tproxy_button), gtk_button_set_label(GTK_BUTTON(controls_tproxy_button),
state.tproxy ? "Stop TProxy Mode" : "Start TProxy Mode"); state.tproxy ? "Stop TProxy Mode" : "Start TProxy Mode");
} }
if (tun_item) { if (tun_item)
{
gtk_menu_item_set_label(GTK_MENU_ITEM(tun_item), gtk_menu_item_set_label(GTK_MENU_ITEM(tun_item),
state.tun ? "[Traffic] Stop TUN Mode" : "[Traffic] Start TUN Mode"); state.tun ? "[Traffic] Stop TUN Mode" : "[Traffic] Start TUN Mode");
} }
if (controls_tun_button) { if (controls_tun_button)
{
gtk_button_set_label(GTK_BUTTON(controls_tun_button), gtk_button_set_label(GTK_BUTTON(controls_tun_button),
state.tun ? "Stop TUN Mode" : "Start TUN Mode"); state.tun ? "Stop TUN Mode" : "Start TUN Mode");
} }
if (zapret_item) { if (zapret_item)
{
gtk_menu_item_set_label( gtk_menu_item_set_label(
GTK_MENU_ITEM(zapret_item), GTK_MENU_ITEM(zapret_item),
state.zapret ? "[Zapret] Stop zapret-discord-youtube" : "[Zapret] Start zapret-discord-youtube" state.zapret ? "[Zapret] Stop zapret-discord-youtube" : "[Zapret] Start zapret-discord-youtube");
);
} }
if (controls_zapret_button) { if (controls_zapret_button)
{
gtk_button_set_label( gtk_button_set_label(
GTK_BUTTON(controls_zapret_button), GTK_BUTTON(controls_zapret_button),
state.zapret ? "Stop zapret-discord-youtube" : "Start zapret-discord-youtube" state.zapret ? "Stop zapret-discord-youtube" : "Start zapret-discord-youtube");
);
} }
g_free(summary_text); g_free(summary_text);
@@ -440,64 +503,91 @@ static void update_status(void) {
g_free(zapret_text); g_free(zapret_text);
} }
static void on_proxy_toggle(GtkWidget *item, gpointer data) { static void on_proxy_toggle(GtkWidget *item, gpointer data)
(void)item; (void)data; {
(void)item;
(void)data;
ServiceState state = get_service_state(); ServiceState state = get_service_state();
if (state.socks) { if (state.socks)
{
run_proxy_ctl2("proxy", "off"); run_proxy_ctl2("proxy", "off");
} else { }
else
{
run_proxy_ctl2("proxy", "on"); run_proxy_ctl2("proxy", "on");
} }
update_status(); update_status();
} }
static void on_tproxy_toggle(GtkWidget *item, gpointer data) { static void on_tproxy_toggle(GtkWidget *item, gpointer data)
(void)item; (void)data; {
(void)item;
(void)data;
ServiceState state = get_service_state(); ServiceState state = get_service_state();
if (state.tproxy) { if (state.tproxy)
{
run_proxy_ctl2("tproxy", "off"); run_proxy_ctl2("tproxy", "off");
} else { }
else
{
run_proxy_ctl2("tproxy", "on"); run_proxy_ctl2("tproxy", "on");
} }
update_status(); update_status();
} }
static void on_tun_toggle(GtkWidget *item, gpointer data) { static void on_tun_toggle(GtkWidget *item, gpointer data)
(void)item; (void)data; {
(void)item;
(void)data;
ServiceState state = get_service_state(); ServiceState state = get_service_state();
if (state.tun) { if (state.tun)
{
run_proxy_ctl2("tun", "off"); run_proxy_ctl2("tun", "off");
} else { }
else
{
run_proxy_ctl2("tun", "on"); run_proxy_ctl2("tun", "on");
} }
update_status(); update_status();
} }
static void on_zapret_toggle(GtkWidget *item, gpointer data) { static void on_zapret_toggle(GtkWidget *item, gpointer data)
(void)item; (void)data; {
(void)item;
(void)data;
ServiceState state = get_service_state(); ServiceState state = get_service_state();
if (state.zapret) { if (state.zapret)
{
run_proxy_ctl2("zapret", "off"); run_proxy_ctl2("zapret", "off");
} else { }
else
{
run_proxy_ctl2("zapret", "on"); run_proxy_ctl2("zapret", "on");
} }
update_status(); update_status();
} }
static void on_restart(GtkWidget *item, gpointer data) { static void on_restart(GtkWidget *item, gpointer data)
(void)item; (void)data; {
(void)item;
(void)data;
run_proxy_ctl1("restart"); run_proxy_ctl1("restart");
update_status(); update_status();
} }
static void on_subscription_update(GtkWidget *item, gpointer data) { static void on_subscription_update(GtkWidget *item, gpointer data)
(void)item; (void)data; {
(void)item;
(void)data;
run_proxy_ctl2("subscription", "update"); run_proxy_ctl2("subscription", "update");
} }
static void on_open_controls(GtkWidget *item, gpointer data) { static void on_open_controls(GtkWidget *item, gpointer data)
(void)item; (void)data; {
if (!controls_window) { (void)item;
(void)data;
if (!controls_window)
{
return; return;
} }
update_status(); update_status();
@@ -505,18 +595,22 @@ static void on_open_controls(GtkWidget *item, gpointer data) {
gtk_window_present(GTK_WINDOW(controls_window)); gtk_window_present(GTK_WINDOW(controls_window));
} }
static void on_quit(GtkWidget *item, gpointer data) { static void on_quit(GtkWidget *item, gpointer data)
(void)item; (void)data; {
(void)item;
(void)data;
gtk_main_quit(); gtk_main_quit();
} }
static gboolean on_timer(gpointer data) { static gboolean on_timer(gpointer data)
{
(void)data; (void)data;
update_status(); update_status();
return TRUE; return TRUE;
} }
static void build_controls_window(void) { static void build_controls_window(void)
{
controls_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); controls_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(controls_window), "Proxy Suite Controls"); gtk_window_set_title(GTK_WINDOW(controls_window), "Proxy Suite Controls");
gtk_window_set_resizable(GTK_WINDOW(controls_window), FALSE); gtk_window_set_resizable(GTK_WINDOW(controls_window), FALSE);
@@ -554,19 +648,22 @@ static void build_controls_window(void) {
gtk_label_set_xalign(GTK_LABEL(controls_traffic_status_label), 0.0f); gtk_label_set_xalign(GTK_LABEL(controls_traffic_status_label), 0.0f);
gtk_box_pack_start(GTK_BOX(traffic_box), controls_traffic_status_label, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(traffic_box), controls_traffic_status_label, FALSE, FALSE, 0);
if (initial_state.tproxy_available) { if (initial_state.tproxy_available)
{
controls_tproxy_button = gtk_button_new_with_label("Start TProxy Mode"); controls_tproxy_button = gtk_button_new_with_label("Start TProxy Mode");
g_signal_connect(controls_tproxy_button, "clicked", G_CALLBACK(on_tproxy_toggle), NULL); g_signal_connect(controls_tproxy_button, "clicked", G_CALLBACK(on_tproxy_toggle), NULL);
gtk_box_pack_start(GTK_BOX(traffic_box), controls_tproxy_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(traffic_box), controls_tproxy_button, FALSE, FALSE, 0);
} }
if (initial_state.tun_available) { if (initial_state.tun_available)
{
controls_tun_button = gtk_button_new_with_label("Start TUN Mode"); controls_tun_button = gtk_button_new_with_label("Start TUN Mode");
g_signal_connect(controls_tun_button, "clicked", G_CALLBACK(on_tun_toggle), NULL); g_signal_connect(controls_tun_button, "clicked", G_CALLBACK(on_tun_toggle), NULL);
gtk_box_pack_start(GTK_BOX(traffic_box), controls_tun_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(traffic_box), controls_tun_button, FALSE, FALSE, 0);
} }
if (initial_state.zapret_available) { if (initial_state.zapret_available)
{
GtkWidget *zapret_frame = gtk_frame_new("[Zapret] DPI bypass"); GtkWidget *zapret_frame = gtk_frame_new("[Zapret] DPI bypass");
GtkWidget *zapret_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); GtkWidget *zapret_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
gtk_container_set_border_width(GTK_CONTAINER(zapret_box), 6); gtk_container_set_border_width(GTK_CONTAINER(zapret_box), 6);
@@ -588,7 +685,8 @@ static void build_controls_window(void) {
gtk_container_add(GTK_CONTAINER(tools_frame), tools_box); gtk_container_add(GTK_CONTAINER(tools_frame), tools_box);
gtk_box_pack_start(GTK_BOX(box), tools_frame, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), tools_frame, FALSE, FALSE, 0);
if (initial_state.subscription_update_available) { if (initial_state.subscription_update_available)
{
GtkWidget *sub_update_button = gtk_button_new_with_label("Update Subscriptions"); GtkWidget *sub_update_button = gtk_button_new_with_label("Update Subscriptions");
g_signal_connect(sub_update_button, "clicked", G_CALLBACK(on_subscription_update), NULL); g_signal_connect(sub_update_button, "clicked", G_CALLBACK(on_subscription_update), NULL);
gtk_box_pack_start(GTK_BOX(tools_box), sub_update_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(tools_box), sub_update_button, FALSE, FALSE, 0);
@@ -610,7 +708,8 @@ static void build_controls_window(void) {
gtk_widget_hide(controls_window); gtk_widget_hide(controls_window);
} }
static void build_menu(void) { static void build_menu(void)
{
menu = gtk_menu_new(); menu = gtk_menu_new();
status_item = gtk_menu_item_new_with_label("[Status] Loading service state..."); status_item = gtk_menu_item_new_with_label("[Status] Loading service state...");
@@ -629,19 +728,22 @@ static void build_menu(void) {
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
if (initial_state.tproxy_available) { if (initial_state.tproxy_available)
{
tproxy_item = gtk_menu_item_new_with_label("[Traffic] Start TProxy Mode"); tproxy_item = gtk_menu_item_new_with_label("[Traffic] Start TProxy Mode");
g_signal_connect(tproxy_item, "activate", G_CALLBACK(on_tproxy_toggle), NULL); g_signal_connect(tproxy_item, "activate", G_CALLBACK(on_tproxy_toggle), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), tproxy_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu), tproxy_item);
} }
if (initial_state.tun_available) { if (initial_state.tun_available)
{
tun_item = gtk_menu_item_new_with_label("[Traffic] Start TUN Mode"); tun_item = gtk_menu_item_new_with_label("[Traffic] Start TUN Mode");
g_signal_connect(tun_item, "activate", G_CALLBACK(on_tun_toggle), NULL); g_signal_connect(tun_item, "activate", G_CALLBACK(on_tun_toggle), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), tun_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu), tun_item);
} }
if (initial_state.zapret_available) { if (initial_state.zapret_available)
{
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
zapret_item = gtk_menu_item_new_with_label("[Zapret] Start zapret-discord-youtube"); zapret_item = gtk_menu_item_new_with_label("[Zapret] Start zapret-discord-youtube");
@@ -649,7 +751,8 @@ static void build_menu(void) {
gtk_menu_shell_append(GTK_MENU_SHELL(menu), zapret_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu), zapret_item);
} }
if (initial_state.subscription_update_available) { if (initial_state.subscription_update_available)
{
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
GtkWidget *sub_update_item = gtk_menu_item_new_with_label("Update Subscriptions"); GtkWidget *sub_update_item = gtk_menu_item_new_with_label("Update Subscriptions");
@@ -672,31 +775,34 @@ static void build_menu(void) {
gtk_widget_show_all(menu); gtk_widget_show_all(menu);
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[])
if (!gtk_init_check(&argc, &argv)) { {
if (!gtk_init_check(&argc, &argv))
{
fprintf(stderr, "proxy-suite-tray: failed to initialize GTK\n"); fprintf(stderr, "proxy-suite-tray: failed to initialize GTK\n");
return 1; return 1;
} }
GError *bus_error = NULL; GError *bus_error = NULL;
GDBusConnection *session_bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &bus_error); GDBusConnection *session_bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &bus_error);
if (session_bus) { if (session_bus)
{
g_dbus_connection_add_filter(session_bus, on_session_bus_message, NULL, NULL); g_dbus_connection_add_filter(session_bus, on_session_bus_message, NULL, NULL);
g_object_unref(session_bus); g_object_unref(session_bus);
} else { }
else
{
fprintf( fprintf(
stderr, stderr,
"proxy-suite-tray: warning: failed to monitor session bus: %s\n", "proxy-suite-tray: warning: failed to monitor session bus: %s\n",
bus_error ? bus_error->message : "unknown error" bus_error ? bus_error->message : "unknown error");
);
g_clear_error(&bus_error); g_clear_error(&bus_error);
} }
indicator = app_indicator_new( indicator = app_indicator_new(
"proxy-suite-tray", "proxy-suite-tray",
"proxy-suite-disabled", "proxy-suite-disabled",
APP_INDICATOR_CATEGORY_SYSTEM_SERVICES APP_INDICATOR_CATEGORY_SYSTEM_SERVICES);
);
app_indicator_set_status(indicator, APP_INDICATOR_STATUS_ACTIVE); app_indicator_set_status(indicator, APP_INDICATOR_STATUS_ACTIVE);
initial_state = get_service_state(); initial_state = get_service_state();
+20 -6
View File
@@ -12,6 +12,7 @@ BUILTIN_ACTIVATION_FALLBACKS = {
"list-twitter.txt": "general", "list-twitter.txt": "general",
} }
def _hostlist_remove_pattern(stem: str) -> str: def _hostlist_remove_pattern(stem: str) -> str:
escaped = re.escape(stem) escaped = re.escape(stem)
return rf'\s+--hostlist=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)' return rf'\s+--hostlist=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)'
@@ -112,8 +113,13 @@ def clone_family_lines(
if any(marker in line for marker in FAMILY_PATTERNS[family]["match"]) if any(marker in line for marker in FAMILY_PATTERNS[family]["match"])
] ]
if not matches: if not matches:
raise ValueError(f"Preset family '{family}' is not present in the selected zapret config") raise ValueError(
return [render_preset_clone(line, family, hostlist_path, standard_excludes) for line in matches] f"Preset family '{family}' is not present in the selected zapret config"
)
return [
render_preset_clone(line, family, hostlist_path, standard_excludes)
for line in matches
]
def activate_builtin_hostlists( def activate_builtin_hostlists(
@@ -139,8 +145,12 @@ def main() -> int:
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Append proxy-suite custom hostlist rules to a zapret config." description="Append proxy-suite custom hostlist rules to a zapret config."
) )
parser.add_argument("--config", required=True, help="Path to the selected zapret config file") parser.add_argument(
parser.add_argument("--spec", required=True, help="JSON file describing custom hostlist rules") "--config", required=True, help="Path to the selected zapret config file"
)
parser.add_argument(
"--spec", required=True, help="JSON file describing custom hostlist rules"
)
args = parser.parse_args() args = parser.parse_args()
config_path = Path(args.config) config_path = Path(args.config)
@@ -171,10 +181,14 @@ def main() -> int:
preset = entry.get("preset") preset = entry.get("preset")
if preset: if preset:
generated_lines.extend( generated_lines.extend(
clone_family_lines(nfqws_lines, preset, hostlist_path, standard_excludes) clone_family_lines(
nfqws_lines, preset, hostlist_path, standard_excludes
)
) )
for fragment in entry.get("nfqwsArgs", []): for fragment in entry.get("nfqwsArgs", []):
generated_lines.append(render_custom_args(fragment, hostlist_path, standard_excludes)) generated_lines.append(
render_custom_args(fragment, hostlist_path, standard_excludes)
)
updated_lines = lines[:end] + generated_lines + lines[end:] updated_lines = lines[:end] + generated_lines + lines[end:]
config_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8") config_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")
+3 -1
View File
@@ -62,7 +62,9 @@ def make_tag(prefix: str, remark: str, index: int) -> str:
return f"{prefix}-{index}" return f"{prefix}-{index}"
def parse_subscription(lines: list[str], tag_prefix: str, routing_mark: int | None) -> list[dict]: def parse_subscription(
lines: list[str], tag_prefix: str, routing_mark: int | None
) -> list[dict]:
outbounds = [] outbounds = []
seen_tags: set[str] = set() seen_tags: set[str] = set()
+9 -3
View File
@@ -47,7 +47,9 @@ def _mk_transport(
return None return None
def _mk_tls(server_name: str, fp: "str | None" = None, alpn: "str | None" = None) -> dict: def _mk_tls(
server_name: str, fp: "str | None" = None, alpn: "str | None" = None
) -> dict:
tls: dict = {"enabled": True, "server_name": server_name} tls: dict = {"enabled": True, "server_name": server_name}
if fp: if fp:
tls["utls"] = {"enabled": True, "fingerprint": fp} tls["utls"] = {"enabled": True, "fingerprint": fp}
@@ -85,7 +87,9 @@ def parse_vless(url: str, tag: str) -> dict:
"short_id": params.get("sid", ""), "short_id": params.get("sid", ""),
} }
elif security == "tls": elif security == "tls":
ob["tls"] = _mk_tls(params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")) ob["tls"] = _mk_tls(
params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")
)
tr = _mk_transport( tr = _mk_transport(
transport, transport,
@@ -159,7 +163,9 @@ def parse_trojan(url: str, tag: str) -> dict:
"server": host, "server": host,
"server_port": int(port), "server_port": int(port),
"password": urllib.parse.unquote(userinfo), "password": urllib.parse.unquote(userinfo),
"tls": _mk_tls(params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")), "tls": _mk_tls(
params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")
),
} }
tr = _mk_transport( tr = _mk_transport(
+5 -1
View File
@@ -46,7 +46,11 @@ class BuildOutboundTests(unittest.TestCase):
self.assertEqual(ob["tls"]["server_name"], "tls.example.com") self.assertEqual(ob["tls"]["server_name"], "tls.example.com")
def test_shadowsocks(self): def test_shadowsocks(self):
credentials = base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd").decode().rstrip("=") credentials = (
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd")
.decode()
.rstrip("=")
)
ob = run_parser(f"ss://{credentials}@ss.example.com:8388") ob = run_parser(f"ss://{credentials}@ss.example.com:8388")
self.assertEqual(ob["type"], "shadowsocks") self.assertEqual(ob["type"], "shadowsocks")
self.assertEqual(ob["method"], "chacha20-ietf-poly1305") self.assertEqual(ob["method"], "chacha20-ietf-poly1305")